List of usage examples for org.apache.commons.cli BasicParser BasicParser
BasicParser
From source file:com.hortonworks.streamline.storage.tool.SQLScriptRunner.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(option(1, "c", OPTION_CONFIG_FILE_PATH, "Config file path")); options.addOption(option(Option.UNLIMITED_VALUES, "f", OPTION_SCRIPT_PATH, "Script path to execute")); options.addOption(option(Option.UNLIMITED_VALUES, "m", OPTION_MYSQL_JAR_URL_PATH, "Mysql client jar url to download")); CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); if (!commandLine.hasOption(OPTION_CONFIG_FILE_PATH) || !commandLine.hasOption(OPTION_SCRIPT_PATH) || commandLine.getOptionValues(OPTION_SCRIPT_PATH).length <= 0) { usage(options);// www. jav a 2 s.co m System.exit(1); } String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH); String[] scripts = commandLine.getOptionValues(OPTION_SCRIPT_PATH); String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH); try { Map<String, Object> conf = Utils.readStreamlineConfig(confFilePath); StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader(); StorageProviderConfiguration storageProperties = confReader.readStorageConfig(conf); String bootstrapDirPath = System.getProperty("bootstrap.dir"); MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl); SQLScriptRunner sqlScriptRunner = new SQLScriptRunner(storageProperties); try { sqlScriptRunner.initializeDriver(); } catch (ClassNotFoundException e) { System.err.println( "Driver class is not found in classpath. Please ensure that driver is in classpath."); System.exit(1); } for (String script : scripts) { sqlScriptRunner.runScriptWithReplaceDBType(script); } } catch (IOException e) { System.err.println("Error occurred while reading config file: " + confFilePath); System.exit(1); } }
From source file:com.google.api.ads.adwords.awreporting.AwReporting.java
/** * Main method./*from www. j a v a2s . c o m*/ * * @param args the command line arguments. */ public static void main(String args[]) { // Proxy JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault()); ProxySelector.setDefault(ps); Options options = createCommandLineOptions(); boolean errors = false; String propertiesPath = null; try { CommandLineParser parser = new BasicParser(); CommandLine cmdLine = parser.parse(options, args); // Print full help and quit if (cmdLine.hasOption("help")) { printHelpMessage(options); printSamplePropertiesFile(); System.exit(0); } setLogLevel(cmdLine); if (cmdLine.hasOption("file")) { propertiesPath = cmdLine.getOptionValue("file"); } else { LOGGER.error("Missing required option: 'file'"); System.exit(0); } LOGGER.info("Using properties file: " + propertiesPath); Set<Long> accountIdsSet = Sets.newHashSet(); if (cmdLine.hasOption("accountIdsFile")) { String accountsFileName = cmdLine.getOptionValue("accountIdsFile"); addAccountsFromFile(accountIdsSet, accountsFileName); } boolean forceOnFileProcessor = false; if (cmdLine.hasOption("onFileReport")) { if (!cmdLine.hasOption("csvReportFile") || !cmdLine.hasOption("startDate") || !cmdLine.hasOption("endDate")) { LOGGER.error("Missing one or more of the required options: " + "'csvReportFile', 'startDate' or 'endDate'"); System.exit(0); } forceOnFileProcessor = true; } Properties properties = initApplicationContextAndProperties(propertiesPath, forceOnFileProcessor); LOGGER.debug("Creating ReportProcessor bean..."); ReportProcessor processor = createReportProcessor(); LOGGER.debug("... success."); String mccAccountId = properties.getProperty("mccAccountId").replaceAll("-", ""); if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) { // Generate Reports String dateStart = cmdLine.getOptionValue("startDate"); String dateEnd = cmdLine.getOptionValue("endDate"); if (cmdLine.hasOption("onFileReport")) { String reportTypeName = cmdLine.getOptionValue("onFileReport"); String csvReportFile = cmdLine.getOptionValue("csvReportFile"); File csvFile = new File(csvReportFile); if (!csvFile.exists()) { LOGGER.error("Could not find CSV file: " + csvReportFile); System.exit(0); } ReportProcessorOnFile onFileProcessor = (ReportProcessorOnFile) processor; List<File> localFiles = new ArrayList<File>(); localFiles.add(csvFile); LOGGER.info( "Starting report processing for dateStart: " + dateStart + " and dateEnd: " + dateEnd); onFileProcessor.processInputFiles(mccAccountId, reportTypeName, localFiles, dateStart, dateEnd, ReportDefinitionDateRangeType.CUSTOM_DATE); } else { LOGGER.info( "Starting report download for dateStart: " + dateStart + " and dateEnd: " + dateEnd); processor.generateReportsForMCC(mccAccountId, ReportDefinitionDateRangeType.CUSTOM_DATE, dateStart, dateEnd, accountIdsSet, properties, null, null); } } else if (cmdLine.hasOption("dateRange")) { ReportDefinitionDateRangeType dateRangeType = ReportDefinitionDateRangeType .fromValue(cmdLine.getOptionValue("dateRange")); LOGGER.info("Starting report download for dateRange: " + dateRangeType.name()); processor.generateReportsForMCC(mccAccountId, dateRangeType, null, null, accountIdsSet, properties, null, null); } else { errors = true; LOGGER.error("Configuration incomplete. Missing options for command line."); } } catch (IOException e) { errors = true; if (e.getMessage().contains("Insufficient Permission")) { LOGGER.error("Insufficient Permission error accessing the API" + e.getMessage()); } else { LOGGER.error("File not found: " + e.getMessage()); } } catch (ParseException e) { errors = true; System.err.println("Error parsing the values for the command line options: " + e.getMessage()); } catch (Exception e) { errors = true; LOGGER.error("Unexpected error accessing the API: " + e.getMessage()); e.printStackTrace(); } if (errors) { System.exit(1); } else { System.exit(0); } }
From source file:com.github.chrbayer84.keybits.KeyBits.java
/** * @param args// ww w . jav a 2 s. c o m */ public static void main(String[] args) throws Exception { int number_of_addresses = 1; int depth = 1; String usage = "java -jar KeyBits.jar [options]"; // create parameters which can be chosen Option help = new Option("h", "print this message"); Option verbose = new Option("v", "verbose"); Option exprt = new Option("e", "export public key to blockchain"); Option imprt = OptionBuilder.withArgName("string").hasArg() .withDescription("import public key from blockchain").create("i"); Option blockchain_address = OptionBuilder.withArgName("string").hasArg().withDescription("bitcoin address") .create("a"); Option create_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("create wallet") .create("c"); Option update_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("update wallet") .create("u"); Option balance_wallet = OptionBuilder.withArgName("file name").hasArg() .withDescription("return balance of wallet").create("b"); Option show_wallet = OptionBuilder.withArgName("file name").hasArg() .withDescription("show content of wallet").create("w"); Option send_coins = OptionBuilder.withArgName("file name").hasArg().withDescription("send satoshis") .create("s"); Option monitor_pending = OptionBuilder.withArgName("file name").hasArg() .withDescription("monitor pending transactions of wallet").create("p"); Option monitor_depth = OptionBuilder.withArgName("file name").hasArg() .withDescription("monitor transaction depths of wallet").create("d"); Option number = OptionBuilder.withArgName("integer").hasArg() .withDescription("in combination with -c, -d, -r or -s").create("n"); Option reset = OptionBuilder.withArgName("file name").hasArg().withDescription("reset wallet").create("r"); Options options = new Options(); options.addOption(help); options.addOption(verbose); options.addOption(imprt); options.addOption(exprt); options.addOption(blockchain_address); options.addOption(create_wallet); options.addOption(update_wallet); options.addOption(balance_wallet); options.addOption(show_wallet); options.addOption(send_coins); options.addOption(monitor_pending); options.addOption(monitor_depth); options.addOption(number); options.addOption(reset); BasicParser parser = new BasicParser(); CommandLine cmd = null; String header = "This is KeyBits v0.01b.1412953962" + System.getProperty("line.separator"); // show help if wrong usage try { cmd = parser.parse(options, args); } catch (Exception e) { printHelp(usage, options, header); } if (cmd.getOptions().length == 0) printHelp(usage, options, header); if (cmd.hasOption("h")) printHelp(usage, options, header); if (cmd.hasOption("v")) System.out.println(header); if (cmd.hasOption("c") && cmd.hasOption("n")) number_of_addresses = new Integer(cmd.getOptionValue("n")).intValue(); if (cmd.hasOption("d") && cmd.hasOption("n")) depth = new Integer(cmd.getOptionValue("n")).intValue(); String checkpoints_file_name = "checkpoints"; if (!new File(checkpoints_file_name).exists()) checkpoints_file_name = null; // --------------------------------------------------------------------- if (cmd.hasOption("c")) { String wallet_file_name = cmd.getOptionValue("c"); String passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name); if (!new File(wallet_file_name).exists()) { String passphrase_ = HelpfulStuff.reInsertPassphrase("enter password for " + wallet_file_name); if (!passphrase.equals(passphrase_)) { System.out.println("passwords do not match"); System.exit(0); } } MyWallet.createWallet(wallet_file_name, wallet_file_name + ".chain", number_of_addresses, passphrase); System.exit(0); } if (cmd.hasOption("u")) { String wallet_file_name = cmd.getOptionValue("u"); MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("b")) { String wallet_file_name = cmd.getOptionValue("b"); System.out.println( MyWallet.getBalanceOfWallet(wallet_file_name, wallet_file_name + ".chain").longValue()); System.exit(0); } if (cmd.hasOption("w")) { String wallet_file_name = cmd.getOptionValue("w"); System.out.println(MyWallet.showContentOfWallet(wallet_file_name, wallet_file_name + ".chain")); System.exit(0); } if (cmd.hasOption("p")) { System.out.println("monitoring of pending transactions ... "); String wallet_file_name = cmd.getOptionValue("p"); MyWallet.monitorPendingTransactions(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("d")) { System.out.println("monitoring of transaction depth ... "); String wallet_file_name = cmd.getOptionValue("d"); MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, depth); System.exit(0); } if (cmd.hasOption("r") && cmd.hasOption("n")) { long epoch = new Long(cmd.getOptionValue("n")); System.out.println("resetting wallet ... "); String wallet_file_name = cmd.getOptionValue("r"); File chain_file = (new File(wallet_file_name + ".chain")); if (chain_file.exists()) chain_file.delete(); MyWallet.setCreationTime(wallet_file_name, epoch); MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("s") && cmd.hasOption("a") && cmd.hasOption("n")) { String wallet_file_name = cmd.getOptionValue("s"); String address = cmd.getOptionValue("a"); Integer amount = new Integer(cmd.getOptionValue("n")); String wallet_passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name); MyWallet.sendCoins(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, address, new BigInteger(amount + ""), wallet_passphrase); System.out.println("waiting ..."); Thread.sleep(10000); System.out.println("monitoring of transaction depth ... "); MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, 1); System.out.println("transaction fixed in blockchain with depth " + depth); System.exit(0); } // ---------------------------------------------------------------------------------------- // creates public key // ---------------------------------------------------------------------------------------- GnuPGP gpg = new GnuPGP(); if (cmd.hasOption("e")) { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String line = null; StringBuffer sb = new StringBuffer(); while ((line = input.readLine()) != null) sb.append(line + "\n"); PGPPublicKeyRing public_key_ring = gpg.getDearmored(sb.toString()); //System.out.println(gpg.showPublicKeys(public_key_ring)); byte[] public_key_ring_encoded = gpg.getEncoded(public_key_ring); String[] addresses = (new Encoding()).encodePublicKey(public_key_ring_encoded); // System.out.println(gpg.showPublicKey(gpg.getDecoded(encoding.decodePublicKey(addresses)))); // file names for message String public_key_file_name = Long.toHexString(public_key_ring.getPublicKey().getKeyID()) + ".wallet"; String public_key_wallet_file_name = public_key_file_name; String public_key_chain_file_name = public_key_wallet_file_name + ".chain"; // hier muss dass passwort noch nach encodeAddresses weitergeleitet werden da sonst zweimal abfrage String public_key_wallet_passphrase = HelpfulStuff .insertPassphrase("enter password for " + public_key_wallet_file_name); if (!new File(public_key_wallet_file_name).exists()) { String public_key_wallet_passphrase_ = HelpfulStuff .reInsertPassphrase("enter password for " + public_key_wallet_file_name); if (!public_key_wallet_passphrase.equals(public_key_wallet_passphrase_)) { System.out.println("passwords do not match"); System.exit(0); } } MyWallet.createWallet(public_key_wallet_file_name, public_key_chain_file_name, 1, public_key_wallet_passphrase); MyWallet.updateWallet(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name); String public_key_address = MyWallet.getAddress(public_key_wallet_file_name, public_key_chain_file_name, 0); System.out.println("address of public key: " + public_key_address); // 10000 additional satoshis for sending transaction to address of recipient of message and 10000 for fees KeyBits.encodeAddresses(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name, addresses, 2 * SendRequest.DEFAULT_FEE_PER_KB.intValue(), depth, public_key_wallet_passphrase); } if (cmd.hasOption("i")) { String location = cmd.getOptionValue("i"); String[] addresses = null; if (location.indexOf(",") > -1) { String[] locations = location.split(","); addresses = MyWallet.getAddressesFromBlockAndTransaction("main.wallet", "main.wallet.chain", checkpoints_file_name, locations[0], locations[1]); } else { addresses = BlockchainDotInfo.getKeys(location); } byte[] encoded = (new Encoding()).decodePublicKey(addresses); PGPPublicKeyRing public_key_ring = gpg.getDecoded(encoded); System.out.println(gpg.getArmored(public_key_ring)); System.exit(0); } }
From source file:eu.annocultor.converter.Analyser.java
static public void main(String... args) throws Exception { // Handling command line parameters with Apache Commons CLI Options options = new Options(); options.addOption(OptionBuilder.withArgName(OPT_FN).hasArg().isRequired() .withDescription("XML file name to be analysed").withValueSeparator(',').create(OPT_FN)); options.addOption(OptionBuilder.withArgName(OPT_MAX_VALUE_SIZE).hasArg().withDescription( "Maximal size when values are counted separately. Longer values are counted altogether. Reasonable values are 100, 300, etc.") .create(OPT_MAX_VALUE_SIZE)); options.addOption(OptionBuilder.withArgName(OPT_VALUES).hasArg().withDescription( "Maximal number of most frequent values displayed in the report. Reasonable values are 10, 25, 50") .create(OPT_VALUES));// w w w.j a va2 s . c o m // now lets parse the input CommandLineParser parser = new BasicParser(); CommandLine cmd; try { cmd = parser.parse(options, Utils.getCommandLineFromANNOCULTOR_ARGS(args)); } catch (ParseException pe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("analyse", options); return; } MAX_VALUE_SIZE = Integer.parseInt(cmd.getOptionValue(OPT_MAX_VALUE_SIZE, Integer.toString(MAX_VALUE_SIZE))); MAX_VALUES = Integer.parseInt(cmd.getOptionValue(OPT_VALUES, Integer.toString(MAX_VALUES))); Analyser analyser = new Analyser(new EnvironmentImpl()); // undo: /* analyser.task.setSrcFiles(new File("."), cmd.getOptionValue(OPT_FN)); if (analyser.task.getSrcFiles().size() > 1) { analyser.task.mergeSourceFiles(); } if (analyser.task.getSrcFiles().size() == 0) { throw new Exception("No files to analyze, pattern " + cmd.getOptionValue(OPT_FN)); } File trg = new File(analyser.task.getSrcFiles().get(0).getParentFile(), "rdf"); if (!trg.exists()) trg.mkdir(); System.out.println("[Analysis] Analysing files " + cmd.getOptionValue(OPT_FN) + ", writing analysis to " + trg.getCanonicalPath() + ", max value length (long values are aggregated into one 'long value' value) " + MAX_VALUE_SIZE + ", number most fequently used values per field shown in report " + MAX_VALUES); */ if (true) throw new Exception("unimplemented"); System.exit(analyser.run()); }
From source file:benchmark.hbase.controller.TestLauncher.java
public static void main(final String[] args) throws Exception { // create the parser final CommandLineParser parser = new BasicParser(); // parse the command line arguments final CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("u")) { displayHelp();/*www .ja v a 2 s . com*/ } final String connectionUrl = cmd.getOptionValue("connection-url"); final StoreType storeType = StoreType.fromName(cmd.getOptionValue("store-type")); final Optional<String> optionalNumReads = Optional.fromNullable(cmd.getOptionValue("num-reads")); final Optional<String> optionalNumWrites = Optional.fromNullable(cmd.getOptionValue("num-writes")); final int readConcurrancy = Integer.parseInt(cmd.getOptionValue("read-concurrancy")); final int writeConcurrancy = Integer.parseInt(cmd.getOptionValue("write-concurrancy")); int numReads = 0; int numWrites = 0; BenchmarkType benchmarkType = BenchmarkType.READ_ONLY; if (optionalNumReads.isPresent() && optionalNumWrites.isPresent()) { benchmarkType = BenchmarkType.READ_AND_WRITE; numReads = Integer.parseInt(optionalNumReads.get()); numWrites = Integer.parseInt(optionalNumWrites.get()); } else if (optionalNumReads.isPresent()) { benchmarkType = BenchmarkType.READ_ONLY; numReads = Integer.parseInt(optionalNumReads.get()); } else if (optionalNumWrites.isPresent()) { benchmarkType = BenchmarkType.WRITE_ONLY; numWrites = Integer.parseInt(optionalNumWrites.get()); } log.info("connectionUrl: {}", connectionUrl); log.info("storeType: {}", storeType); log.info("numReads: {}", numReads); log.info("numWrites: {}", numWrites); log.info("readConcurrancy: {}", readConcurrancy); log.info("writeConcurrancy: {}", writeConcurrancy); log.info("benchmarkType: {}", benchmarkType); TestLauncher.start(storeType, benchmarkType, numReads, numWrites, readConcurrancy, connectionUrl); System.exit(0); }
From source file:com.cloudera.ByteCount.java
public static void main(String[] args) throws Exception { JobConf conf = new JobConf(new Configuration()); // Trim off the hadoop-specific args String[] remArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); // Pull in properties Options options = new Options(); Option property = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator() .withDescription("use value for given property").create("D"); options.addOption(property);// ww w .j av a2 s. c om Option skipChecksums = new Option("skipChecksums", "skip checksums"); options.addOption(skipChecksums); Option profile = new Option("profile", "profile tasks"); options.addOption(profile); CommandLineParser parser = new BasicParser(); CommandLine line = parser.parse(options, remArgs); Properties properties = line.getOptionProperties("D"); for (Entry<Object, Object> prop : properties.entrySet()) { conf.set(prop.getKey().toString(), prop.getValue().toString()); System.out.println("Set config key " + prop.getKey() + " to " + prop.getValue()); } if (line.hasOption("skipChecksums")) { conf.setBoolean("bytecount.skipChecksums", true); System.out.println("Skipping checksums"); } if (line.hasOption("profile")) { conf.setBoolean("mapred.task.profile", true); conf.set("mapred.task.profile.params", "-agentlib:hprof=cpu=samples,depth=100,interval=1ms,lineno=y,thread=y,file=%s"); conf.set(MRJobConfig.NUM_MAP_PROFILES, "0"); conf.set("mapred.task.profile.maps", "1"); System.out.println("Profiling map tasks"); } // Get the positional arguments out remArgs = line.getArgs(); if (remArgs.length != 2) { System.err.println("Usage: ByteCount <inputBase> <outputBase>"); System.exit(1); } String inputBase = remArgs[0]; String outputBase = remArgs[1]; Job job = Job.getInstance(conf); job.setInputFormatClass(ByteBufferInputFormat.class); job.setMapOutputKeyClass(ByteWritable.class); job.setMapOutputValueClass(LongWritable.class); job.setMapperClass(ByteCountMapper.class); job.setReducerClass(ByteCountReducer.class); job.setCombinerClass(ByteCountReducer.class); job.setOutputKeyClass(ByteWritable.class); job.setOutputValueClass(LongWritable.class); FileInputFormat.addInputPath(job, new Path(inputBase)); FileOutputFormat.setOutputPath(job, new Path(outputBase)); job.setJarByClass(ByteCount.class); boolean success = job.waitForCompletion(true); Counters counters = job.getCounters(); System.out.println("\tRead counters"); printCounter(counters, READ_COUNTER.BYTES_READ); printCounter(counters, READ_COUNTER.LOCAL_BYTES_READ); printCounter(counters, READ_COUNTER.SCR_BYTES_READ); printCounter(counters, READ_COUNTER.ZCR_BYTES_READ); System.exit(success ? 0 : 1); }
From source file:edu.ntnu.EASY.Main.java
public static void main(String[] args) { CommandLine cl = null;//from ww w . ja va 2 s . c o m CommandLineParser clp = new BasicParser(); HelpFormatter hf = new HelpFormatter(); try { cl = clp.parse(options, args); } catch (ParseException e) { e.printStackTrace(); hf.printHelp(USAGE, options); System.exit(1); } if (cl.hasOption('h') || cl.hasOption('?')) { hf.printHelp(USAGE, options); System.exit(0); } Environment env = new Environment(); env.populationSize = Integer.parseInt(cl.getOptionValue('p', "200")); env.maxGenerations = Integer.parseInt(cl.getOptionValue('g', "1000")); env.fitnessThreshold = 2.0; env.mutationRate = Double.parseDouble(cl.getOptionValue('m', "0.01")); env.crossoverRate = Double.parseDouble(cl.getOptionValue('c', "0.01")); env.numChildren = Integer.parseInt(cl.getOptionValue('b', "200")); env.numParents = Integer.parseInt(cl.getOptionValue('f', "20")); env.rank = Integer.parseInt(cl.getOptionValue('r', "10")); env.elitism = Integer.parseInt(cl.getOptionValue('e', "3")); ParentSelector<double[]> parentSelector = null; int parent = Integer.parseInt(cl.getOptionValue('P', "1")); switch (parent) { case 1: parentSelector = new FitnessProportionateSelector<double[]>(env.numParents); break; case 2: parentSelector = new RankSelector<double[]>(env.rank); break; case 3: parentSelector = new SigmaScaledSelector<double[]>(env.numParents); break; case 4: parentSelector = new TournamentSelector<double[]>(env.rank, env.numParents); break; case 5: parentSelector = new StochasticTournamentSelector<double[]>(env.rank, env.numParents, 0.3); break; case 6: parentSelector = new BoltzmanSelector<double[]>(env.numParents); break; default: System.out.printf("No such parent selector: %d%n", parent); hf.printHelp(USAGE, options); System.exit(1); } AdultSelector<double[]> adultSelector = null; int adult = Integer.parseInt(cl.getOptionValue('A', "1")); switch (adult) { case 1: adultSelector = new FullGenerationalReplacement<double[]>(); break; case 2: adultSelector = new GenerationalMixing<double[]>(env.numAdults); break; case 3: adultSelector = new Overproduction<double[]>(env.numAdults); break; default: System.out.printf("No such adult selector: %d%n", adult); hf.printHelp(USAGE, options); System.exit(1); } String targetFile = cl.getOptionValue('t', "target.dat"); double[] target = null; try { target = Util.readTargetSpikeTrain(targetFile); } catch (IOException e) { System.out.printf("Couldn't read target file: %s%n", targetFile); hf.printHelp(USAGE, options); System.exit(1); } FitnessCalculator<double[]> fitCalc = null; int calc = Integer.parseInt(cl.getOptionValue('C', "1")); switch (calc) { case 1: fitCalc = new SpikeTimeFitnessCalculator(target); break; case 2: fitCalc = new SpikeIntervalFitnessCalculator(target); break; case 3: fitCalc = new WaveformFitnessCalculator(target); break; default: System.out.printf("No such fitness calculator: %d%n", calc); hf.printHelp(USAGE, options); System.exit(1); } String output = cl.getOptionValue('o', "neuron"); Incubator<double[], double[]> incubator = new NeuronIncubator( new NeuronReplicator(env.mutationRate, env.crossoverRate), env.numChildren); Evolution<double[], double[]> evo = new Evolution<double[], double[]>(fitCalc, adultSelector, parentSelector, incubator); NeuronReport report = new NeuronReport(env.maxGenerations); evo.runEvolution(env, report); try { PrintStream ps = new PrintStream(new FileOutputStream(output + ".log")); report.writeToStream(ps); } catch (FileNotFoundException e) { System.out.printf("Could not write to %s.log%n", output); } double[] bestPhenome = report.getBestPhenome(); Plot train = Plot.newPlot("Neuron").setAxis("x", "ms").setAxis("y", "activation") .with("bestPhenome", bestPhenome).with("target", target).make(); double[] averageFitness = report.getAverageFitness(); double[] bestFitness = report.getBestFitness(); Plot fitness = Plot.newPlot("Fitness").setAxis("x", "generation").setAxis("y", "fitness") .with("average", averageFitness).with("best", bestFitness).make(); train.plot(); fitness.plot(); train.writeToFile(output + "-train"); fitness.writeToFile(output + "-fitness"); }
From source file:jp.primecloud.auto.tool.management.main.Main.java
public static void main(String args[]) { Options options = new Options(); options.addOption("Z", false, "Zabbix mode"); options.addOption("U", false, "UPDATE mode"); options.addOption("S", false, "SELECT mode"); options.addOption("C", false, "Create Mode"); options.addOption("P", false, "Show Platform"); options.addOption("L", false, "Show Users"); options.addOption("E", false, "Ecrypt UserPassword"); options.addOption("I", false, "IaasGateway Mode"); options.addOption("A", false, "PCC-API Genarate ID or Key Mode"); options.addOption("W", false, "Decrypt UserPassword"); options.addOption("username", true, "Create the username"); options.addOption("password", true, "Create the password"); options.addOption("firstname", true, "Create the firstname"); options.addOption("familyname", true, "Create the familyname"); options.addOption("userno", true, "Create the userno"); options.addOption("dburl", "connectionurl", true, "PrimeCloud Controller database url"); options.addOption("dbuser", "username", true, "PrimeCloud Controller database username"); options.addOption("dbpass", "password", true, "PrimeCloud Controller database password"); options.addOption("sql", true, "SQL"); options.addOption("columnname", true, "columnName"); options.addOption("columntype", true, "columnType"); options.addOption("salt", true, "Salt"); OptionBuilder.withLongOpt("prepared"); OptionBuilder.hasArgs();//from w ww. jav a 2 s . com OptionBuilder.withDescription("execute as PreparedStatement"); OptionBuilder.withArgName("params"); Option optionPrepared = OptionBuilder.create(); options.addOption(optionPrepared); // for Zabbix options.addOption("enable", false, "enable"); options.addOption("disable", false, "disable"); options.addOption("get", false, "getUser from zabbix"); options.addOption("check", false, "API setting check for zabbix"); options.addOption("config", true, "Property can obtain from management-config.properties"); options.addOption("platformkind", true, "Platform kind. e.g. ec2 and ec2_vpc or vmware"); options.addOption("platformname", true, "Platform can obtain from auto-config.xml"); options.addOption("platformno", true, "Platform can obtain from auto-config.xml"); // for IaasGateway(AWS, Cloudstack) options.addOption("keyname", true, "import your key pair as keyName"); options.addOption("publickey", true, "import your public key"); // for PCC options.addOption("accessid", true, "accessid for PCC-API"); options.addOption("secretkey", true, "secretkey for PCC-API"); options.addOption("generatetype", true, "genarateType for PCC-API"); options.addOption("h", "help", false, "help"); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); } catch (ParseException e) { System.out.println( "???????? -h?????????"); return; } if (commandLine.hasOption("h")) { HelpFormatter f = new HelpFormatter(); f.printHelp("PCC script ", options); } ManagementConfigLoader.init(); //? //Zabbix? if (commandLine.hasOption("Z")) { if (commandLine.hasOption("C")) { //Zabbix? ZabbixMain.createExecute(commandLine); } else if (commandLine.hasOption("U")) { //Zabbix ZabbixMain.updateExecute(commandLine); } else if (commandLine.hasOption("disable")) { //Zabbix ZabbixMain.disableExecute(commandLine); } else if (commandLine.hasOption("enable")) { //Zabbix ZabbixMain.enableExecute(commandLine); } else if (commandLine.hasOption("get")) { //Zabbix? ZabbixMain.getUser(commandLine); } else if (commandLine.hasOption("check")) { //Zabbix?? ZabbixMain.checkApiVersion(); } //PCC? } else if (commandLine.hasOption("U")) { if (commandLine.hasOption("prepared")) { SQLMain.updateExecutePrepared(commandLine); } else { //Update? SQLMain.updateExecute(commandLine); } } else if (commandLine.hasOption("S")) { //Select? SQLMain.selectExecute(commandLine); } else if (commandLine.hasOption("P")) { //? ConfigMain.showPlatforms(); } else if (commandLine.hasOption("L")) { //PCC? UserService.showUserPlatform(); } else if (commandLine.hasOption("config")) { //??? ConfigMain.getProperty(commandLine.getOptionValue("config")); } else if (commandLine.hasOption("platformname") && commandLine.hasOption("platformkind")) { //?????? ConfigMain.getPlatformNo(commandLine.getOptionValue("platformname"), commandLine.getOptionValue("platformkind")); } else if (commandLine.hasOption("E")) { //PCC?? UserService.encryptUserPassword(commandLine.getOptionValue("password")); } else if (commandLine.hasOption("I")) { //IaasGatewayCall??AWS or Cloudstack??? IaasGatewayMain.importExecute(commandLine); } else if (commandLine.hasOption("A")) { PccApiGenerateService.genarate(commandLine); } else if (commandLine.hasOption("W")) { //PCC?? UserService.decryptUserPassword(commandLine.getOptionValue("password"), commandLine.getOptionValue("salt")); } }
From source file:com.alibaba.jstorm.flux.Flux.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(option(0, "l", OPTION_LOCAL, "Run the topology in local mode.")); options.addOption(option(0, "r", OPTION_REMOTE, "Deploy the topology to a remote cluster.")); options.addOption(option(0, "R", OPTION_RESOURCE, "Treat the supplied path as a classpath resource instead of a file.")); options.addOption(/*from w w w .ja va 2 s .com*/ option(1, "s", OPTION_SLEEP, "ms", "When running locally, the amount of time to sleep (in ms.) " + "before killing the topology and shutting down the local cluster.")); options.addOption(option(0, "d", OPTION_DRY_RUN, "Do not run or deploy the topology. Just build, validate, " + "and print information about the topology.")); options.addOption(option(0, "q", OPTION_NO_DETAIL, "Suppress the printing of topology details.")); options.addOption(option(0, "n", OPTION_NO_SPLASH, "Suppress the printing of the splash screen.")); options.addOption(option(0, "i", OPTION_INACTIVE, "Deploy the topology, but do not activate it.")); options.addOption(option(1, "z", OPTION_ZOOKEEPER, "host:port", "When running in local mode, use the ZooKeeper at the " + "specified <host>:<port> instead of the in-process ZooKeeper. (requires Storm 0.9.3 or later)")); options.addOption(option(1, "f", OPTION_FILTER, "file", "Perform property substitution. Use the specified file " + "as a source of properties, and replace keys identified with {$[property name]} with the value defined " + "in the properties file.")); options.addOption( option(0, "e", OPTION_ENV_FILTER, "Perform environment variable substitution. Replace keys" + "identified with `${ENV-[NAME]}` will be replaced with the corresponding `NAME` environment value")); CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.getArgs().length != 1) { usage(options); System.exit(1); } runCli(cmd); }
From source file:kellinwood.zipsigner.cmdline.Main.java
public static void main(String[] args) { try {//w w w . j av a 2 s . c o m Options options = new Options(); CommandLine cmdLine = null; Option helpOption = new Option("h", "help", false, "Display usage information"); Option modeOption = new Option("m", "keymode", false, "Keymode one of: auto, auto-testkey, auto-none, media, platform, shared, testkey, none"); modeOption.setArgs(1); Option keyOption = new Option("k", "key", false, "PCKS#8 encoded private key file"); keyOption.setArgs(1); Option pwOption = new Option("p", "keypass", false, "Private key password"); pwOption.setArgs(1); Option certOption = new Option("c", "cert", false, "X.509 public key certificate file"); certOption.setArgs(1); Option sbtOption = new Option("t", "template", false, "Signature block template file"); sbtOption.setArgs(1); Option keystoreOption = new Option("s", "keystore", false, "Keystore file"); keystoreOption.setArgs(1); Option aliasOption = new Option("a", "alias", false, "Alias for key/cert in the keystore"); aliasOption.setArgs(1); options.addOption(helpOption); options.addOption(modeOption); options.addOption(keyOption); options.addOption(certOption); options.addOption(sbtOption); options.addOption(pwOption); options.addOption(keystoreOption); options.addOption(aliasOption); Parser parser = new BasicParser(); try { cmdLine = parser.parse(options, args); } catch (MissingOptionException x) { System.out.println("One or more required options are missing: " + x.getMessage()); usage(options); } catch (ParseException x) { System.out.println(x.getClass().getName() + ": " + x.getMessage()); usage(options); } if (cmdLine.hasOption(helpOption.getOpt())) usage(options); Properties log4jProperties = new Properties(); log4jProperties.load(new FileReader("log4j.properties")); PropertyConfigurator.configure(log4jProperties); LoggerManager.setLoggerFactory(new Log4jLoggerFactory()); List<String> argList = cmdLine.getArgList(); if (argList.size() != 2) usage(options); ZipSigner signer = new ZipSigner(); signer.addAutoKeyObserver(new Observer() { @Override public void update(Observable observable, Object o) { System.out.println("Signing with key: " + o); } }); Class bcProviderClass = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); Provider bcProvider = (Provider) bcProviderClass.newInstance(); KeyStoreFileManager.setProvider(bcProvider); signer.loadProvider("org.spongycastle.jce.provider.BouncyCastleProvider"); PrivateKey privateKey = null; if (cmdLine.hasOption(keyOption.getOpt())) { if (!cmdLine.hasOption(certOption.getOpt())) { System.out.println("Certificate file is required when specifying a private key"); usage(options); } String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } URL privateKeyUrl = new File(keyOption.getValue()).toURI().toURL(); privateKey = signer.readPrivateKey(privateKeyUrl, keypw); } X509Certificate cert = null; if (cmdLine.hasOption(certOption.getOpt())) { if (!cmdLine.hasOption(keyOption.getOpt())) { System.out.println("Private key file is required when specifying a certificate"); usage(options); } URL certUrl = new File(certOption.getValue()).toURI().toURL(); cert = signer.readPublicKey(certUrl); } byte[] sigBlockTemplate = null; if (cmdLine.hasOption(sbtOption.getOpt())) { URL sbtUrl = new File(sbtOption.getValue()).toURI().toURL(); sigBlockTemplate = signer.readContentAsBytes(sbtUrl); } if (cmdLine.hasOption(keyOption.getOpt())) { signer.setKeys("custom", cert, privateKey, sigBlockTemplate); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption(modeOption.getOpt())) { signer.setKeymode(modeOption.getValue()); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption((keystoreOption.getOpt()))) { String alias = null; if (!cmdLine.hasOption(aliasOption.getOpt())) { KeyStore keyStore = KeyStoreFileManager.loadKeyStore(keystoreOption.getValue(), (char[]) null); for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) { alias = e.nextElement(); System.out.println("Signing with key: " + alias); break; } } else alias = aliasOption.getValue(); String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } CustomKeySigner.signZip(signer, keystoreOption.getValue(), null, alias, keypw.toCharArray(), "SHA1withRSA", argList.get(0), argList.get(1)); } else { signer.setKeymode("auto-testkey"); signer.signZip(argList.get(0), argList.get(1)); } } catch (Throwable t) { t.printStackTrace(); } }