List of usage examples for org.apache.commons.cli CommandLineParser parse
CommandLine parse(Options options, String[] arguments) throws ParseException;
From source file:fr.inria.edelweiss.kgdqp.core.FedQueryingCLI.java
@SuppressWarnings("unchecked") public static void main(String args[]) throws ParseException, EngineException { List<String> endpoints = new ArrayList<String>(); String queryPath = null;/* ww w. j av a 2s.c o m*/ int slice = -1; Options options = new Options(); Option helpOpt = new Option("h", "help", false, "print this message"); Option queryOpt = new Option("q", "query", true, "specify the sparql query file"); Option endpointOpt = new Option("e", "endpoints", true, "the list of federated sparql endpoint URLs"); Option groupingOpt = new Option("g", "grouping", true, "triple pattern optimisation"); Option slicingOpt = new Option("s", "slicing", true, "size of the slicing parameter"); Option versionOpt = new Option("v", "version", false, "print the version information and exit"); options.addOption(queryOpt); options.addOption(endpointOpt); options.addOption(helpOpt); options.addOption(versionOpt); options.addOption(groupingOpt); options.addOption(slicingOpt); String header = "Corese/KGRAM DQP command line interface"; String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr"; CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("kgdqp", header, options, footer, true); System.exit(0); } if (!cmd.hasOption("e")) { logger.info("You must specify at least the URL of one sparql endpoint !"); System.exit(0); } else { endpoints = new ArrayList<String>(Arrays.asList(cmd.getOptionValues("e"))); } if (!cmd.hasOption("q")) { logger.info("You must specify a path for a sparql query !"); System.exit(0); } else { queryPath = cmd.getOptionValue("q"); } if (cmd.hasOption("s")) { try { slice = Integer.parseInt(cmd.getOptionValue("s")); } catch (NumberFormatException ex) { logger.warn(cmd.getOptionValue("s") + " is not formatted as number for the slicing parameter"); logger.warn("Slicing disabled"); } } if (cmd.hasOption("v")) { logger.info("version 3.0.4-SNAPSHOT"); System.exit(0); } ///////////////// Graph graph = Graph.create(); QueryProcessDQP exec = QueryProcessDQP.create(graph); exec.setGroupingEnabled(cmd.hasOption("g")); if (slice > 0) { exec.setSlice(slice); } Provider sProv = ProviderImplCostMonitoring.create(); exec.set(sProv); for (String url : endpoints) { try { exec.addRemote(new URL(url), WSImplem.REST); } catch (MalformedURLException ex) { logger.error(url + " is not a well-formed URL"); System.exit(1); } } StringBuffer fileData = new StringBuffer(1000); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(queryPath)); } catch (FileNotFoundException ex) { logger.error("Query file " + queryPath + " not found !"); System.exit(1); } char[] buf = new char[1024]; int numRead = 0; try { while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); } catch (IOException ex) { logger.error("Error while reading query file " + queryPath); System.exit(1); } String sparqlQuery = fileData.toString(); // Query q = exec.compile(sparqlQuery, null); // System.out.println(q); StopWatch sw = new StopWatch(); sw.start(); Mappings map = exec.query(sparqlQuery); int dqpSize = map.size(); System.out.println("--------"); long time = sw.getTime(); System.out.println(time + " " + dqpSize); }
From source file:com.github.megatronking.svg.cli.Main.java
public static void main(String[] args) { Options opt = new Options(); opt.addOption("d", "dir", true, "the target svg directory"); opt.addOption("f", "file", true, "the target svg file"); opt.addOption("o", "output", true, "the output vector file or directory"); opt.addOption("w", "width", true, "the width size of target vector image"); opt.addOption("h", "height", true, "the height size of target vector image"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new PosixParser(); CommandLine cl;/*from w w w .j a v a 2 s.co m*/ try { cl = parser.parse(opt, args); } catch (ParseException e) { formatter.printHelp(HELPER_INFO, opt); return; } if (cl == null) { formatter.printHelp(HELPER_INFO, opt); return; } int width = 0; int height = 0; if (cl.hasOption("w")) { width = SCU.parseInt(cl.getOptionValue("w")); } if (cl.hasOption("h")) { height = SCU.parseInt(cl.getOptionValue("h")); } String dir = null; String file = null; if (cl.hasOption("d")) { dir = cl.getOptionValue("d"); } else if (cl.hasOption("f")) { file = cl.getOptionValue("f"); } String output = null; if (cl.hasOption("o")) { output = cl.getOptionValue("o"); } if (output == null) { if (dir != null) { output = dir; } if (file != null) { output = FileUtils.noExtensionName(file) + ".xml"; } } if (dir == null && file == null) { formatter.printHelp(HELPER_INFO, opt); throw new RuntimeException("You must input the target svg file or directory"); } if (dir != null) { File inputDir = new File(dir); if (!inputDir.exists() || !inputDir.isDirectory()) { throw new RuntimeException("The path [" + dir + "] is not exist or valid directory"); } File outputDir = new File(output); if (outputDir.exists() || outputDir.mkdirs()) { svg2vectorForDirectory(inputDir, outputDir, width, height); } else { throw new RuntimeException("The path [" + outputDir + "] is not a valid directory"); } } if (file != null) { File inputFile = new File(file); if (!inputFile.exists() || !inputFile.isFile()) { throw new RuntimeException("The path [" + file + "] is not exist or valid file"); } svg2vectorForFile(inputFile, new File(output), width, height); } }
From source file:com.dattack.dbtools.ping.Ping.java
/** * The <code>main</code> method. * * @param args/*from w w w .ja va 2s .c o m*/ * the program arguments */ public static void main(final String[] args) { final Options options = createOptions(); try { final CommandLineParser parser = new DefaultParser(); final CommandLine cmd = parser.parse(options, args); final String[] filenames = cmd.getOptionValues(FILE_OPTION); final String[] taskNames = cmd.getOptionValues(TASK_NAME_OPTION); HashSet<String> hs = null; if (taskNames != null) { hs = new HashSet<>(Arrays.asList(taskNames)); } final Ping ping = new Ping(); ping.execute(filenames, hs); } catch (@SuppressWarnings("unused") final ParseException e) { showUsage(options); } catch (final ConfigurationException | DbpingParserException e) { System.err.println(e.getMessage()); } }
From source file:com.evolveum.midpoint.tools.ninja.Main.java
public static void main(String[] args) { Options options = new Options(); options.addOption(help);/*w w w.jav a2s. co m*/ options.addOption(validate); options.addOption(create); options.addOption(importOp); options.addOption(schemaOp); options.addOption(exportOp); options.addOption(driver); options.addOption(url); options.addOption(username); options.addOption(password); options.addOption(Password); options.addOption(keyStore); options.addOption(trans); options.addOption(outputFormat); options.addOption(outputDirectory); options.addOption(input); try { CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); if (line.getOptions().length == 0 || line.hasOption(help.getOpt())) { printHelp(options); return; } //repository validation, if proper option is present boolean valid = validate(line, options); //import DDL, if proper option is present if (line.hasOption(create.getOpt())) { ImportDDL ddl = new ImportDDL(createDDLConfig(line)); if (!ddl.execute()) { System.out.println("DLL import was unsuccessful, skipping other steps."); return; } //repository validation after DDL import, if proper option is present valid = validate(line, options); } //import objects, only if repository validation didn't fail (in case it was tested) if (valid && line.hasOption(importOp.getOpt())) { String path = line.getOptionValue(importOp.getOpt()); boolean validateSchema = line.hasOption(schemaOp.getOpt()); ImportObjects objects = new ImportObjects(path, validateSchema); objects.execute(); } if (valid && line.hasOption(exportOp.getOpt())) { String path = line.getOptionValue(exportOp.getOpt()); ExportObjects objects = new ExportObjects(path); objects.execute(); } if (line.hasOption(keyStore.getOpt())) { KeyStoreDumper keyStoreDumper = new KeyStoreDumper(); keyStoreDumper.execute(); } if (line.hasOption(trans.getOpt())) { if (!checkCommand(line)) { return; } FileTransformer transformer = new FileTransformer(); configureTransformer(transformer, line); transformer.execute(); } } catch (ParseException ex) { System.out.println("Error: " + ex.getMessage()); printHelp(options); } catch (Exception ex) { System.out.println("Exception occurred, reason: " + ex.getMessage()); ex.printStackTrace(); } }
From source file:com.linkedin.helix.tools.ZKDumper.java
public static void main(String[] args) throws Exception { if (args == null || args.length == 0) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java " + ZKDumper.class.getName(), options); System.exit(1);/*w w w .j a v a2 s .c om*/ } CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); cmd.hasOption("zkSvr"); boolean download = cmd.hasOption("download"); boolean upload = cmd.hasOption("upload"); boolean del = cmd.hasOption("delete"); String zkAddress = cmd.getOptionValue("zkSvr"); String zkPath = cmd.getOptionValue("zkpath"); String fsPath = cmd.getOptionValue("fspath"); ZKDumper zkDump = new ZKDumper(zkAddress); if (download) { if (cmd.hasOption("addSuffix")) { zkDump.suffix = cmd.getOptionValue("addSuffix"); } zkDump.download(zkPath, fsPath + zkPath); } if (upload) { if (cmd.hasOption("removeSuffix")) { zkDump.removeSuffix = true; } zkDump.upload(zkPath, fsPath); } if (del) { zkDump.delete(zkPath); } }
From source file:com.opengamma.masterdb.batch.cmd.BatchRunner.java
public static void main(String[] args) throws Exception { // CSIGNORE if (args.length == 0) { usage();/*from w ww .ja va 2 s. c om*/ System.exit(-1); } CommandLine line = null; try { CommandLineParser parser = new PosixParser(); line = parser.parse(getOptions(), args); initialize(line); } catch (ParseException e) { usage(); System.exit(-1); } AbstractApplicationContext appContext = null; try { appContext = getApplicationContext(); appContext.start(); ViewProcessor viewProcessor = appContext.getBean("viewProcessor", ViewProcessor.class); ViewClient viewClient = viewProcessor.createViewClient(UserPrincipal.getLocalUser()); MarketDataSpecification marketDataSpec = new FixedHistoricalMarketDataSpecification( s_observationDateTime.toLocalDate()); ViewCycleExecutionOptions cycleOptions = ViewCycleExecutionOptions.builder() .setValuationTime(s_valuationInstant).setMarketDataSpecification(marketDataSpec) .setResolverVersionCorrection(VersionCorrection.of(s_versionAsOf, s_correctedTo)).create(); ViewCycleExecutionSequence executionSequence = ArbitraryViewCycleExecutionSequence.of(cycleOptions); ExecutionOptions executionOptions = new ExecutionOptions(executionSequence, ExecutionFlags.none().awaitMarketData().get(), null, null); viewClient.attachToViewProcess(UniqueId.parse(s_viewDefinitionUid), executionOptions); } finally { if (appContext != null) { appContext.close(); } } /*if (failed) { s_logger.error("Batch failed."); System.exit(-1); } else { s_logger.info("Batch succeeded."); System.exit(0); }*/ }
From source file:gobblin.test.TestWorker.java
@SuppressWarnings("all") public static void main(String[] args) throws Exception { // Build command-line options Option configOption = OptionBuilder.withArgName("framework config file") .withDescription("Configuration properties file for the framework").hasArgs().withLongOpt("config") .create('c'); Option jobConfigsOption = OptionBuilder.withArgName("job config files") .withDescription("Comma-separated list of job configuration files").hasArgs() .withLongOpt("jobconfigs").create('j'); Option modeOption = OptionBuilder.withArgName("run mode") .withDescription("Test mode (schedule|run); 'schedule' means scheduling the jobs, " + "whereas 'run' means running the jobs immediately") .hasArg().withLongOpt("mode").create('m'); Option helpOption = OptionBuilder.withArgName("help").withDescription("Display usage information") .withLongOpt("help").create('h'); Options options = new Options(); options.addOption(configOption);/*from www.j a v a 2 s. c om*/ options.addOption(jobConfigsOption); options.addOption(modeOption); options.addOption(helpOption); // Parse command-line options CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { printUsage(options); System.exit(0); } // Start the test worker with the given configuration properties Configuration config = new PropertiesConfiguration(cmd.getOptionValue('c')); Properties properties = ConfigurationConverter.getProperties(config); TestWorker testWorker = new TestWorker(properties); testWorker.start(); // Job running mode Mode mode = Mode.valueOf(cmd.getOptionValue('m').toUpperCase()); // Get the list of job configuration files List<String> jobConfigFiles = Lists .newArrayList(Splitter.on(',').omitEmptyStrings().trimResults().split(cmd.getOptionValue('j'))); CountDownLatch latch = new CountDownLatch(jobConfigFiles.size()); for (String jobConfigFile : jobConfigFiles) { // For each job, load the job configuration, then run or schedule the job. Properties jobProps = new Properties(); jobProps.load(new FileReader(jobConfigFile)); jobProps.putAll(properties); testWorker.runJob(jobProps, mode, new TestJobListener(latch)); } // Wait for all jobs to finish latch.await(); testWorker.stop(); }
From source file:jrrombaldo.pset.PSETMain.java
public static void main(String[] args) { Options options = prepareOptions();//from w w w. j a va2s . c o m CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, args); String domain = line.getOptionValue("d"); // print help if (line.hasOption("h")) { printHelp(options); return; } // start gui e do nothing else if (!line.hasOption("c")) { startGuiVersion(domain); return; } // start gui e do nothing else if (!line.hasOption("d")) { System.out.println("a target domain is required, none was specified!"); printHelp(options); return; } if (!line.hasOption("g") && !line.hasOption("b")) { System.out.println("No search engine selected, at least one should be present"); printHelp(options); return; } if (line.hasOption("p")) { String proxy = line.getOptionValue("p"); System.out.println(proxy); } Set<String> results = new HashSet<>(); if (line.hasOption("g")) { results.addAll(new GoogleSearch(domain).listSubdomains()); } if (line.hasOption("b")) { results.addAll(new BingSearch(domain).listSubdomains()); } List<String> sortedResult = new ArrayList<String>(results); Collections.sort(sortedResult); int q = 1; for (String subDomain : sortedResult) { if (q == 1) { System.out.println("\nResults:"); } System.out.println(q + ": " + subDomain); q++; } } catch (ParseException exp) { System.out.println(exp.getLocalizedMessage()); printHelp(options); } catch (Exception e) { e.printStackTrace(); } }
From source file:CircularGenerator.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options helpOptions = new Options(); helpOptions.addOption("h", "help", false, "show this help page"); Options options = new Options(); options.addOption("h", "help", false, "show this help page"); options.addOption(OptionBuilder.withLongOpt("input").withArgName("INPUT") .withDescription("the input FastA File").isRequired().hasArg().create("i")); options.addOption(OptionBuilder.withLongOpt("elongation").withArgName("ELONGATION") .withDescription("the elongation factor [INT]").isRequired().hasArg().create("e")); options.addOption(OptionBuilder.withLongOpt("seq").withArgName("SEQ") .withDescription("the names of the sequences that should to be elongated").isRequired().hasArg() .hasOptionalArgs().hasArg().create("s")); HelpFormatter helpformatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); try {//from w w w .jav a 2 s. c o m CommandLine cmd = parser.parse(helpOptions, args); if (cmd.hasOption('h')) { helpformatter.printHelp(CLASS_NAME + "v" + VERSION, options); System.exit(0); } } catch (ParseException e1) { } String input = ""; String tmpElongation = ""; Integer elongation = 0; String[] names = new String[0]; try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('i')) { input = cmd.getOptionValue('i'); } if (cmd.hasOption('e')) { tmpElongation = cmd.getOptionValue('e'); try { elongation = Integer.parseInt(tmpElongation); } catch (Exception e) { System.err.println("elongation not an Integer: " + tmpElongation); System.exit(0); } } if (cmd.hasOption('s')) { names = cmd.getOptionValues('s'); } } catch (ParseException e) { helpformatter.printHelp(CLASS_NAME, options); System.err.println(e.getMessage()); System.exit(0); } CircularGenerator cg = new CircularGenerator(elongation); File f = new File(input); for (String s : names) { cg.keys_to_treat_circular.add(s); } cg.extendFastA(f); }
From source file:com.canyapan.randompasswordgenerator.cli.Main.java
public static void main(String[] args) { Options options = new Options(); options.addOption("h", false, "prints help"); options.addOption("def", false, "generates 8 character password with default options"); options.addOption("p", true, "password length (default 8)"); options.addOption("l", false, "include lower case characters"); options.addOption("u", false, "include upper case characters"); options.addOption("d", false, "include digits"); options.addOption("s", false, "include symbols"); options.addOption("lc", true, "minimum lower case character count (default 0)"); options.addOption("uc", true, "minimum upper case character count (default 0)"); options.addOption("dc", true, "minimum digit count (default 0)"); options.addOption("sc", true, "minimum symbol count (default 0)"); options.addOption("a", false, "avoid ambiguous characters"); options.addOption("f", false, "force every character type"); options.addOption("c", false, "continuous password generation"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null;/*from w ww .j a va 2 s . c o m*/ boolean printHelp = false; try { cmd = parser.parse(options, args); } catch (ParseException e) { printHelp = true; } if (printHelp || args.length == 0 || cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "java -jar RandomPasswordGenerator.jar [-p <arg>] [-l] [-u] [-s] [-d] [-dc <arg>] [-a] [-f]", options); return; } RandomPasswordGenerator rpg = new RandomPasswordGenerator(); if (cmd.hasOption("def")) { rpg.withDefault().withPasswordLength(Integer.parseInt(cmd.getOptionValue("p", "8"))); } else { rpg.withPasswordLength(Integer.parseInt(cmd.getOptionValue("p", "8"))) .withLowerCaseCharacters(cmd.hasOption("l")).withUpperCaseCharacters(cmd.hasOption("u")) .withDigits(cmd.hasOption("d")).withSymbols(cmd.hasOption("s")) .withAvoidAmbiguousCharacters(cmd.hasOption("a")) .withForceEveryCharacterType(cmd.hasOption("f")); if (cmd.hasOption("lc")) { rpg.withMinLowerCaseCharacterCount(Integer.parseInt(cmd.getOptionValue("lc", "0"))); } if (cmd.hasOption("uc")) { rpg.withMinUpperCaseCharacterCount(Integer.parseInt(cmd.getOptionValue("uc", "0"))); } if (cmd.hasOption("dc")) { rpg.withMinDigitCount(Integer.parseInt(cmd.getOptionValue("dc", "0"))); } if (cmd.hasOption("sc")) { rpg.withMinSymbolCount(Integer.parseInt(cmd.getOptionValue("sc", "0"))); } } Scanner scanner = new Scanner(System.in); try { do { final String password = rpg.generate(); final PasswordMeter.Result result = PasswordMeter.check(password); System.out.printf("%s%nScore: %s%%%nComplexity: %s%n%n", password, result.getScore(), result.getComplexity()); if (cmd.hasOption("c")) { System.out.print("Another? y/N: "); } } while (cmd.hasOption("c") && scanner.nextLine().matches("^(?i:y(?:es)?)$")); } catch (RandomPasswordGeneratorException e) { System.err.println(e.getMessage()); } catch (PasswordMeterException e) { System.err.println(e.getMessage()); } }