List of usage examples for org.apache.commons.cli BasicParser BasicParser
BasicParser
From source file:fr.inria.edelweiss.kgimport.RdfSplitter.java
/** * The application entrypoint, configured through the command line input * arguments./*w w w . j a v a 2s . co m*/ * * @param args the input command line arguments. */ public static void main(String args[]) { RdfSplitter rdfSplitter = new RdfSplitter(); Options options = new Options(); Option helpOpt = new Option("h", "help", false, "Print usage information."); Option inDirOpt = new Option("i", "input-dir", true, "The directory containing RDF files to be loaded."); Option outDirOpt = new Option("o", "output-dir", true, "The directory containing the generated RDF fragments"); Option predFiltOpt = new Option("p", "predicate-filter", true, "Predicate filter used to segment the dataset. " + "You can use multiple filters, typically one per fragment."); Option fragNbOpt = new Option("n", "number-of-fragments", true, "Number of fragments generated for the whole input dataset."); Option fragRepOpt = new Option("f", "fractionning-percentage", true, "Percentage of the whole input dataset for this fragment."); Option tdbOpt = new Option("tdb", "tdb-storage", false, "RDF fragments are persisted into a Jena TDB backend."); Option versionOpt = new Option("v", "version", false, "Print the version information and exit."); options.addOption(inDirOpt); options.addOption(outDirOpt); options.addOption(predFiltOpt); options.addOption(helpOpt); options.addOption(versionOpt); options.addOption(fragNbOpt); options.addOption(fragRepOpt); options.addOption(tdbOpt); String header = "RDF data fragmentation tool command line interface"; String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr"; CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar [].jar", header, options, footer, true); System.exit(0); } if (!cmd.hasOption("i")) { logger.warn("You must specify a valid input directory !"); System.exit(-1); } else { rdfSplitter.setInputDirPath(cmd.getOptionValue("i")); } if (!cmd.hasOption("o")) { logger.warn("You must specify a valid output directory !"); System.exit(-1); } else { rdfSplitter.setOutputDirPath(cmd.getOptionValue("o")); } if (cmd.hasOption("p")) { rdfSplitter.setInputPredicates(new ArrayList<String>(Arrays.asList(cmd.getOptionValues("p")))); } if (cmd.hasOption("f")) { ArrayList<String> opts = new ArrayList<String>(Arrays.asList(cmd.getOptionValues("f"))); for (String opt : opts) { try { rdfSplitter.getFragList().add(Integer.parseInt(opt)); } catch (NumberFormatException e) { logger.error(opt + " cannot be pased as an percentage value."); System.exit(-1); } } } if (cmd.hasOption("n")) { try { rdfSplitter.setFragNb(Integer.parseInt(cmd.getOptionValue("n"))); } catch (NumberFormatException e) { logger.error(cmd.getOptionValue("n") + " cannot be pased as an integer value."); System.exit(-1); } } File oDir = new File(rdfSplitter.getOutputDirPath()); if (oDir.exists()) { logger.warn(rdfSplitter.getOutputDirPath() + " already exists !"); oDir = Files.createTempDir(); logger.warn(oDir.getAbsolutePath() + " created."); rdfSplitter.setOutputDirPath(oDir.getAbsolutePath()); } else { if (oDir.mkdir()) { logger.info(rdfSplitter.getOutputDirPath() + " created."); } } if (!cmd.hasOption("n") && !cmd.hasOption("f") && !cmd.hasOption("p")) { logger.error("You must specify just one fragmentation type through '-n', '-f', or 'p' options"); for (String arg : args) { logger.trace(arg); } System.exit(-1); } String fragName = rdfSplitter.getInputDirPath() .substring(rdfSplitter.getInputDirPath().lastIndexOf("/") + 1); //Input data loading Model model = ModelFactory.createDefaultModel(); File inputDir = new File(rdfSplitter.getInputDirPath()); if (inputDir.isDirectory()) { for (File f : inputDir.listFiles()) { logger.info("Loading " + f.getAbsolutePath()); if (f.isDirectory()) { String directory = f.getAbsolutePath(); Dataset dataset = TDBFactory.createDataset(directory); dataset.begin(ReadWrite.READ); // Get model inside the transaction model.add(dataset.getDefaultModel()); dataset.end(); } else { InputStream iS; try { iS = new FileInputStream(f); if (f.getAbsolutePath().endsWith(".n3")) { model.read(iS, null, "N3"); } else if (f.getAbsolutePath().endsWith(".nt")) { model.read(iS, null, "N-TRIPLES"); } else if (f.getAbsolutePath().endsWith(".rdf")) { model.read(iS, null); } } catch (FileNotFoundException ex) { LogManager.getLogger(RdfSplitter.class.getName()).log(Level.ERROR, "", ex); } } } logger.info("Loaded " + model.size() + " triples"); } else { System.exit(0); } StopWatch sw = new StopWatch(); if (cmd.hasOption("n")) { sw.start(); if (cmd.hasOption("tdb")) { rdfSplitter.saveFragmentsTDB(rdfSplitter.getFragHoriz(model, rdfSplitter.getFragNb()), "Homog-" + fragName); } else { rdfSplitter.saveFragmentsRDF(rdfSplitter.getFragHoriz(model, rdfSplitter.getFragNb()), "Homog-" + fragName); } logger.info("Homog horiz frag in " + sw.getTime() + "ms"); sw.reset(); } else if (cmd.hasOption("f")) { sw.start(); if (cmd.hasOption("tdb")) { rdfSplitter.saveFragmentsTDB(rdfSplitter.getFragHoriz(model, rdfSplitter.getFragList()), "Inhomog-" + fragName); } else { rdfSplitter.saveFragmentsRDF(rdfSplitter.getFragHoriz(model, rdfSplitter.getFragList()), "Inhomog-" + fragName); } logger.info("Inhomog horiz frag in " + sw.getTime() + "ms"); sw.reset(); } else if (cmd.hasOption("p")) { sw.start(); if (cmd.hasOption("tdb")) { rdfSplitter.saveFragmentsTDB(rdfSplitter.getFragVert(model, rdfSplitter.getInputPredicates())); } else { rdfSplitter.saveFragmentsRDF(rdfSplitter.getFragVert(model, rdfSplitter.getInputPredicates())); } logger.info("Vert frag in " + sw.getTime() + "ms"); sw.reset(); } } catch (ParseException ex) { logger.error("Impossible to parse the input command line " + cmd.toString()); } }
From source file:com.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java
/** * Method that runs the optimizer (own method for testing with exceptions). * * @param args command line arguments/* w w w. j av a2s .c om*/ * @throws KeywordOptimizerException in case of an exception during the optimization process */ public static void run(String[] args) throws KeywordOptimizerException { Options options = createCommandLineOptions(); CommandLineParser parser = new BasicParser(); CommandLine cmdLine = null; try { cmdLine = parser.parse(options, args); } catch (ParseException e) { throw new KeywordOptimizerException("Error parsing command line parameters", e); } if (args.length == 0 || cmdLine.hasOption("h")) { printHelp(options); return; } logHeadline("Startup"); OptimizationContext context = createContext(cmdLine); SeedGenerator seedGenerator = getSeedGenerator(cmdLine, context); addCpc(cmdLine, seedGenerator); addMatchTypes(cmdLine, seedGenerator); addLocations(cmdLine, seedGenerator); addLanguages(cmdLine, seedGenerator); AlternativesFinder alternativesFinder = createObjectBasedOnProperty(AlternativesFinder.class, KeywordOptimizerProperty.AlternativesFinderClass, context); TrafficEstimator estimator = createObjectBasedOnProperty(TrafficEstimator.class, KeywordOptimizerProperty.EstimatorClass, context); ScoreCalculator scoreCalculator = createObjectBasedOnProperty(ScoreCalculator.class, KeywordOptimizerProperty.ScoreCalculatorClass, context); Evaluator evaluator = new EstimatorBasedEvaluator(new CachedEstimator(estimator), scoreCalculator); RoundStrategy roundStrategy = createObjectBasedOnProperty(RoundStrategy.class, KeywordOptimizerProperty.RoundStrategyClass, context); Optimizer optimizer = new Optimizer(seedGenerator, alternativesFinder, evaluator, roundStrategy); logHeadline("Optimization"); KeywordCollection bestKeywords = optimizer.optimize(); output(cmdLine, bestKeywords); }
From source file:io.warp10.worf.WorfCLI.java
public int execute(String[] args) { try {// w w w . j a v a 2 s .c o m CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); String inputFile = null; boolean interactive = false; boolean token = false; String outputFile = null; String keyStoreFile = null; String producerUID = null; String ownerUID = null; String appName = null; long ttl = 0L; PrintWriter out = new PrintWriter(System.out); if (cmd.hasOption(HELP)) { help(); return 0; } if (cmd.hasOption(VERSION)) { version(out); return 0; } if (cmd.hasOption(VERBOSE)) { verbose = true; } if (cmd.hasOption(INTERACTIVE)) { interactive = true; } if (cmd.hasOption(OUTPUT)) { outputFile = cmd.getOptionValue(OUTPUT); } if (cmd.hasOption(KEYSTORE)) { keyStoreFile = cmd.getOptionValue(KEYSTORE); } if (cmd.hasOption(TOKEN)) { token = true; // PRODUCER UUID OPTION (mandatory) // -------------------------------------------------------------------- if (cmd.hasOption(UUIDGEN_PRODUCER)) { producerUID = UUID.randomUUID().toString(); } else if (cmd.hasOption(P_UUID)) { producerUID = cmd.getOptionValue(P_UUID); UUID.fromString(producerUID); } // OWNER UUID OPTION (mandatory) // -------------------------------------------------------------------- if (cmd.hasOption(UUIDGEN_OWNER)) { ownerUID = UUID.randomUUID().toString(); } else if (cmd.hasOption(O_UUID)) { ownerUID = cmd.getOptionValue(O_UUID); UUID.fromString(ownerUID); } else { ownerUID = producerUID; } if (cmd.hasOption(APPNAME)) { appName = cmd.getOptionValue(APPNAME); } if (cmd.hasOption(TTL)) { ttl = Long.parseLong(cmd.getOptionValue(TTL)); long ttlMax = Long.MAX_VALUE - System.currentTimeMillis(); if (ttl >= ttlMax) { throw new WorfException("TTL can not be upper than " + ttlMax + " ms"); } } else { throw new WorfException("The option 'ttl' is missing "); } } // get the input file name switch (cmd.getArgs().length) { case 0: throw new WorfException("Config or template file missing."); case 1: inputFile = cmd.getArgs()[0]; break; default: throw new WorfException("Too many arguments, only one config or template file expected."); } // load the interactive mode if (interactive) { return runInteractive(inputFile); } Properties config = Worf.readConfig(inputFile, out); // // TEMPLATE CONFIGURATION // if (WorfTemplate.isTemplate(config)) { // load keystore if needed WorfKeyMaster templateKeyMaster = null; if (!Strings.isNullOrEmpty(keyStoreFile)) { // read config Properties keyStoreConfig = Worf.readConfig(keyStoreFile, out); // load key master templateKeyMaster = new WorfKeyMaster(keyStoreConfig); if (!templateKeyMaster.loadKeyStore()) { throw new WorfException("Template Keystore not loaded"); } } WorfTemplate tpl = new WorfTemplate(config, inputFile); // GENERATE CRYPTO KEYS for (String cryptoKey : tpl.getCryptoKeys()) { String keySize = tpl.generateCryptoKey(cryptoKey); if (keySize != null) { out.println(keySize + " bits secured key for " + cryptoKey + " generated"); } else { throw new WorfException("Unable to generate " + cryptoKey + ", template error"); } } // read defaults if (token) { Properties defaultProperties = Worf.readDefault(inputFile, out); appName = Worf.getDefault(defaultProperties, out, appName, APPNAME); producerUID = Worf.getDefault(defaultProperties, out, producerUID, P_UUID); ownerUID = Worf.getDefault(defaultProperties, out, ownerUID, O_UUID); } // GENERATE TOKENS for (String tokenKey : tpl.getTokenKeys()) { if (!token) { throw new WorfException("Unable to generate template tokens missing -t option"); } if (templateKeyMaster == null) { throw new WorfException("Unable to generate template tokens missing -ks option"); } String tokenIdent = tpl.generateTokenKey(tokenKey, appName, ownerUID, producerUID, ttl, templateKeyMaster); out.println("Token generated key=" + tokenKey + " ident=" + tokenIdent); } // GET INTERACTIVE CONFIGURATION if (tpl.getFieldsStack().size() > 0) { throw new WorfException("Unable the update template, you are not in interactive mode"); } // save the template if (Strings.isNullOrEmpty(outputFile)) { Path inputConfigurationPath = Paths.get(inputFile); String outputFileName = inputConfigurationPath.getFileName().toString(); outputFileName = outputFileName.replace("template", "conf"); StringBuilder sb = new StringBuilder(); sb.append(inputConfigurationPath.getParent().toString()); if (!inputConfigurationPath.endsWith(File.separator)) { sb.append(File.separator); } sb.append(outputFileName); outputFile = sb.toString(); } tpl.saveConfig(outputFile); out.println("Warp configuration saved (" + outputFile + ")"); out.flush(); inputFile = outputFile; // Keystore is given as input //end of the job if (!Strings.isNullOrEmpty(keyStoreFile)) { out.println("Warp configuration file used for tokens generation in templates"); out.println("For generate tokens, reload Worf without 'ks' option"); out.flush(); System.exit(0); } } // // GENERATE TOKEN // if (token) { // read config config = Worf.readConfig(inputFile, out); // load key master WorfKeyMaster keyMaster = new WorfKeyMaster(config); if (!keyMaster.loadKeyStore()) { throw new WorfException("Keystore not loaded"); } Properties defaultProperties = Worf.readDefault(inputFile, out); appName = Worf.getDefault(defaultProperties, out, appName, APPNAME); producerUID = Worf.getDefault(defaultProperties, out, producerUID, P_UUID); ownerUID = Worf.getDefault(defaultProperties, out, ownerUID, O_UUID); // save default if (defaultProperties == null) { Worf.saveDefault(inputFile, appName, producerUID, ownerUID); } // deliver token String readToken = keyMaster.deliverReadToken(appName, producerUID, ownerUID, ttl); String writeToken = keyMaster.deliverWriteToken(appName, producerUID, ownerUID, ttl); // write outputformat JSONObject jsonOutput = new JSONObject(); JSONObject jsonToken = new JSONObject(); jsonToken.put("token", readToken); jsonToken.put("tokenIdent", keyMaster.getTokenIdent(readToken)); jsonToken.put("ttl", ttl); jsonToken.put("application", appName); jsonToken.put("owner", ownerUID); jsonToken.put("producer", producerUID); jsonOutput.put("read", jsonToken); jsonToken = new JSONObject(); jsonToken.put("token", writeToken); jsonToken.put("tokenIdent", keyMaster.getTokenIdent(writeToken)); jsonToken.put("ttl", ttl); jsonToken.put("application", appName); jsonToken.put("owner", ownerUID); jsonToken.put("producer", producerUID); jsonOutput.put("write", jsonToken); System.out.println(jsonOutput.toString()); } } catch (Exception we) { if (verbose) { we.printStackTrace(); } else { System.out.println(we.getMessage() + "\n"); } help(); return -1; } return 0; }
From source file:com.apkcategorychecker.cli.CommandLineInterface.java
public void Initialize(String[] args) { /*--CLI options creation--*/ Options options = new Options(); /*--Add options--*/ options.addOption("p", true, "Path of APK or Directory containing APKs"); options.addOption("csv", true, "To obtain a CSV file result"); options.addOption("k", true, "Keep the decoded APK on the filesystem"); options.addOption("deep", true, "How deep you want to analyze an hybrid app"); /*--CLI parser--*/ CommandLineParser parser = new BasicParser(); CommandLine cmd;//from w w w.ja v a2s . co m try { cmd = parser.parse(options, args); } catch (ParseException pe) { usage(options); return; } /*--CLI options switch--*/ if (cmd.hasOption("p")) { /*--Take the given path--*/ String _value = cmd.getOptionValue("p"); if (_value == ".") { this._givenPath = System.getProperty("user.dir"); } else { this._givenPath = _value; } } /*--If k parameter is passed, the directory of decoded APK will be maintained--*/ if (cmd.hasOption("k")) { this._keep = true; this._outDecoded = cmd.getOptionValue("k"); } if (cmd.hasOption("csv")) { this._choosedResultFormat = "csv"; this._outDir = cmd.getOptionValue("csv"); } if (cmd.hasOption("deep")) { this._deep = Integer.parseInt(cmd.getOptionValue("deep")); } }
From source file:com.dm.estore.server.CommandLineOptions.java
public Properties parse(final String executableName, final String[] args) { Properties properties = null; Options options = generateOptions(); CommandLineParser parser = new BasicParser(); try {/* ww w. ja v a 2s .c om*/ // parse the command line arguments CommandLine line = parser.parse(options, args); // validate that block-size has been set if (line.hasOption(CMD_HELP)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(executableName, options, true); return null; } else { properties = new Properties(); @SuppressWarnings("unchecked") Iterator<Option> iter = line.iterator(); while (iter != null && iter.hasNext()) { Option o = iter.next(); String value = o.getValue(); // if empty then set it to true to mark that it was specified if (value == null) value = Boolean.TRUE.toString(); if (propMap.containsKey(o.getOpt())) { properties.put(propMap.get(o.getOpt()), value); } else { properties.put(o.getOpt(), value); } } } } catch (ParseException exp) { // oops, something went wrong System.err.println("Unable to parse arguments. " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(executableName, options, true); } return properties; }
From source file:com.axelor.shell.core.Target.java
public Object[] findArguments(String[] args) { final List<Object> arguments = new ArrayList<>(method.getParameterTypes().length); final Options options = getOptions(); final CommandLineParser lineParser = new BasicParser(); final CommandLine cmdLine; try {/*from w w w.j a v a 2s.c o m*/ cmdLine = lineParser.parse(options, args); } catch (ParseException e) { System.out.println(); System.out.println(e.getMessage()); System.out.println(); return null; } for (CliOption cliOption : cliOptions) { if (cliOption == null) { arguments.add(cmdLine.getArgs()); continue; } String key = "" + cliOption.shortName(); if (isBlank(key)) { key = cliOption.name(); } Option opt = options.getOption(key); Object value = false; if (opt.hasArgs()) { value = cmdLine.getOptionValues(key); } else if (opt.hasArg()) { value = cmdLine.getOptionValue(key); } else { value = cmdLine.hasOption(key); } arguments.add(value); } return arguments.toArray(); }
From source file:com.asakusafw.compiler.bootstrap.BatchCompilerDriver.java
private static boolean start(String[] args) throws Exception { CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(OPTIONS, args); String output = cmd.getOptionValue(OPT_OUTPUT.getOpt()); String className = cmd.getOptionValue(OPT_CLASS.getOpt()); String packageName = cmd.getOptionValue(OPT_PACKAGE.getOpt()); String hadoopWork = cmd.getOptionValue(OPT_HADOOPWORK.getOpt()); String compilerWork = cmd.getOptionValue(OPT_COMPILERWORK.getOpt()); String link = cmd.getOptionValue(OPT_LINK.getOpt()); String plugin = cmd.getOptionValue(OPT_PLUGIN.getOpt()); File outputDirectory = new File(output); Location hadoopWorkLocation = Location.fromPath(hadoopWork, '/'); File compilerWorkDirectory = new File(compilerWork); List<File> linkingResources = new ArrayList<>(); if (link != null) { for (String s : link.split(File.pathSeparator)) { linkingResources.add(new File(s)); }//from w w w . j a v a 2s . c o m } List<URL> pluginLocations = new ArrayList<>(); if (plugin != null) { for (String s : plugin.split(File.pathSeparator)) { if (s.trim().isEmpty()) { continue; } try { File file = new File(s); if (file.exists() == false) { throw new FileNotFoundException(file.getAbsolutePath()); } URL url = file.toURI().toURL(); pluginLocations.add(url); } catch (IOException e) { LOG.warn(MessageFormat.format(Messages.getString("BatchCompilerDriver.warnFailedToLoadPlugin"), //$NON-NLS-1$ s), e); } } } Class<? extends BatchDescription> batchDescription = Class.forName(className) .asSubclass(BatchDescription.class); boolean succeeded = compile(outputDirectory, batchDescription, packageName, hadoopWorkLocation, compilerWorkDirectory, linkingResources, pluginLocations); if (succeeded) { LOG.info(MessageFormat.format(Messages.getString("BatchCompilerDriver.infoComplete"), //$NON-NLS-1$ batchDescription.getName())); } return succeeded; }
From source file:com.yahoo.sql4dclient.Main.java
private static void defineOptions() { options.addOption("bh", "broker_host", true, "Druid broker node hostname/Ip"); options.addOption("bp", "broker_port", true, "Druid broker node port"); options.addOption("ch", "coordinator_host", true, "Druid coordinator node hostname/Ip"); options.addOption("cp", "coordinator_port", true, "Druid coordinator node port"); options.addOption("oh", "overlord_host", true, "Druid overlord node hostname/Ip"); options.addOption("op", "overlord_port", true, "Druid overlord node port"); options.addOption("mh", "mysql_host", true, "Druid MySql hostname/Ip"); options.addOption("mp", "mysql_port", true, "Druid MySql node port"); options.addOption("mid", "mysql_id", true, "Druid MySql user Id"); options.addOption("mpw", "mysql_passwd", true, "Druid MySql password"); options.addOption("mdb", "mysql_dbname", true, "Druid MySql db name"); options.addOption("pp", "proxy_port", true, "Druid proxy node port"); options.addOption("i", "history", true, "Number of commands in history"); parser = new BasicParser(); }
From source file:kieker.tools.AbstractCommandLineTool.java
private CommandLine parseCommandLineArguments(final Options options, final String[] arguments) { final BasicParser parser = new BasicParser(); try {/*from www.ja va2 s . co m*/ return parser.parse(options, arguments); } catch (final ParseException ex) { // Note that we append ex.getMessage() to the log message on purpose to improve the // logging output on the console. LOG.error("An error occurred while parsing the command line arguments: " + ex.getMessage(), ex); LOG.info("Use the option `--" + CMD_OPT_NAME_HELP_LONG + "` for usage information"); return null; } }
From source file:ee.ria.xroad.common.conf.globalconf.ConfigurationClientMain.java
private static CommandLine getCommandLine(String[] args) throws Exception { CommandLineParser parser = new BasicParser(); Options options = new Options(); options.addOption(OPTION_VERIFY_PRIVATE_PARAMS_EXISTS, false, "Verifies that configuration contains private parameters."); options.addOption(OPTION_VERIFY_ANCHOR_FOR_EXTERNAL_SOURCE, false, "Verifies that configuration contains shared parameters."); return parser.parse(options, args); }