List of usage examples for org.apache.commons.cli CommandLine getOptions
public Option[] getOptions()
From source file:org.apache.stratos.cli.commands.UpdateKubernetesHostCommand.java
@Override public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts) throws CommandException { if (log.isDebugEnabled()) { log.debug("Executing command: ", getName()); }/* w ww . j av a 2 s .c o m*/ if ((args == null) || (args.length <= 0)) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } try { CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); //merge newly discovered options with previously discovered ones. Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions()); if (opts.hasOption(CliConstants.RESOURCE_PATH)) { // get resource path arg value String resourcePath = opts.getOption(CliConstants.RESOURCE_PATH).getValue(); if (resourcePath == null) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } String resourceFileContent = CliUtils.readResource(resourcePath); RestCommandLineService.getInstance().updateKubernetesHost(resourceFileContent); return CliConstants.COMMAND_SUCCESSFULL; } else { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } } catch (ParseException e) { log.error("Error parsing arguments", e); System.out.println(e.getMessage()); return CliConstants.COMMAND_FAILED; } catch (IOException e) { System.out.println("Invalid resource path"); return CliConstants.COMMAND_FAILED; } catch (Exception e) { String message = "Unknown error occurred: " + e.getMessage(); System.out.println(message); log.error(message, e); return CliConstants.COMMAND_FAILED; } }
From source file:org.apache.stratos.cli.commands.UpdateKubernetesMasterCommand.java
@Override public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts) throws CommandException { if (log.isDebugEnabled()) { log.debug("Executing command: ", getName()); }//from w w w .j av a2 s .co m if ((args == null) || (args.length <= 0)) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } try { CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); //merge newly discovered options with previously discovered ones. Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions()); if ((opts.hasOption(CliConstants.RESOURCE_PATH)) && (opts.hasOption(CliConstants.CLUSTER_ID_OPTION))) { // get cluster id arg value String clusterId = opts.getOption(CliConstants.CLUSTER_ID_OPTION).getValue(); if (clusterId == null) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } // get resource path arg value String resourcePath = opts.getOption(CliConstants.RESOURCE_PATH).getValue(); if (resourcePath == null) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } String resourceFileContent = CliUtils.readResource(resourcePath); RestCommandLineService.getInstance().updateKubernetesMaster(resourceFileContent, clusterId); return CliConstants.COMMAND_SUCCESSFULL; } else { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } } catch (ParseException e) { log.error("Error parsing arguments", e); System.out.println(e.getMessage()); return CliConstants.COMMAND_FAILED; } catch (IOException e) { System.out.println("Invalid resource path"); return CliConstants.COMMAND_FAILED; } catch (Exception e) { String message = "Unknown error occurred: " + e.getMessage(); System.out.println(message); log.error(message, e); return CliConstants.COMMAND_FAILED; } }
From source file:org.apache.stratos.cli.commands.UpdateNetworkPartitionCommand.java
public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts) throws CommandException { if (log.isDebugEnabled()) { log.debug("Executing {} command...", getName()); }/*www . jav a 2 s. co m*/ if (args != null && args.length > 0) { String resourcePath = null; String resourceFileContent = null; final CommandLineParser parser = new GnuParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); //merge newly discovered options with previously discovered ones. Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions()); if (log.isDebugEnabled()) { log.debug("Network partition deployment"); } if (opts.hasOption(CliConstants.RESOURCE_PATH)) { if (log.isTraceEnabled()) { log.trace("Resource path option is passed"); } resourcePath = opts.getOption(CliConstants.RESOURCE_PATH).getValue(); resourceFileContent = CliUtils.readResource(resourcePath); } if (resourcePath == null) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } RestCommandLineService.getInstance().updateNetworkPartition(resourceFileContent); return CliConstants.COMMAND_SUCCESSFULL; } catch (ParseException e) { log.error("Error parsing arguments", e); System.out.println(e.getMessage()); return CliConstants.COMMAND_FAILED; } catch (IOException e) { System.out.println("Invalid resource path"); return CliConstants.COMMAND_FAILED; } } else { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } }
From source file:org.apache.stratos.cli.commands.UpdateTenantCommand.java
public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts) throws CommandException { if (log.isDebugEnabled()) { log.debug("Executing {} command...", getName()); }/*from ww w .java 2 s .c o m*/ if (args != null && args.length > 0) { String admin = null; String firstName = null; String lastName = null; String password = null; String domain = null; String email = null; int id = 0; final CommandLineParser parser = new GnuParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); //merge newly discovered options with previously discovered ones. Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions()); if (log.isDebugEnabled()) { log.debug("Update tenant"); } if (opts.hasOption(CliConstants.USERNAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Username option is passed"); } admin = opts.getOption(CliConstants.USERNAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.FIRST_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("First name option is passed"); } firstName = opts.getOption(CliConstants.FIRST_NAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.LAST_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Last name option is passed"); } lastName = opts.getOption(CliConstants.LAST_NAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.PASSWORD_OPTION)) { if (log.isTraceEnabled()) { log.trace("Password option is passed"); } password = opts.getOption(CliConstants.PASSWORD_OPTION).getValue(); } if (opts.hasOption(CliConstants.DOMAIN_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Domain name option is passed"); } domain = opts.getOption(CliConstants.DOMAIN_NAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.EMAIL_OPTION)) { if (log.isTraceEnabled()) { log.trace("Email option is passed"); } email = opts.getOption(CliConstants.EMAIL_OPTION).getValue(); } if (opts.hasOption(CliConstants.ID_OPTION)) { if (log.isTraceEnabled()) { log.trace("Id option is passed"); } id = Integer.parseInt(opts.getOption(CliConstants.ID_OPTION).getValue()); } if (id == 0 || admin == null || firstName == null || lastName == null || password == null || domain == null || email == null) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } RestCommandLineService.getInstance().updateTenant(id, admin, firstName, lastName, password, domain, email); return CliConstants.COMMAND_SUCCESSFULL; } catch (ParseException e) { log.error("Error parsing arguments", e); System.out.println(e.getMessage()); return CliConstants.COMMAND_FAILED; } } else { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } }
From source file:org.apache.stratos.cli.commands.UpdateUserCommand.java
public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts) throws CommandException { if (log.isDebugEnabled()) { log.debug("Executing {} command...", getName()); }/*w ww . j a v a2 s .c o m*/ if (args != null && args.length > 0) { String userName = null; String credential = null; String role = null; String firstName = null; String lastName = null; String email = null; String profileName = null; final CommandLineParser parser = new GnuParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); //merge newly discovered options with previously discovered ones. Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions()); if (log.isDebugEnabled()) { log.debug("Update user"); } if (opts.hasOption(CliConstants.USERNAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Username option is passed"); } userName = opts.getOption(CliConstants.USERNAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.PASSWORD_OPTION)) { if (log.isTraceEnabled()) { log.trace("Credential option is passed"); } credential = opts.getOption(CliConstants.PASSWORD_OPTION).getValue(); } if (opts.hasOption(CliConstants.ROLE_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Role option is passed"); } role = opts.getOption(CliConstants.ROLE_NAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.FIRST_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("First name option is passed"); } firstName = opts.getOption(CliConstants.FIRST_NAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.LAST_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Last name option is passed"); } lastName = opts.getOption(CliConstants.LAST_NAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.EMAIL_OPTION)) { if (log.isTraceEnabled()) { log.trace("Email option is passed"); } email = opts.getOption(CliConstants.EMAIL_OPTION).getValue(); } if (opts.hasOption(CliConstants.PROFILE_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Profile name option is passed"); } profileName = opts.getOption(CliConstants.PROFILE_NAME_OPTION).getValue(); } if (userName == null || credential == null || role == null || firstName == null || lastName == null || email == null) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } RestCommandLineService.getInstance().updateUser(userName, credential, role, firstName, lastName, email, profileName); return CliConstants.COMMAND_SUCCESSFULL; } catch (ParseException e) { log.error("Error parsing arguments", e); System.out.println(e.getMessage()); return CliConstants.COMMAND_FAILED; } } else { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } }
From source file:org.apache.tika.batch.fs.FSBatchProcessCLI.java
private void execute(String[] args) throws Exception { CommandLineParser cliParser = new DefaultParser(); CommandLine line = cliParser.parse(options, args); if (line.hasOption("help")) { usage();/*w w w.j av a 2 s . c om*/ System.exit(BatchProcessDriverCLI.PROCESS_NO_RESTART_EXIT_CODE); } Map<String, String> mapArgs = new HashMap<String, String>(); for (Option option : line.getOptions()) { String v = option.getValue(); if (v == null || v.equals("")) { v = "true"; } mapArgs.put(option.getOpt(), v); } BatchProcessBuilder b = new BatchProcessBuilder(); TikaInputStream is = null; BatchProcess process = null; try { is = getConfigInputStream(args, false); process = b.build(is, mapArgs); } finally { IOUtils.closeQuietly(is); } final Thread mainThread = Thread.currentThread(); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<ParallelFileProcessingResult> futureResult = executor.submit(process); ParallelFileProcessingResult result = futureResult.get(); System.out.println(FINISHED_STRING); System.out.println("\n"); System.out.println(result.toString()); System.exit(result.getExitStatus()); }
From source file:org.apache.tika.cli.batch.BundleBatchCLI.java
public void execute(String[] args) throws Exception { CommandLineParser cliParser = new DefaultParser(); CommandLine line = cliParser.parse(options, args); if (line.hasOption("help")) { usage();/*from w w w . j a v a 2 s .c o m*/ System.exit(BatchProcessDriverCLI.PROCESS_NO_RESTART_EXIT_CODE); } Map<String, String> mapArgs = new HashMap<String, String>(); for (Option option : line.getOptions()) { String v = option.getValue(); if (v == null || v.equals("")) { v = "true"; } mapArgs.put(option.getOpt(), v); } BatchProcessBuilder b = new BatchProcessBuilder(); TikaInputStream is = null; BatchProcess process = null; try { is = getConfigInputStream(args, false); process = b.build(is, mapArgs); } finally { IOUtils.closeQuietly(is); } final Thread mainThread = Thread.currentThread(); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<ParallelFileProcessingResult> futureResult = executor.submit(process); ParallelFileProcessingResult result = futureResult.get(); System.out.println(FINISHED_STRING); System.out.println("\n"); System.out.println(result.toString()); }
From source file:org.apparatus_templi.Coordinator.java
/** * Parse all command line arguments. Any preferences read from the command like will be put into * the {@link Prefs} singleton.//from ww w.j a v a 2 s . c o m * * @param argv * the command line arguments to be parsed */ private static void parseCommandLineOptions(String[] argv) { assert argv != null : "command line arguments should never be null"; // Using apache commons cli to parse the command line options Options options = new Options(); options.addOption("help", false, "Display this help message."); // the commons cli parser does not allow '.' within the option names, so we have to replace // the periods with underscores for now. When parsing the args later the underscores will be // converted back to proper dot notation for (String key : prefs.getDefPreferencesMap().keySet()) { String optName; if (key.contains(".")) { optName = key.replaceAll("\\.", "_"); } else { optName = key; } options.addOption(OptionBuilder.withArgName(optName).hasArg() .withDescription(prefs.getPreferenceDesc(key)).create(optName)); } CommandLineParser cliParser = new org.apache.commons.cli.PosixParser(); try { CommandLine cmd = cliParser.parse(options, argv); if (cmd.hasOption("help")) { // show help message and exit HelpFormatter formatter = new HelpFormatter(); formatter.setOptPrefix("--"); formatter.setLongOptPrefix("--"); formatter.printHelp(TAG, options); System.exit(0); } // Load the configuration file URI String configFile; if (cmd.hasOption(Prefs.Keys.configFile)) { configFile = cmd.getOptionValue(Prefs.Keys.configFile); if (configFile.startsWith("~" + File.separator)) { configFile = System.getProperty("user.home") + configFile.substring(1); } } else { configFile = prefs.getDefPreference(Prefs.Keys.configFile); } prefs.putPreference(Prefs.Keys.configFile, configFile); // Read in preferences from the config file prefs.readPreferences(configFile); // Read in preferences from the command line options for (Option opt : cmd.getOptions()) { // Apache CLI parser does not allow '.' within option names, so we have to convert // all '_' back to the '.' notation String key = opt.getArgName().replace("_", "."); String value = opt.getValue(); prefs.putPreference(key, value); } } catch (ParseException e) { System.out.println("Error processing options: " + e.getMessage()); new HelpFormatter().printHelp("Diff", options); Coordinator.exitWithReason("Error parsing command line options"); } }
From source file:org.archive.io.arc.ARCReader.java
/** * Command-line interface to ARCReader./*from w ww . ja va 2 s . c om*/ * * Here is the command-line interface: * <pre> * usage: java org.archive.io.arc.ARCReader [--offset=#] ARCFILE * -h,--help Prints this message and exits. * -o,--offset Outputs record at this offset into arc file.</pre> * * <p>See in <code>$HERITRIX_HOME/bin/arcreader</code> for a script that'll * take care of classpaths and the calling of ARCReader. * * <p>Outputs using a pseudo-CDX format as described here: * <a href="http://www.archive.org/web/researcher/cdx_legend.php">CDX * Legent</a> and here * <a href="http://www.archive.org/web/researcher/example_cdx.php">Example</a>. * Legend used in below is: 'CDX b e a m s c V (or v if uncompressed) n g'. * Hash is hard-coded straight SHA-1 hash of content. * * @param args Command-line arguments. * @throws ParseException Failed parse of the command line. * @throws IOException * @throws java.text.ParseException */ @SuppressWarnings("unchecked") public static void main(String[] args) throws ParseException, IOException, java.text.ParseException { Options options = getOptions(); options.addOption(new Option("p", "parse", false, "Parse headers.")); PosixParser parser = new PosixParser(); CommandLine cmdline = parser.parse(options, args, false); List<String> cmdlineArgs = cmdline.getArgList(); Option[] cmdlineOptions = cmdline.getOptions(); HelpFormatter formatter = new HelpFormatter(); // If no args, print help. if (cmdlineArgs.size() <= 0) { usage(formatter, options, 0); } // Now look at options passed. long offset = -1; boolean digest = false; boolean strict = false; boolean parse = false; String format = CDX; for (int i = 0; i < cmdlineOptions.length; i++) { switch (cmdlineOptions[i].getId()) { case 'h': usage(formatter, options, 0); break; case 'o': offset = Long.parseLong(cmdlineOptions[i].getValue()); break; case 's': strict = true; break; case 'p': parse = true; break; case 'd': digest = getTrueOrFalse(cmdlineOptions[i].getValue()); break; case 'f': format = cmdlineOptions[i].getValue().toLowerCase(); boolean match = false; // List of supported formats. final String[] supportedFormats = { CDX, DUMP, GZIP_DUMP, HEADER, NOHEAD, CDX_FILE }; for (int ii = 0; ii < supportedFormats.length; ii++) { if (supportedFormats[ii].equals(format)) { match = true; break; } } if (!match) { usage(formatter, options, 1); } break; default: throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId()); } } if (offset >= 0) { if (cmdlineArgs.size() != 1) { System.out.println("Error: Pass one arcfile only."); usage(formatter, options, 1); } ARCReader arc = ARCReaderFactory.get((String) cmdlineArgs.get(0), offset); arc.setStrict(strict); // We must parse headers if we need to skip them. if (format.equals(NOHEAD) || format.equals(HEADER)) { parse = true; } arc.setParseHttpHeaders(parse); outputRecord(arc, format); } else { for (String urlOrPath : cmdlineArgs) { try { ARCReader r = ARCReaderFactory.get(urlOrPath); r.setStrict(strict); r.setParseHttpHeaders(parse); r.setDigest(digest); output(r, format); } catch (RuntimeException e) { // Write out name of file we failed on to help with // debugging. Then print stack trace and try to keep // going. We do this for case where we're being fed // a bunch of ARCs; just note the bad one and move // on to the next. System.err.println("Exception processing " + urlOrPath + ": " + e.getMessage()); e.printStackTrace(System.err); System.exit(1); } } } }
From source file:org.archive.io.Arc2Warc.java
/** * Command-line interface to Arc2Warc.// ww w . j a va 2 s . co m * * @param args Command-line arguments. * @throws ParseException Failed parse of the command line. * @throws IOException * @throws java.text.ParseException */ @SuppressWarnings("unchecked") public static void main(String[] args) throws ParseException, IOException, java.text.ParseException { Options options = new Options(); options.addOption(new Option("h", "help", false, "Prints this message and exits.")); options.addOption(new Option("f", "force", false, "Force overwrite of target file.")); PosixParser parser = new PosixParser(); CommandLine cmdline = parser.parse(options, args, false); List<String> cmdlineArgs = cmdline.getArgList(); Option[] cmdlineOptions = cmdline.getOptions(); HelpFormatter formatter = new HelpFormatter(); // If no args, print help. if (cmdlineArgs.size() <= 0) { usage(formatter, options, 0); } // Now look at options passed. boolean force = false; for (int i = 0; i < cmdlineOptions.length; i++) { switch (cmdlineOptions[i].getId()) { case 'h': usage(formatter, options, 0); break; case 'f': force = true; break; default: throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId()); } } // If no args, print help. if (cmdlineArgs.size() != 2) { usage(formatter, options, 0); } (new Arc2Warc()).transform(new File(cmdlineArgs.get(0)), new File(cmdlineArgs.get(1)), force); }