List of usage examples for org.apache.commons.cli HelpFormatter printHelp
public void printHelp(String cmdLineSyntax, String header, Options options, String footer)
options
with the specified command line syntax. From source file:de.citec.csra.highlight.HighlightService.java
public static void main(String[] args) throws InitializeException, RSBException, InterruptedException, ParseException { Options opts = new Options(); opts.addOption("scope", true, "RSB scope for highlight targets.\nDefault: '" + scope + "'"); opts.addOption("server", true, "RSB server for configuration, e.g., tokens.\nDefault: '" + cfg + "'"); opts.addOption("help", false, "Print this help and exit"); String footer = null;/*from www . ja va2 s . c o m*/ // String footer = "\nThe following sub-scopes are registered automatically:\n" // + "\n.../preset for color presets:\n" + Arrays.toString(ColorConfig.values()) // + "\n.../color for color values:\n" + "HSV (comma separated)" // + "\n.../power for power states:\n" + Arrays.toString(PowerState.State.values()) // + "\n.../history for history commands:\n" + Arrays.toString(ColorHistory.values()); CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(opts, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("csra-highlight-service [OPTION...]", "where OPTION includes:", opts, footer); System.exit(0); } if (System.getenv().containsKey(SCOPEVAR)) { scope = System.getenv(SCOPEVAR); } String s = cmd.getOptionValue("scope"); if (s != null) { scope = s; } scope = scope.replaceAll("/$", ""); String c = cmd.getOptionValue("cfg"); if (c != null) { cfg = c; } cfg = cfg.replaceAll("/$", ""); Defaults.loadDefaults(); ExecutorService exec = Executors.newFixedThreadPool(2); exec.submit(() -> { try { ConfigServer cfgServer = new ConfigServer(cfg); cfgServer.execute(); } catch (RSBException ex) { LOG.log(Level.SEVERE, "Config server failed", ex); } }); exec.submit(() -> { try { TaskServer server = new TaskServer(scope, new HighlightTaskHandler()); server.execute(); } catch (RSBException | InterruptedException ex) { LOG.log(Level.SEVERE, "Task server failed", ex); } }); }
From source file:co.cask.cdap.data.tools.CoprocessorBuildTool.java
public static void main(final String[] args) throws ParseException { Options options = new Options().addOption(new Option("h", "help", false, "Print this usage message.")) .addOption(new Option("f", "force", false, "Overwrites any coprocessors that already exist.")); CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); String[] commandArgs = commandLine.getArgs(); // if help is an option, or if there isn't a single 'ensure' command, print usage and exit. if (commandLine.hasOption("h") || commandArgs.length != 1 || !"check".equalsIgnoreCase(commandArgs[0])) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp(CoprocessorBuildTool.class.getName() + " check", "Checks that HBase coprocessors required by CDAP are loaded onto HDFS. " + "If not, the coprocessors are built and placed on HDFS.", options, ""); System.exit(0);/*from w ww .j av a2s .co m*/ } boolean overwrite = commandLine.hasOption("f"); CConfiguration cConf = CConfiguration.create(); Configuration hConf = HBaseConfiguration.create(); Injector injector = Guice.createInjector(new ConfigModule(cConf, hConf), // for LocationFactory new PrivateModule() { @Override protected void configure() { bind(FileContext.class).toProvider(FileContextProvider.class).in(Scopes.SINGLETON); expose(LocationFactory.class); } @Provides @Singleton private LocationFactory providesLocationFactory(Configuration hConf, CConfiguration cConf, FileContext fc) { final String namespace = cConf.get(Constants.CFG_HDFS_NAMESPACE); return new FileContextLocationFactory(hConf, fc, namespace); } }); try { SecurityUtil.loginForMasterService(cConf); } catch (Exception e) { LOG.error("Failed to login as CDAP user", e); System.exit(1); } LocationFactory locationFactory = injector.getInstance(LocationFactory.class); HBaseTableUtil tableUtil = new HBaseTableUtilFactory(cConf).get(); CoprocessorManager coprocessorManager = new CoprocessorManager(cConf, locationFactory, tableUtil); try { Location location = coprocessorManager.ensureCoprocessorExists(overwrite); LOG.info("coprocessor exists at {}.", location); } catch (IOException e) { LOG.error("Unable to build and upload coprocessor jars.", e); System.exit(1); } }
From source file:net.ovres.tuxcourser.TuxCourser.java
public static void main(String[] argss) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("WARN|INFO|FINE").hasArg() .withDescription("Set the log level. Valid values include WARN, INFO, and FINE.") .withLongOpt("loglevel").create("l")); options.addOption("h", "help", false, "Displays this help and exits"); options.addOption("v", "version", false, "Displays version information and exits"); options.addOption(OptionBuilder.withArgName("TYPE").hasArg() .withDescription("Sets the output type. Valid values are tux11 and ppracer05").withLongOpt("output") .create());/*from w w w. j a v a 2 s.co m*/ CommandLineParser parser = new GnuParser(); CommandLine line = null; try { line = parser.parse(options, argss); } catch (ParseException exp) { System.err.println(exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar TuxCourser.jar [Options]", "Options", options, ""); System.exit(-1); } if (line.hasOption("loglevel")) { String lvl = line.getOptionValue("loglevel"); Level logLevel = Level.parse(lvl); Logger.getLogger("net.ovres.tuxcourser").setLevel(logLevel); } if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar TuxCourser.jar [Options]", "Options", options, ""); return; } if (line.hasOption("version")) { System.out.println("TuxCourser Version " + Settings.getVersion()); return; } String[] remaining = line.getArgs(); // Initialize all the different item and terrain types ModuleClassLoader.load(); if (remaining.length == 0) { // Just show the gui. //UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); new net.ovres.tuxcourser.gui.TuxCourserGui().setVisible(true); } else if (remaining.length == 3) { new TuxCourser().convertCourse(new File(remaining[0]), new File(remaining[1]), remaining[2], TYPE_TUXRACER11); } else { usage(); System.exit(-1); } }
From source file:com.github.trohovsky.jira.analyzer.Main.java
public static void main(String[] args) throws Exception { final Options options = new Options(); options.addOption("u", true, "username"); options.addOption("p", true, "password (optional, if not provided, the password is prompted)"); options.addOption("h", false, "show this help"); options.addOption("s", true, "use the strategy for querying and output, the strategy can be either 'issues_toatal' (default) or" + " 'per_month'"); options.addOption("d", true, "CSV delimiter"); // parsing of the command line arguments final CommandLineParser parser = new DefaultParser(); CommandLine cmdLine = null;/*from w w w. j a v a 2s . com*/ try { cmdLine = parser.parse(options, args); if (cmdLine.hasOption('h') || cmdLine.getArgs().length == 0) { final HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(null); formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, null); return; } if (cmdLine.getArgs().length != 3) { throw new ParseException("You should specify exactly three arguments JIRA_SERVER JQL_QUERY_TEMPLATE" + " PATH_TO_PARAMETER_FILE"); } } catch (ParseException e) { System.err.println("Error parsing command line: " + e.getMessage()); final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, null); return; } final String csvDelimiter = (String) (cmdLine.getOptionValue('d') != null ? cmdLine.getOptionObject('d') : CSV_DELIMITER); final URI jiraServerUri = URI.create(cmdLine.getArgs()[0]); final String jqlQueryTemplate = cmdLine.getArgs()[1]; final List<List<String>> queryParametersData = readCSVFile(cmdLine.getArgs()[2], csvDelimiter); final String username = cmdLine.getOptionValue("u"); String password = cmdLine.getOptionValue("p"); final String strategy = cmdLine.getOptionValue("s"); try { // initialization of the REST client final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory(); if (username != null) { if (password == null) { final Console console = System.console(); final char[] passwordCharacters = console.readPassword("Password: "); password = new String(passwordCharacters); } restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, username, password); } else { restClient = factory.create(jiraServerUri, new AnonymousAuthenticationHandler()); } final SearchRestClient searchRestClient = restClient.getSearchClient(); // choosing of an analyzer strategy AnalyzerStrategy analyzer = null; if (strategy != null) { switch (strategy) { case "issues_total": analyzer = new IssuesTotalStrategy(searchRestClient); break; case "issues_per_month": analyzer = new IssuesPerMonthStrategy(searchRestClient); break; default: System.err.println("The strategy does not exist"); return; } } else { analyzer = new IssuesTotalStrategy(searchRestClient); } // analyzing for (List<String> queryParameters : queryParametersData) { analyzer.analyze(jqlQueryTemplate, queryParameters); } } finally { // destroy the REST client, otherwise it stucks restClient.close(); } }
From source file:com.github.trohovsky.just.Main.java
public static void main(String[] args) throws IOException { // parsing of command line final CommandLineParser parser = new GnuParser(); final Options options = new Options(); options.addOption("ai", true, "prefixes of classes from artifacts that will be included"); options.addOption("ae", true, "prefixes of classes from artifacts that will be excluded"); options.addOption("di", true, "prefixes of classes from dependencies that will be included"); options.addOption("de", true, "prefixes of classes from dependencies that will be excluded"); options.addOption("f", "flatten", false, "flatten report, display only used classes"); options.addOption("p", "packages", false, "display package names instead of class names"); options.addOption("u", "unused", false, "display unused classes from dependencies"); options.addOption("h", "help", false, "print this help"); CommandLine cmdLine = null;/* w w w. j av a 2s . com*/ try { cmdLine = parser.parse(options, args); if (cmdLine.hasOption('h')) { final HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(null); formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, HELP_FOOTER); return; } if (cmdLine.getArgs().length == 0) { throw new ParseException("Missing ARTIFACT and/or DEPENDENCY."); } else if (cmdLine.getArgs().length > 2) { throw new ParseException( "More that two arquments found, multiple ARTIFACTs DEPENDENCies should be separated by ','" + " without whitespaces."); } } catch (ParseException e) { System.err.println("Error parsing command line: " + e.getMessage()); final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, HELP_FOOTER); return; } // obtaining of values final String[] artifactPaths = cmdLine.getArgs()[0].split(","); final String[] dependencyPaths = cmdLine.getArgs().length == 2 ? cmdLine.getArgs()[1].split(",") : null; final String[] artifactIncludes = splitValues(cmdLine.getOptionValue("ai")); final String[] artifactExcludes = splitValues(cmdLine.getOptionValue("ae")); final String[] dependencyIncludes = splitValues(cmdLine.getOptionValue("di")); final String[] dependencyExcludes = splitValues(cmdLine.getOptionValue("de")); // validation of values if (dependencyPaths == null) { if (dependencyIncludes != null) { System.err.println("At least one dependency has to be specified to use option -di"); return; } if (dependencyExcludes != null) { System.err.println("At least one dependency has to be specified to use option -de"); return; } if (cmdLine.hasOption('u')) { System.err.println("At least one dependency has to be specified to use option -u"); return; } } // execution Set<String> externalClasses = null; if (dependencyPaths != null) { externalClasses = Reader.from(dependencyPaths).includes(dependencyIncludes).excludes(dependencyExcludes) .listClasses(); } if (cmdLine.hasOption('f') || cmdLine.hasOption('u')) { Set<String> dependencies = Reader.from(artifactPaths).includes(artifactIncludes) .excludes(artifactExcludes).readDependencies(); if (externalClasses != null) { dependencies = DependencyUtils.intersection(dependencies, externalClasses); if (cmdLine.hasOption('u')) { dependencies = DependencyUtils.subtract(externalClasses, dependencies); } } if (cmdLine.hasOption('p')) { dependencies = DependencyUtils.toPackageNames(dependencies); } Reporter.report(dependencies); } else { Map<String, Set<String>> classesWithDependencies = Reader.from(artifactPaths).includes(artifactIncludes) .excludes(artifactExcludes).readClassesWithDependencies(); if (externalClasses != null) { classesWithDependencies = DependencyUtils.intersection(classesWithDependencies, externalClasses); } if (cmdLine.hasOption('p')) { classesWithDependencies = DependencyUtils.toPackageNames(classesWithDependencies); } Reporter.report(classesWithDependencies); } }
From source file:com.jgaap.backend.CLI.java
/** * Parses the arguments passed to jgaap from the command line. Will either * display the help or run jgaap on an experiment. * /*from w w w . j a va 2 s. c o m*/ * @param args * command line arguments * @throws Exception */ public static void main(String[] args) throws Exception { CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { String command = cmd.getOptionValue('h'); if (command == null) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setLeftPadding(5); helpFormatter.setWidth(100); helpFormatter.printHelp( "jgaap -c [canon canon ...] -es [event] -ec [culler culler ...] -a [analysis] <-d [distance]> -l [file] <-s [file]>", "Welcome to JGAAP the Java Graphical Authorship Attribution Program.\nMore information can be found at http://jgaap.com", options, "Copyright 2013 Evaluating Variation in Language Lab, Duquesne University"); } else { List<Displayable> list = new ArrayList<Displayable>(); if (command.equalsIgnoreCase("c")) { list.addAll(Canonicizers.getCanonicizers()); } else if (command.equalsIgnoreCase("es")) { list.addAll(EventDrivers.getEventDrivers()); } else if (command.equalsIgnoreCase("ec")) { list.addAll(EventCullers.getEventCullers()); } else if (command.equalsIgnoreCase("a")) { list.addAll(AnalysisDrivers.getAnalysisDrivers()); } else if (command.equalsIgnoreCase("d")) { list.addAll(DistanceFunctions.getDistanceFunctions()); } else if (command.equalsIgnoreCase("lang")) { list.addAll(Languages.getLanguages()); } for (Displayable display : list) { if (display.showInGUI()) System.out.println(display.displayName() + " - " + display.tooltipText()); } if (list.isEmpty()) { System.out.println("Option " + command + " was not found."); System.out.println("Please use c, es, d, a, or lang"); } } } else if (cmd.hasOption('v')) { System.out.println("Java Graphical Authorship Attribution Program version 5.2.0"); } else if (cmd.hasOption("ee")) { String eeFile = cmd.getOptionValue("ee"); String lang = cmd.getOptionValue("lang"); ExperimentEngine.runExperiment(eeFile, lang); System.exit(0); } else { JGAAP.commandline = true; API api = API.getPrivateInstance(); String documentsFilePath = cmd.getOptionValue('l'); if (documentsFilePath == null) { throw new Exception("No Documents CSV specified"); } List<Document> documents; if (documentsFilePath.startsWith(JGAAPConstants.JGAAP_RESOURCE_PACKAGE)) { documents = Utils.getDocumentsFromCSV( CSVIO.readCSV(com.jgaap.JGAAP.class.getResourceAsStream(documentsFilePath))); } else { documents = Utils.getDocumentsFromCSV(CSVIO.readCSV(documentsFilePath)); } for (Document document : documents) { api.addDocument(document); } String language = cmd.getOptionValue("lang", "english"); api.setLanguage(language); String[] canonicizers = cmd.getOptionValues('c'); if (canonicizers != null) { for (String canonicizer : canonicizers) { api.addCanonicizer(canonicizer); } } String[] events = cmd.getOptionValues("es"); if (events == null) { throw new Exception("No EventDriver specified"); } for (String event : events) { api.addEventDriver(event); } String[] eventCullers = cmd.getOptionValues("ec"); if (eventCullers != null) { for (String eventCuller : eventCullers) { api.addEventCuller(eventCuller); } } String analysis = cmd.getOptionValue('a'); if (analysis == null) { throw new Exception("No AnalysisDriver specified"); } AnalysisDriver analysisDriver = api.addAnalysisDriver(analysis); String distanceFunction = cmd.getOptionValue('d'); if (distanceFunction != null) { api.addDistanceFunction(distanceFunction, analysisDriver); } api.execute(); List<Document> unknowns = api.getUnknownDocuments(); OutputStreamWriter outputStreamWriter; String saveFile = cmd.getOptionValue('s'); if (saveFile == null) { outputStreamWriter = new OutputStreamWriter(System.out); } else { outputStreamWriter = new OutputStreamWriter(new FileOutputStream(saveFile)); } Writer writer = new BufferedWriter(outputStreamWriter); for (Document unknown : unknowns) { writer.append(unknown.getFormattedResult(analysisDriver)); } writer.append('\n'); } }
From source file:co.cask.cdap.etl.tool.UpgradeTool.java
public static void main(String[] args) throws Exception { Options options = new Options().addOption(new Option("h", "help", false, "Print this usage message.")) .addOption(new Option("u", "uri", true, "CDAP instance URI to interact with in the format " + "[http[s]://]<hostname>:<port>. Defaults to localhost:10000.")) .addOption(new Option("a", "accesstoken", true, "File containing the access token to use when interacting " + "with a secure CDAP instance.")) .addOption(new Option("t", "timeout", true, "Timeout in milliseconds to use when interacting with the " + "CDAP RESTful APIs. Defaults to " + DEFAULT_READ_TIMEOUT_MILLIS + ".")) .addOption(new Option("n", "namespace", true, "Namespace to perform the upgrade in. If none is given, " + "pipelines in all namespaces will be upgraded.")) .addOption(new Option("p", "pipeline", true, "Name of the pipeline to upgrade. If specified, a namespace " + "must also be given.")) .addOption(new Option("f", "configfile", true, "File containing old application details to update. " + "The file contents are expected to be in the same format as the request body for creating an " + "ETL application from one of the etl artifacts. " + "It is expected to be a JSON Object containing 'artifact' and 'config' fields." + "The value for 'artifact' must be a JSON Object that specifies the artifact scope, name, and version. " + "The value for 'config' must be a JSON Object specifies the source, transforms, and sinks of the pipeline, " + "as expected by older versions of the etl artifacts.")) .addOption(new Option("o", "outputfile", true, "File to write the converted application details provided in " + "the configfile option. If none is given, results will be written to the input file + '.converted'. " + "The contents of this file can be sent directly to CDAP to update or create an application.")) .addOption(new Option("e", "errorDir", true, "Optional directory to write any upgraded pipeline configs that " + "failed to upgrade. The problematic configs can then be manually edited and upgraded separately. " + "Upgrade errors may happen for pipelines that use plugins that are not backwards compatible. " + "This directory must be writable by the user that is running this tool.")); CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); String[] commandArgs = commandLine.getArgs(); // if help is an option, or if there isn't a single 'upgrade' command, print usage and exit. if (commandLine.hasOption("h") || commandArgs.length != 1 || !"upgrade".equalsIgnoreCase(commandArgs[0])) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp(UpgradeTool.class.getName() + " upgrade", "Upgrades Hydrator pipelines created for 3.2.x versions" + "of the cdap-etl-batch and cdap-etl-realtime artifacts into pipelines compatible with 3.3.x versions of " + "cdap-etl-batch and cdap-etl-realtime. Connects to an instance of CDAP to find any 3.2.x pipelines, then " + "upgrades those pipelines.", options, ""); System.exit(0);/*from w ww .j a va2s. c o m*/ } ClientConfig clientConfig = getClientConfig(commandLine); if (commandLine.hasOption("f")) { String inputFilePath = commandLine.getOptionValue("f"); String outputFilePath = commandLine.hasOption("o") ? commandLine.getOptionValue("o") : inputFilePath + ".new"; convertFile(inputFilePath, outputFilePath, new ArtifactClient(clientConfig)); System.exit(0); } File errorDir = commandLine.hasOption("e") ? new File(commandLine.getOptionValue("e")) : null; if (errorDir != null) { if (!errorDir.exists()) { if (!errorDir.mkdirs()) { LOG.error("Unable to create error directory {}.", errorDir.getAbsolutePath()); System.exit(1); } } else if (!errorDir.isDirectory()) { LOG.error("{} is not a directory.", errorDir.getAbsolutePath()); System.exit(1); } else if (!errorDir.canWrite()) { LOG.error("Unable to write to error directory {}.", errorDir.getAbsolutePath()); System.exit(1); } } UpgradeTool upgradeTool = new UpgradeTool(clientConfig, errorDir); String namespace = commandLine.getOptionValue("n"); String pipelineName = commandLine.getOptionValue("p"); if (pipelineName != null) { if (namespace == null) { throw new IllegalArgumentException("Must specify a namespace when specifying a pipeline."); } Id.Application appId = Id.Application.from(namespace, pipelineName); if (upgradeTool.upgrade(appId)) { LOG.info("Successfully upgraded {}.", appId); } else { LOG.info("{} did not need to be upgraded.", appId); } System.exit(0); } if (namespace != null) { printUpgraded(upgradeTool.upgrade(Id.Namespace.from(namespace))); System.exit(0); } printUpgraded(upgradeTool.upgrade()); }
From source file:com.github.xwgou.namesurfer.fxui.JFXNameSurfer.java
public static void main(String[] args) { JSurferOptions options = new JSurferOptions(); HelpFormatter formatter = new HelpFormatter(); String cmd_line_syntax = "namesurfer [options]"; String help_header = "NameSurfer renders beautiful algebraic surfaces derived from your name."; String help_footer = ""; try {//from www . ja va 2s . com CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption(JSurferOptions.HELP)) { formatter.printHelp(cmd_line_syntax, help_header, options, help_footer); return; } if (cmd.hasOption(JSurferOptions.VERSION)) { System.out.println(JFXNameSurfer.class.getPackage().getImplementationVersion()); return; } fullscreen = cmd.hasOption(JSurferOptions.FULLSCREEN); disable_buttons = cmd.hasOption(JSurferOptions.DISABLE_BUTTONS); InputStream rules = PinyinTranslator.RULES_PATH.openStream(); if (cmd.hasOption(JSurferOptions.RULES)) { rules = new FileInputStream(cmd.getOptionValue(JSurferOptions.RULES)); } InputStream keywords = PinyinTranslator.KEYWORDS_PATH.openStream(); if (cmd.hasOption(JSurferOptions.KEYWORDS)) { keywords = new FileInputStream(cmd.getOptionValue(JSurferOptions.KEYWORDS)); } translator = new PinyinTranslator(rules, keywords); launch(args); } catch (Throwable t) { logger.error("Exception during application startup", t); formatter.printHelp("help", options); System.exit(-1); } }