List of usage examples for org.apache.commons.cli HelpFormatter HelpFormatter
HelpFormatter
From source file:jfractus.app.Main.java
public static void main(String[] args) { createCommandLineOptions();//from w ww. j a v a 2s . c om GnuParser parser = new GnuParser(); HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setOptionComparator(null); CommandLine cmdLine = null; try { cmdLine = parser.parse(cliOptions, args); } catch (ParseException e) { System.err.println(Resources.getString("CLIParseError")); return; } String functionsLibPaths = cmdLine.getOptionValue("libraries"); int threadsNum = FractusPreferencesFactory.prefs.getThreadsNumber(); Dimension outSize = new Dimension(FractusPreferencesFactory.prefs.getDefaultImageWidth(), FractusPreferencesFactory.prefs.getDefaultImageHeight()); AntialiasConfig aaConfig = FractusPreferencesFactory.prefs.getDefaultAntialiasConfig(); boolean printProgress = cmdLine.hasOption("progress"); try { String threadsNumString = cmdLine.getOptionValue("threads"); String imageSizeString = cmdLine.getOptionValue("image-size"); String aaMethodString = cmdLine.getOptionValue("antialias"); String samplingSizeString = cmdLine.getOptionValue("sampling-size"); if (functionsLibPaths != null) FunctionsLoaderFactory.loader.setClassPathsFromString(functionsLibPaths); if (aaMethodString != null) { if (aaMethodString.equals("none")) aaConfig.setMethod(AntialiasConfig.Method.NONE); else if (aaMethodString.equals("normal")) aaConfig.setMethod(AntialiasConfig.Method.NORMAL); else throw new BadValueOfArgumentException("Bad value of argument"); } if (threadsNumString != null) threadsNum = Integer.valueOf(threadsNumString).intValue(); if (imageSizeString != null) parseSize(imageSizeString, outSize); if (samplingSizeString != null) { Dimension samplingSize = new Dimension(); parseSize(samplingSizeString, samplingSize); aaConfig.setSamplingSize(samplingSize.width, samplingSize.height); } if (cmdLine.hasOption("save-prefs")) { FunctionsLoaderFactory.loader.putClassPathsToPrefs(); FractusPreferencesFactory.prefs.setThreadsNumber(threadsNum); FractusPreferencesFactory.prefs.setDefaultImageSize(outSize.width, outSize.height); FractusPreferencesFactory.prefs.setDefaultAntialiasConfig(aaConfig); } } catch (ArgumentParseException e) { System.err.println(Resources.getString("CLIParseError")); return; } catch (NumberFormatException e) { System.err.println(Resources.getString("CLIParseError")); return; } catch (BadValueOfArgumentException e) { System.err.println(Resources.getString("CLIBadValueError")); return; } if (cmdLine.hasOption('h') || (cmdLine.hasOption('n') && cmdLine.getArgs().length < 2)) { helpFormatter.printHelp(Resources.getString("CLISyntax"), cliOptions); return; } if (!cmdLine.hasOption('n')) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } else { String[] cmdArgs = cmdLine.getArgs(); try { FractalDocument fractal = new FractalDocument(); fractal.readFromFile(new File(cmdArgs[0])); FractalRenderer renderer = new FractalRenderer(outSize.width, outSize.height, aaConfig, fractal); FractalImageWriter imageWriter = new FractalImageWriter(renderer, cmdArgs[1]); renderer.setThreadNumber(threadsNum); renderer.prepareFractal(); if (printProgress) { renderer.addRenderProgressListener(new CMDLineProgressEventListener()); imageWriter.addImageWriterProgressListener(new CMDLineImageWriteProgressListener()); } imageWriter.write(); } catch (Exception e) { System.err.println(e.getMessage()); } } }
From source file:me.preilly.SimplePush.java
public static void main(String[] args) throws Exception { /* Parse command line arguments */ Options opt = new Options(); opt.addOption("d", false, "Debug"); opt.addOption("e", true, "Environment to run in"); opt.addOption("h", false, "Print help for this application"); BasicParser parser = new BasicParser(); CommandLine cl = parser.parse(opt, args); boolean err = false; if (cl.hasOption("e")) { environmentKey = cl.getOptionValue("e"); }/*from w w w . j a v a 2s . c o m*/ if (err || cl.hasOption("h")) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("java -jar SimplePush.jar -c cookie [-d -p -e [-f filename]]", opt); System.exit(0); } ConfigFactory factory = ConfigFactory.getInstance(); PropertiesConfiguration config = factory.getConfigProperties(environmentKey, propertiesFileName); Globals.getInstance(config); certName = config.getString(Const.CERT_NAME); certPass = config.getString(Const.CERT_PASSWORD); SimplePush obj = new SimplePush(); obj.pushMessage(); }
From source file:ch.epfl.leb.sass.commandline.CommandLineInterface.java
/** * Shows help, launches the interpreter and executes scripts according to input args. * @param args input arguments/*from w w w. ja va 2 s .c o m*/ */ public static void main(String args[]) { // parse input arguments CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException ex) { System.err.println("Parsing of arguments failed. Reason: " + ex.getMessage()); System.err.println("Use -help for usage."); System.exit(1); } // decide how do we make the interpreter available based on options Interpreter interpreter = null; // show help and exit if (line.hasOption("help")) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java -jar <jar-name>", options, true); System.exit(0); // launch interpreter inside current terminal } else if (line.hasOption("interpreter")) { // assign in, out and err streams to the interpreter interpreter = new Interpreter(new InputStreamReader(System.in), System.out, System.err, true); interpreter.setShowResults(true); // if a script was given, execute it before giving access to user if (line.hasOption("script")) { try { interpreter.source(line.getOptionValue("script")); } catch (IOException ex) { Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE, "IOException while executing shell script.", ex); } catch (EvalError ex) { Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE, "EvalError while executing shell script.", ex); } } // give access to user new Thread(interpreter).start(); // only execute script and exit } else if (line.hasOption("script")) { interpreter = new Interpreter(); try { interpreter.source(line.getOptionValue("script")); System.exit(0); } catch (IOException ex) { Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE, "IOException while executing shell script.", ex); System.exit(1); } catch (EvalError ex) { Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE, "EvalError while executing shell script.", ex); System.exit(1); } // Launches the RPC server with the model contained in the file whose // filename was passed by argument. } else if (line.hasOption("rpc_server")) { IJPluginModel model = new IJPluginModel(); File file = new File(line.getOptionValue("rpc_server")); try { FileInputStream stream = new FileInputStream(file); model = IJPluginModel.read(stream); } catch (FileNotFoundException ex) { System.out.println("Error: " + file.getName() + " not found."); System.exit(1); } catch (Exception ex) { ex.printStackTrace(); } // Check whether a port number was specified. if (line.hasOption("port")) { try { port = Integer.valueOf(line.getOptionValue("port")); System.out.println("Using port: " + String.valueOf(port)); } catch (java.lang.NumberFormatException ex) { System.out.println("Error: the port number argument is not a number."); System.exit(1); } } else { System.out.println("No port number provided. Using default port: " + String.valueOf(port)); } RPCServer server = new RPCServer(model, port); System.out.println("Starting RPC server..."); server.serve(); } else if (line.hasOption("port") & !line.hasOption("rpc_server")) { System.out.println("Error: Port number provided without requesting the RPC server. Exiting..."); System.exit(1); // if System.console() returns null, it means we were launched by // double-clicking the .jar, so launch own BeanShellConsole // if System.console() returns null, it means we were launched by // double-clicking the .jar, so launch own ConsoleFrame } else if (System.console() == null) { BeanShellConsole cframe = new BeanShellConsole("SASS BeanShell Prompt"); interpreter = cframe.getInterpreter(); cframe.setVisible(true); System.setOut(cframe.getInterpreter().getOut()); System.setErr(cframe.getInterpreter().getErr()); new Thread(cframe.getInterpreter()).start(); // otherwise, show help } else { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java -jar <jar-name>", options, true); System.exit(0); } if (interpreter != null) { printWelcomeText(interpreter.getOut()); } }
From source file:name.wagners.fssp.Main.java
/** * @param args/*from ww w. j a v a 2 s.c om*/ * command-line arguments */ public static void main(final String[] args) { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(OptionBuilder.hasArg().withArgName("gn").withLongOpt("generations") .withDescription("Number of generations [default: 50]").withType(Integer.valueOf(0)).create("g")); options.addOption(OptionBuilder.hasArg().withArgName("mp").withLongOpt("mutation") .withDescription("Mutation propability [default: 0.5]").withType(Double.valueOf(0)).create("m")); options.addOption(OptionBuilder.hasArg().withArgName("ps").withLongOpt("populationsize") .withDescription("Size of population [default: 20]").withType(Integer.valueOf(0)).create("p")); options.addOption(OptionBuilder.hasArg().withArgName("rp").withLongOpt("recombination") .withDescription("Recombination propability [default: 0.8]").withType(Double.valueOf(0)) .create("r")); options.addOption(OptionBuilder.hasArg().withArgName("sp").withLongOpt("selectionpressure") .withDescription("Selection pressure [default: 4]").withType(Integer.valueOf(0)).create("s")); options.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message").create("h")); options.addOption(OptionBuilder.hasArg().withArgName("filename").isRequired().withLongOpt("file") .withDescription("Problem file [default: \"\"]").withType(String.valueOf("")).create("f")); options.addOptionGroup(new OptionGroup() .addOption(OptionBuilder.withLongOpt("verbose").withDescription("be extra verbose").create("v")) .addOption(OptionBuilder.withLongOpt("quiet").withDescription("be extra quiet").create("q"))); options.addOption(OptionBuilder.withLongOpt("version") .withDescription("print the version information and exit").create("V")); try { // parse the command line arguments CommandLine line = parser.parse(options, args); // validate that block-size has been set if (line.hasOption("h")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); } } catch (MissingOptionException exp) { log.info("An option was missing:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); } catch (MissingArgumentException exp) { log.info("An argument was missing:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); } catch (AlreadySelectedException exp) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); } catch (ParseException exp) { log.info("Unexpected exception:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); System.exit(1); } // Ausgabe der eingestellten Optionen log.info("Configuration"); // log.info(" Datafile: {}", fname); }
From source file:com.asksunny.tool.RemoteDataStreamer.java
/** * @param args//from w w w .j av a2 s . c om */ public static void main(String[] args) throws Exception { RemoteDataStreamer streamer = new RemoteDataStreamer(); Options options = CLIOptionAnnotationBasedBinder.getOptions(streamer); CLIOptionAnnotationBasedBinder.bindPosix(options, args, streamer); if (streamer.isHelp() || streamer.isVersion() || streamer.getFilePath() == null) { HelpFormatter hfmt = new HelpFormatter(); if (streamer.isHelp()) { hfmt.printHelp(streamer.getClass().getName() + " <options>", options); System.exit(0); } else if (streamer.isVersion()) { System.out.println(VERSION); System.exit(0); } else { hfmt.printHelp(streamer.getClass().getName() + " <options>", options); System.exit(1); } } File f = new File(streamer.getFilePath()); boolean sender = f.exists() && f.isFile(); if (sender && streamer.getHost() == null) { System.err.println("Host option is required for sender"); HelpFormatter hfmt = new HelpFormatter(); hfmt.printHelp(streamer.getClass().getName() + " <options>", options); System.exit(1); } if (sender && streamer.isCompress()) { streamer.sendCompress(); } else if (sender && !streamer.isCompress()) { streamer.send(); } else if (!sender && streamer.isCompress()) { streamer.receiveCompress(); } else { streamer.receive(); } System.out.printf("File %s transfer complete.", streamer.getFilePath()); }
From source file:com.twitter.bazel.checkstyle.CppCheckstyle.java
public static void main(String[] args) throws IOException { CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); options.addOption(Option.builder("f").required(true).hasArg().longOpt("extra_action_file") .desc("bazel extra action protobuf file").build()); options.addOption(Option.builder("c").required(true).hasArg().longOpt("cpplint_file") .desc("Executable cpplint file to invoke").build()); try {/* www. ja va2s .c om*/ // parse the command line arguments CommandLine line = parser.parse(options, args); String extraActionFile = line.getOptionValue("f"); String cpplintFile = line.getOptionValue("c"); Collection<String> sourceFiles = getSourceFiles(extraActionFile); if (sourceFiles.size() == 0) { LOG.fine("No cpp files found by checkstyle"); return; } LOG.fine(sourceFiles.size() + " cpp files found by checkstyle"); // Create and run the command List<String> commandBuilder = new ArrayList<>(); commandBuilder.add(cpplintFile); commandBuilder.add("--linelength=100"); // TODO: https://github.com/twitter/heron/issues/466, // Remove "runtime/references" when we fix all non-const references in our codebase. // TODO: https://github.com/twitter/heron/issues/467, // Remove "runtime/threadsafe_fn" when we fix all non-threadsafe libc functions commandBuilder.add("--filter=-build/header_guard,-runtime/references,-runtime/threadsafe_fn"); commandBuilder.addAll(sourceFiles); runLinter(commandBuilder); } catch (ParseException exp) { LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage())); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java " + CLASSNAME, options); } }
From source file:cc.twittertools.search.local.RunQueries.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(//from ww w . j a v a 2s. c o m OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return") .create(NUM_RESULTS_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("file containing topics in TREC format").create(QUERIES_OPTION)); options.addOption(OptionBuilder.withArgName("similarity").hasArg() .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION)); options.addOption(new Option(VERBOSE_OPTION, "print out complete document")); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(QUERIES_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(RunQueries.class.getName(), options); System.exit(-1); } File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION)); if (!indexLocation.exists()) { System.err.println("Error: " + indexLocation + " does not exist!"); System.exit(-1); } String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG; String topicsFile = cmdline.getOptionValue(QUERIES_OPTION); int numResults = 1000; try { if (cmdline.hasOption(NUM_RESULTS_OPTION)) { numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION)); } } catch (NumberFormatException e) { System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION)); System.exit(-1); } String similarity = "LM"; if (cmdline.hasOption(SIMILARITY_OPTION)) { similarity = cmdline.getOptionValue(SIMILARITY_OPTION); } boolean verbose = cmdline.hasOption(VERBOSE_OPTION); PrintStream out = new PrintStream(System.out, true, "UTF-8"); IndexReader reader = DirectoryReader.open(FSDirectory.open(indexLocation)); IndexSearcher searcher = new IndexSearcher(reader); if (similarity.equalsIgnoreCase("BM25")) { searcher.setSimilarity(new BM25Similarity()); } else if (similarity.equalsIgnoreCase("LM")) { searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); } QueryParser p = new QueryParser(Version.LUCENE_43, StatusField.TEXT.name, IndexStatuses.ANALYZER); TrecTopicSet topics = TrecTopicSet.fromFile(new File(topicsFile)); for (TrecTopic topic : topics) { Query query = p.parse(topic.getQuery()); Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, topic.getQueryTweetTime(), true, true); TopDocs rs = searcher.search(query, filter, numResults); int i = 1; for (ScoreDoc scoreDoc : rs.scoreDocs) { Document hit = searcher.doc(scoreDoc.doc); out.println(String.format("%s Q0 %s %d %f %s", topic.getId(), hit.getField(StatusField.ID.name).numericValue(), i, scoreDoc.score, runtag)); if (verbose) { out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " ")); } i++; } } reader.close(); out.close(); }
From source file:com.anjlab.sat3.Program.java
public static void main(String[] args) throws Exception { System.out.println("Reference Implementation of Romanov's Polynomial Algorithm for 3-SAT Problem" + "\nCopyright (c) 2010 AnjLab" + "\nThis program comes with ABSOLUTELY NO WARRANTY." + "\nThis is free software, and you are welcome to redistribute it under certain conditions." + "\nSee LICENSE.txt file or visit <http://www.gnu.org/copyleft/lesser.html> for details."); LOGGER.debug("Reading version number from manifest"); String implementationVersion = Helper.getImplementationVersionFromManifest("3-SAT Core RI"); System.out.println("Version: " + implementationVersion + "\n"); Options options = getCommandLineOptions(); CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse(options, args); if (commandLine.getArgs().length != 1 || commandLine.hasOption(HELP_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Program.class.getName() + " [OPTIONS] <input-file-name>" + "\nWhere <input-file-name> is a path to file containing k-SAT formula instance in DIMACS CNF or Romanov SKT file format.", options);/* w w w.ja va 2 s .co m*/ System.exit(0); } String formulaFile = commandLine.getArgs()[0]; Helper.UsePrettyPrint = commandLine.hasOption(USE_PRETTY_PRINT_OPTION); Helper.EnableAssertions = !commandLine.hasOption(DISABLE_ASSERTIONS_OPTION); Helper.UseUniversalVarNames = !commandLine.hasOption(USE_ABC_VAR_NAMES_OPTION); Properties statistics = new Properties(); StopWatch stopWatch = new StopWatch(); try { statistics.put(Helper.IMPLEMENTATION_VERSION, implementationVersion); stopWatch.start("Load formula"); ITabularFormula formula = Helper.loadFromFile(formulaFile); long timeElapsed = stopWatch.stop(); statistics.put(Helper.INITIAL_FORMULA_LOAD_TIME, String.valueOf(timeElapsed)); if (commandLine.hasOption(GENERATE_3SAT_OPTION)) { String generated3SatFilename = formulaFile + "-3sat.cnf"; LOGGER.info("Saving 3-SAT formula to {}...", generated3SatFilename); Helper.saveToDIMACSFileFormat(formula, generated3SatFilename); } if (formula.getVarCount() > 26) { LOGGER.info("Variables count > 26 => force using universal names for variables."); Helper.UseUniversalVarNames = true; } statistics.put(Helper.INITIAL_FORMULA_VAR_COUNT, String.valueOf(formula.getVarCount())); statistics.put(Helper.INITIAL_FORMULA_CLAUSES_COUNT, String.valueOf(formula.getClausesCount())); Helper.prettyPrint(formula); stopWatch.printElapsed(); if (commandLine.hasOption(FIND_HSS_ROUTE_OPTION)) { String hssPath = commandLine.getOptionValue(FIND_HSS_ROUTE_OPTION); stopWatch.start("Load HSS from " + hssPath); ObjectArrayList hss = Helper.loadHSS(hssPath); stopWatch.stop(); stopWatch.printElapsed(); findHSSRoute(commandLine, formulaFile, statistics, stopWatch, formula, null, null, hss, hssPath); return; } if (commandLine.hasOption(EVALUATE_OPTION)) { String resultsFilename = commandLine.getOptionValue(EVALUATE_OPTION); boolean satisfiable = evaluateFormula(stopWatch, formula, resultsFilename); if (satisfiable) { System.out.println("Formula evaluated as SAT"); } else { System.out.println("Formula evaluated as UNSAT"); } // Only evaluate formula value return; } // Find if formula is SAT // Clone initial formula to verify formula satisfiability later ITabularFormula formulaClone = null; if (Helper.EnableAssertions) { stopWatch.start("Clone initial formula"); formulaClone = formula.clone(); stopWatch.stop(); stopWatch.printElapsed(); } stopWatch.start("Create CTF"); ObjectArrayList ct = Helper.createCTF(formula); timeElapsed = stopWatch.stop(); printFormulas(ct); stopWatch.printElapsed(); statistics.put(Helper.CTF_CREATION_TIME, String.valueOf(timeElapsed)); statistics.put(Helper.CTF_COUNT, String.valueOf(ct.size())); LOGGER.info("CTF count: {}", ct.size()); if (Helper.EnableAssertions) { assertNoTripletsLost(formula, ct); } // Clone CTF to verify formula satisfiability against it later ObjectArrayList ctfClone = null; if (Helper.EnableAssertions) { ctfClone = Helper.cloneStructures(ct); } stopWatch.start("Create CTS"); Helper.completeToCTS(ct, formula.getPermutation()); timeElapsed = stopWatch.stop(); printFormulas(ct); stopWatch.printElapsed(); statistics.put(Helper.CTS_CREATION_TIME, String.valueOf(timeElapsed)); if (commandLine.hasOption(CREATE_SKT_OPTION)) { String sktFilename = formulaFile + ".skt"; stopWatch.start("Convert CTS to " + sktFilename); Helper.convertCTStructuresToRomanovSKTFileFormat(ct, sktFilename); stopWatch.stop(); stopWatch.printElapsed(); return; } ObjectArrayList hss = unifyAndCreateHSS(statistics, stopWatch, ct); String hssPath = formulaFile + "-hss"; stopWatch.start("Save HSS to " + hssPath + "..."); Helper.saveHSS(hssPath, hss); stopWatch.stop(); stopWatch.printElapsed(); findHSSRoute(commandLine, formulaFile, statistics, stopWatch, formula, formulaClone, ctfClone, hss, hssPath); } catch (EmptyStructureException e) { stopWatch.stop(); stopWatch.printElapsed(); LOGGER.info("One of the structures was built empty", e); String resultsFilename = getResultsFilename(commandLine, formulaFile); stopWatch.start("Saving current statictics of calculations to " + resultsFilename); writeUnsatToFile(resultsFilename, statistics); stopWatch.stop(); stopWatch.printElapsed(); System.out.println("Formula not satisfiable"); } finally { System.out.println("Program completed"); } }
From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java
public static void main(String[] args) { // check & validate cmdline options OptionGroup opt_g = getCMDLineOptionsGroups(); Options opt = getCMDLineOptions();//w w w . j ava 2 s. com opt.addOptionGroup(opt_g); CommandLineParser cli = new DefaultParser(); try { CommandLine cl = cli.parse(opt, args); if (cl.hasOption("v")) { VerboseOutputFilter.SHOW_VERBOSE = true; } switch (opt_g.getSelected()) { case "V": try { URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation(); String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8"); JarFile jarFile = new JarFile(jarPath); Manifest m = jarFile.getManifest(); StringBuilder versionInfo = new StringBuilder(); for (Object key : m.getMainAttributes().keySet()) { versionInfo.append(key).append(":").append(m.getMainAttributes().getValue(key.toString())) .append("\n"); } System.out.println(versionInfo.toString()); } catch (Exception e) { log.error("Version info could not be read."); } break; case "h": HelpFormatter help = new HelpFormatter(); String header = ""; //TODO: missing infotext StringBuilder footer = new StringBuilder("Supported configuration properties :"); help.printHelp("CodeGen -h | -V | -g [...]", header, opt, footer.toString()); break; case "g": // target dir if (cl.hasOption("t")) { File target = new File(cl.getOptionValue("t")); if (target.isDirectory() && target.canExecute() && target.canWrite()) { config.setProperty("target.dir", cl.getOptionValue("t")); } else { log.error("Target dir '{}' is inaccessible!", cl.getOptionValue("t")); break; } } else { config.setProperty("target.dir", System.getProperty("java.io.tmpdir")); } // project dir if (cl.hasOption("p")) { File project = new File(cl.getOptionValue("p")); if (!project.exists()) { if (!project.mkdirs()) { log.error("Project dir '{}' can't be created!", cl.getOptionValue("p")); break; } } if (project.isDirectory() && project.canExecute() && project.canWrite()) { config.setProperty("project.dir", cl.getOptionValue("p")); } else { log.error("Project dir '{}' is inaccessible!", cl.getOptionValue("p")); break; } } generateAppfromXML(cl.getOptionValue("g")); break; } } catch (ParseException e) { log.error("ParseException occurred while parsing cmdline arguments!\n{}", e.getLocalizedMessage()); } }
From source file:com.asual.lesscss.LessEngineCli.java
public static void main(String[] args) throws LessException, URISyntaxException { Options cmdOptions = new Options(); cmdOptions.addOption(LessOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8."); cmdOptions.addOption(LessOptions.COMPRESS_OPTION, false, "Flag that enables compressed CSS output."); cmdOptions.addOption(LessOptions.CSS_OPTION, false, "Flag that enables compilation of .css files."); cmdOptions.addOption(LessOptions.LESS_OPTION, true, "Path to a custom less.js for Rhino version."); try {//from w w w.j a va2 s .c o m CommandLineParser cmdParser = new GnuParser(); CommandLine cmdLine = cmdParser.parse(cmdOptions, args); LessOptions options = new LessOptions(); if (cmdLine.hasOption(LessOptions.CHARSET_OPTION)) { options.setCharset(cmdLine.getOptionValue(LessOptions.CHARSET_OPTION)); } if (cmdLine.hasOption(LessOptions.COMPRESS_OPTION)) { options.setCompress(true); } if (cmdLine.hasOption(LessOptions.CSS_OPTION)) { options.setCss(true); } if (cmdLine.hasOption(LessOptions.LESS_OPTION)) { options.setLess(new File(cmdLine.getOptionValue(LessOptions.LESS_OPTION)).toURI().toURL()); } LessEngine engine = new LessEngine(options); if (System.in.available() != 0) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringWriter sw = new StringWriter(); char[] buffer = new char[1024]; int n = 0; while (-1 != (n = in.read(buffer))) { sw.write(buffer, 0, n); } String src = sw.toString(); if (!src.isEmpty()) { System.out.println(engine.compile(src, null, options.isCompress())); System.exit(0); } } String[] files = cmdLine.getArgs(); if (files.length == 1) { System.out.println(engine.compile(new File(files[0]), options.isCompress())); System.exit(0); } if (files.length == 2) { engine.compile(new File(files[0]), new File(files[1]), options.isCompress()); System.exit(0); } } catch (IOException ioe) { System.err.println("Error opening input file."); } catch (ParseException pe) { System.err.println("Error parsing arguments."); } String[] paths = LessEngine.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath() .split(File.separator); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar " + paths[paths.length - 1] + " input [output] [options]", cmdOptions); System.exit(1); }