List of usage examples for org.apache.commons.cli BasicParser BasicParser
BasicParser
From source file:com.spidasoftware.EclipseFormatter.FormatterTest.java
/** * OptionToFormat on a file that does exist *///from w ww . j a v a 2s. co m public void testoptionToFormatDirectoryAbsolutePathDoesExist() { log.info("Formatter.OptionToFormat on a directory that does exist"); String dirName = System.getProperty("user.dir") + File.separator + "test"; CommandLine cmd = null; CommandLineParser parser = new BasicParser(); Options options = new Options(); absolutePathFile = new File(dirName); try { absolutePathFile.mkdir(); options.addOption("b", false, "create a backup file"); cmd = parser.parse(options, new String[] { dirName }); } catch (ParseException e) { log.error(e, e); } catch (SecurityException e) { log.error(e, e); } String[] args = new String[] { dirName }; boolean exists = Formatter.optionToFormat(cmd, args); assertTrue("Formatter.OptionToFormat on a directory that does exist", exists); }
From source file:com.alcatel_lucent.nz.wnmsextract.WNMSDataExtractor.java
/** readArgs. Read command line arguments and parse * @param args//from www. j av a 2 s . c om * @return read with/without error */ public boolean readArgs(String[] args) { boolean ret = true; boolean af = true; boolean bs = true; boolean ws = true; boolean vp = false; //boolean ns = false; DatabaseType df = DatabaseType.TNZ_NZRSDB; LogAppType lf = LogAppType.File; Calendar tf = Calendar.getInstance(); tf.add(Calendar.DATE, -1); //DocumentType xf = null;//default is the list of all doc types so do that in init() String bsd = null; String bfd = null; try { Options opt = new Options(); opt.addOption("h", "help", false, "Print help for this application"); //opt.addOption("e", "extract", true, "Extraction Source {c=CPV Archive, t=TNZ Ops TAR file, g=GTA ZIP file. No default.}"); opt.addOption("l", "log", true, "Logging Appender {f=File (def), c=Console, s=Socket}"); opt.addOption("t", "time", true, "Specific process date {yyyy-MM-dd}. Default to 'Yesterday'"); opt.addOption("d", "database", true, "Database to send Results {NPO48, NPO33, TEST, MPM, TNZ_NZRSDB , GTA_NZRSDB. No Default}"); opt.addOption("x", "doctype", true, "Document Type to parse {WNMS_NodeB, WMNS_INode, WNMS_RncCn, WIPS_mRNb, WIPS_mRVcc, WIPS_mFB, WIPS_cNbP}. Default to 'All'"); opt.addOption("a", "aggskip", false, "Skip Aggregation Step (useful for batch requests)"); opt.addOption("b", "borgskip", false, "Skip Borg Extraction Step (useful if Borg data is redundant)"); opt.addOption("w", "wnmsskip", false, "Skip WNMS Extraction Step (useful if WNMS is overflowing disk)"); opt.addOption("s", "borgstartdate", false, "Start date for selected Borg data range"); opt.addOption("f", "borgfinishdate", false, "End date for selected Borg data range"); opt.addOption("v", "variablexsl", false, "Use dynamic-position XSL transformer (def static)"); opt.addOption("n", "network", true, "Selecting GTA or TNZ sets: scrape vs file read, xmlns:HTML vs xmlns namespace (will add db when mature)"); BasicParser bp = new BasicParser(); CommandLine cl = bp.parse(opt, args); if (cl.hasOption('h')) { HelpFormatter f = new HelpFormatter(); f.printHelp("OptionsTip", opt); ret = false; System.exit(0); } else { //Extraction /* if (cl.hasOption('e')){ String lval = cl.getOptionValue("e"); if ("c".compareTo(lval.toLowerCase())==0){ extractor = new Extractor(); } else if ("t".compareTo(lval.toLowerCase())==0){ extractor = new Extractor(); } else if ("g".compareTo(lval.toLowerCase())==0){ extractor = new Extractor(); } else { System.out.println("Extractor specifier ["+lval+"] incorrect, default to 'TAR'"); extractor = new Extractor(); } } else{ System.out.println("Extractor not specified, default to 'TAR'"); System.out.println("*** TESTING!\n*** NO DEFAULT EXTRACOR SET UP.\nPrecaution to prevent cross network pollution, exiting"); System.exit(1); } */ //Logging if (cl.hasOption('l')) { String lval = cl.getOptionValue("l"); if ("f".compareTo(lval.toLowerCase()) == 0) { lf = LogAppType.File; } else if ("c".compareTo(lval.toLowerCase()) == 0) { lf = LogAppType.Console; } else if ("s".compareTo(lval.toLowerCase()) == 0) { lf = LogAppType.Socket; } else { System.out.println("Logging Appender [" + lval + "] incorrect, default to 'File'"); } } else { System.out.println("Logging Appender not specified, default to 'File'"); } //DateTime if (cl.hasOption('t')) { try { tf = parseTimestamp(cl.getOptionValue("t")); } catch (java.text.ParseException pe) { System.err.println("Date not specified correctly. " + pe + ". Using Default 'today'"); } } else { System.out.println("Date not specified. Using Default 'today'"); } //Database /* if (cl.hasOption('d') && DatabaseType.valueOf(cl.getOptionValue("d"))!=null){ df = DatabaseType.valueOf(cl.getOptionValue("d")); } else { System.out.println("DatabaseType not specified"); System.out.println("*** ATTENTION! ***\nNO DEFAULT DATABASE SET UP.\nOnly you can prevent cross network data pollution. Exiting"); System.exit(1); } */ //Document if (cl.hasOption('x')) { String xstr = cl.getOptionValue("x"); if ("WNMS_All".compareTo(xstr) == 0) { System.out.println("DocumentType WNMS_All {RncCn,INode,NodeB,INodeVcc}"); this.alldocs = EnumSet.of(DocumentType.WNMS_RncCn, DocumentType.WNMS_INode, DocumentType.WNMS_NodeB, DocumentType.WNMS_INodeVcc); } else if ("WIPS_All".compareTo(xstr) == 0) { System.out.println("DocumentType WIPS_All {cNbP,mFB,mRNb,mRVcc}"); this.alldocs = EnumSet.of(DocumentType.WIPS_cNbP, DocumentType.WIPS_mFB, DocumentType.WIPS_mRNb, DocumentType.WIPS_mRVcc); } else { //get what is requested, assuming selection is correct System.out.println("DocumentType {" + xstr + "}"); this.alldocs = EnumSet.of(DocumentType.valueOf(xstr)); } } else { //get all the docs, WNMS and WiPS System.out.println( "DocumentType not specified, Default All {RncCn,INode,NodeB,INodeVcc,cNbP,mFB,mRNb,mRVcc}"); this.alldocs = EnumSet.allOf(DocumentType.class); } /* Aggregation. * if -a then SKIP aggregation and therefore skip WiPS import. Makes no * sense to set -x WIPS option if also setting -a option */ if (cl.hasOption('a')) { af = false; } else { System.out.println("Post insert-log/aggregation not specified. Default to TRUE"); } //Borg (skip Borg processing, just do WNMS) if (cl.hasOption('b')) { bs = false; } else { System.out.println("Borg Skip not requested. Default to TRUE"); //borg start if (cl.hasOption('s')) { bsd = cl.getOptionValue("s"); } else { System.out.println("Borg startdate not specified. Default to Yesterday"); } //borg finish if (cl.hasOption('f')) { bfd = cl.getOptionValue("f"); } else { System.out.println("Borg finishdate not specified. Default to Today"); } } //WNMS (skip WNMS processing, just do Borg) if (cl.hasOption('w')) { ws = false; } else { System.out.println("Process WNMS Source not specified. Default to TRUE"); } //Variable position Static/Dynamic XSL transformer for WNMS if (cl.hasOption('v')) { vp = true; } else { System.out.println("Variable/Dynamic parser not requested, default to static"); } //Namespace has subdeclaration xmlns:HTML if (cl.hasOption('n')) { String netw = cl.getOptionValue("n"); if ("GTA".compareTo(netw) == 0) { this.networktype = NetworkType.GTA; } else if ("TNZ".compareTo(netw) == 0) { this.networktype = NetworkType.TNZ; } else { System.out.println("Network Selection invalid: " + netw + ", Exiting"); System.exit(1); } } else { System.out.println("Network Selection required! Exiting"); System.exit(1); } } } catch (ParseException e) { e.printStackTrace(); System.exit(1); } this.wdl.addLoggingAppender(lf); this.setAggregateTables(af); this.setBorgStep(bs); this.setWNMSStep(ws); //if(xf!=null)this.alldocs = EnumSet.of(xf); this.setDatabaseType(df); this.setCalendar(tf); this.setBorgStartDate(bsd); this.setBorgFinishDate(bfd); this.setTransformerType(vp); jlog.info("LG:" + lf + ", DT:" + tf.getTime() + ", DB:" + df + ", DC:" + this.alldocs + ", AT:" + af + ", BS:" + bs + ", NT:" + networktype); System.out.println("LG:" + lf + ", DT:" + tf.getTime() + ", DB:" + df + ", DC:" + this.alldocs + ", AT:" + af + ", BS:" + bs + ", WS:" + ws + ", NT:" + networktype + ", VP:" + vp); return ret; }
From source file:edu.cornell.med.icb.geo.tools.MicroarrayTrainEvaluate.java
private void proccess(final String[] args) { // create the Options final Options options = new Options(); // help/*w ww. j a va 2 s. c o m*/ options.addOption("h", "help", false, "print this message. When -r is used with a non zero integer n, " + "a set of n random gene lists is evaluated for each line of the task list. The evaluation statistics " + "reported is the number of random gene lists that obtained the same or better leave-one-out performance than " + "the gene list from the task list. Accuracy is used to evaluate performance for random trials. "); // input file name final Option inputOption = new Option("i", "input", true, "specify a GEO or RES data set file (GDS file or whitehead RES format)"); inputOption.setArgName("file"); inputOption.setRequired(true); options.addOption(inputOption); // output file name final Option outputOption = new Option("o", "output", true, "specify the destination file where statistics will be written"); outputOption.setArgName("file"); outputOption.setRequired(true); options.addOption(outputOption); // task list file name final Option tasksFilenameOption = new Option("t", "task-list", true, "specify the file with the list of tasks to perform. This file is tab separated"); tasksFilenameOption.setArgName("file"); tasksFilenameOption.setRequired(true); options.addOption(tasksFilenameOption); // condition identifiers file name final Option conditionsIdsFilenameOption = new Option("c", "conditions", true, "specify the file with the mapping condition-name column-identifier (tab separated, on mapping per line)."); conditionsIdsFilenameOption.setArgName("file"); conditionsIdsFilenameOption.setRequired(true); options.addOption(conditionsIdsFilenameOption); // gene lists file name final Option geneListsFilenameOption = new Option("g", "gene-list", true, "specify the file with the gene lists (one per line)."); geneListsFilenameOption.setArgName("file"); geneListsFilenameOption.setRequired(true); options.addOption(geneListsFilenameOption); // Geo platform description file name final Option platformDescriptionFilenameOption = new Option("p", "platform", true, "specify the platform description file(s) (GEO GPL file format). Multiple platorm files may be provided " + " if separated by coma (e.g., file1,file2). Each file is read in the order provided."); platformDescriptionFilenameOption.setArgName("file,file"); platformDescriptionFilenameOption.setRequired(true); options.addOption(platformDescriptionFilenameOption); // Number of random runs (picking probesets randomly that are not in the gene list) final Option randomRunCountOption = new Option("r", "random-run-count", true, "Number of random runs to execute for each random gene list."); randomRunCountOption.setArgName("number"); randomRunCountOption.setRequired(false); options.addOption(randomRunCountOption); // Number of probeset to randomly select for each random run final Option batchSizeRandomRun = new Option("b", "batch-size-random-run", true, "Number of probeset to randomly select for each random run. Default is " + DEFAULT_RANDOM_BATCH_SIZE + "."); batchSizeRandomRun.setArgName("number"); batchSizeRandomRun.setRequired(false); options.addOption(batchSizeRandomRun); // Number of shuffle runs (shuffling the training label). final Option shuffleRunCountOption = new Option("u", "shuffle-run-count", true, "Number of shuffle runs (label permutations) to execute for each training set."); shuffleRunCountOption.setArgName("number"); shuffleRunCountOption.setRequired(false); options.addOption(shuffleRunCountOption); // Minimal signal value for signal floor adjustment. final Option floorSignalValueOption = new Option("f", "floor", true, "Specify a floor value for the signal. If a signal is lower than the floor, it is set to the floor."); floorSignalValueOption.setArgName("number"); floorSignalValueOption.setRequired(false); options.addOption(floorSignalValueOption); // distinguish between one channel array and two channel array final Option channelOption = new Option("a", "two-channel-array", false, "Indicate that the data is for a two channel array. This flag affects how the floor value is interpreted." + "For two channel arrays, values on the array are set to 1.0 if (Math.abs(oldValue-1.0)+1)<=floorValue, " + "whereas for one channel array the condition becomes: oldValue<=floorValue."); channelOption.setRequired(false); options.addOption(channelOption); // Minimal signal value for signal floor adjustment. final Option svmLightOption = new Option("l", "light", false, "Choose svmLight. (default libSVM)."); svmLightOption.setRequired(false); options.addOption(svmLightOption); // Number of random runs final Option seedOption = new Option("s", "seed", true, "Seed for the number generator."); seedOption.setArgName("number"); seedOption.setRequired(false); // Timeout for stopping svmlight in seconds if the process does not complete. final Option timeoutOption = new Option("x", "timeout", true, "Timeout for svmLight training, in seconds (default 3600 seconds/1h)."); timeoutOption.setArgName("number"); timeoutOption.setRequired(false); options.addOption(timeoutOption); final Option clusterFilename = new Option("e", "clusters", true, "Name of file that describes clusters of genes. "); clusterFilename.setArgName("filename"); clusterFilename.setRequired(false); options.addOption(clusterFilename); // parse the command line arguments CommandLine line = null; final double defaultLabelValue = 0; try { // create the command line parser final CommandLineParser parser = new BasicParser(); line = parser.parse(options, args, true); } catch (ParseException e) { System.err.println(e.getMessage()); usage(options); System.exit(1); } // print help and exit if (line.hasOption("h")) { usage(options); System.exit(0); } try { int randomRunCount = 0; final String randomCount = line.getOptionValue("r"); if (randomCount != null) { randomRunCount = Integer.parseInt(randomCount); } if (line.hasOption("l")) { this.svmLight = true; } System.out.println("Using " + (svmLight ? "svmLight" : "libSVM")); final String batchSize = line.getOptionValue("b"); if (batchSize != null) { this.randomBatchSize = Integer.parseInt(batchSize); } else { this.randomBatchSize = DEFAULT_RANDOM_BATCH_SIZE; } System.out.println("Will do " + randomRunCount + " random runs with batch-size=" + randomBatchSize); if (line.hasOption("a")) { this.oneChannelArray = false; } else { this.oneChannelArray = true; } final String floorOptionValue = line.getOptionValue("f"); if (floorOptionValue != null) { adjustSignalToFloorValue = true; if (oneChannelArray) { this.signalFloorValue = DEFAULT_SIGNAL_FLOOR_VALUE_SINGLE_CHANNEL; this.signalFloorValue = Integer.parseInt(floorOptionValue); } else { this.signalFloorValue = DEFAULT_SIGNAL_FLOOR_VALUE_TWO_CHANNELS; this.signalFloorValue = Float.parseFloat(floorOptionValue); } System.out.println("Clipping signal at floor value: " + signalFloorValue); System.out.println("This chip has " + (oneChannelArray ? " one channel." : "two channels.")); } int seed = (int) new Date().getTime(); if (line.getOptionValue("s") != null) { seed = Integer.parseInt(line.getOptionValue("s")); } randomGenerator = new MersenneTwister(seed); int timeout = 60 * 60; // in seconds. // 1 hour if (line.getOptionValue("x") != null) { if (!svmLight) { System.out.println("Error: --timeout option can only be used with --light option."); System.exit(1); } timeout = Integer.parseInt(line.getOptionValue("x")); System.out.println("Timeout set to " + timeout + " second(s)."); } this.timeout = timeout * 1000; final ClassificationTask[] tasks = readTasksAndConditions(line.getOptionValue("t"), line.getOptionValue("c")); final GeneList[] geneList = readGeneList(line.getOptionValue("p"), line.getOptionValue("g")); formatter = new DecimalFormat(); formatter.setMaximumFractionDigits(2); final String uOption = line.getOptionValue("u"); if (uOption == null) { countShuffleLabelTests = 0; } else { countShuffleLabelTests = Integer.parseInt(uOption); } System.out.println("Will do " + countShuffleLabelTests + " shuffling runs"); final File outputFile = new File(line.getOptionValue("o")); final boolean outputFilePreexist = outputFile.exists(); final PrintWriter statWriter = new PrintWriter(new FileWriter(outputFile, true)); // append stats to output. if (!outputFilePreexist) { ClassificationResults.writeHeader(statWriter, shuffleLabelTest); } convert(line.getOptionValue("i"), statWriter, tasks, geneList, randomRunCount); statWriter.close(); System.exit(0); } catch (Exception e) { System.out.println(e); e.printStackTrace(); System.exit(10); } }
From source file:au.org.ala.names.search.DwcaNameIndexer.java
/** * Example run//from w w w . ja v a 2 s .c o m * * java cp .:names.jar au.org.ala.checklist.lucene.DwcaNameIndexer * -all * -dwca /data/bie-staging/names-lists/dwca-col * -target /data/lucene/testdwc-namematching * -irmng /data/bie-staging/irmng/IRMNG_DWC_HOMONYMS * -common /data/bie-staging/ala-names/col_vernacular.txt * * @param args */ public static void main(String[] args) { final String DEFAULT_DWCA = "/data/lucene/sources/dwca-col"; final String DEFAULT_IRMNG = "/data/lucene/sources/IRMNG_DWC_HOMONYMS"; final String DEFAULT_COMMON_NAME = "/data/lucene/sources/col_vernacular.txt"; final String DEFAULT_TARGET_DIR = "/data/lucene/namematching"; final String DEFAULT_TMP_DIR = "/data/lucene/nmload-tmp"; Options options = new Options(); options.addOption("v", "version", false, "Retrieve version information"); options.addOption("h", "help", false, "Retrieve options"); options.addOption("all", false, "Generates the load index and search index"); options.addOption("load", false, "Generate the load index only. " + "The load index is a temporary index generated from the raw data files" + " used to load the main search index"); options.addOption("search", false, "Generates the search index. A load index must already be created for this to run."); options.addOption("irmng", true, "The absolute path to the unzipped irmng DwCA. IRMNG is used to detect homonyms. Defaults to " + DEFAULT_IRMNG); options.addOption("dwca", true, "The absolute path to the unzipped DwCA for the scientific names. Defaults to " + DEFAULT_DWCA); options.addOption("target", true, "The target directory to write the new name index to. Defaults to " + DEFAULT_TARGET_DIR); options.addOption("tmp", true, "The tmp directory for the load index. Defaults to " + DEFAULT_TMP_DIR); options.addOption("common", true, "The common (vernacular) name file. Defaults to " + DEFAULT_COMMON_NAME); options.addOption("testSearch", true, "Debug a name search. This uses the target directory to search against."); CommandLineParser parser = new BasicParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("v")) { //only load the properties file if it exists otherwise default to the biocache-test-config.properties on the classpath InputStream stream = DwcaNameIndexer.class.getResourceAsStream("/git.properties"); Properties properties = new Properties(); if (stream != null) { properties.load(stream); properties.list(System.out); } else { System.err.println("Unable to retrieve versioning information"); } System.exit(-1); } if (line.hasOption("help")) { //only load the properties file if it exists otherwise default to the biocache-test-config.properties on the classpath new HelpFormatter().printHelp("nameindexer", options); System.exit(-1); } if (line.hasOption("testSearch")) { boolean indexExists = (new File(DEFAULT_TARGET_DIR).exists()); if (indexExists) { //do a name search - with option flag pointing to index location System.out.println("Search for name"); ALANameSearcher searcher = new ALANameSearcher( line.getOptionValue("target", DEFAULT_TARGET_DIR)); NameSearchResult nsr = searcher.searchForRecord(line.getOptionValue("testSearch")); if (nsr != null) { Map<String, String> props = nsr.toMap(); for (Map.Entry<String, String> entry : props.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } else { System.err.println("No match for " + line.getOptionValue("testSearch")); } } else { System.err.println("Index unreadable. Check " + DEFAULT_TARGET_DIR); } System.exit(-1); } boolean load = line.hasOption("load") || line.hasOption("all"); boolean search = line.hasOption("search") || line.hasOption("all"); if (!line.hasOption("load") && !line.hasOption("search") && !line.hasOption("all")) { load = true; search = true; } log.info("Generating loading index: " + load); log.info("Generating searching index: " + search); boolean defaultIrmngReadable = (new File(DEFAULT_IRMNG).exists()); boolean defaultCommonReadable = (new File(DEFAULT_COMMON_NAME).exists()); boolean defaultDwcaReadable = (new File(DEFAULT_DWCA).exists()); if (line.getOptionValue("dwca") != null) { log.info("Using the DwCA name file: " + line.getOptionValue("dwca")); } else if (defaultDwcaReadable) { log.info("Using the default DwCA name file: " + DEFAULT_DWCA); } else { log.error( "No DwC Archive specified and the default file path does not exist or is inaccessible. Default path: " + DEFAULT_DWCA); System.exit(-1); } if (line.getOptionValue("irmng") == null && !defaultIrmngReadable) { log.warn( "No IRMNG export specified and the default file path does not exist or is inaccessible. Default path: " + DEFAULT_IRMNG); } else { log.info("Using the default IRMNG name file: " + DEFAULT_IRMNG); } if (line.getOptionValue("common") == null && !defaultCommonReadable) { log.warn( "No common name export specified and the default file path does not exist or is inaccessible. Default path: " + DEFAULT_COMMON_NAME); } else { log.info("Using the default common name file: " + DEFAULT_COMMON_NAME); } File targetDirectory = new File(line.getOptionValue("target", DEFAULT_TARGET_DIR)); if (targetDirectory.exists()) { String newPath = targetDirectory.getAbsolutePath() + "_" + DateFormatUtils.format(new Date(), "yyyy-MM-dd_hh-mm-ss"); log.info("Target directory already exists. Backing up to : " + newPath); File newTargetDirectory = new File(newPath); FileUtils.moveDirectory(targetDirectory, newTargetDirectory); FileUtils.forceMkdir(targetDirectory); } DwcaNameIndexer indexer = new DwcaNameIndexer(); indexer.create(load, search, line.getOptionValue("target", DEFAULT_TARGET_DIR), line.getOptionValue("tmp", DEFAULT_TMP_DIR), line.getOptionValue("dwca", DEFAULT_DWCA), line.getOptionValue("irmng", DEFAULT_IRMNG), line.getOptionValue("common", DEFAULT_COMMON_NAME)); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.alcatel_lucent.nz.wnmsextract.WNMSTransform.java
/** * Called if the Transformer class is called as a main. Useful for one off XML parse jobs * @param args//from w w w . ja v a 2 s . c o m */ public void processcli(String[] args) { String xf = null, sf = null, of = null; try { Options opt = new Options(); opt.addOption("h", "help", false, "Print help for this application"); opt.addOption("x", "xml", true, "The XCM file to load"); opt.addOption("s", "xsl", true, "The stylesheet to apply"); opt.addOption("o", true, "The output CSV to generate"); BasicParser bp = new BasicParser(); CommandLine cl = bp.parse(opt, args); ALUParser p = new ALUParserFactory("WIPS").getInstance(); if (cl.hasOption('h')) { HelpFormatter f = new HelpFormatter(); f.printHelp("OptionsTip", opt); } else { //XCM snapshot if (cl.hasOption('x')) { xf = cl.getOptionValue("x"); } else { System.err.println("XML File not Specified"); System.exit(1); } //stylesheet if (cl.hasOption('s')) { sf = cl.getOptionValue("s"); } else { System.err.println("XSL File not Specified"); System.exit(1); } //output if (cl.hasOption('o')) { of = cl.getOptionValue("o"); } else { String sfn = sf.substring(sf.lastIndexOf("\\") + 1, sf.length() - 4); of = xf.substring(0, xf.length() - 4) + "." + sfn + ".csv"; } System.out.println(xf + " + " + sf + " -> " + of); p.setParseFile(xf); p.setTransformFile(sf); p.setResultFile(of); //how is this ever supposed to work if you never call transform?!? } } catch (ParseException e) { e.printStackTrace(); } }
From source file:com.spidasoftware.EclipseFormatter.FormatterTest.java
/** * Test where Formatter.formatOne does not return a backup file when ran on a java file *//*from ww w . java 2 s. c o m*/ public void testformatOneBackupFileJavaAbsolutePath() { log.info( "Formatter.formatOne returns no backup file when ran on a java file with it's absolute path when the option is not set"); fileName = System.getProperty("user.dir") + File.separator + "javaEclipseFormatterTest13243546.java"; absolutePathFile = new File(fileName); Options options = new Options(); options.addOption("b", false, "create a backup file"); CommandLine cmd = null; CommandLineParser parser = new BasicParser(); try { cmd = parser.parse(options, new String[] { "-b" }); FileUtils.writeStringToFile(absolutePathFile, "package groovyTest;\npublic class genericJavaClass" + "{\npublic static void main(String[] args) {\n// TODO Auto-generated method stub\n}\n}"); } catch (ParseException e) { log.error(e, e); } catch (IOException e) { log.error(e, e); } nameWithDate = Formatter.formatOne(absolutePathFile, cmd); assertTrue( "Formatter.formatOne did not return a backup file when ran on a java file with it's absolute path when the option is not set", nameWithDate != null); }
From source file:mitm.application.djigzo.tools.Upgrade.java
public void handleCommandline(String[] args) throws IOException, ParseException, WSProxyFactoryException, WebServiceCheckedException { CommandLineParser parser = new BasicParser(); Options options = createCommandLineOptions(); HelpFormatter formatter = new HelpFormatter(); CommandLine commandLine;/*from w w w .j a v a2s . c o m*/ try { commandLine = parser.parse(options, args); } catch (ParseException e) { formatter.printHelp(COMMAND_NAME, options, true); throw e; } user = commandLine.getOptionValue("user"); password = commandLine.getOptionValue("password"); String version = commandLine.getOptionValue("version"); if (commandLine.getOptions().length == 0 || commandLine.hasOption("help")) { formatter.printHelp(COMMAND_NAME, options, true); return; } if (StringUtils.equalsIgnoreCase(version, "1.3")) { upgradeTo13(); } else { throw new IllegalArgumentException("Unsupported version."); } }
From source file:alluxio.examples.JournalCrashTest.java
/** * Parse the input args with a command line format, using * {@link org.apache.commons.cli.CommandLineParser}. This method handles printing help information * if parsing fails or --help is specified. * * @param args the input args/* w ww. j a va2 s . co m*/ * @return true if parsing succeeded and --help wasn't specified, false otherwise */ private static boolean parseInputArgs(String[] args) { Options options = new Options(); options.addOption("help", false, "Show help for this test"); options.addOption("maxAlive", true, "The maximum time a master should ever be alive during the test, in seconds"); options.addOption("totalTime", true, "The total time to run this test, in seconds." + " This value should be greater than [maxAlive]"); options.addOption("creates", true, "Number of Client Threads to request create operations"); options.addOption("deletes", true, "Number of Client Threads to request create/delete operations"); options.addOption("renames", true, "Number of Client Threads to request create/rename operations"); options.addOption("testDir", true, "Test Directory on Alluxio"); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; boolean ret = true; try { cmd = parser.parse(options, args); } catch (ParseException e) { LOG.error("Failed to parse input args", e); ret = false; } if (ret && !cmd.hasOption("help")) { sMaxAliveTimeMs = 1000 * Long.parseLong(cmd.getOptionValue("maxAlive", "5")); sTotalTimeMs = 1000 * Long.parseLong(cmd.getOptionValue("totalTime", "20")); sCreateFileClientNum = Integer.parseInt(cmd.getOptionValue("creates", "2")); sCreateDeleteClientNum = Integer.parseInt(cmd.getOptionValue("deletes", "2")); sCreateRenameClientNum = Integer.parseInt(cmd.getOptionValue("renames", "2")); sTestDir = cmd.getOptionValue("testDir", "/default_tests_files"); } else { ret = false; new HelpFormatter().printHelp( "java -cp alluxio-" + Version.VERSION + "-jar-with-dependencies.jar alluxio.examples.JournalCrashTest", "Test the Master Journal System in a crash scenario", options, "e.g. options '-maxAlive 5 -totalTime 20 -creates 2 -deletes 2 -renames 2'" + "will launch total 6 clients connecting to the Master and the Master" + "will crash randomly with the max alive time 5 seconds.", true); } return ret; }
From source file:com.spidasoftware.EclipseFormatter.FormatterTest.java
/** * Test where Formatter.formatOne returned a backup file when ran on a groovy file *//* ww w. j a v a2s. c om*/ public void testformatOneBackupFileGroovy() { log.info("Formatter.formatOne returned a backup file when ran on a groovy file"); Options options = new Options(); options.addOption("b", false, "create a backup file"); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, new String[] { "-b" }); FileUtils.writeStringToFile(groovyFile, "package groovyTest\nclass genericClass " + "{\nstatic main(args) {\n}\n}\n"); } catch (ParseException e) { log.error(e, e); } catch (IOException e) { log.error(e, e); } nameWithDate = Formatter.formatOne(groovyFile, cmd); assertTrue("Formatter.formatOne returned a backup file", nameWithDate != null); }
From source file:com.spidasoftware.EclipseFormatter.FormatterTest.java
/** * Test where Formatter.formatOne does not return a backup file when ran on a groovy file *///from w w w . ja v a 2s .c om public void testformatOneNoBackupFileGroovy() { log.info("Formatter.formatOne returns no backup file when ran on a groovy file when the option is not set"); Options options = new Options(); CommandLine cmd = null; CommandLineParser parser = new BasicParser(); try { cmd = parser.parse(options, new String[] {}); FileUtils.writeStringToFile(groovyFile, "package groovyTest\nclass genericClass " + "{\nstatic main(args) {\n}\n}\n"); } catch (ParseException e) { log.error(e, e); } catch (IOException e) { log.error(e, e); } nameWithDate = Formatter.formatOne(groovyFile, cmd); assertTrue("Formatter.formatOne did not return a backup file", nameWithDate == null); }