List of usage examples for org.apache.commons.cli ParseException printStackTrace
public void printStackTrace()
From source file:edu.ntnu.EASY.Main.java
public static void main(String[] args) { CommandLine cl = null;//from w w w . j a va2 s . c om 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:com.pinterest.terrapin.tools.HFileGenerator.java
public static void main(String[] args) { Options options = getCommandLineOptions(); CommandLineParser cmdParser = new PosixParser(); if (args.length < 1) { printHelpMessage(options);// w ww .j a v a 2s . c o m } else { File outputFolder = new File(args[args.length - 1]); checkOutputFolder(outputFolder); String[] optionArgs = new String[args.length - 1]; System.arraycopy(args, 0, optionArgs, 0, args.length - 1); try { CommandLine cmd = cmdParser.parse(options, optionArgs); if (hasHelp(cmd)) { printHelpMessage(options); } else { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); generateHFiles(fs, conf, outputFolder, getPartitionerType(cmd), getNumOfPartitions(cmd), getNumOfKeys(cmd)); } } catch (ParseException e) { printHelpMessage(options); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } catch (IOException e) { e.printStackTrace(); } } }
From source file:jmdbtools.JMdbTools.java
public static void main(String[] args) { System.out.println("[INFO] Starting mdb file processing"); Options options = createOptions();// w w w . j a v a 2 s .c o m CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("f")) { JMdbTools tool = new JMdbTools(cmd); tool.processOptions(cmd); if (cmd.hasOption("s")) { tool.showStats(); } //export if (cmd.hasOption("e")) { tool.exportCSV(); } //export to mysql if (cmd.hasOption("db")) { tool.exportToMySQL(); } } else { System.out.println("[ERROR] No file parameter given!"); } } catch (ParseException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.FilterTranTable.java
public static void main(String[] args) { Options options = new Options(); options.addOption(INPUT_PARAM, null, true, INPUT_DESC); options.addOption(OUTPUT_PARAM, null, true, OUTPUT_DESC); options.addOption(CommonParams.MEM_FWD_INDEX_PARAM, null, true, CommonParams.MEM_FWD_INDEX_DESC); options.addOption(CommonParams.GIZA_ITER_QTY_PARAM, null, true, CommonParams.GIZA_ITER_QTY_PARAM); options.addOption(CommonParams.GIZA_ROOT_DIR_PARAM, null, true, CommonParams.GIZA_ROOT_DIR_PARAM); options.addOption(CommonParams.MIN_PROB_PARAM, null, true, CommonParams.MIN_PROB_DESC); options.addOption(CommonParams.MAX_WORD_QTY_PARAM, null, true, CommonParams.MAX_WORD_QTY_PARAM); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {//from w w w . ja va 2s . c o m CommandLine cmd = parser.parse(options, args); String outputFile = null; outputFile = cmd.getOptionValue(OUTPUT_PARAM); if (null == outputFile) { Usage("Specify 'A name of the output file'", options); } String gizaRootDir = cmd.getOptionValue(CommonParams.GIZA_ROOT_DIR_PARAM); if (null == gizaRootDir) { Usage("Specify '" + CommonParams.GIZA_ROOT_DIR_DESC + "'", options); } String gizaIterQty = cmd.getOptionValue(CommonParams.GIZA_ITER_QTY_PARAM); if (null == gizaIterQty) { Usage("Specify '" + CommonParams.GIZA_ITER_QTY_DESC + "'", options); } float minProb = 0; String tmpf = cmd.getOptionValue(CommonParams.MIN_PROB_PARAM); if (tmpf != null) { minProb = Float.parseFloat(tmpf); } int maxWordQty = Integer.MAX_VALUE; String tmpi = cmd.getOptionValue(CommonParams.MAX_WORD_QTY_PARAM); if (null != tmpi) { maxWordQty = Integer.parseInt(tmpi); } String memFwdIndxName = cmd.getOptionValue(CommonParams.MEM_FWD_INDEX_PARAM); if (null == memFwdIndxName) { Usage("Specify '" + CommonParams.MEM_FWD_INDEX_DESC + "'", options); } System.out.println("Filtering index: " + memFwdIndxName + " max # of frequent words: " + maxWordQty + " min. probability:" + minProb); VocabularyFilterAndRecoder filter = new FrequentIndexWordFilterAndRecoder(memFwdIndxName, maxWordQty); String srcVocFile = CompressUtils.findFileVariant(gizaRootDir + "/source.vcb"); System.out.println("Source vocabulary file: " + srcVocFile); GizaVocabularyReader srcVoc = new GizaVocabularyReader(srcVocFile, filter); String dstVocFile = CompressUtils.findFileVariant(gizaRootDir + "/target.vcb"); System.out.println("Target vocabulary file: " + dstVocFile); GizaVocabularyReader dstVoc = new GizaVocabularyReader(CompressUtils.findFileVariant(dstVocFile), filter); String inputFile = CompressUtils.findFileVariant(gizaRootDir + "/output.t1." + gizaIterQty); BufferedReader finp = new BufferedReader( new InputStreamReader(CompressUtils.createInputStream(inputFile))); BufferedWriter fout = new BufferedWriter( new OutputStreamWriter(CompressUtils.createOutputStream(outputFile))); try { String line; int prevSrcId = -1; int wordQty = 0; long addedQty = 0; long totalQty = 0; boolean isNotFiltered = false; for (totalQty = 0; (line = finp.readLine()) != null;) { ++totalQty; // Skip empty lines line = line.trim(); if (line.isEmpty()) continue; GizaTranRec rec = new GizaTranRec(line); if (rec.mSrcId != prevSrcId) { ++wordQty; } if (totalQty % REPORT_INTERVAL_QTY == 0) { System.out.println(String.format( "Processed %d lines (%d source word entries) from '%s', added %d lines", totalQty, wordQty, inputFile, addedQty)); } // isNotFiltered should be set after procOneWord if (rec.mSrcId != prevSrcId) { if (rec.mSrcId == 0) isNotFiltered = true; else { String wordSrc = srcVoc.getWord(rec.mSrcId); isNotFiltered = filter == null || (wordSrc != null && filter.checkWord(wordSrc)); } } prevSrcId = rec.mSrcId; if (rec.mProb >= minProb && isNotFiltered) { String wordDst = dstVoc.getWord(rec.mDstId); if (filter == null || (wordDst != null && filter.checkWord(wordDst))) { fout.write(String.format(rec.mSrcId + " " + rec.mDstId + " " + rec.mProb)); fout.newLine(); addedQty++; } } } System.out.println( String.format("Processed %d lines (%d source word entries) from '%s', added %d lines", totalQty, wordQty, inputFile, addedQty)); } finally { finp.close(); fout.close(); } } catch (ParseException e) { Usage("Cannot parse arguments", options); } catch (Exception e) { e.printStackTrace(); System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:com.evolveum.midpoint.tools.gui.Main.java
public static void main(String[] args) throws Exception { Options options = new Options(); Option propertiesLocaleDelimiter = new Option("d", "delimiter", true, "Delimiter for locale name in properties file. Default is '_' (underscore)."); options.addOption(propertiesLocaleDelimiter); Option targetFolder = new Option("t", "targetFolder", true, "Target folder where properties file is generated."); targetFolder.setRequired(true);/* w w w . j a va 2s .co m*/ options.addOption(targetFolder); Option baseFolder = new Option("b", "baseFolder", true, "Base folder used for properties files searching."); baseFolder.setRequired(true); options.addOption(baseFolder); Option localesToCheck = new Option("l", "locale", true, "Locales to check."); localesToCheck.setRequired(true); options.addOption(localesToCheck); Option recursiveFolderToCheck = new Option("r", "folderRecursive", true, "Folder used for recursive search for properties files."); options.addOption(recursiveFolderToCheck); Option nonRecursiveFolderToCheck = new Option("n", "folderNonRecursive", true, "Folder used for non recursive search for properties files."); options.addOption(nonRecursiveFolderToCheck); Option help = new Option("h", "help", false, "Print this help."); options.addOption(help); Option disableBackup = new Option("db", "disableBackup", false, "Disable backuping property files."); options.addOption(disableBackup); try { CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); if (line.hasOption(help.getOpt())) { printHelp(options); return; } if (!line.hasOption(recursiveFolderToCheck.getOpt()) && !line.hasOption(nonRecursiveFolderToCheck.getOpt())) { printHelp(options); return; } GeneratorConfiguration config = new GeneratorConfiguration(); if (line.hasOption(baseFolder.getOpt())) { config.setBaseFolder(new File(line.getOptionValue(baseFolder.getOpt()))); } if (line.hasOption(targetFolder.getOpt())) { config.setTargetFolder(new File(line.getOptionValue(targetFolder.getOpt()))); } if (line.hasOption(propertiesLocaleDelimiter.getOpt())) { config.setPropertiesLocaleDelimiter(line.getOptionValue(propertiesLocaleDelimiter.getOpt())); } if (line.hasOption(recursiveFolderToCheck.getOpt())) { String[] recursives = line.getOptionValues(recursiveFolderToCheck.getOpt()); if (recursives != null && recursives.length > 0) { for (String recursive : recursives) { config.getRecursiveFolderToCheck().add(recursive); } } } if (line.hasOption(nonRecursiveFolderToCheck.getOpt())) { String[] nonRecursives = line.getOptionValues(nonRecursiveFolderToCheck.getOpt()); if (nonRecursives != null && nonRecursives.length > 0) { for (String nonRecursive : nonRecursives) { config.getNonRecursiveFolderToCheck().add(nonRecursive); } } } if (line.hasOption(localesToCheck.getOpt())) { String[] locales = line.getOptionValues(localesToCheck.getOpt()); for (String locale : locales) { config.getLocalesToCheck().add(getLocaleFromString(locale)); } } if (line.hasOption(disableBackup.getOpt())) { config.setDisableBackup(true); } PropertiesGenerator generator = new PropertiesGenerator(config); generator.generate(); } catch (ParseException ex) { System.out.println("Error: " + ex.getMessage()); printHelp(options); } catch (Exception ex) { System.out.println("Something is broken."); ex.printStackTrace(); } }
From source file:executables.Align.java
@SuppressWarnings("static-access") public static void main(String[] args) throws IOException { Options options = new Options() .addOption(OptionBuilder.withArgName("f1").withDescription("Fasta file 1").hasArg().create("f1")) .addOption(OptionBuilder.withArgName("f2").withDescription("Fasta file 2").hasArg().create("f2")) .addOption(OptionBuilder.withArgName("s1").withDescription("sequence 1").hasArg().create("s1")) .addOption(OptionBuilder.withArgName("s2").withDescription("sequence 2").hasArg().create("s2")) .addOption(OptionBuilder.withArgName("gap-linear").withDescription("Linear gap cost").hasArg() .create("gl")) .addOption(OptionBuilder.withArgName("gap-open").withDescription("Affine gap open cost").hasArg() .create("go")) .addOption(OptionBuilder.withArgName("gap-extend").withDescription("Affine gap extend cost") .hasArg().create("ge")) .addOption(OptionBuilder.withArgName("gap-function").withDescription("Gap function file").hasArg() .create("gf")) .addOption(//ww w . ja v a 2 s . c o m OptionBuilder.withArgName("gapless").withDescription("Gapless alignment").create("gapless")) .addOption(OptionBuilder.withArgName("mode") .withDescription("Alignment mode: global,local,freeshift (Default: freeshift)").hasArg() .create('m')) .addOption(OptionBuilder.withArgName("match").withDescription("Match score").hasArg().create("ma")) .addOption(OptionBuilder.withArgName("mismatch").withDescription("Mismatch score").hasArg() .create("mi")) .addOption(OptionBuilder.withDescription("Do not append unaligned flanking sequences") .create("noflank")) .addOption(OptionBuilder.withArgName("check").withDescription("Calculate checkscore").create('c')) .addOption(OptionBuilder.withArgName("format").withDescription( "Output format, see String.format, parameters are: id1,id2,score,alignment (alignment only, if -f is specified); (default: '%s %s %.4f' w/o -f and '%s %s %.4f\n%s' w/ -f)") .hasArg().create("format")) .addOption(OptionBuilder.withArgName("matrix") .withDescription("Output dynamic programming matrix as well").create("matrix")) .addOption(OptionBuilder.withArgName("quasar-format") .withDescription("Scoring matrix in quasar format").hasArg().create('q')) .addOption( OptionBuilder.withArgName("pairs").withDescription("Pairs file").hasArg().create("pairs")) .addOption(OptionBuilder.withArgName("output").withDescription("Output").hasArg().create('o')) .addOption(OptionBuilder.withArgName("seqlib").withDescription("Seqlib file").hasArg() .create("seqlib")) .addOption(OptionBuilder.withArgName("full").withDescription("Full output").create('f')); CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); LongScoring<CharSequence> scoring = createScoring(cmd); AlignmentMode mode = createMode(cmd); if (mode == null) throw new ParseException("Mode unknown: " + cmd.getOptionValue('m')); Iterator<MutablePair<String, String>> idIterator = createSequences(scoring, cmd); GapCostFunction gap = createGapFunction(cmd); String format = getFormat(cmd); LongAligner<CharSequence> aligner; if (gap instanceof AffineGapCostFunction) aligner = new LongAligner<CharSequence>(scoring, ((AffineGapCostFunction) gap).getGapOpen(), ((AffineGapCostFunction) gap).getGapExtend(), mode); else if (gap instanceof LinearGapCostFunction) aligner = new LongAligner<CharSequence>(scoring, ((LinearGapCostFunction) gap).getGap(), mode); else if (gap instanceof InfiniteGapCostFunction) aligner = new LongAligner<CharSequence>(scoring, mode); else throw new RuntimeException("Gap cost function " + gap.toString() + " currently not supported!"); SimpleAlignmentFormatter formatter = cmd.hasOption('f') ? new SimpleAlignmentFormatter().setAppendUnaligned(!cmd.hasOption("noflank")) : null; CheckScore checkscore = cmd.hasOption('c') ? new CheckScore() : null; Alignment alignment = checkscore != null || formatter != null ? new Alignment() : null; float score; String ali; LineOrientedFile out = new LineOrientedFile( cmd.hasOption('o') ? cmd.getOptionValue('o') : LineOrientedFile.STDOUT); Writer wr = out.startWriting(); while (idIterator.hasNext()) { MutablePair<String, String> ids = idIterator.next(); score = alignment == null ? aligner.alignCache(ids.Item1, ids.Item2) : aligner.alignCache(ids.Item1, ids.Item2, alignment); ali = formatter != null ? formatter.format(alignment, scoring, gap, mode, scoring.getCachedSubject(ids.Item1), scoring.getCachedSubject(ids.Item2)) : ""; out.writeLine(String.format(Locale.US, format, ids.Item1, ids.Item2, score, ali)); if (cmd.hasOption("matrix")) { aligner.writeMatrix(wr, aligner.getScoring().getCachedSubject(ids.Item1).toString().toCharArray(), aligner.getScoring().getCachedSubject(ids.Item2).toString().toCharArray()); } if (checkscore != null) checkscore.checkScore(aligner, scoring.getCachedSubject(ids.Item1).length(), scoring.getCachedSubject(ids.Item2).length(), alignment, score); } out.finishWriting(); } catch (ParseException e) { e.printStackTrace(); HelpFormatter f = new HelpFormatter(); f.printHelp("Align", options); } }
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);//from w ww. j av a 2s.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:com.evolveum.midpoint.tools.ninja.Main.java
public static void main(String[] args) { Options options = new Options(); options.addOption(help);/*w w w .j a v a 2 s.c o m*/ options.addOption(validate); options.addOption(create); options.addOption(importOp); options.addOption(schemaOp); options.addOption(exportOp); options.addOption(driver); options.addOption(url); options.addOption(username); options.addOption(password); options.addOption(Password); options.addOption(keyStore); options.addOption(trans); options.addOption(outputFormat); options.addOption(outputDirectory); options.addOption(input); try { CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); if (line.getOptions().length == 0 || line.hasOption(help.getOpt())) { printHelp(options); return; } //repository validation, if proper option is present boolean valid = validate(line, options); //import DDL, if proper option is present if (line.hasOption(create.getOpt())) { ImportDDL ddl = new ImportDDL(createDDLConfig(line)); if (!ddl.execute()) { System.out.println("DLL import was unsuccessful, skipping other steps."); return; } //repository validation after DDL import, if proper option is present valid = validate(line, options); } //import objects, only if repository validation didn't fail (in case it was tested) if (valid && line.hasOption(importOp.getOpt())) { String path = line.getOptionValue(importOp.getOpt()); boolean validateSchema = line.hasOption(schemaOp.getOpt()); ImportObjects objects = new ImportObjects(path, validateSchema); objects.execute(); } if (valid && line.hasOption(exportOp.getOpt())) { String path = line.getOptionValue(exportOp.getOpt()); ExportObjects objects = new ExportObjects(path); objects.execute(); } if (line.hasOption(keyStore.getOpt())) { KeyStoreDumper keyStoreDumper = new KeyStoreDumper(); keyStoreDumper.execute(); } if (line.hasOption(trans.getOpt())) { if (!checkCommand(line)) { return; } FileTransformer transformer = new FileTransformer(); configureTransformer(transformer, line); transformer.execute(); } } catch (ParseException ex) { System.out.println("Error: " + ex.getMessage()); printHelp(options); } catch (Exception ex) { System.out.println("Exception occurred, reason: " + ex.getMessage()); ex.printStackTrace(); } }
From source file:com.continuuity.loom.common.queue.internal.ElementsTrackingQueueCliTool.java
public static void main(String[] args) throws Exception { ElementsTrackingQueueCliTool client = null; try {//from w ww. java2s . com client = new ElementsTrackingQueueCliTool(); client.configure(args); } catch (ParseException e) { printHelp(); return; } catch (Throwable e) { printHelp(); // to divide usage from stacktrace output. It's lame, yes. Thread.sleep(10); System.out.println("ERROR"); e.printStackTrace(); return; } client.execute(); }
From source file:com.genentech.application.property.TPSA.java
public static void main(String args[]) { try {//ww w . j a v a 2s.c o m boolean countP = false; boolean countS = false; String[] molFiles; // create Options object Options options = new Options(); // add options options.addOption("P", false, "Count phosphorus atoms"); options.addOption("S", false, "Count sulfur atoms"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("P")) countP = true; if (cmd.hasOption("S")) countS = true; //get rest of arguments as an array of string molFiles = cmd.getArgs(); if (molFiles.length < 1) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("TPSA [options] <mol files> ... ", options); System.exit(1); } TPSA myTPSA = new TPSA(); myTPSA.runTest(countP, countS); OEGraphMol mol = new OEGraphMol(); oemolistream ifs = new oemolistream(); ; for (int i = 0; i < molFiles.length; i++) { ifs = new oemolistream(molFiles[i]); while (oechem.OEReadMolecule(ifs, mol)) { double tpsa = myTPSA.calculateTPSA(mol, countP, countS); if (tpsa < 0) { System.out.printf("%s 0\n", mol.GetTitle()); } else { System.out.printf("%s %d\n", mol.GetTitle(), (int) tpsa); } } } ifs.close(); } catch (ParseException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }