List of usage examples for org.apache.commons.cli DefaultParser DefaultParser
DefaultParser
From source file:be.i8c.sag.wm.is.SwaggerImporter.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new DefaultParser(); Options options = getOptions();// w w w . j ava2s. com CommandLine cmd = parser.parse(options, args); HelpFormatter formatter = new HelpFormatter(); if (cmd.hasOption("h")) { formatter.printHelp("", options); } else if (cmd.hasOption("is") && cmd.hasOption("u") && cmd.hasOption("p") && cmd.hasOption("swf") && cmd.hasOption("pkg")) { SwaggerParser swaggerParser = new SwaggerParser(); Swagger swaggerModel = swaggerParser.read(cmd.getOptionValue("swf")); String[] conn = cmd.getOptionValue("is").split(":"); String host = conn[0]; String port = "80"; if (conn.length > 1) { port = conn[1]; } ServerConnection sc = new ServerConnection(host, port, cmd.getOptionValue("u"), cmd.getOptionValue("p"), false); try { logger.info("Connecting to server " + host + "(" + port + ")"); sc.connect(); logger.info("Connected to server"); RestImplementation ri = new RestImplementation(sc, swaggerModel, cmd.getOptionValue("pkg"), cmd.getOptionValue("acl")); ri.generateImplementation(); } catch (Throwable e) { logger.error("Error: " + e.getMessage()); //logger.error(e.getStackTrace()); e.printStackTrace(); } finally { logger.info("Disconnecting from server"); sc.disconnect(); ServerConnectionManager.getInstance().closeServerConnectionManager(); logger.info("Disconnected from server"); logger.info("BYE"); System.exit(0); } } }
From source file:com.github.braully.graph.UtilResultCompare.java
public static void main(String... args) throws Exception { Options options = new Options(); Option input = new Option("i", "input", true, "input file path"); input.setRequired(false);//ww w .j a va 2 s . c o m options.addOption(input); Option output = new Option("o", "output", true, "output file"); output.setRequired(false); options.addOption(output); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("UtilResult", options); System.exit(1); return; } String inputFilePath = cmd.getOptionValue("input"); if (inputFilePath == null) { inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-quartic-ht.txt"; // inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-mft-parcial-ht.txt"; // inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-highlyirregular-ht.txt"; // inputFilePath = "/home/strike/Documentos/grafos-processados/mtf/resultado-ht.txt"; // inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-hypo-parcial-ht.txt"; // inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-eul-ht.txt"; // inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-almhypo-ht.txt"; // inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-Almost_hypohamiltonian_graphs_cubic-parcial-ht.txt"; } if (inputFilePath != null) { if (inputFilePath.toLowerCase().endsWith(".txt")) { processFileTxt(inputFilePath); } else if (inputFilePath.toLowerCase().endsWith(".json")) { processFileJson(inputFilePath); } } }
From source file:example.HelloConsole.java
public static void main(String[] args) throws Exception { Option msg = Option.builder("m").longOpt("message").hasArg().desc("the message to capitalize").build(); Options options = new Options(); options.addOption(msg);// w ww. ja va 2 s .com CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); String message = line.getOptionValue("m", "Hello Ivy!"); System.out.println("standard message : " + message); System.out.println( "capitalized by " + WordUtils.class.getName() + " : " + WordUtils.capitalizeFully(message)); }
From source file:cloudlens.cli.Main.java
public static void main(String[] args) throws Exception { final CommandLineParser optionParser = new DefaultParser(); final HelpFormatter formatter = new HelpFormatter(); final Option lens = Option.builder("r").longOpt("run").hasArg().argName("lens file").desc("Lens file.") .required(true).build();//ww w . java 2 s . co m final Option log = Option.builder("l").longOpt("log").hasArg().argName("log file").desc("Log file.") .build(); final Option jsonpath = Option.builder().longOpt("jsonpath").hasArg().argName("path") .desc("Path to logs in a json object.").build(); final Option js = Option.builder().longOpt("js").hasArg().argName("js file").desc("Load JS file.").build(); final Option format = Option.builder("f").longOpt("format").hasArg() .desc("Choose log format (text or json).").build(); final Option streaming = Option.builder().longOpt("stream").desc("Streaming mode.").build(); final Option history = Option.builder().longOpt("history").desc("Store history.").build(); final Options options = new Options(); options.addOption(log); options.addOption(lens); options.addOption(format); options.addOption(jsonpath); options.addOption(js); options.addOption(streaming); options.addOption(history); try { final CommandLine cmd = optionParser.parse(options, args); final String jsonPath = cmd.getOptionValue("jsonpath"); final String[] jsFiles = cmd.getOptionValues("js"); final String[] lensFiles = cmd.getOptionValues("run"); final String[] logFiles = cmd.getOptionValues("log"); final String source = cmd.getOptionValue("format"); final boolean stream = cmd.hasOption("stream") || !cmd.hasOption("log"); final boolean withHistory = cmd.hasOption("history") || !stream; final CL cl = new CL(System.out, System.err, stream, withHistory); try { final InputStream input = (cmd.hasOption("log")) ? FileReader.readFiles(logFiles) : System.in; if (source == null) { cl.source(input); } else { switch (source) { case "text": cl.source(input); break; case "json": cl.json(input, jsonPath); break; default: input.close(); throw new CLException("Unsupported format: " + source); } } for (final String jsFile : FileReader.fullPaths(jsFiles)) { cl.engine.eval("CL.loadjs('file://" + jsFile + "')"); } final List<ASTElement> top = ASTBuilder.parseFiles(lensFiles); cl.launch(top); } catch (final CLException | ASTException e) { cl.errWriter.println(e.getMessage()); } finally { cl.outWriter.flush(); cl.errWriter.flush(); } } catch (final ParseException e) { System.err.println(e.getMessage()); formatter.printHelp("cloudlens", options); } }
From source file:com.github.braully.graph.UtilResult.java
public static void main(String... args) throws Exception { Options options = new Options(); Option input = new Option("i", "input", true, "input file path"); input.setRequired(false);//from w ww .ja va 2s . co m options.addOption(input); Option verb = new Option("v", "verbose", false, "verbose process"); input.setRequired(false); options.addOption(verb); Option output = new Option("o", "output", true, "output file"); output.setRequired(false); options.addOption(output); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("UtilResult", options); System.exit(1); return; } String inputFilePath = cmd.getOptionValue("input"); if (inputFilePath == null) { inputFilePath = "/home/strike/grafos-para-processar/mft2/resultado.txt"; } if (inputFilePath != null) { if (inputFilePath.toLowerCase().endsWith(".txt")) { processFileTxt(inputFilePath); } else if (inputFilePath.toLowerCase().endsWith(".json")) { processFileJson(inputFilePath); } } }
From source file:com.github.jasmo.Bootstrap.java
public static void main(String[] args) { Options options = new Options().addOption("h", "help", false, "Print help message") .addOption("v", "verbose", false, "Increase verbosity") .addOption("c", "cfn", true, "Enable 'crazy fucking names and set name length (large names == large output size)'") .addOption("p", "package", true, "Move obfuscated classes to this package") .addOption("k", "keep", true, "Don't rename this class"); try {/* www . ja v a 2 s . com*/ CommandLineParser clp = new DefaultParser(); CommandLine cl = clp.parse(options, args); if (cl.hasOption("help")) { help(options); return; } if (cl.hasOption("verbose")) { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); loggerConfig.setLevel(Level.DEBUG); ctx.updateLoggers(); } String[] keep = cl.getOptionValues("keep"); if (cl.getArgList().size() < 2) { throw new ParseException("Expected at-least two arguments"); } log.debug("Input: {}, Output: {}", cl.getArgList().get(0), cl.getArgList().get(1)); Obfuscator o = new Obfuscator(); try { o.supply(Paths.get(cl.getArgList().get(0))); } catch (Exception e) { log.error("An error occurred while reading the source target", e); return; } try { UniqueStringGenerator usg; if (cl.hasOption("cfn")) { int size = Integer.parseInt(cl.getOptionValue("cfn")); usg = new UniqueStringGenerator.Crazy(size); } else { usg = new UniqueStringGenerator.Default(); } o.apply(new FullAccessFlags()); o.apply(new ScrambleStrings()); o.apply(new ScrambleClasses(usg, cl.getOptionValue("package", ""), keep == null ? new String[0] : keep)); o.apply(new ScrambleFields(usg)); o.apply(new ScrambleMethods(usg)); o.apply(new InlineAccessors()); o.apply(new RemoveDebugInfo()); o.apply(new ShuffleMembers()); } catch (Exception e) { log.error("An error occurred while applying transform", e); return; } try { o.write(Paths.get(cl.getArgList().get(1))); } catch (Exception e) { log.error("An error occurred while writing to the destination target", e); return; } } catch (ParseException e) { log.error("Failed to parse command line arguments", e); help(options); } }
From source file:io.rhiot.spec.IoTSpec.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new DefaultParser(); Options options = new Options(); options.addOption(Option.builder("c").longOpt(CONFIG).desc( "Location of the test configuration file. A default value is 'src/main/resources/test.yaml' for easy IDE testing") .hasArg().build());//from ww w. j ava2 s . c om options.addOption(Option.builder("i").longOpt(INSTANCE).desc("Instance of the test; A default value is 1") .hasArg().build()); options.addOption(Option.builder("r").longOpt(REPORT) .desc("Location of the test report. A default value is 'target/report.csv'").hasArg().build()); CommandLine line = parser.parse(options, args); ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); TestProfile test = mapper.readValue(new File(line.getOptionValue(CONFIG, "src/main/resources/test.yaml")), TestProfile.class); int instance = Integer.valueOf(line.getOptionValue(INSTANCE, "1")); test.setInstance(instance); String report = line.getOptionValue(REPORT, "target/report.csv"); test.setReport(new CSVReport(report)); LOG.info("Test '" + test.getName() + "' instance " + instance + " started"); final List<Driver> drivers = test.getDrivers(); ExecutorService executorService = Executors.newFixedThreadPool(drivers.size()); List<Future<Void>> results = executorService.invokeAll(drivers, test.getDuration(), TimeUnit.MILLISECONDS); executorService.shutdownNow(); executorService.awaitTermination(5, TimeUnit.SECONDS); results.forEach(result -> { try { result.get(); } catch (ExecutionException execution) { LOG.warn("Exception running driver", execution); } catch (Exception interrupted) { } }); drivers.forEach(driver -> { driver.stop(); try { test.getReport().print(driver); } catch (Exception e) { LOG.warn("Failed to write reports for the driver " + driver); } LOG.debug("Driver " + driver); LOG.debug("\t " + driver.getResult()); }); test.getReport().close(); LOG.info("Test '" + test.getName() + "' instance " + instance + " finished"); }
From source file:it.anyplace.sync.webclient.Main.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("C", "set-config", true, "set config file for s-client"); options.addOption("h", "help", false, "print help"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("s-client", options); return;/* w w w . ja va2 s.c o m*/ } File configFile = cmd.hasOption("C") ? new File(cmd.getOptionValue("C")) : new File(System.getProperty("user.home"), ".s-client.properties"); logger.info("using config file = {}", configFile); try (ConfigurationService configuration = ConfigurationService.newLoader().loadFrom(configFile)) { FileUtils.cleanDirectory(configuration.getTemp()); KeystoreHandler.newLoader().loadAndStore(configuration); logger.debug("{}", configuration.getStorageInfo().dumpAvailableSpace()); try (HttpService httpService = new HttpService(configuration)) { httpService.start(); if (Desktop.isDesktopSupported()) { Desktop.getDesktop().browse( URI.create("http://localhost:" + httpService.getPort() + "/web/webclient.html")); } httpService.join(); } } }
From source file:br.usp.poli.lta.cereda.spa2run.Main.java
public static void main(String[] args) { Utils.printBanner();/*from ww w .j ava 2 s .co m*/ CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(Utils.getOptions(), args); List<Spec> specs = Utils.fromFilesToSpecs(line.getArgs()); List<Metric> metrics = Utils.fromFilesToMetrics(line); Utils.setMetrics(metrics); Utils.resetCalculations(); AdaptiveAutomaton automaton = Utils.getAutomatonFromSpecs(specs); System.out.println("SPA generated successfully:"); System.out.println("- " + specs.size() + " submachine(s) found."); if (!Utils.detectEpsilon(automaton)) { System.out.println("- No empty transitions."); } if (!metrics.isEmpty()) { System.out.println("- " + metrics.size() + " metric(s) found."); } System.out.println("\nStarting shell, please wait...\n" + "(press CTRL+C or type `:quit'\n" + "to exit the application)\n"); String query = ""; Scanner scanner = new Scanner(System.in); String prompt = "[%d] query> "; String result = "[%d] result> "; int counter = 1; do { try { String term = String.format(prompt, counter); System.out.print(term); query = scanner.nextLine().trim(); if (!query.equals(":quit")) { boolean accept = automaton.recognize(Utils.toSymbols(query)); String type = automaton.getRecognitionPaths().size() == 1 ? " (deterministic)" : " (nondeterministic)"; System.out.println(String.format(result, counter) + accept + type); if (!metrics.isEmpty()) { System.out.println(StringUtils.repeat(" ", String.format("[%d] ", counter).length()) + Utils.prettyPrintMetrics()); } System.out.println(); } } catch (Exception exception) { System.out.println(); Utils.printException(exception); System.out.println(); } counter++; Utils.resetCalculations(); } while (!query.equals(":quit")); System.out.println("That's all folks!"); } catch (ParseException nothandled) { Utils.printHelp(); } catch (Exception exception) { Utils.printException(exception); } }
From source file:io.github.azige.mages.Cli.java
public static void main(String[] args) { Options options = new Options().addOption("h", "help", false, "print this message") .addOption(Option.builder("r").hasArg().argName("bundle").desc("set the ResourceBundle").build()) .addOption(Option.builder("l").hasArg().argName("locale").desc("set the locale").build()) .addOption(Option.builder("t").hasArg().argName("template").desc("set the template").build()) .addOption(Option.builder("p").hasArg().argName("plugin dir") .desc("set the directory to load plugins").build()) .addOption(Option.builder("f").desc("force override existed file").build()); try {/*from ww w.ja v a2s . c om*/ CommandLineParser parser = new DefaultParser(); CommandLine cl = parser.parse(options, args); if (cl.hasOption('h')) { printHelp(System.out, options); return; } MagesSiteGenerator msg = new MagesSiteGenerator(new File("."), new File(".")); String[] fileArgs = cl.getArgs(); if (fileArgs.length < 1) { msg.addTask("."); } else { for (String path : fileArgs) { msg.addTask(path); } } if (cl.hasOption("t")) { msg.setTemplate(new File(cl.getOptionValue("t"))); } if (cl.hasOption("r")) { msg.setResource(new File(cl.getOptionValue("r"))); } else { File resource = new File("Resource.properties"); if (resource.exists()) { msg.setResource(resource); } } if (cl.hasOption("p")) { msg.setPluginDir(new File(cl.getOptionValue("p"))); } if (cl.hasOption("f")) { msg.setForce(true); } msg.start(); } catch (ParseException ex) { System.err.println(ex.getMessage()); printHelp(System.err, options); } }