List of usage examples for org.apache.commons.cli PosixParser PosixParser
PosixParser
From source file:com.genentech.chemistry.openEye.apps.SDFALogP.java
/** * @param args/*from w ww. java 2 s .c om*/ */ public static void main(String... args) throws IOException { // create command line Options object Options options = new Options(); Option opt = new Option(OPT_INFILE, true, "input file oe-supported Use .sdf|.smi to specify the file type."); opt.setRequired(true); options.addOption(opt); opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type."); opt.setRequired(true); options.addOption(opt); opt = new Option(OPT_SMARTS_FILE, true, "Optional: to overwrite atom type definition file."); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_PRINT_COUNTS, false, "If set the count of each atom type is added to the output file."); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_VALIDATE_ASSIGNMENT, false, "Print warning if no atomtype matches an atom in a candidte molecule."); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_SUPRESS_ZERO, false, "If given atom type counts with count=0 will not be added."); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_NEUTRALIZE, true, "y|n to neutralize molecule if possible (default=y)"); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(options); } args = cmd.getArgs(); if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } String inFile = cmd.getOptionValue(OPT_INFILE); String outFile = cmd.getOptionValue(OPT_OUTFILE); String smartsFile = cmd.getOptionValue(OPT_SMARTS_FILE); boolean outputCount = cmd.hasOption(OPT_PRINT_COUNTS); boolean outputZero = !cmd.hasOption(OPT_SUPRESS_ZERO); boolean neutralize = !"n".equalsIgnoreCase(cmd.getOptionValue(OPT_NEUTRALIZE)); boolean ValidateAssignment = cmd.hasOption(OPT_VALIDATE_ASSIGNMENT); SDFALogP sdfALogP = new SDFALogP(smartsFile, outFile, outputZero, neutralize, ValidateAssignment); sdfALogP.run(inFile, outputCount); sdfALogP.close(); }
From source file:com.cws.esolutions.security.main.UserManagementUtility.java
public static final void main(final String[] args) { final String methodName = UserManagementUtility.CNAME + "#main(final String[] args)"; if (DEBUG) {//from w w w .j a v a2 s. com DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", (Object) args); } if (args.length == 0) { HelpFormatter usage = new HelpFormatter(); usage.printHelp(UserManagementUtility.CNAME, options, true); return; } try { CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse(options, args); if (DEBUG) { DEBUGGER.debug("CommandLineParser parser: {}", parser); DEBUGGER.debug("CommandLine commandLine: {}", commandLine); DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions()); DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList()); } if ((commandLine.hasOption("configFile")) && (!(StringUtils.isBlank(commandLine.getOptionValue("configFile"))))) { SecurityServiceInitializer.initializeService(commandLine.getOptionValue("configFile"), UserManagementUtility.LOG_CONFIG, true); } else { SecurityServiceInitializer.initializeService(UserManagementUtility.SEC_CONFIG, UserManagementUtility.LOG_CONFIG, true); } AccountControlResponse response = null; final UserAccount userAccount = new UserAccount(); final RequestHostInfo reqInfo = new RequestHostInfo(); final SecurityConfigurationData secConfigData = UserManagementUtility.svcBean.getConfigData(); final SecurityConfig secConfig = secConfigData.getSecurityConfig(); try { reqInfo.setHostAddress(InetAddress.getLocalHost().getHostAddress()); reqInfo.setHostName(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException uhx) { reqInfo.setHostAddress("127.0.0.1"); reqInfo.setHostName("localhost"); } if (DEBUG) { DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData); DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig); DEBUGGER.debug("RequestHostInfo reqInfo: {}", reqInfo); } AccountControlRequest request = new AccountControlRequest(); request.setApplicationId(secConfig.getApplicationId()); request.setApplicationName(secConfig.getApplicationName()); request.setHostInfo(reqInfo); request.setRequestor(secConfig.getSvcAccount()); if (DEBUG) { DEBUGGER.debug("AccountControlRequest request: {}", request); } if (commandLine.hasOption("search")) { if (StringUtils.isEmpty(commandLine.getOptionValue("search"))) { throw new ParseException("No entry option was provided. Cannot continue."); } userAccount.setEmailAddr(commandLine.getOptionValue("search")); if (DEBUG) { DEBUGGER.debug("UserAccount userAccount: {}", userAccount); } request.setUserAccount(userAccount); if (DEBUG) { DEBUGGER.debug("AccountControlRequest: {}", request); } response = processor.searchAccounts(request); } else if (commandLine.hasOption("load")) { if (StringUtils.isEmpty(commandLine.getOptionValue("load"))) { throw new ParseException("No entry option was provided. Cannot continue."); } userAccount.setGuid(commandLine.getOptionValue("load")); request.setUserAccount(userAccount); if (DEBUG) { DEBUGGER.debug("AccountControlRequest: {}", request); } response = processor.loadUserAccount(request); } if (DEBUG) { DEBUGGER.debug("AccountControlResponse response: {}", response); } if ((response != null) && (response.getRequestStatus() == SecurityRequestStatus.SUCCESS)) { UserAccount account = response.getUserAccount(); if (DEBUG) { DEBUGGER.debug("UserAccount: {}", account); } System.out.println(account); } } catch (ParseException px) { ERROR_RECORDER.error(px.getMessage(), px); System.err.println("An error occurred during processing: " + px.getMessage()); } catch (SecurityException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); System.err.println("An error occurred during processing: " + sx.getMessage()); } catch (SecurityServiceException ssx) { ERROR_RECORDER.error(ssx.getMessage(), ssx); System.err.println("An error occurred during processing: " + ssx.getMessage()); } }
From source file:asl.seedscan.DQAWeb.java
public static void main(String args[]) { db = new MetricDatabase("", "", ""); findConsoleHandler();//from ww w .ja va 2 s .co m consoleHandler.setLevel(Level.ALL); Logger.getLogger("").setLevel(Level.CONFIG); // Default locations of config and schema files File configFile = new File("dqaweb-config.xml"); File schemaFile = new File("schemas/DQAWebConfig.xsd"); boolean parseConfig = true; boolean testMode = false; ArrayList<File> schemaFiles = new ArrayList<File>(); schemaFiles.add(schemaFile); // ==== Command Line Parsing ==== Options options = new Options(); Option opConfigFile = new Option("c", "config-file", true, "The config file to use for seedscan. XML format according to SeedScanConfig.xsd."); Option opSchemaFile = new Option("s", "schema-file", true, "The schame file which should be used to verify the config file format. "); Option opTest = new Option("t", "test", false, "Run in test console mode rather than as a servlet."); OptionGroup ogConfig = new OptionGroup(); ogConfig.addOption(opConfigFile); OptionGroup ogSchema = new OptionGroup(); ogConfig.addOption(opSchemaFile); OptionGroup ogTest = new OptionGroup(); ogTest.addOption(opTest); options.addOptionGroup(ogConfig); options.addOptionGroup(ogSchema); options.addOptionGroup(ogTest); PosixParser optParser = new PosixParser(); CommandLine cmdLine = null; try { cmdLine = optParser.parse(options, args, true); } catch (org.apache.commons.cli.ParseException e) { logger.severe("Error while parsing command-line arguments."); System.exit(1); } Option opt; Iterator iter = cmdLine.iterator(); while (iter.hasNext()) { opt = (Option) iter.next(); if (opt.getOpt().equals("c")) { configFile = new File(opt.getValue()); } else if (opt.getOpt().equals("s")) { schemaFile = new File(opt.getValue()); } else if (opt.getOpt().equals("t")) { testMode = true; } } String query = ""; System.out.println("Entering Test Mode"); System.out.println("Enter a query string to view results or type \"help\" for example query strings"); InputStreamReader input = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(input); String result = ""; while (testMode == true) { try { System.out.printf("Query: "); query = reader.readLine(); if (query.equals("exit")) { testMode = false; } else if (query.equals("help")) { System.out.println("Need to add some help for people"); //TODO } else { result = processCommand(query); } System.out.println(result); } catch (IOException err) { System.err.println("Error reading line, in DQAWeb.java"); } } System.err.printf("DONE.\n"); }
From source file:ca.uhn.hunit.run.TestRunner.java
/** * @param args/*from w w w . ja va 2 s. co m*/ * @throws URISyntaxException * @throws JAXBException * @throws ConfigurationException * @throws InterfaceWontStartException * @throws FileNotFoundException * @throws ParseException */ public static void main(String[] theArgs) throws URISyntaxException, JAXBException, InterfaceWontStartException, ConfigurationException, FileNotFoundException, ParseException { Options options = new Options(); OptionGroup fileOptionGroup = new OptionGroup(); fileOptionGroup.setRequired(false); Option option = new Option("f", "file", true, "The path to the file to load the test battery from"); option.setValueSeparator('='); fileOptionGroup.addOption(option); option = new Option("c", "classpath", true, "The classpath path to the file to load the test battery from"); option.setValueSeparator('='); fileOptionGroup.addOption(option); options.addOptionGroup(fileOptionGroup); OptionGroup uiOptionGroup = new OptionGroup(); option = new Option("g", "gui", false, "Start hUnit in GUI mode (default)"); uiOptionGroup.addOption(option); option = new Option("x", "text", false, "Start hUnit in Text mode"); uiOptionGroup.addOption(option); options.addOptionGroup(uiOptionGroup); option = new Option("t", "tests", true, "A comma separated list of tests to execute (default is all)"); option.setValueSeparator('='); option.setRequired(false); options.addOption(option); Resource defFile = null; CommandLine parser; boolean textMode = false; try { parser = new PosixParser().parse(options, theArgs); if (parser.hasOption("f")) { defFile = new FileSystemResource(parser.getOptionValue("f")); } else if (parser.hasOption("c")) { defFile = new ClassPathResource(parser.getOptionValue("c")); } if (parser.hasOption("x")) { textMode = true; } } catch (Exception e) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("java -jar hunit-[version]-jar-with-dependencies.jar [-c FILE|-f FILE] [options]", options); return; } String[] testsToExecute = null; if (parser.hasOption("t")) { testsToExecute = parser.getOptionValue("t").split(","); } if (textMode) { executeInTextMode(defFile, testsToExecute); } else { executeInGuiMode(defFile, testsToExecute); } }
From source file:eqtlmappingpipeline.util.ModuleEqtlGeuvadisReplication.java
/** * @param args the command line arguments *//*from w ww. j a v a 2s. c o m*/ public static void main(String[] args) throws IOException, LdCalculatorException { System.out.println(HEADER); System.out.println(); System.out.flush(); //flush to make sure header is before errors try { Thread.sleep(25); //Allows flush to complete } catch (InterruptedException ex) { } CommandLineParser parser = new PosixParser(); final CommandLine commandLine; try { commandLine = parser.parse(OPTIONS, args, true); } catch (ParseException ex) { System.err.println("Invalid command line arguments: " + ex.getMessage()); System.err.println(); new HelpFormatter().printHelp(" ", OPTIONS); System.exit(1); return; } final String[] genotypesBasePaths = commandLine.getOptionValues("g"); final RandomAccessGenotypeDataReaderFormats genotypeDataType; final String replicationQtlFilePath = commandLine.getOptionValue("e"); final String interactionQtlFilePath = commandLine.getOptionValue("i"); final String outputFilePath = commandLine.getOptionValue("o"); final double ldCutoff = Double.parseDouble(commandLine.getOptionValue("ld")); final int window = Integer.parseInt(commandLine.getOptionValue("w")); System.out.println("Genotype: " + Arrays.toString(genotypesBasePaths)); System.out.println("Interaction file: " + interactionQtlFilePath); System.out.println("Replication file: " + replicationQtlFilePath); System.out.println("Output: " + outputFilePath); System.out.println("LD: " + ldCutoff); System.out.println("Window: " + window); try { if (commandLine.hasOption("G")) { genotypeDataType = RandomAccessGenotypeDataReaderFormats .valueOf(commandLine.getOptionValue("G").toUpperCase()); } else { if (genotypesBasePaths[0].endsWith(".vcf")) { System.err.println( "Only vcf.gz is supported. Please see manual on how to do create a vcf.gz file."); System.exit(1); return; } try { genotypeDataType = RandomAccessGenotypeDataReaderFormats .matchFormatToPath(genotypesBasePaths[0]); } catch (GenotypeDataException e) { System.err .println("Unable to determine input 1 type based on specified path. Please specify -G"); System.exit(1); return; } } } catch (IllegalArgumentException e) { System.err.println("Error parsing --genotypesFormat \"" + commandLine.getOptionValue("G") + "\" is not a valid input data format"); System.exit(1); return; } final RandomAccessGenotypeData genotypeData; try { genotypeData = genotypeDataType.createFilteredGenotypeData(genotypesBasePaths, 100, null, null, null, 0.8); } catch (TabixFileNotFoundException e) { LOGGER.fatal("Tabix file not found for input data at: " + e.getPath() + "\n" + "Please see README on how to create a tabix file"); System.exit(1); return; } catch (IOException e) { LOGGER.fatal("Error reading input data: " + e.getMessage(), e); System.exit(1); return; } catch (IncompatibleMultiPartGenotypeDataException e) { LOGGER.fatal("Error combining the impute genotype data files: " + e.getMessage(), e); System.exit(1); return; } catch (GenotypeDataException e) { LOGGER.fatal("Error reading input data: " + e.getMessage(), e); System.exit(1); return; } ChrPosTreeMap<ArrayList<EQTL>> replicationQtls = new QTLTextFile(replicationQtlFilePath, false) .readQtlsAsTreeMap(); int interactionSnpNotInGenotypeData = 0; int noReplicationQtlsInWindow = 0; int noReplicationQtlsInLd = 0; int multipleReplicationQtlsInLd = 0; int replicationTopSnpNotInGenotypeData = 0; final CSVWriter outputWriter = new CSVWriter(new FileWriter(new File(outputFilePath)), '\t', '\0'); final String[] outputLine = new String[14]; int c = 0; outputLine[c++] = "Chr"; outputLine[c++] = "Pos"; outputLine[c++] = "SNP"; outputLine[c++] = "Gene"; outputLine[c++] = "Module"; outputLine[c++] = "DiscoveryZ"; outputLine[c++] = "ReplicationZ"; outputLine[c++] = "DiscoveryZCorrected"; outputLine[c++] = "ReplicationZCorrected"; outputLine[c++] = "DiscoveryAlleleAssessed"; outputLine[c++] = "ReplicationAlleleAssessed"; outputLine[c++] = "bestLd"; outputLine[c++] = "bestLd_dist"; outputLine[c++] = "nextLd"; outputWriter.writeNext(outputLine); HashSet<String> notFound = new HashSet<>(); CSVReader interactionQtlReader = new CSVReader(new FileReader(interactionQtlFilePath), '\t'); interactionQtlReader.readNext();//skip header String[] interactionQtlLine; while ((interactionQtlLine = interactionQtlReader.readNext()) != null) { String snp = interactionQtlLine[1]; String chr = interactionQtlLine[2]; int pos = Integer.parseInt(interactionQtlLine[3]); String gene = interactionQtlLine[4]; String alleleAssessed = interactionQtlLine[9]; String module = interactionQtlLine[12]; double discoveryZ = Double.parseDouble(interactionQtlLine[10]); GeneticVariant interactionQtlVariant = genotypeData.getSnpVariantByPos(chr, pos); if (interactionQtlVariant == null) { System.err.println("Interaction QTL SNP not found in genotype data: " + chr + ":" + pos); ++interactionSnpNotInGenotypeData; continue; } EQTL bestMatch = null; double bestMatchR2 = Double.NaN; Ld bestMatchLd = null; double nextBestR2 = Double.NaN; ArrayList<EQTL> sameSnpQtls = replicationQtls.get(chr, pos); if (sameSnpQtls != null) { for (EQTL sameSnpQtl : sameSnpQtls) { if (sameSnpQtl.getProbe().equals(gene)) { bestMatch = sameSnpQtl; bestMatchR2 = 1; } } } NavigableMap<Integer, ArrayList<EQTL>> potentionalReplicationQtls = replicationQtls.getChrRange(chr, pos - window, true, pos + window, true); for (ArrayList<EQTL> potentialReplicationQtls : potentionalReplicationQtls.values()) { for (EQTL potentialReplicationQtl : potentialReplicationQtls) { if (!potentialReplicationQtl.getProbe().equals(gene)) { continue; } GeneticVariant potentialReplicationQtlVariant = genotypeData.getSnpVariantByPos( potentialReplicationQtl.getRsChr().toString(), potentialReplicationQtl.getRsChrPos()); if (potentialReplicationQtlVariant == null) { notFound.add(potentialReplicationQtl.getRsChr().toString() + ":" + potentialReplicationQtl.getRsChrPos()); ++replicationTopSnpNotInGenotypeData; continue; } Ld ld = interactionQtlVariant.calculateLd(potentialReplicationQtlVariant); double r2 = ld.getR2(); if (r2 > 1) { r2 = 1; } if (bestMatch == null) { bestMatch = potentialReplicationQtl; bestMatchR2 = r2; bestMatchLd = ld; } else if (r2 > bestMatchR2) { bestMatch = potentialReplicationQtl; nextBestR2 = bestMatchR2; bestMatchR2 = r2; bestMatchLd = ld; } } } double replicationZ = Double.NaN; double replicationZCorrected = Double.NaN; double discoveryZCorrected = Double.NaN; String replicationAlleleAssessed = null; if (bestMatch != null) { replicationZ = bestMatch.getZscore(); replicationAlleleAssessed = bestMatch.getAlleleAssessed(); if (pos != bestMatch.getRsChrPos()) { String commonHap = null; double commonHapFreq = -1; for (Map.Entry<String, Double> hapFreq : bestMatchLd.getHaplotypesFreq().entrySet()) { double f = hapFreq.getValue(); if (f > commonHapFreq) { commonHapFreq = f; commonHap = hapFreq.getKey(); } } String[] commonHapAlleles = StringUtils.split(commonHap, '/'); discoveryZCorrected = commonHapAlleles[0].equals(alleleAssessed) ? discoveryZ : discoveryZ * -1; replicationZCorrected = commonHapAlleles[1].equals(replicationAlleleAssessed) ? replicationZ : replicationZ * -1; } else { discoveryZCorrected = discoveryZ; replicationZCorrected = alleleAssessed.equals(replicationAlleleAssessed) ? replicationZ : replicationZ * -1; } } c = 0; outputLine[c++] = chr; outputLine[c++] = String.valueOf(pos); outputLine[c++] = snp; outputLine[c++] = gene; outputLine[c++] = module; outputLine[c++] = String.valueOf(discoveryZ); outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(replicationZ); outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(discoveryZCorrected); outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(replicationZCorrected); outputLine[c++] = alleleAssessed; outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(bestMatch.getAlleleAssessed()); outputLine[c++] = String.valueOf(bestMatchR2); outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(Math.abs(pos - bestMatch.getRsChrPos())); outputLine[c++] = String.valueOf(nextBestR2); outputWriter.writeNext(outputLine); } outputWriter.close(); for (String e : notFound) { System.err.println("Not found: " + e); } System.out.println("interactionSnpNotInGenotypeData: " + interactionSnpNotInGenotypeData); System.out.println("noReplicationQtlsInWindow: " + noReplicationQtlsInWindow); System.out.println("noReplicationQtlsInLd: " + noReplicationQtlsInLd); System.out.println("multipleReplicationQtlsInLd: " + multipleReplicationQtlsInLd); System.out.println("replicationTopSnpNotInGenotypeData: " + replicationTopSnpNotInGenotypeData); }
From source file:com.cloudera.recordbreaker.learnstructure.test.GenerateRandomData.java
/** *//*from w ww . j a va 2 s. com*/ public static void main(String argv[]) throws IOException { CommandLine cmd = null; Options options = new Options(); options.addOption("?", false, "Help for command-line"); options.addOption("n", true, "Number elts to emit"); try { CommandLineParser parser = new PosixParser(); cmd = parser.parse(options, argv); } catch (ParseException pe) { HelpFormatter fmt = new HelpFormatter(); fmt.printHelp("GenerateRandomData", options, true); System.exit(-1); } if (cmd.hasOption("?")) { HelpFormatter fmt = new HelpFormatter(); fmt.printHelp("GenerateRandomData", options, true); System.exit(0); } int numToEmit = 100; if (cmd.hasOption("n")) { try { numToEmit = Integer.parseInt(cmd.getOptionValue("n")); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } } String[] argArray = cmd.getArgs(); if (argArray.length == 0) { HelpFormatter fmt = new HelpFormatter(); fmt.printHelp("GenerateRandomData", options, true); System.exit(0); } File inputSchemaFile = new File(argArray[0]).getCanonicalFile(); File outputDataFile = new File(argArray[1]).getCanonicalFile(); if (outputDataFile.exists()) { System.err.println("Output file already exists: " + outputDataFile.getCanonicalPath()); System.exit(0); } GenerateRandomData grd = new GenerateRandomData(); Schema schema = Schema.parse(inputSchemaFile); GenericDatumWriter datum = new GenericDatumWriter(schema); DataFileWriter out = new DataFileWriter(datum); out.create(schema, outputDataFile); try { for (int i = 0; i < numToEmit; i++) { out.append((GenericData.Record) grd.generateData(schema)); } } finally { out.close(); } }
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(/*from w w w. j a va 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:edu.ksu.cis.indus.staticanalyses.callgraphs.CallGraphXMLizerCLI.java
/** * The entry point to the program via command line. * /* w ww. ja v a 2 s . c o m*/ * @param args is the command line arguments. * @throws RuntimeException when the analyses fail. */ public static void main(final String[] args) { final Options _options = new Options(); Option _option = new Option("c", "cumulative", false, "Builds one call graph that includes all root methods."); _options.addOption(_option); _option = new Option("o", "output", true, "Directory into which xml files will be written into. Defaults to current directory if omitted"); _option.setArgs(1); _option.setArgName("output-dir"); _options.addOption(_option); _option = new Option("j", "jimple", false, "Dump xmlized jimple."); _option.setArgName("dump-jimple"); _options.addOption(_option); _option = new Option("p", "soot-classpath", true, "Prepend this to soot class path."); _option.setArgs(1); _option.setArgName("classpath"); _option.setOptionalArg(false); _options.addOption(_option); _option = new Option("h", "help", false, "Display message."); _option.setOptionalArg(false); _options.addOption(_option); _option = new Option("t", "call-graph-type", true, "Call graph type. This has to be one of {cha, rta, ofa-oi, " + "ofa-oirt, ofa-os}."); _option.setArgs(1); _option.setArgName("type"); _option.setRequired(true); _options.addOption(_option); _option = new Option("S", "scope", true, "The scope that should be analyzed."); _option.setArgs(1); _option.setArgName("scope"); _option.setRequired(false); _options.addOption(_option); final PosixParser _parser = new PosixParser(); try { final CommandLine _cl = _parser.parse(_options, args); if (_cl.hasOption('h')) { printUsage(_options); System.exit(1); } String _outputDir = _cl.getOptionValue('o'); if (_outputDir == null) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Defaulting to current directory for output."); } _outputDir = "."; } if (_cl.getArgList().isEmpty()) { throw new MissingArgumentException("Please specify atleast one class."); } final CallGraphXMLizerCLI _cli = new CallGraphXMLizerCLI(); _cli.xmlizer.setXmlOutputDir(_outputDir); _cli.xmlizer.setGenerator(new UniqueJimpleIDGenerator()); _cli.setCumulative(_cl.hasOption('c')); _cli.setClassNames(_cl.getArgList()); _cli.addToSootClassPath(_cl.getOptionValue('p')); if (_cl.hasOption('S')) { _cli.setScopeSpecFile(_cl.getOptionValue('S')); } _cli.initialize(); _cli.execute(_cl.hasOption('j'), _cl.getOptionValue('t')); } catch (final ParseException _e) { LOGGER.error("Error while parsing command line.", _e); System.out.println("Error while parsing command line." + _e); printUsage(_options); } catch (final Throwable _e) { LOGGER.error("Beyond our control. May day! May day!", _e); throw new RuntimeException(_e); } }
From source file:com.netscape.cmstools.OCSPClient.java
public static void main(String args[]) throws Exception { Options options = createOptions();/* www .j a va 2 s . c o m*/ CommandLine cmd = null; try { CommandLineParser parser = new PosixParser(); cmd = parser.parse(options, args); } catch (Exception e) { printError(e); System.exit(1); } if (cmd.hasOption("help")) { printHelp(); System.exit(0); } boolean verbose = cmd.hasOption("v"); String databaseDir = cmd.getOptionValue("d", "."); String hostname = cmd.getOptionValue("h", InetAddress.getLocalHost().getCanonicalHostName()); int port = Integer.parseInt(cmd.getOptionValue("p", "8080")); String path = cmd.getOptionValue("t", "/ocsp/ee/ocsp"); String caNickname = cmd.getOptionValue("c", "CA Signing Certificate"); int times = Integer.parseInt(cmd.getOptionValue("n", "1")); String input = cmd.getOptionValue("input"); String serial = cmd.getOptionValue("serial"); String output = cmd.getOptionValue("output"); if (times < 1) { printError("Invalid number of submissions"); System.exit(1); } try { if (verbose) System.out.println("Initializing security database"); CryptoManager.initialize(databaseDir); String url = "http://" + hostname + ":" + port + path; OCSPProcessor processor = new OCSPProcessor(); processor.setVerbose(verbose); OCSPRequest request; if (serial != null) { if (verbose) System.out.println("Creating request for serial number " + serial); BigInteger serialNumber = new BigInteger(serial); request = processor.createRequest(caNickname, serialNumber); } else if (input != null) { if (verbose) System.out.println("Loading request from " + input); try (FileInputStream in = new FileInputStream(input)) { byte[] data = new byte[in.available()]; in.read(data); request = processor.createRequest(data); } } else { throw new Exception("Missing serial number or input file."); } OCSPResponse response = null; for (int i = 0; i < times; i++) { if (verbose) System.out.println("Submitting OCSP request"); response = processor.submitRequest(url, request); ResponseBytes bytes = response.getResponseBytes(); BasicOCSPResponse basic = (BasicOCSPResponse) BasicOCSPResponse.getTemplate() .decode(new ByteArrayInputStream(bytes.getResponse().toByteArray())); ResponseData rd = basic.getResponseData(); for (int j = 0; j < rd.getResponseCount(); j++) { SingleResponse sr = rd.getResponseAt(j); if (sr == null) { throw new Exception("No OCSP Response data."); } System.out.println("CertID.serialNumber=" + sr.getCertID().getSerialNumber()); CertStatus status = sr.getCertStatus(); if (status instanceof GoodInfo) { System.out.println("CertStatus=Good"); } else if (status instanceof UnknownInfo) { System.out.println("CertStatus=Unknown"); } else if (status instanceof RevokedInfo) { System.out.println("CertStatus=Revoked"); } } } if (output != null) { if (verbose) System.out.println("Storing response into " + output); try (FileOutputStream out = new FileOutputStream(output)) { ByteArrayOutputStream os = new ByteArrayOutputStream(); response.encode(os); out.write(os.toByteArray()); } System.out.println("Success: Output " + output); } } catch (Exception e) { if (verbose) e.printStackTrace(); printError(e); System.exit(1); } }
From source file:com.zimbra.doc.soap.changelog.SoapApiChangeLog.java
/** * Main/*w ww. j av a 2 s . c o m*/ */ public static void main(String[] args) throws Exception { CommandLineParser parser = new PosixParser(); Options options = new Options(); Option opt; opt = new Option("d", ARG_OUTPUT_DIR, true, "Output directory for changelog information"); opt.setRequired(true); options.addOption(opt); opt = new Option("t", ARG_TEMPLATES_DIR, true, "Directory containing Freemarker templates"); opt.setRequired(true); options.addOption(opt); opt = new Option("b", ARG_APIDESC_BASELINE_JSON, true, "JSON file - description of baseline SOAP API"); opt.setRequired(true); options.addOption(opt); opt = new Option("c", ARG_APIDESC_CURRENT_JSON, true, "JSON file - description of current SOAP API"); opt.setRequired(true); options.addOption(opt); CommandLine cl = null; try { cl = parser.parse(options, args, true); } catch (ParseException pe) { System.err.println("error: " + pe.getMessage()); System.exit(2); } String baselineApiDescriptionJson = cl.getOptionValue('b'); String currentApiDescriptionJson = cl.getOptionValue('c'); SoapApiChangeLog clog = new SoapApiChangeLog(cl.getOptionValue('d'), cl.getOptionValue('t')); clog.setBaselineDesc(SoapApiDescription.deserializeFromJson(new File(baselineApiDescriptionJson))); clog.setCurrentDesc(SoapApiDescription.deserializeFromJson(new File(currentApiDescriptionJson))); clog.makeChangeLogDataModel(); clog.writeChangelog(); }