List of usage examples for org.apache.commons.cli Options Options
Options
From source file:com.crushpaper.Main.java
public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption("help", false, "print this message"); options.addOption("properties", true, "file system path to the crushpaper properties file"); // Parse the command line. CommandLineParser parser = new BasicParser(); CommandLine commandLine = null;/*from www. j av a 2s . c o m*/ try { commandLine = parser.parse(options, args); } catch (ParseException e) { System.err.println("crushpaper: Sorry, could not parse command line because `" + e.getMessage() + "`."); System.exit(1); } if (commandLine == null || commandLine.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("crushpaper", options); return; } // Get the properties path. String properties = null; if (commandLine.hasOption("properties")) { properties = commandLine.getOptionValue("properties"); } if (properties == null || properties.isEmpty()) { System.err.println("crushpaper: Sorry, the `properties` command argument must be specified."); System.exit(1); } Configuration configuration = new Configuration(); if (!configuration.load(new File(properties))) { System.exit(1); } // Get values. File databaseDirectory = configuration.getDatabaseDirectory(); File keyStorePath = configuration.getKeyStoreFile(); Integer httpPort = configuration.getHttpPort(); Integer httpsPort = configuration.getHttpsPort(); Integer httpsProxiedPort = configuration.getHttpsProxiedPort(); String keyStorePassword = configuration.getKeyStorePassword(); String keyManagerPassword = configuration.getKeyManagerPassword(); File temporaryDirectory = configuration.getTemporaryDirectory(); String singleUserName = configuration.getSingleUserName(); Boolean allowSelfSignUp = configuration.getAllowSelfSignUp(); Boolean allowSaveIfNotSignedIn = configuration.getAllowSaveIfNotSignedIn(); File logDirectory = configuration.getLogDirectory(); Boolean loopbackIsAdmin = configuration.getLoopbackIsAdmin(); File sessionStoreDirectory = configuration.getSessionStoreDirectory(); Boolean isOfficialSite = configuration.getIsOfficialSite(); File extraHeaderFile = configuration.getExtraHeaderFile(); // Validate the values. if (httpPort != null && httpsPort != null && httpPort.equals(httpsPort)) { System.err.println("crushpaper: Sorry, `" + configuration.getHttpPortKey() + "` and `" + configuration.getHttpsPortKey() + "` must not be set to the same value."); System.exit(1); } if ((httpsPort == null) != (keyStorePath == null)) { System.err.println("crushpaper: Sorry, `" + configuration.getHttpsPortKey() + "` and `" + configuration.getKeyStoreKey() + "` must either both be set or not set."); System.exit(1); } if (httpsProxiedPort != null && httpsPort == null) { System.err.println("crushpaper: Sorry, `" + configuration.getHttpsProxiedPortKey() + "` can only be set if `" + configuration.getHttpsPortKey() + "` is set."); System.exit(1); } if (databaseDirectory == null) { System.err.println("crushpaper: Sorry, `" + configuration.getDatabaseDirectoryKey() + "` must be set."); System.exit(1); } if (singleUserName != null && !AccountAttributeValidator.isUserNameValid(singleUserName)) { System.err.println( "crushpaper: Sorry, the username in `" + configuration.getSingleUserKey() + "` is not valid."); return; } if (allowSelfSignUp == null || allowSaveIfNotSignedIn == null || loopbackIsAdmin == null) { System.exit(1); } String extraHeader = null; if (extraHeaderFile != null) { extraHeader = readFile(extraHeaderFile); if (extraHeader == null) { System.err.println("crushpaper: Sorry, the file `" + extraHeaderFile.getPath() + "` set in `" + configuration.getExtraHeaderKey() + "` could not be read."); System.exit(1); } } final DbLogic dbLogic = new DbLogic(databaseDirectory); dbLogic.createDb(); final Servlet servlet = new Servlet(dbLogic, singleUserName, allowSelfSignUp, allowSaveIfNotSignedIn, loopbackIsAdmin, httpPort, httpsPort, httpsProxiedPort, keyStorePath, keyStorePassword, keyManagerPassword, temporaryDirectory, logDirectory, sessionStoreDirectory, isOfficialSite, extraHeader); servlet.run(); }
From source file:cc.wikitools.lucene.ScoreWikipediaArticle.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(// www .j av a 2 s . c om OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption( OptionBuilder.withArgName("num").hasArg().withDescription("article id").create(ID_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("article title").create(TITLE_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION)); 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(ID_OPTION) || cmdline.hasOption(TITLE_OPTION)) || !cmdline.hasOption(INDEX_OPTION) || !cmdline.hasOption(QUERY_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ScoreWikipediaArticle.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 queryText = cmdline.getOptionValue(QUERY_OPTION); WikipediaSearcher searcher = new WikipediaSearcher(indexLocation); PrintStream out = new PrintStream(System.out, true, "UTF-8"); if (cmdline.hasOption(ID_OPTION)) { out.println("score: " + searcher.scoreArticle(queryText, Integer.parseInt(cmdline.getOptionValue(ID_OPTION)))); } else { out.println("score: " + searcher.scoreArticle(queryText, cmdline.getOptionValue(TITLE_OPTION))); } searcher.close(); out.close(); }
From source file:ant_ivy.Hello.java
public static void main(String[] args) throws Exception { Option msg = OptionBuilder.withArgName("msg").hasArg().withDescription("the message to capitalize") .create("message"); Options options = new Options(); options.addOption(msg);/*from w w w. j a v a2 s .co m*/ CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); String message = line.getOptionValue("message", "hello ivy !"); System.out.println("standard message : " + message); System.out.println( "capitalized by " + WordUtils.class.getName() + " : " + WordUtils.capitalizeFully(message)); }
From source file:com.benasmussen.tools.testeditor.ExtractorCLI.java
public static void main(String[] args) throws Exception { HelpFormatter formatter = new HelpFormatter(); // cli options Options options = new Options(); options.addOption(CMD_OPT_INPUT, true, "Input file"); // options.addOption(CMD_OPT_OUTPUT, true, "Output file"); try {/* ww w . j a v a2s . c o m*/ // evaluate command line options CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption(CMD_OPT_INPUT)) { // option value String optionValue = cmd.getOptionValue(CMD_OPT_INPUT); // input file File inputFile = new File(optionValue); // id extractor IdExtractor idExtractor = new IdExtractor(inputFile); Vector<Vector> data = idExtractor.parse(); // // TODO implement output folder // if (cmd.hasOption(CMD_OPT_OUTPUT)) // { // // file output // throw new Exception("Not implemented"); // } // else // { // console output System.out.println("Id;Value"); for (Vector vector : data) { StringBuilder sb = new StringBuilder(); if (vector.size() >= 1) { sb.append(vector.get(0)); } sb.append(";"); if (vector.size() >= 2) { sb.append(vector.get(1)); } System.out.println(sb.toString()); } // } } else { throw new IllegalArgumentException(); } } catch (ParseException e) { formatter.printHelp("ExtractorCLI", options); } catch (IllegalArgumentException e) { formatter.printHelp("ExtractorCLI", options); } }
From source file:net.robyf.dbpatcher.Launcher.java
public static void main(final String[] args) throws DBPatcherException { //NOSONAR Options options = new Options(); Option usernameOption = new Option("u", "username", true, "Database username"); usernameOption.setRequired(true);/*from w ww .ja v a2 s. co m*/ options.addOption(usernameOption); Option passwordOption = new Option("p", "password", true, "Database password"); passwordOption.setRequired(true); options.addOption(passwordOption); Option databaseOption = new Option("d", "databaseName", true, "Database name"); databaseOption.setRequired(true); options.addOption(databaseOption); options.addOption("r", "rollback-if-error", false, "Rolls back the entire operation in case of errors"); options.addOption("v", "to-version", true, "Target version number"); options.addOption("s", "simulation", false, "Simulate the operation without touching the current database"); options.addOption("c", "character-set", true, "Character set (default value: ISO-8859-1)"); Parameters parameters = new Parameters(); boolean showHelp = false; try { CommandLine commandLine = new PosixParser().parse(options, args); parameters.setUsername(commandLine.getOptionValue("u")); parameters.setPassword(commandLine.getOptionValue("p")); parameters.setDatabaseName(commandLine.getOptionValue("d")); parameters.setRollbackIfError(commandLine.hasOption("r")); parameters.setSimulationMode(commandLine.hasOption("s")); if (commandLine.hasOption("v")) { parameters.setTargetVersion(new Long(commandLine.getOptionValue("v"))); } if (commandLine.hasOption("c")) { parameters.setCharset(Charset.forName(commandLine.getOptionValue("c"))); } if (commandLine.getArgs().length == 1) { parameters.setSchemaPath(commandLine.getArgs()[0]); } else { showHelp = true; } } catch (ParseException pe) { showHelp = true; } if (showHelp) { new HelpFormatter().printHelp("java -jar dbpatcher.jar" + " -u username -p password -d database_name" + " [options] schema_root", "Available options:", options, ""); } else { DBPatcherFactory.getDBPatcher().patch(parameters); } }
From source file:com.nextdoor.bender.CreateSchema.java
public static void main(String[] args) throws ParseException, InterruptedException, IOException { /*//from w w w .j a va 2s . c o m * Parse cli arguments */ Options options = new Options(); options.addOption(Option.builder().longOpt("out-file").hasArg() .desc("Filename to output schema to. Default: schema.json").build()); options.addOption(Option.builder().longOpt("docson").hasArg(false) .desc("Create a schema that is able to be read by docson").build()); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); String filename = cmd.getOptionValue("out-file", "schema.json"); /* * Write schema */ BenderSchema schema = new BenderSchema(); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); JsonNode node = schema.getSchema(); if (cmd.hasOption("docson")) { modifyNode(node); } mapper.writeValue(new File(filename), node); }
From source file:ISMAGS.CommandLineInterface.java
public static void main(String[] args) throws IOException { String folder = null, files = null, motifspec = null, output = null; Options opts = new Options(); opts.addOption("folder", true, "Folder name"); opts.addOption("linkfiles", true, "Link files seperated by spaces (format: linktype[char] directed[d/u] filename)"); opts.addOption("motif", true, "Motif description by two strings (format: linktypes)"); opts.addOption("output", true, "Output file name"); CommandLineParser parser = new PosixParser(); try {//from www .j ava2 s .c o m CommandLine cmd = parser.parse(opts, args); if (cmd.hasOption("folder")) { folder = cmd.getOptionValue("folder"); } if (cmd.hasOption("linkfiles")) { files = cmd.getOptionValue("linkfiles"); } if (cmd.hasOption("motif")) { motifspec = cmd.getOptionValue("motif"); } if (cmd.hasOption("output")) { output = cmd.getOptionValue("output"); } } catch (ParseException e) { Die("Error: Parsing error"); } if (print) { printBanner(folder, files, motifspec, output); } if (folder == null || files == null || motifspec == null || output == null) { Die("Error: not all options are provided"); } else { ArrayList<String> linkfiles = new ArrayList<String>(); ArrayList<String> linkTypes = new ArrayList<String>(); ArrayList<String> sourcenetworks = new ArrayList<String>(); ArrayList<String> destinationnetworks = new ArrayList<String>(); ArrayList<Boolean> directed = new ArrayList<Boolean>(); StringTokenizer st = new StringTokenizer(files, " "); while (st.hasMoreTokens()) { linkTypes.add(st.nextToken()); directed.add(st.nextToken().equals("d")); sourcenetworks.add(st.nextToken()); destinationnetworks.add(st.nextToken()); linkfiles.add(folder + st.nextToken()); } ArrayList<LinkType> allLinkTypes = new ArrayList<LinkType>(); HashMap<Character, LinkType> typeTranslation = new HashMap<Character, LinkType>(); for (int i = 0; i < linkTypes.size(); i++) { String n = linkTypes.get(i); char nn = n.charAt(0); LinkType t = typeTranslation.get(nn); if (t == null) { t = new LinkType(directed.get(i), n, i, nn, sourcenetworks.get(i), destinationnetworks.get(i)); } allLinkTypes.add(t); typeTranslation.put(nn, t); } if (print) { System.out.println("Reading network.."); } Network network = Network.readNetworkFromFiles(linkfiles, allLinkTypes); Motif motif = getMotif(motifspec, typeTranslation); if (print) { System.out.println("Starting the search.."); } MotifFinder mf = new MotifFinder(network); long tijd = System.nanoTime(); Set<MotifInstance> motifs = mf.findMotif(motif, false); tijd = System.nanoTime() - tijd; if (print) { System.out.println("Completed search in " + tijd / 1000000 + " milliseconds"); } if (print) { System.out.println("Found " + motifs.size() + " instances of " + motifspec + " motif"); } if (print) { System.out.println("Writing instances to file: " + output); } printMotifs(motifs, output); if (print) { System.out.println("Done."); } // Set<MotifInstance> motifs=null; // MotifFinder mf=null; // System.out.println("Starting the search.."); // long tstart = System.nanoTime(); // for (int i = 0; i < it; i++) { // // mf = new MotifFinder(network, allLinkTypes, true); // motifs = mf.findMotif(motif); // } // // long tend = System.nanoTime(); // double time_in_ms = (tend - tstart) / 1000000.0; // System.out.println("Found " + mf.totalFound + " motifs, " + time_in_ms + " ms"); //// System.out.println("Evaluated " + mf.totalNrMappedNodes+ " search nodes"); //// System.out.println("Found " + motifs.size() + " motifs, " + time_in_ms + " ms"); // printMotifs(motifs, output); } }
From source file:com.edduarte.argus.Main.java
public static void main(String[] args) { installUncaughtExceptionHandler();/*from w w w.j a v a 2 s . co m*/ CommandLineParser parser = new GnuParser(); Options options = new Options(); options.addOption("t", "threads", true, "Number of threads to be used " + "for computation and indexing processes. Defaults to the number " + "of available cores."); options.addOption("p", "port", true, "Core server port. Defaults to 9000."); options.addOption("dbh", "db-host", true, "Database host. Defaults to localhost."); options.addOption("dbp", "db-port", true, "Database port. Defaults to 27017."); options.addOption("case", "preserve-case", false, "Keyword matching with case sensitivity."); options.addOption("stop", "stopwords", false, "Keyword matching with stopword filtering."); options.addOption("stem", "stemming", false, "Keyword matching with stemming (lexical variants)."); options.addOption("h", "help", false, "Shows this help prompt."); CommandLine commandLine; try { // Parse the program arguments commandLine = parser.parse(options, args); } catch (ParseException ex) { logger.error("There was a problem processing the input arguments. " + "Write -h or --help to show the list of available commands."); logger.error(ex.getMessage(), ex); return; } if (commandLine.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar argus-core.jar", options); return; } int maxThreads = Runtime.getRuntime().availableProcessors() - 1; maxThreads = maxThreads > 0 ? maxThreads : 1; if (commandLine.hasOption('t')) { String threadsText = commandLine.getOptionValue('t'); maxThreads = Integer.parseInt(threadsText); if (maxThreads <= 0 || maxThreads > 32) { logger.error("Invalid number of threads. Must be a number between 1 and 32."); return; } } int port = 9000; if (commandLine.hasOption('p')) { String portString = commandLine.getOptionValue('p'); port = Integer.parseInt(portString); } String dbHost = "localhost"; if (commandLine.hasOption("dbh")) { dbHost = commandLine.getOptionValue("dbh"); } int dbPort = 27017; if (commandLine.hasOption("dbp")) { String portString = commandLine.getOptionValue("dbp"); dbPort = Integer.parseInt(portString); } boolean isIgnoringCase = true; if (commandLine.hasOption("case")) { isIgnoringCase = false; } boolean isStoppingEnabled = false; if (commandLine.hasOption("stop")) { isStoppingEnabled = true; } boolean isStemmingEnabled = false; if (commandLine.hasOption("stem")) { isStemmingEnabled = true; } try { Context context = Context.getInstance(); context.setIgnoreCase(isIgnoringCase); context.setStopwordsEnabled(isStoppingEnabled); context.setStemmingEnabled(isStemmingEnabled); context.start(port, maxThreads, dbHost, dbPort); } catch (Exception ex) { ex.printStackTrace(); logger.info("Shutting down the server..."); System.exit(1); } }
From source file:fr.tpt.s3.mcdag.generator.MainGenerator.java
/** * Main method for the generator: it launches a given number of threads with the parameters * given//from w w w . ja v a 2 s .c om * @param args */ public static void main(String[] args) { /* ============================ Command line ================= */ Options options = new Options(); Option o_hi = new Option("mu", "max_utilization", true, "Upper bound utilization"); o_hi.setRequired(true); options.addOption(o_hi); Option o_tasks = new Option("nt", "nb_tasks", true, "Number of tasks for the system"); o_tasks.setRequired(true); options.addOption(o_tasks); Option o_eprob = new Option("e", "eprobability", true, "Probability of edges"); o_eprob.setRequired(true); options.addOption(o_eprob); Option o_levels = new Option("l", "levels", true, "Number of criticality levels"); o_levels.setRequired(true); options.addOption(o_levels); Option o_para = new Option("p", "parallelism", true, "Max parallelism for the DAGs"); o_para.setRequired(true); options.addOption(o_para); Option o_nbdags = new Option("nd", "num_dags", true, "Number of DAGs"); o_nbdags.setRequired(true); options.addOption(o_nbdags); Option o_nbfiles = new Option("nf", "num_files", true, "Number of files"); o_nbfiles.setRequired(true); options.addOption(o_nbfiles); Option o_rfactor = new Option("rf", "reduc_factor", true, "Reduction factor for criticality modes"); o_rfactor.setRequired(false); options.addOption(o_rfactor); Option o_out = new Option("o", "output", true, "Output file for the DAG"); o_out.setRequired(true); options.addOption(o_out); Option graphOpt = new Option("g", "graphviz", false, "Generate a graphviz DOT file"); graphOpt.setRequired(false); options.addOption(graphOpt); Option debugOpt = new Option("d", "debug", false, "Enabling debug"); debugOpt.setRequired(false); options.addOption(debugOpt); Option jobsOpt = new Option("j", "jobs", true, "Number of jobs"); jobsOpt.setRequired(false); options.addOption(jobsOpt); 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("DAG Generator", options); System.exit(1); return; } double maxU = Double.parseDouble(cmd.getOptionValue("max_utilization")); int edgeProb = Integer.parseInt(cmd.getOptionValue("eprobability")); int levels = Integer.parseInt(cmd.getOptionValue("levels")); int nbDags = Integer.parseInt(cmd.getOptionValue("num_dags")); int nbFiles = Integer.parseInt(cmd.getOptionValue("num_files")); int para = Integer.parseInt(cmd.getOptionValue("parallelism")); int nbTasks = Integer.parseInt(cmd.getOptionValue("nb_tasks")); boolean graph = cmd.hasOption("graphviz"); boolean debug = cmd.hasOption("debug"); String output = cmd.getOptionValue("output"); int nbJobs = 1; if (cmd.hasOption("jobs")) nbJobs = Integer.parseInt(cmd.getOptionValue("jobs")); double rfactor = 2.0; if (cmd.hasOption("reduc_factor")) rfactor = Double.parseDouble(cmd.getOptionValue("reduc_factor")); /* ============================= Generator parameters ============================= */ if (nbFiles < 0 || nbDags < 0 || nbJobs < 0) { System.err.println("[ERROR] Generator: Number of files & DAGs need to be positive."); formatter.printHelp("DAG Generator", options); System.exit(1); return; } Thread threads[] = new Thread[nbJobs]; int nbFilesCreated = 0; int count = 0; while (nbFilesCreated != nbFiles) { int launched = 0; for (int i = 0; i < nbJobs && count < nbFiles; i++) { String outFile = output.substring(0, output.lastIndexOf('.')).concat("-" + count + ".xml"); GeneratorThread gt = new GeneratorThread(maxU, nbTasks, edgeProb, levels, para, nbDags, rfactor, outFile, graph, debug); threads[i] = new Thread(gt); threads[i].setName("GeneratorThread-" + i); launched++; count++; threads[i].start(); } for (int i = 0; i < launched; i++) { try { threads[i].join(); nbFilesCreated++; } catch (InterruptedException e) { e.printStackTrace(); } } } }
From source file:com.github.zerkseez.codegen.wrappergenerator.Main.java
public static void main(final String[] args) throws Exception { final Options options = new Options(); options.addOption(Option.builder().longOpt("outputDirectory").hasArg().required().build()); options.addOption(Option.builder().longOpt("classMappings").hasArgs().required().build()); final CommandLineParser parser = new DefaultParser(); try {// w w w . j ava 2 s. c om final CommandLine line = parser.parse(options, args); final String outputDirectory = line.getOptionValue("outputDirectory"); final String[] classMappings = line.getOptionValues("classMappings"); for (String classMapping : classMappings) { final String[] tokens = classMapping.split(":"); if (tokens.length != 2) { throw new IllegalArgumentException( String.format("Invalid class mapping format \"%s\"", classMapping)); } final Class<?> wrappeeClass = Class.forName(tokens[0]); final String fullWrapperClassName = tokens[1]; final int indexOfLastDot = fullWrapperClassName.lastIndexOf('.'); final String wrapperPackageName = (indexOfLastDot == -1) ? "" : fullWrapperClassName.substring(0, indexOfLastDot); final String simpleWrapperClassName = (indexOfLastDot == -1) ? fullWrapperClassName : fullWrapperClassName.substring(indexOfLastDot + 1); System.out.println(String.format("Generating wrapper class for %s...", wrappeeClass)); final WrapperGenerator generator = new WrapperGenerator(wrappeeClass, wrapperPackageName, simpleWrapperClassName); generator.writeTo(outputDirectory, true); } System.out.println("Done"); } catch (MissingOptionException e) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(String.format("java -cp CLASSPATH %s", Main.class.getName()), options); } }