List of usage examples for org.apache.commons.cli HelpFormatter HelpFormatter
HelpFormatter
From source file:com.linkedin.restli.tools.idlgen.RestLiResourceModelExporterCmdLineApp.java
/** * @param args restliexporter -sourcepath sourcepath -resourcepackages packagenames [-name api_name] [-outdir outdir] *//*from w w w . java2s. com*/ public static void main(String[] args) { // args = new String[] {"-name", "groups", // "-resourcepackages", "com.linkedin.groups.server.rest1.impl com.linkedin.groups.server.rest2.impl ", // "-resourceclasses", "com.linkedin.groups.server.restX.impl.FooResource", // "-sourcepath", "src/main/java", // "-outdir", "src/codegen/idl", // "-split"}; CommandLine cl = null; try { final CommandLineParser parser = new GnuParser(); cl = parser.parse(OPTIONS, args); } catch (ParseException e) { System.err.println("Invalid arguments: " + e.getMessage()); final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "restliexporter -sourcepath sourcepath [-resourcepackages packagenames] [-resourceclasses classnames]" + "[-name api_name] [-outdir outdir]", OPTIONS); System.exit(0); } try { new RestLiResourceModelExporter().export(cl.getOptionValue("name"), null, cl.getOptionValues("sourcepath"), cl.getOptionValues("resourcepackages"), cl.getOptionValues("resourceclasses"), cl.getOptionValue("outdir", "."), AdditionalDocProvidersUtil.findDocProviders(log, cl.hasOption("loadAdditionalDocProviders"))); } catch (Throwable e) { log.error("Error writing IDL files", e); System.exit(1); } }
From source file:de.huberlin.cuneiform.main.Main.java
public static void main(String[] args) throws ParseException, IOException, NotDerivableException, InterruptedException, JSONException { GnuParser gnuParser;/*from w w w. j a v a 2 s.c o m*/ CommandLine cmdline; Options opt; String value; int platform; File outputDir; String[] fileList; StringBuffer buf; String line; String dagid; File logFile; opt = new Options(); opt.addOption("p", "platform", true, "The platform to perform the Cuneiform script's interpretation. " + "Possible platforms are: 'dot', 'local', and 'debug'. Default is 'local'."); opt.addOption("d", "directory", true, "The output directory, to put the interpretation intermediate and output result as well as the default location to store the log."); opt.addOption("c", "clean", false, "If set, the execution engine ignores all cached results and starts a clean workflow run."); opt.addOption("r", "runid", true, "If set, a custom id is set for this workflow run. By default a UUID string is used."); opt.addOption("f", "file", true, "Override the default location of the log file and use the specified filename instead. If the platform is 'dot', this option sets the name of the output dot-file."); opt.addOption("h", "help", false, "Print help text."); gnuParser = new GnuParser(); cmdline = gnuParser.parse(opt, args); if (cmdline.hasOption("help")) { System.out.println("CUNEIFORM - A Functional Workflow Language\n" + LABEL_VERSION); new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt); return; } if (cmdline.hasOption("platform")) { value = cmdline.getOptionValue("platform"); if (value.equals("dot")) platform = PLATFORM_DOT; else if (value.equals("local")) platform = PLATFORM_LOCAL; else if (value.equals("debug")) platform = PLATFORM_DEBUG; else throw new RuntimeException("Specified platform '" + value + "' not recognized."); } else platform = PLATFORM_LOCAL; if (cmdline.hasOption('d')) { value = cmdline.getOptionValue('d'); } else value = "build"; outputDir = new File(value); if (outputDir.exists()) { if (!outputDir.isDirectory()) throw new IOException( "Output directory '" + outputDir.getAbsolutePath() + "' exists but is not a directory."); else if (cmdline.hasOption('c')) { FileUtils.deleteDirectory(outputDir); if (!outputDir.mkdirs()) throw new IOException( "Could not create output directory '" + outputDir.getAbsolutePath() + "'"); } } else if (!outputDir.mkdirs()) throw new IOException("Could not create output directory '" + outputDir.getAbsolutePath() + "'"); if (cmdline.hasOption('r')) dagid = cmdline.getOptionValue('r'); else dagid = UUID.randomUUID().toString(); if (cmdline.hasOption('f')) logFile = new File(cmdline.getOptionValue('f')); else logFile = null; fileList = cmdline.getArgs(); buf = new StringBuffer(); if (fileList.length == 0) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { while ((line = reader.readLine()) != null) buf.append(line).append('\n'); } switch (platform) { case PLATFORM_DOT: createDot(buf.toString(), outputDir, logFile); break; case PLATFORM_LOCAL: runLocal(buf.toString(), outputDir, logFile, dagid); break; case PLATFORM_DEBUG: runDebug(buf.toString(), outputDir, logFile, dagid); break; default: throw new RuntimeException("Platform not recognized."); } } else switch (platform) { case PLATFORM_DOT: createDot(fileList, outputDir, logFile); break; case PLATFORM_LOCAL: runLocal(fileList, outputDir, logFile, dagid); break; case PLATFORM_DEBUG: runDebug(fileList, outputDir, logFile, dagid); break; default: throw new RuntimeException("Platform not recognized."); } }
From source file:com.blackducksoftware.integration.hubdiff.HubDiff.java
public static void main(String[] args) throws IOException, IllegalArgumentException, EncryptionException, HubIntegrationException, JSONException { Options options = new Options(); Option optUrl1 = new Option("h1", "hub-url-1", true, "the base url to the hub. Example: http://int-hub01.dc1.lan:8080"); Option optUsername1 = new Option("u1", "username-1", true, "the username for your hub instance"); Option optPassword1 = new Option("p1", "password-1", true, "the password for your hub instance and username"); Option optUrl2 = new Option("h2", "hub-url-2", true, "the base url to the hub. Example: http://int-auto.dc1.lan:9000"); Option optUsername2 = new Option("u2", "username-2", true, "the username for your hub instance"); Option optPassword2 = new Option("p2", "password-2", true, "the password for your hub instance and username"); Option optOutputFile = new Option("o", "output", true, "the file path to your output file"); optUrl1.setRequired(true);/* w w w . j a v a 2s . c o m*/ optUsername1.setRequired(true); optPassword1.setRequired(true); optUsername2.setRequired(true); optUrl1.setRequired(true); optPassword2.setRequired(true); optOutputFile.setRequired(false); // Add options to collection options.addOption(optUrl1); options.addOption(optUsername1); options.addOption(optPassword1); options.addOption(optUrl2); options.addOption(optUsername2); options.addOption(optPassword2); options.addOption(optOutputFile); // Parse the arguments array for the options CommandLineParser cliParser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine optionParser; try { optionParser = cliParser.parse(options, args); } catch (ParseException e) { formatter.printHelp("hub-model-generator", options); log.error(e.getMessage()); System.exit(1); return; } // Read arguments String url1 = optionParser.getOptionValue("hub-url-1"); String username1 = optionParser.getOptionValue("username-1"); String password1 = optionParser.getOptionValue("password-1"); String url2 = optionParser.getOptionValue("hub-url-2"); String username2 = optionParser.getOptionValue("username-2"); String password2 = optionParser.getOptionValue("password-2"); String outputFilePath = optionParser.getOptionValue("output"); HubServerConfigBuilder configBuilder = new HubServerConfigBuilder(); configBuilder.setHubUrl(url1); configBuilder.setUsername(username1); configBuilder.setPassword(password1); HubServerConfig config1 = configBuilder.build(); HubServerConfigBuilder configBuilder2 = new HubServerConfigBuilder(); configBuilder2.setHubUrl(url2); configBuilder2.setUsername(username2); configBuilder2.setPassword(password2); HubServerConfig config2 = configBuilder2.build(); HubDiff hubDiff = new HubDiff(config1, config2); hubDiff.printDiff(System.out); if (outputFilePath != null) { File outputFile = new File(outputFilePath); hubDiff.writeDiffAsCSV(outputFile); } }
From source file:escada.tpc.common.clients.jmx.ClientEmulationStartup.java
public static void main(String args[]) { // create Options object Options options = new Options(); // add clients option options.addOption("clients", true, "Number of clients concurrently accessing the database."); options.addOption("frag", true, "It shifts the clients in order to access different warehouses."); options.addOption("hostId", true, "Host identifier, allow to have statistics per host."); options.addOption("dbConnectionString", true, "Database JDBC url."); try {//from w w w. j a v a2s . co m CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); ClientEmulationStartup c = new ClientEmulationStartup(); String clients = cmd.getOptionValue("clients"); if (clients != null) { c.getWorkloadResources().setClients(new Integer(clients)); } String frag = cmd.getOptionValue("frag"); if (frag != null) { c.getWorkloadResources().setFrag(new Integer(frag)); } String hostId = cmd.getOptionValue("hostId"); if (hostId != null) { c.getWorkloadResources().setHostId(new Integer(hostId)); } String dbConnectionString = cmd.getOptionValue("dbConnectionString"); if (dbConnectionString != null) { c.getDatabaseResources().setConnectionString(dbConnectionString); } c.start(true); } catch (ParseException e) { System.err.println("Parsing failed. Reason: " + e.getMessage()); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ClientEmulationStartup", options); } catch (NumberFormatException e) { System.err.println("Parsing failed. Reason: " + e.getMessage()); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ClientEmulationStartup", options); } catch (Exception ex) { Thread.dumpStack(); System.exit(-1); } }
From source file:de.prozesskraft.pkraft.Waitinstance.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { /*---------------------------- get options from ini-file/* w ww . j a v a2 s . c om*/ ----------------------------*/ java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Waitinstance.class) + "/" + "../etc/pkraft-waitinstance.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option oinstance = OptionBuilder.withArgName("FILE").hasArg().withDescription( "[mandatory if no -scandir] instance file (process.pmb) that this program will wait till its status is 'error' or 'finished'") // .isRequired() .create("instance"); Option oscandir = OptionBuilder.withArgName("DIR").hasArg().withDescription( "[mandatory if no -instance] directory tree with instances (process.pmb). the first instance found will be tracked.") // .isRequired() .create("scandir"); Option omaxrun = OptionBuilder.withArgName("INTEGER").hasArg().withDescription( "[optional, default: 4320] time period (in minutes, default: 3 days) this program waits till it aborts further waiting.") // .isRequired() .create("maxrun"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(oinstance); options.addOption(oscandir); options.addOption(omaxrun); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); // parse the command line arguments commandline = parser.parse(options, args); /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("waitinstance", options); System.exit(0); } if (commandline.hasOption("v")) { System.out.println("author: alexander.vogel@caegroup.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ Integer maxrun = new Integer(4320); String pathInstance = null; String pathScandir = null; // instance & scandir if (!(commandline.hasOption("instance")) && !(commandline.hasOption("scandir"))) { System.err.println("one of the options -instance/-scandir is mandatory"); exiter(); } else if ((commandline.hasOption("instance")) && (commandline.hasOption("scandir"))) { System.err.println("both options -instance/-scandir are not allowed"); exiter(); } else if (commandline.hasOption("instance")) { pathInstance = commandline.getOptionValue("instance"); } else if (commandline.hasOption("scandir")) { pathScandir = commandline.getOptionValue("scandir"); } // maxrun if (commandline.hasOption("maxrun")) { maxrun = new Integer(commandline.getOptionValue("maxrun")); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ // scannen nach dem ersten process.pmb if ((pathScandir != null) && (pathInstance == null)) { String[] allBinariesOfScanDir = getProcessBinaries(pathScandir); if (allBinariesOfScanDir.length == 0) { System.err.println("no instance (process.pmb) found in directory tree " + pathScandir); exiter(); } else { pathInstance = allBinariesOfScanDir[0]; System.err.println("found instance: " + pathInstance); } } // ueberpruefen ob instance file existiert java.io.File fileInstance = new java.io.File(pathInstance); if (!fileInstance.exists()) { System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath()); exiter(); } if (!fileInstance.isFile()) { System.err.println("instance file is not a file: " + fileInstance.getAbsolutePath()); exiter(); } // zeitpunkt wenn spaetestens beendet werden soll long runTill = System.currentTimeMillis() + (maxrun * 60 * 1000); // logging System.err.println("waiting for instance: " + fileInstance.getAbsolutePath()); System.err.println("checking its status every 5 minutes"); System.err.println("now is: " + new Timestamp(startInMillis).toString()); System.err.println("maxrun till: " + new Timestamp(runTill).toString()); // instanz einlesen Process p1 = new Process(); p1.setInfilebinary(fileInstance.getAbsolutePath()); Process p2 = p1.readBinary(); // schleife, die prozess einliest und ueberprueft ob er noch laeuft while (!(p2.getStatus().equals("error") || p2.getStatus().equals("finished"))) { // logging System.err.println(new Timestamp(System.currentTimeMillis()) + " instance status: " + p2.getStatus()); // 5 minuten schlafen: 300000 millis try { Thread.sleep(300000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // ist die maximale laufzeit von this erreicht, dann soll beendet werden (3 tage) if (System.currentTimeMillis() > runTill) { System.err .println("exiting because of maxrun. now is: " + new Timestamp(System.currentTimeMillis())); System.exit(2); } // den prozess frisch einlesen p2 = p1.readBinary(); } System.err.println("exiting because instance status is: " + p2.getStatus()); System.err.println("now is: " + new Timestamp(System.currentTimeMillis()).toString()); System.exit(0); }
From source file:cc.wikitools.lucene.IndexWikipediaDump.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("bz2 Wikipedia XML dump file") .create(INPUT_OPTION));/*from w ww . java 2 s . c o m*/ options.addOption( OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg() .withDescription("maximum number of documents to index").create(MAX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of indexing threads") .create(THREADS_OPTION)); options.addOption(new Option(OPTIMIZE_OPTION, "merge indexes into a single segment")); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(IndexWikipediaDump.class.getCanonicalName(), options); System.exit(-1); } String indexPath = cmdline.getOptionValue(INDEX_OPTION); int maxdocs = cmdline.hasOption(MAX_OPTION) ? Integer.parseInt(cmdline.getOptionValue(MAX_OPTION)) : Integer.MAX_VALUE; int threads = cmdline.hasOption(THREADS_OPTION) ? Integer.parseInt(cmdline.getOptionValue(THREADS_OPTION)) : DEFAULT_NUM_THREADS; long startTime = System.currentTimeMillis(); String path = cmdline.getOptionValue(INPUT_OPTION); PrintStream out = new PrintStream(System.out, true, "UTF-8"); WikiClean cleaner = new WikiCleanBuilder().withTitle(true).build(); Directory dir = FSDirectory.open(new File(indexPath)); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_43, ANALYZER); config.setOpenMode(OpenMode.CREATE); IndexWriter writer = new IndexWriter(dir, config); LOG.info("Creating index at " + indexPath); LOG.info("Indexing with " + threads + " threads"); try { WikipediaBz2DumpInputStream stream = new WikipediaBz2DumpInputStream(path); ExecutorService executor = Executors.newFixedThreadPool(threads); int cnt = 0; String page; while ((page = stream.readNext()) != null) { String title = cleaner.getTitle(page); // These are heuristic specifically for filtering out non-articles in enwiki-20120104. if (title.startsWith("Wikipedia:") || title.startsWith("Portal:") || title.startsWith("File:")) { continue; } if (page.contains("#REDIRECT") || page.contains("#redirect") || page.contains("#Redirect")) { continue; } Runnable worker = new AddDocumentRunnable(writer, cleaner, page); executor.execute(worker); cnt++; if (cnt % 10000 == 0) { LOG.info(cnt + " articles added"); } if (cnt >= maxdocs) { break; } } executor.shutdown(); // Wait until all threads are finish while (!executor.isTerminated()) { } LOG.info("Total of " + cnt + " articles indexed."); if (cmdline.hasOption(OPTIMIZE_OPTION)) { LOG.info("Merging segments..."); writer.forceMerge(1); LOG.info("Done!"); } LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms"); } catch (Exception e) { e.printStackTrace(); } finally { writer.close(); dir.close(); out.close(); } }
From source file:apps.classification.ClassifySVMPerf.java
public static void main(String[] args) throws IOException { boolean dumpConfidences = false; String cmdLineSyntax = ClassifySVMPerf.class.getName() + " [OPTIONS] <path to svm_perf_classify> <testIndexDirectory> <modelDirectory>"; Options options = new Options(); OptionBuilder.withArgName("d"); OptionBuilder.withDescription("Dump confidences file"); OptionBuilder.withLongOpt("d"); OptionBuilder.isRequired(false);/*from w ww .j av a2s. co m*/ OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("t"); OptionBuilder.withDescription("Path for temporary files"); OptionBuilder.withLongOpt("t"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("v"); OptionBuilder.withDescription("Verbose output"); OptionBuilder.withLongOpt("v"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("s"); OptionBuilder.withDescription("Don't delete temporary training file in svm_perf format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmPerfClassifierCustomizer customizer = null; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); customizer = new SvmPerfClassifierCustomizer(remainingArgs[0]); if (line.hasOption("d")) dumpConfidences = true; if (line.hasOption("v")) customizer.printSvmPerfOutput(true); if (line.hasOption("s")) { customizer.setDeleteTestFiles(false); customizer.setDeletePredictionsFiles(false); } if (line.hasOption("t")) customizer.setTempPath(line.getOptionValue("t")); } catch (Exception exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } if (remainingArgs.length != 3) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String testFile = remainingArgs[1]; File file = new File(testFile); String testName = file.getName(); String testPath = file.getParent(); String classifierFile = remainingArgs[2]; file = new File(classifierFile); String classifierName = file.getName(); String classifierPath = file.getParent(); FileSystemStorageManager storageManager = new FileSystemStorageManager(testPath, false); storageManager.open(); IIndex test = TroveReadWriteHelper.readIndex(storageManager, testName, TroveContentDBType.Full, TroveClassificationDBType.Full); storageManager.close(); SvmPerfDataManager dataManager = new SvmPerfDataManager(customizer); storageManager = new FileSystemStorageManager(classifierPath, false); storageManager.open(); SvmPerfClassifier classifier = (SvmPerfClassifier) dataManager.read(storageManager, classifierName); storageManager.close(); classifier.setRuntimeCustomizer(customizer); // CLASSIFICATION String classificationName = testName + "_" + classifierName; Classifier classifierModule = new Classifier(test, classifier, dumpConfidences); classifierModule.setClassificationMode(ClassificationMode.PER_CATEGORY); classifierModule.exec(); IClassificationDB testClassification = classifierModule.getClassificationDB(); storageManager = new FileSystemStorageManager(testPath, false); storageManager.open(); TroveReadWriteHelper.writeClassification(storageManager, testClassification, classificationName + ".cla", true); storageManager.close(); if (dumpConfidences) { ClassificationScoreDB confidences = classifierModule.getConfidences(); ClassificationScoreDB.write(testPath + Os.pathSeparator() + classificationName + ".confidences", confidences); } }
From source file:ca.cutterslade.match.scheduler.Main.java
public static void main(final String[] args) throws InterruptedException { final CommandLineParser parser = new PosixParser(); try {// w w w. j ava 2 s . c o m final CommandLine line = parser.parse(OPTIONS, args); final int teams = Integer.parseInt(line.getOptionValue('t')); final int tiers = Integer.parseInt(line.getOptionValue('r')); final int gyms = Integer.parseInt(line.getOptionValue('g')); final int courts = Integer.parseInt(line.getOptionValue('c')); final int times = Integer.parseInt(line.getOptionValue('m')); final int days = Integer.parseInt(line.getOptionValue('d')); final int size = Integer.parseInt(line.getOptionValue('z')); final Configuration config; if (line.hasOption("random")) config = Configuration.RANDOM_CONFIGURATION; else config = new Configuration(ImmutableMap.<SadFaceFactor, Integer>of(), line.hasOption("randomMatches"), line.hasOption("randomSlots"), line.hasOption("randomDays")); final Scheduler s = new Scheduler(config, teams, tiers, gyms, courts, times, days, size); System.out.println(summary(s)); } catch (final ParseException e) { final HelpFormatter f = new HelpFormatter(); final PrintWriter pw = new PrintWriter(System.err); f.printHelp(pw, 80, "match-scheduler", null, OPTIONS, 2, 2, null, true); pw.println( "For example: match-scheduler -t 48 -r 3 -d 12 -m 2 -g 3 -c 2 -z 4 --randomMatches --randomSlots"); pw.close(); } }
From source file:edu.msu.cme.rdp.kmer.KmerSearch.java
public static void main(String[] args) throws IOException { KmerTrie kmerTrie = null;/*from w ww.ja v a 2s . c om*/ SeqReader queryReader = null; SequenceType querySeqType = SequenceType.Unknown; FastaWriter out = null; boolean exhaustive = true; boolean translQuery = false; int wordSize = -1; int translTable = 11; try { CommandLine cmdLine = new PosixParser().parse(options, args); args = cmdLine.getArgs(); if (args.length != 3) { throw new Exception("Unexpected number of arguments"); } if (cmdLine.hasOption("out")) { out = new FastaWriter(cmdLine.getOptionValue("out")); } else { out = new FastaWriter(System.out); } if (cmdLine.hasOption("correct")) { exhaustive = false; } else { exhaustive = true; } if (cmdLine.hasOption("transl-table")) { translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table")); } File trainingFile = new File(args[0]); wordSize = Integer.valueOf(args[1]); File queryFile = new File(args[2]); querySeqType = SeqUtils.guessSequenceType(queryFile); queryReader = new SequenceReader(new File(args[2])); kmerTrie = KmerTrie.buildTrie(new SequenceReader(trainingFile), wordSize); if (querySeqType == SequenceType.Protein && kmerTrie.getTreeSeqType() == SequenceType.Nucleotide) { throw new Exception("Trie is made of nucleotide sequences but the query sequences are protein"); } if (querySeqType == SequenceType.Nucleotide && kmerTrie.getTreeSeqType() == SequenceType.Protein) { translQuery = true; System.err.println( "Query sequences are nucleotide but trie is in protein space, query sequences will be translated"); } if (querySeqType == SequenceType.Protein && exhaustive) { System.err.println("Cannot do an exaustive search with protein sequences, disabling"); exhaustive = false; } } catch (Exception e) { new HelpFormatter().printHelp("KmerSearch <ref_file> <word_size> <query_file>", options); System.err.println(e.getMessage()); System.exit(1); } long startTime = System.currentTimeMillis(); long seqCount = 0, passedCount = 0; Sequence querySeq; while ((querySeq = queryReader.readNextSequence()) != null) { seqCount++; List<Sequence> testSequences; if (!exhaustive) { if (translQuery) { testSequences = Arrays.asList(new Sequence(querySeq.getSeqName(), "", ProteinUtils.getInstance() .translateToProtein(querySeq.getSeqString(), true, translTable))); } else { testSequences = Arrays.asList(querySeq); } } else { if (translQuery) { testSequences = ProteinUtils.getInstance().allTranslate(querySeq); } else { testSequences = Arrays.asList(querySeq, new Sequence(querySeq.getSeqName(), "", IUBUtilities.reverseComplement(querySeq.getSeqString()))); } } boolean passed = false; for (Sequence seq : testSequences) { for (char[] kmer : KmerGenerator.getKmers(seq.getSeqString(), wordSize)) { if (kmerTrie.contains(kmer) != null) { passed = true; break; } } if (passed) { out.writeSeq(seq); passedCount++; break; } } } System.err.println("Processed: " + seqCount); System.err.println("Passed: " + passedCount); System.err.println("Failed: " + (seqCount - passedCount)); System.err.println("Time: " + (System.currentTimeMillis() - startTime) + " ms"); }
From source file:de.topobyte.livecg.ShowVisualization.java
public static void main(String[] args) { EnumNameLookup<Visualization> visualizationSwitch = new EnumNameLookup<Visualization>(Visualization.class, true);//w w w .j av a 2s . c om // @formatter:off Options options = new Options(); OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file"); OptionHelper.add(options, OPTION_VISUALIZATION, true, true, "type", "type of visualization. one of <" + VisualizationUtil.getListOfAvailableVisualizations() + ">"); OptionHelper.add(options, OPTION_STATUS, true, false, "status to " + "set the algorithm to. The format depends on the algorithm"); // @formatter:on Option propertyOption = new Option(OPTION_PROPERTIES, "set a special property"); propertyOption.setArgName("property=value"); propertyOption.setArgs(2); propertyOption.setValueSeparator('='); options.addOption(propertyOption); CommandLineParser clp = new GnuParser(); CommandLine line = null; try { line = clp.parse(options, args); } catch (ParseException e) { System.err.println("Parsing command line failed: " + e.getMessage()); new HelpFormatter().printHelp(HELP_MESSAGE, options); System.exit(1); } String[] extra = line.getArgs(); if (extra.length == 0) { System.out.println("Missing file argument"); new HelpFormatter().printHelp(HELP_MESSAGE, options); System.exit(1); } String input = extra[0]; StringOption argConfig = ArgumentHelper.getString(line, OPTION_CONFIG); if (argConfig.hasValue()) { String configPath = argConfig.getValue(); LiveConfig.setPath(configPath); } StringOption argVisualization = ArgumentHelper.getString(line, OPTION_VISUALIZATION); StringOption argStatus = ArgumentHelper.getString(line, OPTION_STATUS); Visualization visualization = visualizationSwitch.find(argVisualization.getValue()); if (visualization == null) { System.err.println("Unsupported visualization '" + argVisualization.getValue() + "'"); System.exit(1); } System.out.println("Visualization: " + visualization); ContentReader contentReader = new ContentReader(); Content content = null; try { content = contentReader.read(new File(input)); } catch (Exception e) { System.out.println("Error while reading input file '" + input + "'. Exception type: " + e.getClass().getSimpleName() + ", message: " + e.getMessage()); System.exit(1); } Properties properties = line.getOptionProperties(OPTION_PROPERTIES); ContentLauncher launcher = null; switch (visualization) { case GEOMETRY: { launcher = new ContentDisplayLauncher(); break; } case DCEL: { launcher = new DcelLauncher(); break; } case FREESPACE: { launcher = new FreeSpaceChainsLauncher(); break; } case DISTANCETERRAIN: { launcher = new DistanceTerrainChainsLauncher(); break; } case CHAN: { launcher = new ChanLauncher(); break; } case FORTUNE: { launcher = new FortunesSweepLauncher(); break; } case MONOTONE_PIECES: { launcher = new MonotonePiecesLauncher(); break; } case MONOTONE_TRIANGULATION: { launcher = new MonotoneTriangulationLauncher(); break; } case TRIANGULATION: { launcher = new MonotonePiecesTriangulationLauncher(); break; } case SPIP: { launcher = new ShortestPathInPolygonLauncher(); break; } case BUFFER: { launcher = new PolygonBufferLauncher(); break; } } try { launcher.launch(content, true); } catch (LaunchException e) { System.err.println("Unable to start visualization"); System.err.println("Error message: " + e.getMessage()); System.exit(1); } }