List of usage examples for org.apache.commons.cli CommandLine getOptionValues
public String[] getOptionValues(char opt)
From source file:com.denimgroup.threadfix.cli.CommandLineParser.java
public static void main(String[] args) { Options options = getOptions();//from w w w. ja v a 2s. c o m PosixParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar tfcli.jar", options); } else if (cmd.hasOption("s")) { String[] setArgs = cmd.getOptionValues("s"); if (setArgs == null || setArgs.length != 2) { throw new ParseException("Bad arguments for set."); } if ("url".equals(setArgs[0])) { System.out.println("Setting URL to " + setArgs[1]); client.setUrl(setArgs[1]); } else if ("key".equals(setArgs[0])) { System.out.println("Setting API Key to " + setArgs[1]); client.setKey(setArgs[1]); } else { throw new ParseException("First argument to set must be url or key"); } } else if (cmd.hasOption("ct")) { String[] createArgs = cmd.getOptionValues("ct"); if (createArgs.length != 1) { throw new ParseException("Wrong number of arguments."); } System.out.println("Creating a Team with the name " + createArgs[0] + "."); System.out.println(client.createTeam(createArgs[0])); } else if (cmd.hasOption("cw")) { String[] createArgs = cmd.getOptionValues("cw"); if (createArgs.length != 2) { throw new ParseException("Wrong number of arguments."); } System.out.println("Creating a Waf with the name " + createArgs[0] + "."); System.out.println(client.createWaf(createArgs[0], createArgs[1])); } else if (cmd.hasOption("ca")) { String[] createArgs = cmd.getOptionValues("ca"); if (createArgs.length != 3) { throw new ParseException("Wrong number of arguments."); } System.out.println("Creating an Application with the name " + createArgs[1] + "."); System.out.println(client.createApplication(createArgs[0], createArgs[1], createArgs[2])); } else if (cmd.hasOption("teams")) { System.out.println("Getting all teams."); System.out.println(client.getAllTeams()); } else if (cmd.hasOption("u")) { String[] uploadArgs = cmd.getOptionValues("u"); // Upload a scan if (uploadArgs.length != 2) { throw new ParseException("Wrong number of arguments."); } System.out.println("Uploading " + uploadArgs[1] + " to Application " + uploadArgs[0] + "."); System.out.println(client.uploadScan(uploadArgs[0], uploadArgs[1])); } else if (cmd.hasOption("st")) { String[] searchArgs = cmd.getOptionValues("st"); if (searchArgs.length != 2) { throw new ParseException("Wrong number of arguments."); } if ("id".equals(searchArgs[0])) { System.out.println("Searching for team with the id " + searchArgs[1] + "."); System.out.println(client.searchForTeamById(searchArgs[1])); } else if ("name".equals(searchArgs[0])) { System.out.println("Searching for team with the name " + searchArgs[1] + "."); System.out.println(client.searchForTeamByName(searchArgs[1])); } else { System.out.println("Unknown property argument. Try either id or name."); return; } } else if (cmd.hasOption("sw")) { String[] searchArgs = cmd.getOptionValues("sw"); if (searchArgs.length != 4) { throw new ParseException("Wrong number of arguments."); } if ("id".equals(searchArgs[0])) { System.out.println("Searching for WAF with the id " + searchArgs[1] + "."); System.out.println(client.searchForWafById(searchArgs[1])); } else if ("name".equals(searchArgs[0])) { System.out.println("Searching for WAF with the name " + searchArgs[1] + "."); System.out.println(client.searchForWafByName(searchArgs[1])); } else { throw new ParseException("Unknown property argument. Try either id or name."); } } else if (cmd.hasOption("sa")) { String[] searchArgs = cmd.getOptionValues("sa"); if ("id".equals(searchArgs[0])) { if (searchArgs.length != 2) { System.out.println("Wrong number of arguments."); return; } System.out.println("Searching for application with the id " + searchArgs[1] + "."); System.out.println(client.searchForApplicationById(searchArgs[1])); } else if ("name".equals(searchArgs[0])) { if (searchArgs.length != 3) { System.out.println( "Wrong number of arguments. You need to input application name and team name as well."); return; } System.out.println("Searching for application with the name " + searchArgs[1] + " of team " + searchArgs[2]); System.out.println(client.searchForApplicationByName(searchArgs[1], searchArgs[2])); } else { System.out.println("Unknown property argument. Try either id or name."); return; } } else if (cmd.hasOption("r")) { String[] ruleArgs = cmd.getOptionValues("r"); if (ruleArgs.length != 1) { System.out.println("Wrong number of arguments.'"); } System.out.println("Downloading rules from WAF with ID " + ruleArgs[0] + "."); System.out.println(client.getRules(ruleArgs[0])); } else { throw new ParseException("No arguments found."); } } catch (ParseException e) { if (e.getMessage() != null) { System.out.println(e.getMessage()); } HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar tfcli.jar", options); } }
From source file:de.uni_koblenz.west.splendid.tools.NQuadSourceAggregator.java
public static void main(String[] args) { try {//from ww w . j a va2 s .c o m // parse the command line arguments CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(OPTIONS, args); // print help message if (cmd.hasOption("h") || cmd.hasOption("help")) { new HelpFormatter().printHelp(USAGE, OPTIONS); System.exit(0); } // get input files (from option -i or all remaining parameters) String[] inputFiles = cmd.getOptionValues("i"); if (inputFiles == null) inputFiles = cmd.getArgs(); if (inputFiles.length == 0) { System.out.println("need at least one input file."); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE); System.exit(1); } String outputFile = cmd.getOptionValue("o"); // process all input files new NQuadSourceAggregator().process(outputFile, inputFiles); } catch (ParseException exp) { // print parse error and display usage message System.out.println(exp.getMessage()); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE, OPTIONS); } }
From source file:com.google.flightmap.parsing.faa.nasr.AirspaceParser.java
public static void main(String args[]) { CommandLine line = null; try {/* w w w .j a v a 2 s. c o m*/ final CommandLineParser parser = new PosixParser(); line = parser.parse(OPTIONS, args); } catch (ParseException pEx) { System.err.println(pEx.getMessage()); printHelp(line); System.exit(1); } if (line.hasOption(HELP_OPTION)) { printHelp(line); System.exit(0); } final String[] shapefiles = line.getOptionValues(SHAPEFILES_OPTION); final String dbFile = line.getOptionValue(AVIATION_DB_OPTION); try { for (String shapefile : shapefiles) { (new AirspaceParser(shapefile, dbFile)).execute(); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } }
From source file:com.sindicetech.siren.demo.loader.Loader.java
/** checks parameters, instantiate loader and starts load */ public static void main(String[] args) { CommandLineParser cmdLineParser = new BasicParser(); CommandLine cmd = null; Options options = buildOptions();//from w w w .j av a2s. co m try { cmd = cmdLineParser.parse(options, args); } catch (ParseException e) { showHelpExit(options); } if (cmd.hasOption(HELP_OPT)) { showExtendHelpExit(options); } List<File> filesToProcess = Loader.checkInputFilesAndFolders(cmd.getOptionValues(INPUT_FILE_OPT)); if (filesToProcess.size() == 0) { logger.error("no file to process"); System.exit(-1); } Loader loader = new Loader(new HttpSolrServer(cmd.getOptionValue(URL_OPT, DEFAULT_SOLR_URL)), Loader.retrieveAndChekBatchSize(cmd.getOptionValue(BATCH_OPT)), cmd.getOptionValue(EXT_OPT, DEFAULT_JSON_EXTENSION), !cmd.hasOption(NO_EXT_CHECK_OPT), cmd.hasOption(COMMIT_EACH_OPT), cmd.hasOption(FILENAME_AS_ID_OPT)); loader.loadFiles(filesToProcess); }
From source file:com.ricston.akka.matrix.Main.java
public static void main(String[] args) throws InterruptedException, NumberFormatException, IOException { CommandLineParser parser = new GnuParser(); int numberOfActors = -1; Options options = new Options(); // Set the command line options recognized by this program. setUpCLOptions(options);// w ww. j a va 2 s . com // Parse the command line arguments. CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { quitApp(options); } if (cmd.hasOption(ACTORS)) { // Set the number of actors to create if the user supplied this argument. numberOfActors = Integer.parseInt(cmd.getOptionValue(ACTORS)); } if (cmd.hasOption(GENERATE)) { // Generate a file containing two randomly generated matrices. String[] genArgs = cmd.getOptionValues(GENERATE); if (genArgs.length != 5) { quitApp(options); } MatrixFile.writeMatrixFile(genArgs[0], generateMatrix(Integer.parseInt(genArgs[1]), Integer.parseInt(genArgs[2])), generateMatrix(Integer.parseInt(genArgs[3]), Integer.parseInt(genArgs[4])), new ArrayList<List<Double>>()); } if (cmd.hasOption(COMPUTE)) { // Compute the matrix multiplication of the matrices in the files // given as argument. String[] compArgs = cmd.getOptionValues(COMPUTE); ActorRef managerRef = null; if (numberOfActors > 0) { final int actors = numberOfActors; managerRef = actorOf(new UntypedActorFactory() { public UntypedActor create() { return new ManagerActor(actors); } }); } else { managerRef = actorOf(ManagerActor.class); } // Start the manager actor. managerRef.start(); // Create and send an AllJobsMsg. managerRef.tell(new AllJobsMsg(compArgs)); } if (cmd.getArgs().length > 0 || args.length == 0) { // Handle unrecognized arguments. quitApp(options); } }
From source file:edu.cwru.jpdg.JPDG.java
public static void main(String[] argv) throws pDG_Builder.Error { final Option helpOpt = new Option("h", "help", false, "print this message"); final Option outputOpt = new Option("o", "output", true, "output file location"); final Option baseOpt = new Option("b", "base-dir", true, "base directory to analyze"); final Option excludeOpt = new Option("e", "exclude", true, "exclude these directories"); final Option classOpt = new Option("c", "classpath", true, "classpath for soot"); final Option labelOpt = new Option("l", "label-type", true, "label type, valid choices are: expr-tree, inst"); final org.apache.commons.cli.Options options = new org.apache.commons.cli.Options(); options.addOption(helpOpt);/* w w w .j a va2 s. co m*/ options.addOption(outputOpt); options.addOption(baseOpt); options.addOption(classOpt); options.addOption(labelOpt); options.addOption(excludeOpt); String cp = null; String base_dir = null; String label_type = "expr-tree"; String output_file = null; List<String> excluded = new ArrayList<String>(); try { GnuParser parser = new GnuParser(); CommandLine line = parser.parse(options, argv); if (line.hasOption(helpOpt.getLongOpt())) { Usage(options); } cp = line.getOptionValue(classOpt.getLongOpt()); base_dir = line.getOptionValue(baseOpt.getLongOpt()); label_type = line.getOptionValue(labelOpt.getLongOpt()); output_file = line.getOptionValue(outputOpt.getLongOpt()); String[] ex = line.getOptionValues(excludeOpt.getLongOpt()); if (ex != null) { excluded = Arrays.asList(ex); } } catch (final MissingOptionException e) { System.err.println(e.getMessage()); Usage(options); } catch (final UnrecognizedOptionException e) { System.err.println(e.getMessage()); Usage(options); } catch (final ParseException e) { System.err.println(e.getMessage()); System.exit(1); } List<String> dirs = new ArrayList<String>(); dirs.add(base_dir); soot.Scene S = runSoot(cp, dirs, excluded); writeGraph(build_PDG(S, excluded, label_type), output_file); }
From source file:com.c4om.xsdfriendlyvalidator.XSDFriendlyValidatorLauncher.java
/** * Method called at application start./*w w w. ja v a 2s . com*/ * * @param args command line args */ public static void main(String[] args) throws Exception { CommandLineParser parser = new BasicParser(); CommandLine commandLine1 = parser.parse(OPTIONS, args); CommandLine commandLine = commandLine1; if (commandLine.hasOption(OPTION_NAME_HELP)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(COMMAND_LINE_SYNTAX, OPTIONS); System.exit(0); } else if (!commandLine.hasOption(OPTION_NAME_INPUT_FILES)) { System.err.println("You must specify input files. Invoke with --help to see how."); System.exit(1); } String[] inputFileOptionValues = commandLine.getOptionValues(OPTION_NAME_INPUT_FILES); List<Document> inputFilesList = getListOfInputDocumentsFromCommandLine(inputFileOptionValues); String[] schemasOptionValues = commandLine.getOptionValues(OPTION_NAME_SCHEMAS); Map<String, Document> schemasMap = getSchemaFilesFromCommandLine(schemasOptionValues); XSDFriendlyValidator validator = new XSDFriendlyValidatorImpl(); ValidationResults validationResults = validator.validate(inputFilesList, Arrays.asList(inputFileOptionValues), schemasMap); System.out.println(validationResults.toString()); }
From source file:com.github.jasmo.Bootstrap.java
public static void main(String[] args) { Options options = new Options().addOption("h", "help", false, "Print help message") .addOption("v", "verbose", false, "Increase verbosity") .addOption("c", "cfn", true, "Enable 'crazy fucking names and set name length (large names == large output size)'") .addOption("p", "package", true, "Move obfuscated classes to this package") .addOption("k", "keep", true, "Don't rename this class"); try {/* www .j a v a 2 s . c om*/ CommandLineParser clp = new DefaultParser(); CommandLine cl = clp.parse(options, args); if (cl.hasOption("help")) { help(options); return; } if (cl.hasOption("verbose")) { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); loggerConfig.setLevel(Level.DEBUG); ctx.updateLoggers(); } String[] keep = cl.getOptionValues("keep"); if (cl.getArgList().size() < 2) { throw new ParseException("Expected at-least two arguments"); } log.debug("Input: {}, Output: {}", cl.getArgList().get(0), cl.getArgList().get(1)); Obfuscator o = new Obfuscator(); try { o.supply(Paths.get(cl.getArgList().get(0))); } catch (Exception e) { log.error("An error occurred while reading the source target", e); return; } try { UniqueStringGenerator usg; if (cl.hasOption("cfn")) { int size = Integer.parseInt(cl.getOptionValue("cfn")); usg = new UniqueStringGenerator.Crazy(size); } else { usg = new UniqueStringGenerator.Default(); } o.apply(new FullAccessFlags()); o.apply(new ScrambleStrings()); o.apply(new ScrambleClasses(usg, cl.getOptionValue("package", ""), keep == null ? new String[0] : keep)); o.apply(new ScrambleFields(usg)); o.apply(new ScrambleMethods(usg)); o.apply(new InlineAccessors()); o.apply(new RemoveDebugInfo()); o.apply(new ShuffleMembers()); } catch (Exception e) { log.error("An error occurred while applying transform", e); return; } try { o.write(Paths.get(cl.getArgList().get(1))); } catch (Exception e) { log.error("An error occurred while writing to the destination target", e); return; } } catch (ParseException e) { log.error("Failed to parse command line arguments", e); help(options); } }
From source file: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;/*from w w w . j a v a2s .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.basistech.ninja.Train.java
/** * Command line interface to train a model. * * <pre>/* w w w.ja va 2 s . c o m*/ * usage: Train [options] * --batch-size <arg> batch size (default = 10) * --epochs <arg> epochs (default = 5) * --examples <arg> input examples file (required) * --layer-sizes <arg> layer sizes, including input/output, e.g. 3 4 2 (required) * --learning-rate <arg> learning-rate (default = 0.7) * --model <arg> output model file (required) * </pre> * * @param args command line arguments * @throws IOException */ public static void main(String[] args) throws IOException { String defaultBatchSize = "10"; String deafaultEpochs = "5"; String defaultLearningRate = "0.7"; Options options = new Options(); Option option; option = new Option(null, "examples", true, "input examples file (required)"); option.setRequired(true); options.addOption(option); option = new Option(null, "model", true, "output model file (required)"); option.setRequired(true); options.addOption(option); option = new Option(null, "layer-sizes", true, "layer sizes, including input/output, e.g. 3 4 2 (required)"); option.setRequired(true); option.setArgs(Option.UNLIMITED_VALUES); options.addOption(option); option = new Option(null, "batch-size", true, String.format("batch size (default = %s)", defaultBatchSize)); options.addOption(option); option = new Option(null, "epochs", true, String.format("epochs (default = %s)", deafaultEpochs)); options.addOption(option); option = new Option(null, "learning-rate", true, String.format("learning-rate (default = %s)", defaultLearningRate)); options.addOption(option); CommandLineParser parser = new GnuParser(); CommandLine cmdline = null; try { cmdline = parser.parse(options, args); } catch (org.apache.commons.cli.ParseException e) { System.err.println(e.getMessage()); usage(options); System.exit(1); } String[] remaining = cmdline.getArgs(); if (remaining == null) { usage(options); System.exit(1); } List<Integer> layerSizes = Lists.newArrayList(); for (String s : cmdline.getOptionValues("layer-sizes")) { layerSizes.add(Integer.parseInt(s)); } File examplesFile = new File(cmdline.getOptionValue("examples")); Train that = new Train(layerSizes, examplesFile); int batchSize = Integer.parseInt(cmdline.getOptionValue("batch-size", defaultBatchSize)); int epochs = Integer.parseInt(cmdline.getOptionValue("epochs", deafaultEpochs)); double learningRate = Double.parseDouble(cmdline.getOptionValue("learning-rate", defaultLearningRate)); File modelFile = new File(cmdline.getOptionValue("model")); that.train(batchSize, epochs, learningRate, modelFile); }