List of usage examples for org.apache.commons.cli Option getValues
public String[] getValues()
From source file:org.lib4j.cli.Options.java
public String[] getOptions(final String name) { final Option reqOption = optionNameToOption.get(name); return reqOption != null ? reqOption.getValues() : null; }
From source file:org.libx4j.cli.Options.java
public static Options parse(final cli_cli binding, final Class<?> mainClass, final String[] args) throws OptionsException { final Set<String> requiredNames = new HashSet<String>(); final Map<String, String> nameToAltName = new HashMap<String, String>(); final org.apache.commons.cli.Options apacheOptions = new org.apache.commons.cli.Options(); apacheOptions.addOption(null, "help", false, "Print help and usage."); int argumentsMinOccurs = 0; int argumentsMaxOccurs = 0; final cli_cli._arguments cliArguments; if (binding != null) { cliArguments = binding._arguments(0); if (!cliArguments.isNull()) { argumentsMinOccurs = cliArguments._minOccurs$().text(); argumentsMaxOccurs = "unbounded".equals(cliArguments._maxOccurs$().text()) ? Integer.MAX_VALUE : Integer.parseInt(cliArguments._maxOccurs$().text()); if (argumentsMaxOccurs < argumentsMinOccurs) { logger.error("minOccurs > maxOccurs on <arguments> element"); System.exit(1);/*from w ww . j a v a2s . com*/ } } if (binding._option() != null) { for (final cli_cli._option option : binding._option()) { final cli_cli._option._name optionName = option._name(0); final String longName = optionName._long$().isNull() ? null : optionName._long$().text(); final String shortName = optionName._short$().isNull() ? null : optionName._short$().text(); final String name = longName != null ? longName : shortName; if (longName == null && shortName == null) { logger.error("both [long] and [short] option names are null in cli spec"); System.exit(1); } nameToAltName.put(name, shortName != null ? shortName : longName); OptionBuilder.withLongOpt(name == longName ? longName : null); // Record which options are required if (option._argument() != null && option._argument().size() != 0) { final cli_cli._option._argument argument = option._argument(0); final boolean isRequired = $cli_use.required.text().equals(argument._use$().text()); if (isRequired) { OptionBuilder.isRequired(); requiredNames.add(longName); } final int maxOccurs = argument._maxOccurs$().isNull() ? 1 : "unbounded".equals(argument._maxOccurs$().text()) ? Integer.MAX_VALUE : Integer.parseInt(argument._maxOccurs$().text()); if (maxOccurs == 1) { if (isRequired) OptionBuilder.hasArgs(1); else OptionBuilder.hasOptionalArgs(1); } else if (maxOccurs == Integer.MAX_VALUE) { if (isRequired) OptionBuilder.hasArgs(); else OptionBuilder.hasOptionalArgs(); } else { if (isRequired) OptionBuilder.hasArgs(maxOccurs); else OptionBuilder.hasOptionalArgs(maxOccurs); } final char valueSeparator = argument._valueSeparator$().text() != null ? argument._valueSeparator$().text().charAt(0) : ' '; OptionBuilder.withArgName( formatArgumentName(argument._label$().text(), maxOccurs, valueSeparator)); OptionBuilder.withValueSeparator(valueSeparator); if (option._description(0).isNull()) { logger.error("missing <description> for " + name + " option"); System.exit(1); } final StringBuilder description = new StringBuilder(option._description(0).text()); if (!option._argument(0)._default$().isNull()) description.append("\nDefault: ").append(option._argument(0)._default$().text()); OptionBuilder.withDescription(description.toString()); } apacheOptions.addOption(OptionBuilder.create(shortName)); } } } else { cliArguments = null; } final Map<String, Option> optionsMap = new HashMap<String, Option>(); final Set<String> specifiedLongNames; CommandLine commandLine = null; if (args != null && args.length != 0) { specifiedLongNames = new HashSet<String>(); final CommandLineParser parser = new PosixParser(); do { try { commandLine = parser.parse(apacheOptions, args); } catch (final UnrecognizedOptionException e) { if (e.getMessage().startsWith("Unrecognized option: ")) { final String unrecognizedOption = e.getMessage().substring(21); logger.error("Unrecognized option: " + unrecognizedOption); for (int i = 0; i < args.length; i++) if (args[i].equals(unrecognizedOption)) args[i] = "--help"; } else { throw new OptionsException(e); } } catch (final org.apache.commons.cli.ParseException e) { Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err); } } while (commandLine == null); } else { specifiedLongNames = null; } final Collection<String> arguments = commandLine != null ? commandLine.getArgList() : null; if (arguments != null && arguments.size() > 0) { if (argumentsMaxOccurs < arguments.size() || arguments.size() < argumentsMinOccurs) { Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err); } } else if (argumentsMinOccurs > 0) { Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err); } if (commandLine != null) { for (final org.apache.commons.cli.Option option : commandLine.getOptions()) { specifiedLongNames.add(option.getLongOpt()); if ("help".equals(option.getLongOpt())) Options.trapPrintHelp(apacheOptions, cliArguments, null, System.out); final String optionName = option.getLongOpt() != null ? option.getLongOpt() : option.getOpt(); optionsMap.put(optionName, option.getValue() != null ? new Option(optionName, option.getValueSeparator(), option.getValues()) : new Option(optionName, option.getValueSeparator(), "true")); } } // See if some arguments are missing if (requiredNames.size() != 0) { if (specifiedLongNames != null) requiredNames.removeAll(specifiedLongNames); if (requiredNames.size() != 0) { final StringBuilder builder = new StringBuilder(); for (final String longName : requiredNames) { final String shortName = nameToAltName.get(longName); if (shortName.equals(longName)) builder.append("\nMissing argument: -").append(shortName); else builder.append("\nMissing argument: -").append(shortName).append(",--").append(longName); } Options.trapPrintHelp(apacheOptions, cliArguments, builder.substring(1), System.out); } } // Include default values for options that are not specified if (binding._option() != null) { for (final cli_cli._option option : binding._option()) { if (!option._argument(0)._default$().isNull()) { final String optionName = !option._name(0)._long$().isNull() ? option._name(0)._long$().text() : option._name(0)._short$().text(); if (!optionsMap.containsKey(optionName)) { final String valueSeparator = option._argument(0)._valueSeparator$().text(); final String defaultValue = option._argument(0)._default$().text(); optionsMap.put(optionName, valueSeparator != null ? new Option(optionName, valueSeparator.charAt(0), defaultValue) : new Option(optionName, defaultValue)); } } } } // Check pattern for specified and default options if (binding._option() != null) { final StringBuilder builder = new StringBuilder(); for (final cli_cli._option option : binding._option()) { if (!option._argument(0)._pattern$().isNull()) { final String optionName = !option._name(0)._long$().isNull() ? option._name(0)._long$().text() : option._name(0)._short$().text(); final Option opt = optionsMap.get(optionName); if (opt != null) { for (final String value : opt.getValues()) { if (!value.matches(option._argument(0)._pattern$().text())) { if (option._name(0)._long$().isNull() || option._name(0)._short$().isNull()) builder.append("\nIncorrect argument form: -").append(optionName); else builder.append("\nIncorrect argument form: -") .append(option._name(0)._short$().text()).append(",--") .append(option._name(0)._long$().text()); builder.append(" ").append(value).append("\n Required: ") .append(option._argument(0)._pattern$().text()); } } } } } if (builder.length() > 0) Options.trapPrintHelp(apacheOptions, cliArguments, builder.substring(1), System.out); } return new Options(mainClass, args, optionsMap.values(), arguments == null || arguments.size() == 0 ? null : arguments.toArray(new String[arguments.size()])); }
From source file:org.libx4j.cli.Options.java
public String getOption(final String name) { final Option options = optionNameToOption.get(name); return options == null || options.getValues().length == 0 ? null : options.getValues().length == 1 ? options.getValues()[0] : Arrays.toString(options.getValues(), options.getValueSeparator()); }
From source file:org.mitre.ccv.mapred.CompleteCompositionVectors.java
/** * * The JSO data will be the same as {@link org.mitre.ccv.CompleteMatrix#jsonCompleteMatrix}, but the features * will be in a different order. This version, by default sorts, only by entropy values, whereas the * ccv in-memory version sorts by the k-mer natural order (i.e., lexigraphic). * @param argv/* ww w . jav a 2 s . co m*/ * @return * @throws java.lang.Exception */ @Override @SuppressWarnings("static-access") // For OptionBuilder public int run(String[] argv) throws Exception { JobConf conf = new JobConf(getConf()); String cli_title = "CompleteCompositionVectorHadoop"; int start = CalculateKmerCounts.DEFAULT_START; int end = CalculateKmerCounts.DEFAULT_END; int topkmers = 0; String input = null; String output = null; String vectorJsonOutput = null; //String kmerJsonOutput = null; boolean cleanLogs = false; /** create the Options */ Options options = new Options(); /** Hadoop Options */ options.addOption( OptionBuilder.withArgName("number").hasArg(true).withDescription("number of maps").create("m")); options.addOption( OptionBuilder.withArgName("number").hasArg(true).withDescription("number of reducers").create("r")); // org.hadoop.util.GenericOptionsParser should captures this, but it doesn't options.addOption(OptionBuilder.withArgName("property=value").hasArg(true).withValueSeparator() .withDescription("use value for given property").create("D")); /** CompleteCompositionVector Options */ options.addOption(OptionBuilder.withArgName("number").hasArg(true) .withDescription("number of top k-mers to use in calculations").create("topKmers")); options.addOption(OptionBuilder.withArgName("start").hasArg(true).withDescription("starting length of tile") .create("start")); options.addOption(OptionBuilder.withArgName("end").hasArg(true).withDescription("ending length of title") .create("end")); options.addOption(OptionBuilder.hasArg(true).withArgName("file") .withDescription("JSON file to write out k-mers to").create("kmersfile")); options.addOption(OptionBuilder.hasArg(true).withArgName("file") .withDescription("JSON file to write out feature vectors to " + "(Overrides kmersout, only one file will be written).") .create("vectorsfile")); options.addOption(OptionBuilder.withArgName("number").hasArg(true) .withDescription("What preference to use: 0-min 1-median 2-avg(min,med): default is median") .create("prefval")); options.addOption(OptionBuilder.withArgName("help").hasArg(false).withDescription("print this message") .create("help")); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); //GenericOptionsParser gop = new GenericOptionsParser(conf, options, argv); GenericOptionsParser gop = new GenericOptionsParser(conf, argv); String[] remaining_args = gop.getRemainingArgs(); // create the parser CommandLineParser parser = new GnuParser(); //CommandLine line = gop.getCommandLine(); String[] other_args = new String[] {}; try { CommandLine line = parser.parse(options, remaining_args); other_args = line.getArgs(); // Make sure there is a parameter left. if (other_args.length == 0) { System.out.println(cli_title); System.out.println("Missing input path!"); formatter.printHelp("hccv [options] <input> [<output>] ", options); GenericOptionsParser.printGenericCommandUsage(System.out); return -1; } Option[] opts = line.getOptions(); if (line.hasOption("help")) { System.out.println(cli_title); formatter.printHelp("hccv [options] <input> [<output>] ", options); GenericOptionsParser.printGenericCommandUsage(System.out); return -1; } // could also use line.iterator() for (Option opt : opts) { if (opt.getOpt().equals("m")) { conf.setNumMapTasks(Integer.parseInt(opt.getValue())); } if (opt.getOpt().equals("r")) { conf.setNumReduceTasks(Integer.parseInt(opt.getValue())); } if (opt.getOpt().equals("D")) { // We can have multiple properties we want to set String[] properties = opt.getValues(); for (String property : properties) { String[] keyval = property.split("="); conf.set(keyval[0], keyval[1]); } } if (opt.getOpt().equals("start")) { start = Integer.parseInt(opt.getValue()); } if (opt.getOpt().equals("end")) { end = Integer.parseInt(opt.getValue()); } if (opt.getOpt().equals("topKmers")) { topkmers = Integer.parseInt(opt.getValue()); } if (opt.getOpt().equals("vectorsfile")) { vectorJsonOutput = opt.getValue(); } } } catch (ParseException e) { LOG.warn("options parsing faild: " + e.getMessage()); System.out.println(cli_title); formatter.printHelp("hccv [options] <input> [<output>] ", options); GenericOptionsParser.printGenericCommandUsage(System.out); } if (start <= 2) { throw new IllegalArgumentException("Value of 'start' argument must be larger than 2"); } input = other_args[0]; if (other_args.length < 2) { output = input + "_" + FileUtils.getSimpleDate(); } else { output = other_args[2]; } /** * Check output path. Either needs to exist as a directory or not exist */ Path outputPath = new Path(output); FileSystem fs = outputPath.getFileSystem(conf); if (!fs.exists(outputPath)) { fs.mkdirs(outputPath); } else if (fs.exists(outputPath) || !fs.getFileStatus(outputPath).isDir()) { LOG.fatal(String.format("Output directory %s already exists", outputPath.makeQualified(fs))); throw new FileAlreadyExistsException( String.format("Output directory %s already exists", outputPath.makeQualified(fs))); } String outputDir = output + Path.SEPARATOR; int res; /** * Zero, CalculateCompositionVectors */ LOG.info("Starting CalculateCompositionVectors Map-Reduce job"); CalculateCompositionVectors cv = new CalculateCompositionVectors(); res = cv.initJob(conf, start, end, input, outputDir + COMPOSITION_VECTORS, cleanLogs); if (res != 0) { LOG.info("CalculateCompositionVectors returned non-zero result!"); return res; } // We can stop now or continue to reduce dimensionallity using RRE or other means /** * First, CalculateKmerCounts */ LOG.info("Starting CalculateKmerCounts Map-Reduce job"); // FastMap option for CalculateKmers!?! CalculateKmerCounts ckc = new CalculateKmerCounts(); res = ckc.initJob(conf, start, end, input, outputDir + KMER_COUNTS); if (res != 0) { LOG.fatal("CalculateKmerCounts returned non-zero result!"); return res; } /** * Second, TotalSequenceLength */ LOG.info("Starting TotalSequenceLength Map-Reduce job"); TotalSequenceLength tsl = new TotalSequenceLength(); res = tsl.initJob(conf, input, outputDir + TOTAL_LENGTH, cleanLogs); if (res != 0) { LOG.fatal("TotalSequenceLength returned non-zero result!"); return res; } int length = tsl.getCount(conf, outputDir + TOTAL_LENGTH); if (length < 3) { LOG.fatal("TotalSequenceLength returned a total sequence length of less than 3."); return -1; } else { LOG.info(String.format("TotalSequenceLength returned a total sequence length of %d.", length)); } /** * Third, CalculateKmerProbabilities */ LOG.info("Starting CalculateKmerProbabilities Map-Reduce job"); CalculateKmerProbabilities ckp = new CalculateKmerProbabilities(); res = ckp.initJob(conf, start, end, length, outputDir + KMER_COUNTS, outputDir + KMER_PROBABILITIES, cleanLogs); if (res != 0) { LOG.fatal("CalculateKmerProbabilities returned non-zero result!"); return res; } /** * Fourth, InvertKmerProbabilities */ LOG.info("Starting InvertKmerProbabilities Map-Reduce job"); InvertKmerProbabilities ikp = new InvertKmerProbabilities(); res = ikp.initJob(conf, outputDir + KMER_PROBABILITIES, outputDir + INVERTED_KMER_PROBABILITIES, cleanLogs); if (res != 0) { LOG.fatal("InvertKmerProbabilities returned non-zero result!"); return res; } /** * Fifth, CalculateKmerPiValues */ LOG.info("Starting CalculateKmerPiValues Map-Reduce job"); CalculateKmerPiValues kpv = new CalculateKmerPiValues(); res = kpv.initJob(conf, start, end, outputDir + INVERTED_KMER_PROBABILITIES, outputDir + KMER_PI_VALUES, cleanLogs); if (res != 0) { LOG.fatal("CalculateKmerPiValues returned non-zero result!"); return res; } /** * Sixth,CalculateKmerRevisedRelativeEntropy */ LOG.info("Starting CalculateKmerRevisedRelativeEntropy Map-Reduce job"); CalculateKmerRevisedRelativeEntropy krre = new CalculateKmerRevisedRelativeEntropy(); res = krre.initJob(conf, outputDir + KMER_PI_VALUES, outputDir + COMPOSITION_VECTORS, outputDir + ENTROPY_VALUES, cleanLogs); if (res != 0) { LOG.fatal("CalculateKmerRevisedRelativeEntropy returned non-zero result!"); return res; } /** * Seventh, SortKmerRevisedRelativeEntropies */ SortKmerRevisedRelativeEntropies srre = new SortKmerRevisedRelativeEntropies(); res = srre.initJob(conf, outputDir + ENTROPY_VALUES, outputDir + SORTED_ENTROPY_VALUES, cleanLogs); if (res != 0) { LOG.fatal("SortKmerRevisedRelativeEntropies returned non-zero result!"); return res; } /** * Eigth, GenerateFeatureVectors * * Generate a flatten list to add to the cache to be distributed to the map-tasks. */ Path listOutputPath = new Path(outputDir + Integer.toString(topkmers) + KMER_ENTROPY_SET); LOG.info(String.format("Loading %d sorted k-mers from %s to %s", topkmers, outputDir + SORTED_ENTROPY_VALUES, listOutputPath.toString())); int num = CompleteCompositionVectorUtils.flattenKmerEntropySequenceFile(conf, topkmers, outputDir + SORTED_ENTROPY_VALUES, listOutputPath.toString(), cleanLogs); if (num != topkmers) { LOG.fatal(String.format("Requested %d k-mers, but got %d. Using %d", topkmers, num, num)); topkmers = num; } GenerateFeatureVectors fv = new GenerateFeatureVectors(); res = fv.initJob(conf, listOutputPath.toString(), topkmers, outputDir + COMPOSITION_VECTORS, outputDir + FEATURE_VECTORS, cleanLogs); if (res != 0) { LOG.fatal("GenerateFeatureVectors returned non-zero result!"); return res; } /** * Save feature vectors, features (k-mers), and properties to a JSON file. * * The data will be the same as {@link org.mitre.ccv.CompleteMatrix#jsonCompleteMatrix}, but the features * will be in a different order. This version, by default sorts, only by entropy values, whereas the * ccv in-memory version sorts by the k-mer natural order (i.e., lexigraphic). */ if (vectorJsonOutput != null && vectorJsonOutput.length() > 0) { LOG.info("Writing features out to " + vectorJsonOutput); CompleteCompositionVectorUtils.featureVectors2Json(conf, start, end, topkmers, outputDir + SORTED_ENTROPY_VALUES, outputDir + FEATURE_VECTORS, vectorJsonOutput); } LOG.info("All done generating complete composition vectors and feature vectors."); return res; }
From source file:org.obiba.genobyte.cli.GenotypeReportCommand.java
/** * Executes the file loading procedure. The type and filename are extracted from the <tt>Option</tt> instance. * The method {@link GenotypeReport#loadFile(CliContext, File)} is called on the appropriate instance. If no such instance * exists, an error message is printed on the {@link CliContext#getOutput()} stream. *///from w ww.j a va2 s . co m public boolean execute(Option opt, CliContext context) throws ParseException { String args[] = opt.getValues(); if (args == null || args.length == 0) { context.getOutput().println( "Missing argument to genotype report command. Please specify the type of report to obtain."); return false; } String type = args[0]; GenotypeReport r = null; for (GenotypeReport report : reports_) { if (report.getReportType().equalsIgnoreCase(type) || (type.length() == 1 && report.getShortReportType() == type.charAt(0))) { r = report; break; } } if (r == null) { context.getOutput() .println("There is no genotype report registered for the type [" + type + "] specified."); return false; } int filesToOutput = r.getNumberOfOutputFiles(); File[] outputFiles = new File[filesToOutput]; Set<String> filenames = new TreeSet<String>(); for (int i = 0; i < filesToOutput; i++) { String filename = r.getDefaultFileName(i); // Find user specified filename int found = 0; for (int j = 1; j < args.length; j++) { // Iterate on all arguments until we find a parameter that is not a query reference and that is the ith filename found. if (context.getHistory().isQueryReference(args[j]) == false && i == found++) { filename = args[j]; } } // No filename specified by report nor by user: generate one if (filename == null) { filename = r.getReportType() + "-file" + i + ".txt"; } if (filenames.add(filename) == false) { context.getOutput().println("The filename [" + filename + "] is already used as an output for this report. Please specify disctinct filenames for each output file."); return false; } outputFiles[i] = new File(filename); if (outputFiles[i].exists() && outputFiles[i].canWrite() == false) { context.getOutput().println("Cannot write to file [" + filename + "]."); return false; } } GenotypingRecordStore<?, ?, ?> assays = context.getStore().getAssayRecordStore(); GenotypingRecordStore<?, ?, ?> samples = context.getStore().getSampleRecordStore(); QueryResult assayMask = new BitVectorQueryResult(assays.getStore().all()); QueryResult sampleMask = new BitVectorQueryResult(samples.getStore().all()); for (int i = 1; i < args.length; i++) { String arg = args[i]; if (context.getHistory().isQueryReference(arg) == true) { QueryExecution qe = context.getHistory().resolveQuery(arg); if (qe != null && qe.getStore() == assays) { assayMask = qe.getResult(); } else if (qe != null && qe.getStore() == samples) { sampleMask = qe.getResult(); } } } context.getOutput() .println("Creating [" + r.getReportType() + "] report on " + sampleMask.count() + " samples and " + assayMask.count() + " assays. Outputing report to file(s) " + Arrays.toString(outputFiles)); try { r.generateReport(context.getStore(), sampleMask, assayMask, outputFiles); } catch (RuntimeException e) { context.getOutput().println( "An unexpected error occured while generating the report. The reported error message was: " + e.getMessage()); e.printStackTrace(); } return false; }
From source file:org.obiba.genobyte.cli.LoadFileCommand.java
/** * Executes the file loading procedure. The type and filename are extracted from the <tt>Option</tt> instance. * The method {@link FileTypeLoader#loadFile(CliContext, File)} is called on the appropriate instance. If no such instance * exists, an error message is printed on the {@link CliContext#getOutput()} stream. *//*w ww . j ava 2 s.co m*/ public boolean execute(Option opt, CliContext context) throws ParseException { String args[] = opt.getValues(); if (args == null || args.length != 2) { context.getOutput().println( "Missing argument to load command. Please specify the type of file and the filename to load."); return false; } String type = args[0]; String filename = args[1]; FileTypeLoader l = null; for (FileTypeLoader loader : loaders_) { if (loader.getFileType().equalsIgnoreCase(type) || (type.length() == 1 && loader.getShortFileType() == type.charAt(0))) { l = loader; break; } } if (l == null) { context.getOutput() .println("There is no loader registered for the file type [" + type + "] specified."); return false; } if (l.requiresOpenStore() && context.getStore() == null) { context.getOutput().println("Open a store before loading a file of type [" + l.getFileType() + "]"); return false; } File files[] = WildcardFileFilter.listFiles(new File("."), filename); if (files == null || files.length == 0) { context.getOutput().println("No match for filename [" + filename + "]."); return false; } for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.canRead() == false) { context.getOutput().println("The file [" + f.getName() + "] cannot be read."); return false; } } if (files.length > 1 && l.allowsMultipleFile() == false) { context.getOutput().println("Cannot load multiple files of type [" + l.getFileType() + "]. Please specify only one file to load."); return false; } if (files.length > 1) { context.getOutput().println("Loading files " + Arrays.toString(files)); } else { context.getOutput().println("Loading file [" + files[0].getName() + "]"); } l.loadFiles(context, files); return false; }
From source file:org.obiba.genobyte.cli.ReportCommand.java
/** * Launches the report generation. The type of report to be produced and the output filename are extracted * from the <tt>Option</tt> instance. * The method {@link ReportProducer#generateReport(CliContext, File)} is called on the appropriate instance. * If no such instance exists, an error message is printed on the {@link CliContext#getOutput()} stream. *///from w w w .j av a 2 s. c o m public boolean execute(Option opt, CliContext context) throws ParseException { String args[] = opt.getValues(); if (args == null || args.length == 0) { context.getOutput().println("Missing argument to report command. Please specify the type of report."); return false; } String reportType = args[0]; String reportFilename = null; if (args.length > 1) { reportFilename = args[1]; } String[] parameters = null; if (args.length > 2) { parameters = new String[args.length - 2]; for (int i = 2; i < args.length; i++) { parameters[i - 2] = args[i]; } } ReportProducer r = null; for (ReportProducer report : reports_) { if (report.getReportType().equalsIgnoreCase(reportType)) { r = report; break; } } // Error if no report with such name exists if (r == null) { context.getOutput() .println("There is no producer registered for the report type [" + reportType + "]."); return false; } // Error if store is not opened yet but is required (we could want to generate report on non store-related information) if (r.requiresOpenStore() && context.getStore() == null) { context.getOutput().println("Open a store before loading a file of type [" + r.getReportType() + "]"); return false; } boolean closeStream = false; PrintStream output = context.getOutput(); if (reportFilename != null && reportFilename.equals("-") == false) { try { output = new PrintStream(new FileOutputStream(reportFilename)); closeStream = true; } catch (IOException e) { context.getOutput().println("Cannot output to file [" + reportFilename + "]: " + e.getMessage()); return false; } } else { reportFilename = "console output"; } context.getOutput().println( "Producing report type [" + r.getReportType() + "]. Outputing report to [" + reportFilename + "]."); try { r.generateReport(context, parameters, output); } catch (Exception e) { context.getOutput().println("An error occured during the report generation: " + e.getMessage()); e.printStackTrace(); } finally { if (closeStream) { try { output.close(); } catch (Throwable t) { //ignore } } } return false; }
From source file:org.objectweb.proactive.examples.fastdeployment.Main.java
public void parseArguments(String[] args) { CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption(Params.concurrency.sOpt, Params.concurrency.toString(), true, Params.concurrency.desc); options.addOption(Params.pause.sOpt, Params.pause.toString(), true, Params.pause.desc); Option descOption;/*from w w w. j a va2s . co m*/ descOption = new Option(Params.descriptor.sOpt, Params.descriptor.toString(), true, Params.descriptor.desc); descOption.setArgs(Option.UNLIMITED_VALUES); options.addOption(descOption); Option vnOption; vnOption = new Option(Params.virtualNode.sOpt, Params.virtualNode.toString(), true, Params.virtualNode.desc); vnOption.setArgs(Option.UNLIMITED_VALUES); options.addOption(vnOption); CommandLine line = null; String arg; try { line = parser.parse(options, args); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fast Deployment", options); System.exit(1); } Option[] pOptions = line.getOptions(); for (Option pOption : pOptions) { if (pOption.getOpt().equals(Params.virtualNode.sOpt)) { for (String s : pOption.getValues()) { virtualNodes.add(s); } } if (pOption.getOpt().equals(Params.descriptor.sOpt)) { for (String s : pOption.getValues()) { descriptors.add(s); } } } arg = line.getOptionValue(Params.concurrency.sOpt); if (arg != null) { try { concurrency = new Integer(arg); } catch (NumberFormatException e) { logger.warn("Invalid option value " + arg); } } arg = line.getOptionValue(Params.pause.sOpt); if (arg != null) { try { pause = new Integer(arg); } catch (NumberFormatException e) { logger.warn("Invalid option value " + arg); } } }
From source file:org.stathissideris.ascii2image.core.CommandLineConverter.java
private static void printRunInfo(CommandLine cmdLine) { System.out.println("\n" + notice + "\n"); System.out.println("Running with options:"); Option[] opts = cmdLine.getOptions(); for (Option option : opts) { if (option.hasArgs()) { for (String value : option.getValues()) { System.out.println(option.getLongOpt() + " = " + value); }//from w ww . j a v a2 s . com } else if (option.hasArg()) { System.out.println(option.getLongOpt() + " = " + option.getValue()); } else { System.out.println(option.getLongOpt()); } } }
From source file:org.vetmeduni.tools.AbstractTool.java
/** * Get the arguments with the string/* w w w .ja va 2 s .com*/ * * @param cmd the already parsed command line with the programParser * * @return the string with the arguments in the command line properly formatted */ protected String getCmdLineString(CommandLine cmd) { StringBuilder builder = new StringBuilder(""); for (Option opt : cmd.getOptions()) { if (opt.hasArg()) { for (String val : opt.getValues()) { builder.append("--"); builder.append(opt.getLongOpt()); builder.append(" "); builder.append(val); builder.append(" "); } } else { builder.append("--"); builder.append(opt.getLongOpt()); builder.append(" "); } } return builder.toString(); }