List of usage examples for org.apache.commons.cli Option getValue
public String getValue(String defaultValue)
defaultValue
if there is no value. From source file:com.netflix.subtitles.cli.TtmlConverterCmdLineParser.java
private int parseTtmlParameter(Option option, int optionIndex, String parameterName) { try {//from w ww. j ava2 s . c o m return Integer.parseInt(option.getValue(optionIndex)); } catch (NumberFormatException e) { throw new ParseException(parameterName + " in --ttml must be an integer"); } }
From source file:com.netflix.cc.cli.CmdLineParametersParser.java
private int parseTtmlParameter(Option option, int optionIndex, String parameterName) throws ParseException { try {/*from w w w. ja va 2 s .c om*/ return Integer.parseInt(option.getValue(optionIndex)); } catch (NumberFormatException e) { throw new ParseException(parameterName + " in --ttml must be an integer"); } }
From source file:com.netflix.cc.cli.CmdLineParametersParser.java
/** * Parses cmd line arguments./* w ww . j a v a 2 s. co m*/ * * @param args arguments from a command line * @return a command line parameter object or null if help was invoked. */ public CmdLineParameters parseCmdOptions(String[] args) throws ParseException { // create the parser CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); // --help if (line.hasOption(help.getLongOpt())) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("ttml-to-stl", options); return null; } CmdLineParameters result = new CmdLineParameters(); // --ttml parameters for (Option option : line.getOptions()) { if (option.equals(ttmlFile)) { TtmlInDescriptor ttmlInDescriptor = new TtmlInDescriptor(); try { ttmlInDescriptor.setFile(option.getValue(0)); ttmlInDescriptor.setOffsetMS(parseTtmlParameter(option, 1, "offsetMS")); ttmlInDescriptor.setStartMS(parseTtmlParameter(option, 2, "startMS")); ttmlInDescriptor.setEndMS(parseTtmlParameter(option, 3, "endMS")); } catch (IndexOutOfBoundsException e) { //It is error only if don't have file name //For required file it may not be thrown. We will check it later. } if (ttmlInDescriptor.getFile() == null) { throw new ParseException("--ttml parameter must have at least <file> attribute defined."); } result.getTtmlInDescriptors().add(ttmlInDescriptor); } } if (result.getTtmlInDescriptors().isEmpty()) { throw new ParseException("At least one input TTML file must be provided"); } // TTML mode parameters boolean doOutputTTML = line.hasOption(outputTtml.getLongOpt()); if (doOutputTTML) { result.setDoOuputTtml(true); result.setOutputTtmlFile(line.getOptionValue(outputTtml.getLongOpt())); } // SCC mode parameters boolean doOutputScc = line.hasOption(outputScc.getLongOpt()); if (doOutputScc) { result.setDoOutputScc(true); result.setOutputSccFile(line.getOptionValue(outputScc.getLongOpt())); } return result; }
From source file:com.netflix.imfutility.ttmltostl.inputparameters.CmdLineParametersParser.java
/** * Parses cmd line arguments.// w w w.j ava 2 s . c om * * @param args arguments from a command line * @return a command line parameter object or null if help was invoked. */ public CmdLineParameters parseCmdOptions(String[] args) throws ParseException { // create the parser CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); // --help if (line.hasOption(help.getLongOpt())) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("ttml-to-stl", options); return null; } CmdLineParameters result = new CmdLineParameters(); // --ttml parameters for (Option option : line.getOptions()) { if (option.equals(ttmlFile)) { TtmlInDescriptor ttmlInDescriptor = new TtmlInDescriptor(); try { ttmlInDescriptor.setFile(option.getValue(0)); ttmlInDescriptor.setOffsetMS(parseTtmlParameter(option, 1, "offsetMS")); ttmlInDescriptor.setStartMS(parseTtmlParameter(option, 2, "startMS")); ttmlInDescriptor.setEndMS(parseTtmlParameter(option, 3, "endMS")); } catch (IndexOutOfBoundsException e) { //It is error only if don't have file name //For required file it may not be thrown. We will check it later. } if (ttmlInDescriptor.getFile() == null) { throw new ParseException("--ttml parameter must have at least <file> attribute defined."); } result.getTtmlInDescriptors().add(ttmlInDescriptor); } } if (result.getTtmlInDescriptors().size() == 0) { throw new ParseException("At least one input TTML file must be provided"); } // TTML mode parameters boolean doOutputTTML = line.hasOption(outputTTML.getLongOpt()); if (doOutputTTML) { result.setDoOuputTTML(true); result.setOutputTTMLFile(line.getOptionValue(outputTTML.getLongOpt())); } // STL mode parameters boolean doOutputSTL = line.hasOption(outputSTL.getLongOpt()); if (doOutputSTL) { result.setDoOutputSTL(true); result.setOutputSTLFile(line.getOptionValue(outputSTL.getLongOpt())); if (!line.hasOption(metadataOpt.getLongOpt())) { throw new ParseException("A metadata.xml must be specified for STL mode"); } String metadataXml = line.getOptionValue(metadataOpt.getLongOpt()); if (!new File(metadataXml).isFile()) { throw new ParseException("A metadata.xml must be an existing file."); } result.setMetadataXml(metadataXml); } return result; }
From source file:com.databasepreservation.cli.CLI.java
/** * Obtains the arguments needed to create new import and export modules * * @param factoriesPair/*from w w w . j a va 2s . co m*/ * A pair of DatabaseModuleFactory objects containing the selected * import and export module factories * @param args * The command line arguments * @return A DatabaseModuleFactoriesArguments containing the arguments to * create the import and export modules * @throws ParseException * If the arguments could not be parsed or are invalid */ private DatabaseModuleFactoriesArguments getModuleArguments(DatabaseModuleFactoriesPair factoriesPair, List<String> args) throws ParseException, OperationNotSupportedException { DatabaseModuleFactory importModuleFactory = factoriesPair.getImportModuleFactory(); DatabaseModuleFactory exportModuleFactory = factoriesPair.getExportModuleFactory(); // get appropriate command line options CommandLineParser commandLineParser = new DefaultParser(); CommandLine commandLine; Options options = new Options(); HashMap<String, Parameter> mapOptionToParameter = new HashMap<String, Parameter>(); for (Parameter parameter : importModuleFactory.getImportModuleParameters().getParameters()) { Option option = parameter.toOption("i", "import"); options.addOption(option); mapOptionToParameter.put(getUniqueOptionIdentifier(option), parameter); } for (ParameterGroup parameterGroup : importModuleFactory.getImportModuleParameters().getGroups()) { OptionGroup optionGroup = parameterGroup.toOptionGroup("i", "import"); options.addOptionGroup(optionGroup); for (Parameter parameter : parameterGroup.getParameters()) { mapOptionToParameter.put(getUniqueOptionIdentifier(parameter.toOption("i", "import")), parameter); } } for (Parameter parameter : exportModuleFactory.getExportModuleParameters().getParameters()) { Option option = parameter.toOption("e", "export"); options.addOption(option); mapOptionToParameter.put(getUniqueOptionIdentifier(option), parameter); } for (ParameterGroup parameterGroup : exportModuleFactory.getExportModuleParameters().getGroups()) { OptionGroup optionGroup = parameterGroup.toOptionGroup("e", "export"); options.addOptionGroup(optionGroup); for (Parameter parameter : parameterGroup.getParameters()) { mapOptionToParameter.put(getUniqueOptionIdentifier(parameter.toOption("e", "export")), parameter); } } Option importOption = Option.builder("i").longOpt("import").hasArg().optionalArg(false).build(); Option exportOption = Option.builder("e").longOpt("export").hasArg().optionalArg(false).build(); Option pluginOption = Option.builder("p").longOpt("plugin").hasArg().optionalArg(false).build(); options.addOption(importOption); options.addOption(exportOption); options.addOption(pluginOption); // new HelpFormatter().printHelp(80, "dbptk", "\nModule Options:", options, // null, true); // parse the command line arguments with those options try { commandLine = commandLineParser.parse(options, args.toArray(new String[] {}), false); if (!commandLine.getArgList().isEmpty()) { throw new ParseException("Unrecognized option: " + commandLine.getArgList().get(0)); } } catch (MissingOptionException e) { // use long names instead of short names in the error message List<String> missingShort = e.getMissingOptions(); List<String> missingLong = new ArrayList<String>(); for (String shortOption : missingShort) { missingLong.add(options.getOption(shortOption).getLongOpt()); } LOGGER.debug("MissingOptionException (the original, unmodified exception)", e); throw new MissingOptionException(missingLong); } // create arguments to pass to factory HashMap<Parameter, String> importModuleArguments = new HashMap<Parameter, String>(); HashMap<Parameter, String> exportModuleArguments = new HashMap<Parameter, String>(); for (Option option : commandLine.getOptions()) { Parameter p = mapOptionToParameter.get(getUniqueOptionIdentifier(option)); if (p != null) { if (isImportModuleOption(option)) { if (p.hasArgument()) { importModuleArguments.put(p, option.getValue(p.valueIfNotSet())); } else { importModuleArguments.put(p, p.valueIfSet()); } } else if (isExportModuleOption(option)) { if (p.hasArgument()) { exportModuleArguments.put(p, option.getValue(p.valueIfNotSet())); } else { exportModuleArguments.put(p, p.valueIfSet()); } } else { throw new ParseException("Unexpected parse exception occurred."); } } } return new DatabaseModuleFactoriesArguments(importModuleArguments, exportModuleArguments); }
From source file:org.efaps.cli.StartUp.java
/** * The main method.//from w ww .j ava 2s . co m * * @param _args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(final String[] _args) throws IOException { LOG.info("Startup at {}", new Date()); final Options options = new Options() .addOption( Option.builder("l").numberOfArgs(2).desc("set login information").longOpt("login").build()) .addOption(Option.builder("u").numberOfArgs(1).desc("set url").longOpt("url").build()) .addOption(Option.builder("ll").numberOfArgs(1) .desc("set Log Level, One of 'ALL','TRACE','DEBUG','INFO','WARN','ERROR', 'OFF'") .longOpt("logLevel").build()) .addOption(Option.builder("h").desc("print this help information").longOpt("help").build()); final CommandLineParser parser = new DefaultParser(); try { final CommandLine cmd = parser.parse(options, _args); if (cmd.hasOption("h")) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("eFaps-CLI", options); } else { final Shell shell = ShellBuilder.shell("eFaps").behavior() .setHistoryFile(new File(System.getProperty("user.home") + "/.eFapsCLI", "history")) .addHandler(ContextHandler.get()).addHandler(new CommandHandler()) .addHandler(new MessageResolver()).addHandler(new EQLHandler()) .addHandler(EQLObserver.get()).addHandler(new EQLCandidatesChooser()) .addHandler(new EQLFilter()).build(); shell.setAppName("\"eFaps Command Line Interface\""); for (final Option opt : cmd.getOptions()) { switch (opt.getOpt()) { case "l": shell.getEnvironment().setVariable(CLISettings.USER, opt.getValue(0)); shell.getEnvironment().setVariable(CLISettings.PWD, opt.getValue(1)); break; case "u": shell.getEnvironment().setVariable(CLISettings.URL, opt.getValue()); break; case "ll": LOG.info("Setting Log level to {}", opt.getValue()); final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(Logger.ROOT_LOGGER_NAME); root.setLevel(Level.toLevel(opt.getValue())); LOG.info("ROOT Log level set to {}", root.getLevel()); break; default: break; } } shell.processLine("company " + ContextHandler.FAKECOMPANY); shell.commandLoop(); } } catch (final ParseException e) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("eFaps-CLI", options); LOG.error("ParseException", e); } catch (final CLIException e) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("eFaps-CLI", options); LOG.error("ParseException", e); } }
From source file:org.jcryptool.commands.core.HelpCommand.java
/** * Recovers the command line form of which a CommandLine object could've originated from. Assumes, that all options * have been stated in short form./*from w ww.j a va 2s. co m*/ * * @param commandName the name of the command * @param cmdLine the CommandLine object to parse * @return a command line, which would parse to a CommandLine object equal to the given one. */ public static String reverseCommandline(String commandName, CommandLine cmdLine) { StringBuilder builder = new StringBuilder(); builder.append(commandName); for (String arg : cmdLine.getArgs()) { builder.append(" " + arg); //$NON-NLS-1$ } for (Option option : cmdLine.getOptions()) { builder.append(" -" + option.getOpt()); //$NON-NLS-1$ for (int i = 0; i < option.getArgs(); i++) { builder.append(" " + (option.getValue(i).contains(" ") ? "\"" + option.getValue(i) + "\"" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ : option.getValue(i))); } } return builder.toString(); }
From source file:org.mitre.ccv.weka.CompositionCompositionVectorClassifiers.java
/** * Min things needed://from ww w. ja v a2s. com * 1) a json file with ccv params, nmers and vectors, and a fasta file with * samples to classify * 2) a json file with ccv params and nmers, a classifier file, and a fasta file * with samples to classify * * @param argv * @throws java.lang.Exception */ @SuppressWarnings("static-access") public static void main(String[] argv) throws FileNotFoundException, JSONException { CompositionCompositionVectorClassifiers ccvc = new CompositionCompositionVectorClassifiers(); /** JSON file with data set. */ FileReader dataSetReader = null; /** Optional sequences to generate ccvs and classify. */ FastaIterator seqIter = null; /** Optional filename to output the classifier to. */ String outputModelFileName = null; /** Optional filename to input the classifer from. */ String inputModelFileName = null; /** Optional filename (also need a JSON data set) to input sequence data from. */ String inputDataFileName = null; /** Optional filename for the JSON data set containing features and window sizes. */ String inputJsonFileName = null; /** If set, do cross-validation numFolds and quit. */ Integer numFolds = null; /** How to parse the sample name */ int nameParser = 1; /** Limit the max length of sequences processed */ Integer limitLength = null; /** What we are */ String cli_title = APPLICATION_TITLE + " [build: " + APPLICATION_BUILD + "]\n(C) Copyright 2007-2009, by The MITRE Corporation.\n"; /** create the Options */ Options options = new Options(); options.addOption(OptionBuilder.withArgName("file").hasArg(true) .withDescription( "JSON file with ccv " + "parameters, nmers, and vectors for generating " + "the classifier") .create("dataset")); options.addOption(OptionBuilder.withArgName("file").hasArg(true) .withDescription("a saved classifier (must use the same classifier)" + "(dataset then only needs parameters and nmers. " + "Vectors are no longer needed generating) ") .create("inputModel")); options.addOption(OptionBuilder.withArgName("file").hasArg(true) .withDescription("Output the generated tree " + "to a file as binary" + "(optional)") .create("outputModel")); options.addOption( OptionBuilder.withArgName("numFolds").hasArg(true) .withDescription("Cross validate the generated model " + "using the given training set. No final model " + "will be outputed or samples classified. " + "(optional)") .create("crossValidate")); options.addOption(OptionBuilder.withArgName("file").hasArg(true) .withDescription("file with samples" + " to generate ccvs and classify (optional)") .create("samples")); options.addOption(OptionBuilder.withArgName("number").hasArg(true).withDescription( "what name to use: 1-name(default);2-description;3-full header(might break newick-style trees)") .create("name")); options.addOption(OptionBuilder.withArgName("number").hasArg(true) .withDescription("limits the max length of the input samples processed").create("limitLength")); options.addOption(OptionBuilder.withArgName("help").hasArg(false).withDescription("print this message") .create("help")); options.addOption(OptionBuilder.withArgName("level").hasArg(true).withDescription( "Set the logging (verbosity) level: OFF, FATAL, ERROR, WARN, INFO, DEBUG. TRACE, ALL (none to everything)") .create("verbosity")); options.addOption(OptionBuilder.withArgName("property=value").hasArgs().withValueSeparator() .withDescription("use value for given property").create('D')); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); // create the parser CommandLineParser parser = new GnuParser(); // parse the command line arguments CommandLine line; try { line = parser.parse(options, argv); if (line.hasOption("help") || line.hasOption("h")) { USAGE(cli_title, formatter, options); System.exit(0); // they asked for help } if (line.getOptions().length == 0) { USAGE(cli_title, formatter, options); System.exit(-1); // we need some options } if (line.hasOption("verbosity")) { // if this fails then they get DEBUG! ccvc.setLoggingLevel(Level.toLevel(line.getOptionValue("verbosity"))); } Option[] opts = line.getOptions(); for (Option opt : opts) { if (opt.getOpt().equals("D")) { String propertyName = opt.getValue(0); String propertyValue = opt.getValue(1); System.setProperty(propertyName, propertyValue); continue; } if (opt.getOpt().equals("dataset")) { inputJsonFileName = line.getOptionValue("dataset"); continue; } if (opt.getOpt().equals("inputModel")) { inputModelFileName = line.getOptionValue("inputModel"); continue; } if (opt.getOpt().equals("outputModel")) { outputModelFileName = line.getOptionValue("outputModel"); continue; } if (opt.getOpt().equals("samples")) { inputDataFileName = line.getOptionValue("samples"); continue; } if (opt.getOpt().equals("crossValidate")) { try { numFolds = Integer.parseInt(line.getOptionValue("crossValidate")); } catch (NumberFormatException nfe) { LOG.warn("Error while parsing number of fold cross validate", nfe); System.exit(-1); } continue; } if (line.hasOption("name")) { try { nameParser = Integer.parseInt(line.getOptionValue("name")); } catch (NumberFormatException nfe) { throw new ParseException("Error parsing 'name' option. Reason: " + nfe.getMessage()); } } //"limitLength" if (line.hasOption("limitLength")) { try { limitLength = Integer.parseInt(line.getOptionValue("limitLength")); } catch (NumberFormatException nfe) { throw new ParseException("Error parsing 'limitLength' option. Reason: " + nfe.getMessage()); } } } // for opts } catch (ParseException pex) { System.err.println("Error while parse options\n" + pex.getMessage()); USAGE(cli_title, formatter, options); System.exit(-1); } /** Print out who we are */ LOG.info(cli_title); /** Do we have a saved model? */ if (inputModelFileName != null && numFolds == null) { LOG.info(String.format("Loading previous model from '%s'", inputModelFileName)); ccvc.loadClassifierFromModel(inputModelFileName); // we cannot cross-validate because we no longer have the instance data! // @todo: can we set the classifier class at the same time? } else if (inputJsonFileName != null) { /** * Load the dataset and process the sequecnes */ LOG.info("Loading data set from '" + inputJsonFileName + "'"); dataSetReader = new FileReader(inputJsonFileName); JSONObject jsonDataSet = new JSONObject(JsonLoader.getJsonString(dataSetReader)); try { dataSetReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing file reader!"); } ccvc.loadClassifierFromData(jsonDataSet); if (numFolds != null) { LOG.info(String.format("Cross-validating model %d fold using training data....", numFolds)); ccvc.classifier.crossValidateModel(ccvc.classifier.getClassifier(), ccvc.classifier.getInstances(), numFolds); /** Exit, we only do cross validation */ LOG.info("Done."); System.exit(0); } /** * Train/Build the classifier - move this to a method */ LOG.info(String.format("Building the %s classifier...", ccvc.classifier.getClassiferName())); try { ccvc.classifier.buildClassifier(); } catch (Exception ex) { LOG.fatal("Error while building the classifier with the given dataset", ex); throw new RuntimeException(); } /** * Save it? */ if (outputModelFileName != null) { LOG.info("Saving classifier model to '" + outputModelFileName + "'"); try { ccvc.classifier.saveModelObject(outputModelFileName); } catch (IOException ioe) { LOG.warn("IO error while saving model", ioe); } catch (Exception ex) { LOG.fatal("Unknown error", ex); throw new RuntimeException(); } } } else { LOG.fatal("Unknown set of options!"); System.out.println(cli_title); formatter.printHelp(cli_title + " options ", options); System.exit(-1); } /** Check to see if we loaded a classifier!*/ if (ccvc.classifier == null) { LOG.fatal("Somehow we didn't load a classifier!"); throw new RuntimeException(); } /** * Do we have samples to classify? */ if (inputDataFileName == null) { LOG.info("No samples to classify. Quiting."); return; } BufferedReader br = new BufferedReader(new FileReader(inputDataFileName)); seqIter = new FastaIterator(br); if (seqIter != null) { /** Get the ccv begin and end */ Integer begin = ccvc.classifier.getBegin(); Integer end = ccvc.classifier.getEnd(); /** * no way to get FastVector of attirbutes from an Instances Object? */ Attribute classAttribute = (Attribute) ccvc.classifier.getAttributes() .elementAt(ccvc.classifier.getClassIndex()); Integer cv = 0; /** Load and generate CCVs */ while (seqIter.hasNext()) { cv++; Sequence s = null; try { s = seqIter.next(); } catch (NoSuchElementException nsee) { //System.err.println("Iteration error in sequence file!\n " + e.getMessage()); LOG.fatal("Iteration error in sequence file!", nsee); throw new RuntimeException(); } String seqString = s.seqString(); String seqName = CompleteCompositionVectorMain.parseSequenceName(s, nameParser); /** Check the length of the sequence */ if (limitLength != null && seqString.length() > limitLength) { LOG.info(String.format( "Skipping sample '%s' because it is longer (%d) than the limit length (%d)", seqName, seqString.length(), limitLength)); continue; } /** Generate the complete composition vector for this sample */ IndexedCompositionDistribution cd; try { cd = new IndexedCompositionDistribution(new DistributionIndex(), cv, seqString, begin, end); } catch (IllegalArgumentException e) { LOG.warn(String.format( "Composition distribution error on '%s'" + "(potentially to small of a sequence '%d')!", s.getName(), seqString.length()), e); continue; } CompleteCompositionVector ccv = new IndexedCompleteCompositionVector(seqName, cv, begin, end, cd); /** Generate an instance for this */ Instance inst; try { inst = ccvc.classifier.getInstanceSparse(ccv); } catch (Exception ex) { LOG.warn("Error while getting instance! Skipping...", ex); continue; } /** To classify, we need to be part of a DataSet/Instance */ try { LabeledInstance li = ccvc.classifier.runClassifier(inst, classAttribute); double[] clsDist = ccvc.classifier.getClassifier().distributionForInstance(inst); int clsValue = (int) li.inst.classValue(); System.out.printf("%s\t%s\t%f\n", s.getName(), classAttribute.value(clsValue), li.clsDist[clsValue]); /* Below outputs all the confidence values for all the classes. StringBuffer sb = new StringBuffer(); for (int i = 0; i < clsDist.length; i++) { sb.append(clsDist[i]); if (i + 1 < clsDist.length) { sb.append(", "); } } System.out.printf("%s\t%s\t[%s]\n", seqName, classAttribute.value(clsValue), sb.toString()); */ } catch (Exception ex) { LOG.warn(String.format("Error while classifying sample '%s' (# %d)", seqName, cv)); } } } }
From source file:org.mule.util.SystemUtils.java
/** * Returns a Map of all options in the command line. The Map is keyed off the * option name. The value will be whatever is present on the command line. * Options that don't have an argument will have the String "true". *///from ww w. ja v a2 s .c o m // TODO MULE-1947 Command-line arguments should be handled exclusively by the bootloader public static Map<String, Object> getCommandLineOptions(String args[], String opts[][]) throws DefaultMuleException { CommandLine line = parseCommandLine(args, opts); Map<String, Object> ret = new HashMap<String, Object>(); Option[] options = line.getOptions(); for (int i = 0; i < options.length; i++) { Option option = options[i]; ret.put(option.getOpt(), option.getValue("true")); } return ret; }