List of usage examples for org.apache.commons.cli Option setOptionalArg
public void setOptionalArg(boolean optionalArg)
From source file:org.apache.stratos.cli.commands.SubscribeCommand.java
/** * Construct Options./* www .j a v a 2 s. c o m*/ * * @return Options expected from command-line. */ private Options constructOptions() { final Options options = new Options(); //Option policyOption = new Option(CliConstants.POLICY_OPTION, CliConstants.POLICY_LONG_OPTION, true, // "Auto-scaling policy.\nPlease use \"" + CliConstants.POLICIES_ACTION // + "\" command to view the available policies."); //policyOption.setArgName("policy name"); //options.addOption(policyOption); Option autoscaling = new Option(CliConstants.AUTOSCALING_POLICY_OPTION, CliConstants.AUTOSCALING_POLICY_LONG_OPTION, true, "Auto-scaling policy"); autoscaling.setArgName("auto-scaling-policy"); options.addOption(autoscaling); Option deployment = new Option(CliConstants.DEPLOYMENT_POLICY_OPTION, CliConstants.DEPLOYMENT_POLICY_LONG_OPTION, true, "Deployment-policy"); deployment.setArgName("deployment-policy"); options.addOption(deployment); Option removeOnTermination = new Option(CliConstants.REMOVE_ON_TERMINATION_OPTION, CliConstants.REMOVE_ON_TERMINATION_LONG_OPTION, true, "Remove-on-termination"); removeOnTermination.setArgName("remove-on-termination"); options.addOption(removeOnTermination); Option size = new Option(CliConstants.VOLUME_SIZE_OPTION, CliConstants.VOLUME_SIZE_LONG_OPTION, true, "Volume-size"); size.setArgName("volume-size"); options.addOption(size); Option persistance = new Option(CliConstants.PERSISTANCE_VOLUME_OPTION, CliConstants.PERSISTANCE_VOLUME_LONG_OPTION, true, "Persistance-volume"); persistance.setArgName("persistance-volume"); options.addOption(persistance); Option urlOption = new Option(CliConstants.REPO_URL_OPTION, CliConstants.REPO_URL_LONG_OPTION, true, "GIT repository URL"); urlOption.setArgName("url"); options.addOption(urlOption); //options.addOption(CliConstants.PRIVATE_REPO_OPTION, CliConstants.PRIVATE_REPO_LONG_OPTION, false, // "Private repository"); Option usernameOption = new Option(CliConstants.USERNAME_OPTION, CliConstants.USERNAME_LONG_OPTION, true, "GIT repository username"); usernameOption.setArgName("username"); options.addOption(usernameOption); Option passwordOption = new Option(CliConstants.PASSWORD_OPTION, CliConstants.PASSWORD_LONG_OPTION, true, "GIT repository password"); passwordOption.setArgName("password"); passwordOption.setOptionalArg(true); options.addOption(passwordOption); Option upstreamCommitsEnabledOption = new Option(CliConstants.ENABLE_COMMITS_OPTION, CliConstants.ENABLE_COMMITS_LONG_OPTION, true, "Enable Git commit upstream"); upstreamCommitsEnabledOption.setArgName("enable-commits"); upstreamCommitsEnabledOption.setOptionalArg(true); options.addOption(upstreamCommitsEnabledOption); return options; }
From source file:org.dcm4che2.tool.xml2dcm.Xml2Dcm.java
private static CommandLine parse(String[] args) { Options opts = new Options(); Option ifile = new Option("i", true, "Update attributes in specified DICOM file instead " + "generating new one."); ifile.setArgName("dcmfile"); opts.addOption(ifile);//from ww w . j a v a2s. c o m Option xmlfile = new Option("x", true, "XML input, used to update or generate new DICOM file." + "Without <xmlfile>, read from standard input."); xmlfile.setOptionalArg(true); xmlfile.setArgName("xmlfile"); opts.addOption(xmlfile); Option basedir = new Option("d", true, "Directory to resolve external attribute values referenced by " + "XML read from standard input."); basedir.setArgName("basedir"); opts.addOption(basedir); Option ofile = new Option("o", true, "Generated DICOM file or ACR/NEMA-2 dump"); ofile.setArgName("dcmfile"); opts.addOption(ofile); Option tsuid = new Option("t", true, "Store result with specified Transfer Syntax."); tsuid.setArgName("tsuid"); opts.addOption(tsuid); opts.addOption("a", "acrnema2", false, "Store result as ACR/NEMA 2 dump. Mutual exclusive " + "with option -d"); opts.addOption("d", "dicom", false, "Store result as DICOM Part 10 File. Mutual exclusive " + "with option -a"); opts.addOption("g", "grlen", false, "Include (gggg,0000) Group Length attributes." + "By default, optional Group Length attributes are excluded."); opts.addOption("E", "explseqlen", false, "Encode sequences with explicit length. At default, non-empty " + "sequences are encoded with undefined length."); opts.addOption("e", "explitemlen", false, "Encode sequence items with explicit length. At default, " + "non-empty sequence items are encoded with undefined length."); opts.addOption("U", "undefseqlen", false, "Encode all sequences with undefined length. Mutual exclusive " + "with option -E."); opts.addOption("u", "undefitemlen", false, "Encode all sequence items with undefined length. Mutual " + "exclusive with option -e."); opts.addOption("h", "help", false, "print this message"); opts.addOption("V", "version", false, "print the version information and exit"); CommandLine cl = null; try { cl = new PosixParser().parse(opts, args); } catch (ParseException e) { exit("dcm2xml: " + e.getMessage()); throw new RuntimeException("unreachable"); } if (cl.hasOption('V')) { Package p = Xml2Dcm.class.getPackage(); System.out.println("dcm2xml v" + p.getImplementationVersion()); System.exit(0); } if (cl.hasOption('h') || !cl.hasOption("o") || (!cl.hasOption("x") && !cl.hasOption("i"))) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(USAGE, DESCRIPTION, opts, EXAMPLE); System.exit(0); } if (cl.hasOption("a") && cl.hasOption("d")) exit("xml2dcm: Option -a and -d are mutual exclusive"); if (cl.hasOption("e") && cl.hasOption("u")) exit("xml2dcm: Option -e and -u are mutual exclusive"); if (cl.hasOption("E") && cl.hasOption("U")) exit("xml2dcm: Option -E and -U are mutual exclusive"); return cl; }
From source file:org.dspace.app.itemupdate.ItemUpdate.java
/** * /*from w ww . j a v a 2 s . c om*/ * @param argv */ public static void main(String[] argv) { // create an options object and populate it CommandLineParser parser = new PosixParser(); Options options = new Options(); //processing basis for determining items //item-specific changes with metadata in source directory with dublin_core.xml files options.addOption("s", "source", true, "root directory of source dspace archive "); //actions on items options.addOption("a", "addmetadata", true, "add metadata specified for each item; multiples separated by semicolon ';'"); options.addOption("d", "deletemetadata", true, "delete metadata specified for each item"); options.addOption("A", "addbitstreams", false, "add bitstreams as specified for each item"); // extra work to get optional argument Option delBitstreamOption = new Option("D", "deletebitstreams", true, "delete bitstreams as specified for each item"); delBitstreamOption.setOptionalArg(true); delBitstreamOption.setArgName("BitstreamFilter"); options.addOption(delBitstreamOption); //other params options.addOption("e", "eperson", true, "email of eperson doing the update"); options.addOption("i", "itemfield", true, "optional metadata field that containing item identifier; default is dc.identifier.uri"); options.addOption("F", "filter-properties", true, "filter class name; only for deleting bitstream"); options.addOption("v", "verbose", false, "verbose logging"); //special run states options.addOption("t", "test", false, "test run - do not actually import items"); options.addOption("P", "provenance", false, "suppress altering provenance field for bitstream changes"); options.addOption("h", "help", false, "help"); int status = 0; boolean isTest = false; boolean alterProvenance = true; String itemField = null; String metadataIndexName = null; Context context = null; ItemUpdate iu = new ItemUpdate(); try { CommandLine line = parser.parse(options, argv); if (line.hasOption('h')) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("ItemUpdate", options); pr(""); pr("Examples:"); pr(" adding metadata: ItemUpdate -e jsmith@mit.edu -s sourcedir -a dc.contributor -a dc.subject "); pr(" deleting metadata: ItemUpdate -e jsmith@mit.edu -s sourcedir -d dc.description.other"); pr(" adding bitstreams: ItemUpdate -e jsmith@mit.edu -s sourcedir -A -i dc.identifier"); pr(" deleting bitstreams: ItemUpdate -e jsmith@mit.edu -s sourcedir -D ORIGINAL "); pr(""); System.exit(0); } if (line.hasOption('v')) { verbose = true; } if (line.hasOption('P')) { alterProvenance = false; pr("Suppressing changes to Provenance field option"); } iu.eperson = line.getOptionValue('e'); // db ID or email if (!line.hasOption('s')) // item specific changes from archive dir { pr("Missing source archive option"); System.exit(1); } String sourcedir = line.getOptionValue('s'); if (line.hasOption('t')) //test { isTest = true; pr("**Test Run** - not actually updating items."); } if (line.hasOption('i')) { itemField = line.getOptionValue('i'); } if (line.hasOption('d')) { String[] targetFields = line.getOptionValues('d'); DeleteMetadataAction delMetadataAction = (DeleteMetadataAction) iu.actionMgr .getUpdateAction(DeleteMetadataAction.class); delMetadataAction.addTargetFields(targetFields); //undo is an add for (String field : targetFields) { iu.undoActionList.add(" -a " + field + " "); } pr("Delete metadata for fields: "); for (String s : targetFields) { pr(" " + s); } } if (line.hasOption('a')) { String[] targetFields = line.getOptionValues('a'); AddMetadataAction addMetadataAction = (AddMetadataAction) iu.actionMgr .getUpdateAction(AddMetadataAction.class); addMetadataAction.addTargetFields(targetFields); //undo is a delete followed by an add of a replace record for target fields for (String field : targetFields) { iu.undoActionList.add(" -d " + field + " "); } for (String field : targetFields) { iu.undoActionList.add(" -a " + field + " "); } pr("Add metadata for fields: "); for (String s : targetFields) { pr(" " + s); } } if (line.hasOption('D')) // undo not supported { pr("Delete bitstreams "); String[] filterNames = line.getOptionValues('D'); if ((filterNames != null) && (filterNames.length > 1)) { pr("Error: Only one filter can be a used at a time."); System.exit(1); } String filterName = line.getOptionValue('D'); pr("Filter argument: " + filterName); if (filterName == null) // indicates using delete_contents files { DeleteBitstreamsAction delAction = (DeleteBitstreamsAction) iu.actionMgr .getUpdateAction(DeleteBitstreamsAction.class); delAction.setAlterProvenance(alterProvenance); } else { // check if param is on ALIAS list String filterClassname = filterAliases.get(filterName); if (filterClassname == null) { filterClassname = filterName; } BitstreamFilter filter = null; try { Class<?> cfilter = Class.forName(filterClassname); pr("BitstreamFilter class to instantiate: " + cfilter.toString()); filter = (BitstreamFilter) cfilter.newInstance(); //unfortunate cast, an erasure consequence } catch (Exception e) { pr("Error: Failure instantiating bitstream filter class: " + filterClassname); System.exit(1); } String filterPropertiesName = line.getOptionValue('F'); if (filterPropertiesName != null) //not always required { try { // TODO try multiple relative locations, e.g. source dir if (!filterPropertiesName.startsWith("/")) { filterPropertiesName = sourcedir + File.separator + filterPropertiesName; } filter.initProperties(filterPropertiesName); } catch (Exception e) { pr("Error: Failure finding properties file for bitstream filter class: " + filterPropertiesName); System.exit(1); } } DeleteBitstreamsByFilterAction delAction = (DeleteBitstreamsByFilterAction) iu.actionMgr .getUpdateAction(DeleteBitstreamsByFilterAction.class); delAction.setAlterProvenance(alterProvenance); delAction.setBitstreamFilter(filter); //undo not supported } } if (line.hasOption('A')) { pr("Add bitstreams "); AddBitstreamsAction addAction = (AddBitstreamsAction) iu.actionMgr .getUpdateAction(AddBitstreamsAction.class); addAction.setAlterProvenance(alterProvenance); iu.undoActionList.add(" -D "); // delete_contents file will be written, no arg required } if (!iu.actionMgr.hasActions()) { pr("Error - an action must be specified"); System.exit(1); } else { pr("Actions to be performed: "); for (UpdateAction ua : iu.actionMgr) { pr(" " + ua.getClass().getName()); } } pr("ItemUpdate - initializing run on " + (new Date()).toString()); context = new Context(); iu.setEPerson(context, iu.eperson); context.setIgnoreAuthorization(true); HANDLE_PREFIX = ConfigurationManager.getProperty("handle.canonical.prefix"); if (HANDLE_PREFIX == null || HANDLE_PREFIX.length() == 0) { HANDLE_PREFIX = "http://hdl.handle.net/"; } iu.processArchive(context, sourcedir, itemField, metadataIndexName, alterProvenance, isTest); context.complete(); // complete all transactions context.setIgnoreAuthorization(false); } catch (Exception e) { if (context != null && context.isValid()) { context.abort(); context.setIgnoreAuthorization(false); } e.printStackTrace(); pr(e.toString()); status = 1; } if (isTest) { pr("***End of Test Run***"); } else { pr("End."); } System.exit(status); }
From source file:org.duracloud.sync.config.SyncToolConfigParser.java
/** * Creates a parser for command line configuration options. *//*from w w w . j ava 2s .c o m*/ public SyncToolConfigParser() { cmdLineUtil = new CommandLineToolUtil(); // Command Line Options cmdOptions = new Options(); Option hostOption = new Option("h", "host", true, "the host address of the DuraCloud " + "DuraStore application"); hostOption.setRequired(true); cmdOptions.addOption(hostOption); Option portOption = new Option("r", "port", true, "the port of the DuraCloud DuraStore application " + "(optional, default value is " + DEFAULT_PORT + ")"); portOption.setRequired(false); cmdOptions.addOption(portOption); Option usernameOption = new Option("u", "username", true, "the username necessary to perform writes to DuraStore"); usernameOption.setRequired(true); cmdOptions.addOption(usernameOption); Option passwordOption = new Option("p", "password", true, "the password necessary to perform writes to DuraStore; NOTICE: " + "if no password is specified in the command line the sync tool will " + "look for an environment variable named " + CommandLineToolUtil.PASSWORD_ENV_VARIABLE_NAME + " containing the password. Finally, if this environment variable " + "does not exist the user will be prompted for the password."); passwordOption.setRequired(false); cmdOptions.addOption(passwordOption); Option storeIdOption = new Option("i", "store-id", true, "the Store ID for the DuraCloud storage provider"); storeIdOption.setRequired(false); cmdOptions.addOption(storeIdOption); Option spaceId = new Option("s", "space-id", true, "the ID of the DuraCloud space where content " + "will be stored"); spaceId.setRequired(true); cmdOptions.addOption(spaceId); Option workDirOption = new Option("w", "work-dir", true, "the state of the sync tool is persisted to " + "this directory (optional, default value is " + "duracloud-sync-work directory in user home)"); workDirOption.setRequired(false); cmdOptions.addOption(workDirOption); Option contentDirs = new Option("c", "content-dirs", true, "the directory paths to monitor and sync with DuraCloud"); contentDirs.setRequired(true); contentDirs.setArgs(Option.UNLIMITED_VALUES); cmdOptions.addOption(contentDirs); Option pollFrequency = new Option("f", "poll-frequency", true, "the time (in ms) to wait between each poll of the " + "sync-dirs (optional, default value is " + DEFAULT_POLL_FREQUENCY + ")"); pollFrequency.setRequired(false); cmdOptions.addOption(pollFrequency); Option numThreads = new Option("t", "threads", true, "the number of threads in the pool used to manage " + "file transfers (optional, default value is " + DEFAULT_NUM_THREADS + ")"); numThreads.setRequired(false); cmdOptions.addOption(numThreads); Option maxFileSize = new Option("m", "max-file-size", true, "the maximum size of a stored file in GB (value must " + "be between 1 and 5), larger files will be split into " + "pieces (optional, default value is " + DEFAULT_MAX_FILE_SIZE + ")"); maxFileSize.setRequired(false); cmdOptions.addOption(maxFileSize); Option renameUpdates = new Option("n", "rename-updates", true, "indicates that updates should be synced to the cloud and renamed. " + "Specify an optional suffix to override default " + "( \"" + SyncToolConfig.DEFAULT_UPDATE_SUFFIX + "\"); " + "To prevent updates altogether, see option -o. " + "(optional, not set by default)"); renameUpdates.setRequired(false); renameUpdates.setArgName("suffix"); renameUpdates.setOptionalArg(true); cmdOptions.addOption(renameUpdates); Option syncUpdates = new Option("o", "no-update", false, "indicates that changed files should not be updated; " + "to perform updates without overwriting, see option -n. " + "(optional, not set by default)"); syncUpdates.setRequired(false); cmdOptions.addOption(syncUpdates); Option syncDeletes = new Option("d", "sync-deletes", false, "indicates that deletes performed on files within the " + "sync directories should also be performed on those " + "files in DuraCloud; if this option is not included " + "all deletes are ignored (optional, not set by default)"); syncDeletes.setRequired(false); cmdOptions.addOption(syncDeletes); Option cleanStart = new Option("l", "clean-start", false, "indicates that the sync tool should perform a clean " + "start, ensuring that all files in all content " + "directories are checked against DuraCloud, even if " + "those files have not changed locally since the last " + "run of the sync tool. (optional, not set by default)"); cleanStart.setRequired(false); cmdOptions.addOption(cleanStart); Option jumpStart = new Option("j", "jump-start", false, "indicates that the sync tool should not attempt to " + "check if content to be synchronized is already in " + "DuraCloud, but should instead transfer all content. " + "This option is best used for new data sets. " + "(optional, not set by default)"); jumpStart.setRequired(false); cmdOptions.addOption(jumpStart); Option exitOnCompletion = new Option("x", "exit-on-completion", false, "indicates that the sync tool should exit once it has " + "completed a scan of the content directories and synced " + "all files; if this option is included, the sync tool " + "will not continue to monitor the sync dirs " + "(optional, not set by default)"); exitOnCompletion.setRequired(false); cmdOptions.addOption(exitOnCompletion); Option excludeOption = new Option("e", "exclude", true, "file which provides a list of files and/or " + "directories to exclude from the sync (one file or " + "directory name rule per line)"); excludeOption.setRequired(false); cmdOptions.addOption(excludeOption); Option prefixOption = new Option("a", "prefix", true, "a prefix that is added to the beginning of the ID of " + "each content item that is stored in DuraCloud. For " + "example, a prefix value of 'a/b/c/' with a content " + "item whose path is 'dir1/file.txt' would result in " + "the file stored in DuraCloud as 'a/b/c/dir1/file.txt " + "(optional)"); prefixOption.setRequired(false); cmdOptions.addOption(prefixOption); // Options to use Backup Config configFileOptions = new Options(); Option configFileOption = new Option("g", "config-file", true, "read configuration from this file (a file containing " + "the most recently used configuration can be found in " + "the work-dir, named " + BACKUP_FILE_NAME + ")"); configFileOption.setRequired(true); configFileOptions.addOption(configFileOption); }
From source file:org.eclipse.jubula.app.testexec.core.TestexecClient.java
/** * {@inheritDoc}//from w w w. j a va 2s. c o m */ protected void extendOptions(Options options, boolean req) { options.addOption(createOption(ClientTestStrings.SERVER, true, ClientTestStrings.HOSTNAME, Messages.ClientServerOpt, false)); options.addOption(createOption(ClientTestStrings.PORT, true, ClientTestStrings.PORT_NUMBER, Messages.ClientPortOpt, false)); options.addOption(createOption(ClientTestStrings.PROJECT, true, ClientTestStrings.PROJECT_NAME, Messages.ClientProjectOpt, req)); options.addOption(createOption(ClientTestStrings.PROJECT_VERSION, true, ClientTestStrings.PROJECT_VERSION_EX, Messages.ClientProjectVersionOpt, req)); options.addOption(createOption(ClientTestStrings.LANGUAGE, true, ClientTestStrings.LANGUAGE, Messages.ClientLanguageOpt, req)); options.addOption(createOption(ClientTestStrings.RESULTDIR, true, ClientTestStrings.RESULTDIR, Messages.ClientResultdirOpt, false)); options.addOption(createOption(ClientStrings.RESULT_NAME, true, ClientStrings.RESULT_NAME, Messages.ClientResultnameOpt, false)); // AUT option group (AUT Configuration / AUT ID) OptionGroup autOptionGroup = new OptionGroup(); autOptionGroup.setRequired(false); autOptionGroup.addOption(createOption(ClientTestStrings.AUT_CONFIG, true, ClientTestStrings.AUT_CONFIG, Messages.ClientAutconfigOpt, req)); autOptionGroup.addOption(createOption(ClientTestStrings.AUT_ID, true, ClientTestStrings.AUT_ID, Messages.ClientAutIdOpt, req)); options.addOptionGroup(autOptionGroup); // Test execution type option group (Test Suite / Test Job) OptionGroup testExecutionGroup = new OptionGroup(); testExecutionGroup.setRequired(req); testExecutionGroup.addOption(createOption(ClientTestStrings.TESTJOB, true, ClientTestStrings.TESTJOB, Messages.ClientTestJobOpt, req)); testExecutionGroup.addOption(createOption(ClientTestStrings.TESTSUITE, true, ClientTestStrings.TESTSUITE, Messages.ClientTestSuiteOpt, req)); options.addOptionGroup(testExecutionGroup); options.addOption(createOption(ClientTestStrings.DATA_DIR, true, ClientTestStrings.DATA_DIR_EX, Messages.ClientDataFile, false)); Option noRunOption = createOption(ClientStrings.NORUN, true, ClientStrings.NORUN_MODE, Messages.ClientNoRunOpt, false); noRunOption.setOptionalArg(true); options.addOption(noRunOption); options.addOption(createOption(ClientTestStrings.AUTO_SCREENSHOT, false, StringConstants.EMPTY, Messages.ClientAutoScreenshot, false)); options.addOption(createOption(ClientTestStrings.NO_XML_SCREENSHOT, false, StringConstants.EMPTY, Messages.ClientNoXmlScreenshot, false)); options.addOption(createOption(ClientTestStrings.TIMEOUT, true, ClientTestStrings.TIMEOUT, Messages.ClientTimeout, false)); // server option for the CLC extension options.addOption(createOption(ClientTestStrings.STARTSERVER, true, ClientTestStrings.PORT_NUMBER, Messages.ClientStartServerOpt, false)); }
From source file:org.eclipse.winery.cli.WineryCli.java
public static void main(String[] args) throws Exception { Option repositoryPathOption = new Option("p", "path", true, "use given path as repository path"); Option serviceTemplatesOnlyOption = new Option("so", "servicetemplatesonly", false, "checks service templates instead of the whole repository"); Option checkDocumentationOption = new Option("cd", "checkdocumentation", false, "check existence of README.md and LICENSE. Default: No check"); Option verboseOption = new Option("v", "verbose", false, "be verbose: Output the checked elements"); Option generateCopybaraConfigOption = new Option("cb", "generatecopybaraconfig", true, "Generates a configuration for Copybara."); generateCopybaraConfigOption.setOptionalArg(true); Option helpOption = new Option("h", "help", false, "prints this help"); Options options = new Options(); options.addOption(repositoryPathOption); options.addOption(serviceTemplatesOnlyOption); options.addOption(checkDocumentationOption); options.addOption(verboseOption);/*from w w w. j a va 2s.c om*/ options.addOption(generateCopybaraConfigOption); options.addOption(helpOption); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (line.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("winery", options); System.exit(0); } IRepository repository; if (line.hasOption("p")) { repository = RepositoryFactory.getRepository(Paths.get(line.getOptionValue("p"))); } else { repository = RepositoryFactory.getRepository(); } if (line.hasOption("cb")) { CopybaraGenerator copybaraGenerator = new CopybaraGenerator(); String outfile = line.getOptionValue("cb"); if (outfile == null) { String copybaraConfigFile = copybaraGenerator.generateCopybaraConfigFile(); System.out.println(copybaraConfigFile); } else { Path file = Paths.get(outfile); copybaraGenerator.generateCopybaraConfigFile(file); } System.exit(0); } if (repository instanceof FilebasedRepository) { System.out.println( "Using repository path " + ((FilebasedRepository) repository).getRepositoryRoot() + "..."); } else { System.out.println("Using non-filebased repository"); } doConsistencyCheck(line, repository); }
From source file:org.jcryptool.commands.core.api.OptionsBuilder.java
public OptionsBuilder addOption(String longOption, String shortOption, boolean required, String description, String argName, boolean argRequired, char argValueSeparator, int argsCount) { Option option = new Option(shortOption, longOption, true, description); option.setArgName(argName);//from www.jav a2 s . co m option.setRequired(required); option.setOptionalArg(argRequired); option.setValueSeparator(argValueSeparator); option.setArgs(argsCount); options.add(option); return this; }
From source file:org.lexgrid.valuesets.admin.LoadResolvedValueSetDefinition.java
/** * Return supported command options.//ww w . j ava2 s.c o m * * @return org.apache.commons.cli.Options */ private Options getCommandOptions() { Options options = new Options(); Option o; o = new Option("u", "urn", true, "URN uniquely identifying the code system."); o.setArgName("urn"); o.setRequired(true); options.addOption(o); o = new Option("a", "activate", true, "Activate the code system."); o.setArgName("activate"); o.setRequired(false); o.setOptionalArg(true); options.addOption(o); o = new Option("l", "list", true, "List of coding schemes to use."); o.setArgName("id"); o.setRequired(false); options.addOption(o); o = new Option("csVersionTag", "csVersionTag", false, "Coding Scheme version tag to use"); o.setRequired(false); options.addOption(o); return options; }
From source file:org.ow2.proactive.authentication.crypto.CreateCredentials.java
/** * Entry point/*w w w . j a va2 s. c o m*/ * * @see org.ow2.proactive.authentication.crypto.Credentials * @param args arguments, try '-h' for help * @throws IOException * @throws ParseException * */ public static void main(String[] args) throws IOException, ParseException { SecurityManagerConfigurator.configureSecurityManager( CreateCredentials.class.getResource("/all-permissions.security.policy").toString()); Console console = System.console(); /** * default values */ boolean interactive = true; String pubKeyPath = null; PublicKey pubKey = null; String login = null; String pass = null; String keyfile = null; String cipher = "RSA/ECB/PKCS1Padding"; String path = Credentials.getCredentialsPath(); String rm = null; String scheduler = null; String url = null; Options options = new Options(); Option opt = new Option("h", "help", false, "Display this help"); opt.setRequired(false); options.addOption(opt); OptionGroup group = new OptionGroup(); group.setRequired(false); opt = new Option("F", "file", true, "Public key path on the local filesystem [default:" + Credentials.getPubKeyPath() + "]"); opt.setArgName("PATH"); opt.setArgs(1); opt.setRequired(false); group.addOption(opt); opt = new Option("R", "rm", true, "Request the public key to the Resource Manager at URL"); opt.setArgName("URL"); opt.setArgs(1); opt.setRequired(false); group.addOption(opt); opt = new Option("S", "scheduler", true, "Request the public key to the Scheduler at URL"); opt.setArgName("URL"); opt.setArgs(1); opt.setRequired(false); group.addOption(opt); options.addOptionGroup(group); opt = new Option("l", "login", true, "Generate credentials for this specific user, will be asked interactively if not specified"); opt.setArgName("LOGIN"); opt.setArgs(1); opt.setRequired(false); options.addOption(opt); opt = new Option("p", "password", true, "Use this password, will be asked interactively if not specified"); opt.setArgName("PWD"); opt.setArgs(1); opt.setRequired(false); options.addOption(opt); opt = new Option("k", "keyfile", true, "Use specified ssh private key, asked interactively if specified without PATH, not specified otherwise."); opt.setArgName("PATH"); opt.setOptionalArg(true); opt.setRequired(false); options.addOption(opt); opt = new Option("o", "output", true, "Output the resulting credentials to the specified file [default:" + path + "]"); opt.setArgName("PATH"); opt.setArgs(1); opt.setRequired(false); options.addOption(opt); opt = new Option("c", "cipher", true, "Use specified cipher parameters, need to be compatible with the specified key [default:" + cipher + "]"); opt.setArgName("PARAMS"); opt.setArgs(1); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(newline + "ERROR : " + e.getMessage() + newline); System.out.println("type -h or --help to display help screen"); System.exit(1); } if (cmd.hasOption("help")) { displayHelp(options); } if (cmd.hasOption("file")) { pubKeyPath = cmd.getOptionValue("file"); } if (cmd.hasOption("rm")) { rm = cmd.getOptionValue("rm"); } if (cmd.hasOption("scheduler")) { scheduler = cmd.getOptionValue("scheduler"); } if (cmd.hasOption("login")) { login = cmd.getOptionValue("login"); } if (cmd.hasOption("password")) { pass = cmd.getOptionValue("password"); } if (cmd.hasOption("keyfile") && cmd.getOptionValues("keyfile") != null) { keyfile = cmd.getOptionValue("keyfile"); } if (cmd.hasOption("output")) { path = cmd.getOptionValue("output"); } if (cmd.hasOption("cipher")) { cipher = cmd.getOptionValue("cipher"); } int acc = 0; if (pubKeyPath != null) { acc++; } if (scheduler != null) { url = Connection.normalize(scheduler) + "SCHEDULER"; acc++; } if (rm != null) { url = Connection.normalize(rm) + "RMAUTHENTICATION"; acc++; } if (acc > 1) { System.out.println("--rm, --scheduler and --file arguments cannot be combined."); System.out.println("try -h for help."); System.exit(1); } if (url != null) { try { Connection<AuthenticationImpl> conn = new Connection<AuthenticationImpl>(AuthenticationImpl.class) { public Logger getLogger() { return Logger.getLogger("pa.scheduler.credentials"); } }; AuthenticationImpl auth = conn.connect(url); pubKey = auth.getPublicKey(); } catch (Exception e) { System.err.println("ERROR : Could not retrieve public key from '" + url + "'"); e.printStackTrace(); System.exit(3); } System.out.println("Successfully obtained public key from " + url + newline); } else if (pubKeyPath != null) { try { pubKey = Credentials.getPublicKey(pubKeyPath); } catch (KeyException e) { System.err .println("ERROR : Could not retrieve public key from '" + pubKeyPath + "' (no such file)"); System.exit(4); } } else { System.out.println("No public key specified, attempting to retrieve it from default location."); pubKeyPath = Credentials.getPubKeyPath(); try { pubKey = Credentials.getPublicKey(pubKeyPath); } catch (KeyException e) { System.err .println("ERROR : Could not retrieve public key from '" + pubKeyPath + "' (no such file)"); System.exit(5); } } if (login != null && pass != null && (!cmd.hasOption("keyfile") || cmd.getOptionValues("keyfile") != null)) { System.out.println("Running in non-interactive mode." + newline); interactive = false; } else { System.out.println("Running in interactive mode."); } if (interactive) { System.out.println("Please enter Scheduler credentials,"); System.out.println("they will be stored encrypted on disk for future logins." + newline); System.out.print("login: "); if (login == null) { login = console.readLine(); } else { System.out.println(login); } System.out.print("password: "); if (pass == null) { pass = new String(console.readPassword()); } else { System.out.println("*******"); } System.out.print("keyfile: "); if (!cmd.hasOption("keyfile")) { System.out.println("no key file specified"); } else if (cmd.hasOption("keyfile") && cmd.getOptionValues("keyfile") != null) { System.out.println(keyfile); } else { keyfile = console.readLine(); } } try { CredData credData; if (keyfile != null && keyfile.length() > 0) { byte[] keyfileContent = FileToBytesConverter.convertFileToByteArray(new File(keyfile)); credData = new CredData(CredData.parseLogin(login), CredData.parseDomain(login), pass, keyfileContent); } else { System.out.println("--> Ignoring keyfile, credential does not contain SSH key"); credData = new CredData(CredData.parseLogin(login), CredData.parseDomain(login), pass); } Credentials cred = Credentials.createCredentials(credData, pubKey, cipher); cred.writeToDisk(path); } catch (FileNotFoundException e) { System.err.println("ERROR : Could not retrieve ssh private key from '" + keyfile + "' (no such file)"); System.exit(6); } catch (Throwable t) { t.printStackTrace(); System.exit(7); } System.out.println("Successfully stored encrypted credentials on disk at :"); System.out.println("\t" + path); System.exit(0); }
From source file:org.ow2.proactive.resourcemanager.utils.console.ResourceManagerController.java
protected OptionGroup addCommandLineOptions(Options options) { OptionGroup actionGroup = new OptionGroup(); Option addNodesOpt = new Option("a", "addnodes", true, control + "Add nodes by their URLs"); addNodesOpt.setArgName("node URLs"); addNodesOpt.setRequired(false);/* w ww . j a v a 2 s.co m*/ addNodesOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(addNodesOpt); Option removeNodesOpt = new Option("d", "removenodes", true, control + "Remove nodes by their URLs"); removeNodesOpt.setArgName("node URLs"); removeNodesOpt.setRequired(false); removeNodesOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(removeNodesOpt); Option lockNodesOpt = new Option("locknodes", true, control + "Lock nodes by their URLs"); lockNodesOpt.setArgName("node URLs"); lockNodesOpt.setRequired(false); lockNodesOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(lockNodesOpt); Option unlockNodesOpt = new Option("unlocknodes", true, control + "Unlock nodes by their URLs"); unlockNodesOpt.setArgName("node URLs"); unlockNodesOpt.setRequired(false); unlockNodesOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(unlockNodesOpt); Option createNSOpt = new Option("cn", "createns", true, control + "Create new node sources"); createNSOpt.setArgName("names"); createNSOpt.setRequired(false); createNSOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(createNSOpt); Option infrastuctureOpt = new Option("i", "infrastructure", true, "Specify an infrastructure when node source is created"); infrastuctureOpt.setArgName("params"); infrastuctureOpt.setRequired(false); infrastuctureOpt.setOptionalArg(true); infrastuctureOpt.setArgs(Option.UNLIMITED_VALUES); options.addOption(infrastuctureOpt); Option policyOpt = new Option("p", "policy", true, "Specify a policy when node source is created"); policyOpt.setArgName("params"); policyOpt.setOptionalArg(true); policyOpt.setRequired(false); policyOpt.setArgs(Option.UNLIMITED_VALUES); options.addOption(policyOpt); Option listNodesOpt = new Option("ln", "listnodes", true, control + "List nodes handled by Resource Manager. Display is : NODESOURCE HOSTNAME STATE NODE_URL"); listNodesOpt.setRequired(false); listNodesOpt.setOptionalArg(true); listNodesOpt.setArgName("nodeSourceName"); actionGroup.addOption(listNodesOpt); Option listNSOpt = new Option("lns", "listns", false, control + "List node sources on Resource Manager. Display is : NODESOURCE TYPE"); listNSOpt.setRequired(false); actionGroup.addOption(listNSOpt); Option topologyOpt = new Option("t", "topology", false, control + "Displays nodes topology."); topologyOpt.setRequired(false); actionGroup.addOption(topologyOpt); Option removeNSOpt = new Option("r", "removens", true, control + "Remove given node sources"); removeNSOpt.setArgName("names"); removeNSOpt.setRequired(false); removeNSOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(removeNSOpt); Option shutdownOpt = new Option("s", "shutdown", false, control + "Shutdown Resource Manager"); shutdownOpt.setRequired(false); actionGroup.addOption(shutdownOpt); Option acopt = new Option("stats", "statistics", false, control + "Display some statistics about the Resource Manager"); acopt.setRequired(false); acopt.setArgs(0); actionGroup.addOption(acopt); acopt = new Option("ma", "myaccount", false, control + "Display current user account informations"); acopt.setRequired(false); acopt.setArgs(0); actionGroup.addOption(acopt); acopt = new Option("ua", "useraccount", false, control + "Display account information by username"); acopt.setRequired(false); acopt.setArgs(1); acopt.setArgName("username"); actionGroup.addOption(acopt); acopt = new Option("ni", "nodeinfo", true, control + "Display node information"); acopt.setRequired(false); acopt.setArgs(1); acopt.setArgName("nodeURL"); actionGroup.addOption(acopt); acopt = new Option("rc", "reloadconfig", false, control + "Reloads the resource manager permission policy and log4j config"); acopt.setRequired(false); acopt.setArgs(0); actionGroup.addOption(acopt); options.addOptionGroup(actionGroup); Option nodeSourceNameOpt = new Option("ns", "nodesource", true, control + "Specify an existing node source name for adding nodes"); nodeSourceNameOpt.setArgName("nodes URLs"); nodeSourceNameOpt.setRequired(false); nodeSourceNameOpt.setArgs(1); options.addOption(nodeSourceNameOpt); Option preeemptiveRemovalOpt = new Option("f", "force", false, control + "Do not wait for busy nodes to be freed before " + "nodes removal, node source removal and shutdown actions (-d, -r and -s)"); preeemptiveRemovalOpt.setRequired(false); options.addOption(preeemptiveRemovalOpt); Option script = new Option("sf", "script", true, control + "Execute the given javascript file with optional arguments."); script.setArgName("filePath arg1=val1 arg2=val2 ..."); script.setArgs(Option.UNLIMITED_VALUES); script.setOptionalArg(true); script.setRequired(false); options.addOption(script); script = new Option("env", "environment", true, "Execute the given script and go into interactive mode"); script.setArgName("filePath"); script.setRequired(false); script.setOptionalArg(true); options.addOption(script); Option opt = new Option("c", "credentials", true, "Path to the credentials (" + Credentials.getCredentialsPath() + ")."); opt.setRequired(false); opt.setArgs(1); options.addOption(opt); return actionGroup; }