List of usage examples for org.apache.commons.cli DefaultParser DefaultParser
DefaultParser
From source file:Generate.java
private static void parseCommandline(String[] args) { CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null;/* w w w . j a v a 2s. c om*/ int compileOptSetTimes = 0; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("Pyjama:", options); System.exit(1); } //Parse the compilation option if (cmd.hasOption("j2c")) { compileFlag = CompileOption.J2C; compileOptSetTimes++; } else if (cmd.hasOption("j2j")) { compileFlag = CompileOption.J2J; compileOptSetTimes++; } else if (cmd.hasOption("p2j")) { compileFlag = CompileOption.P2J; compileOptSetTimes++; } else if (cmd.hasOption("p2c")) { compileFlag = CompileOption.P2C; compileOptSetTimes++; } //Parse the source files sourceFileNames = cmd.getArgList(); if (cmd.hasOption("h")) { formatter.printHelp("Pyjama", options); } //Parse the target file directory if (cmd.hasOption("d")) { targetFileDirectory = cmd.getOptionValue("d"); } if (compileOptSetTimes > 1) { System.err.println("Error: More than one compile options are set."); System.exit(1); } if (sourceFileNames.isEmpty()) { System.err.println("Error: no input files."); formatter.printHelp("Pyjama", options); } }
From source file:fr.ortolang.diffusion.client.cmd.ImportReferentialCommand.java
@Override public void execute(String[] args) { CommandLineParser parser = new DefaultParser(); CommandLine cmd;//w w w . ja v a2s .c o m Map<String, String> params = new HashMap<>(); Map<String, File> files = new HashMap<>(); try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) { help(); } String[] credentials = getCredentials(cmd); String username = credentials[0]; String password = credentials[1]; if (cmd.hasOption("f")) { params.put("referentialpath", cmd.getOptionValue("f")); } else { help(); } OrtolangClient client = OrtolangClient.getInstance(); if (username.length() > 0) { client.getAccountManager().setCredentials(username, password); client.login(username); } System.out.println("Connected as user: " + client.connectedProfile()); String pkey = client.createProcess("import-referential", "Import Referential '" + cmd.getOptionValue("f").substring(cmd.getOptionValue("f").lastIndexOf("/") + 1) + "'", params, files); System.out.println("Import-Referential process created with key : " + pkey); client.logout(); client.close(); } catch (ParseException e) { System.out.println("Failed to parse command line properties " + e.getMessage()); help(); } catch (OrtolangClientException | OrtolangClientAccountException e) { System.out.println("Unexpected error !!"); e.printStackTrace(); } }
From source file:com.example.cloud.iot.examples.DeviceRegistryExampleOptions.java
/** Construct an DeviceRegistryExampleOptions class from command line flags. */ public static DeviceRegistryExampleOptions fromFlags(String[] args) { Options options = new Options(); // Required arguments options.addOption(Option.builder().type(String.class).longOpt("pubsub_topic").hasArg() .desc("Pub/Sub topic to create registry in.").required().build()); options.addOption(Option.builder().type(String.class).longOpt("command").hasArg() .desc("Command to run:" + "\n\tcreate-iot-topic" // TODO: Descriptions or too verbose? + "\n\tcreate-rsa" + "\n\tcreate-es" + "\n\tcreate-unauth" + "\n\tcreate-registry" + "\n\tdelete-device" + "\n\tdelete-registry" + "\n\tget-device" + "\n\tget-device-state" + "\n\tget-registry" + "\n\tlist-devices" + "\n\tlist-registries" + "\n\tpatch-device-es" + "\n\tpatch-device-rsa") .required().build());/*from w ww .j a v a 2s . co m*/ // Optional arguments. options.addOption(Option.builder().type(String.class).longOpt("ec_public_key_file").hasArg() .desc("Path to ES256 public key file.").build()); options.addOption(Option.builder().type(String.class).longOpt("rsa_certificate_file").hasArg() .desc("Path to RS256 certificate file.").build()); options.addOption(Option.builder().type(String.class).longOpt("cloud_region").hasArg() .desc("GCP cloud region.").build()); options.addOption(Option.builder().type(String.class).longOpt("project_id").hasArg() .desc("GCP cloud project name.").build()); options.addOption(Option.builder().type(String.class).longOpt("registry_name").hasArg() .desc("Name for your Device Registry.").build()); options.addOption(Option.builder().type(String.class).longOpt("device_id").hasArg() .desc("Name for your Device.").build()); CommandLineParser parser = new DefaultParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); DeviceRegistryExampleOptions res = new DeviceRegistryExampleOptions(); res.command = commandLine.getOptionValue("command"); if (res.command.equals("help") || res.command.equals("")) { throw new ParseException("Invalid command, showing help."); } if (commandLine.hasOption("project_id")) { res.projectId = commandLine.getOptionValue("project_id"); } else { try { res.projectId = System.getenv("GOOGLE_CLOUD_PROJECT"); } catch (NullPointerException npe) { res.projectId = System.getenv("GCLOUD_PROJECT"); } } if (commandLine.hasOption("pubsub_topic")) { res.pubsubTopic = commandLine.getOptionValue("pubsub_topic"); } else { // TODO: Get from environment variable } if (commandLine.hasOption("ec_public_key_file")) { res.ecPublicKeyFile = commandLine.getOptionValue("ec_public_key_file"); } if (commandLine.hasOption("rsa_certificate_file")) { res.rsaCertificateFile = commandLine.getOptionValue("rsa_certificate_file"); } if (commandLine.hasOption("cloud_region")) { res.cloudRegion = commandLine.getOptionValue("cloud_region"); } if (commandLine.hasOption("registry_name")) { res.registryName = commandLine.getOptionValue("registry_name"); } if (commandLine.hasOption("device_id")) { res.deviceId = commandLine.getOptionValue("device_id"); } return res; } catch (ParseException e) { String header = "Cloud IoT Core Commandline Example (Device / Registry management): \n\n"; String footer = "\nhttps://cloud.google.com/iot-core"; HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DeviceRegistryExample", header, options, footer, true); System.err.println(e.getMessage()); return null; } }
From source file:com.teradata.benchto.driver.DriverApp.java
private static CommandLine processArguments(String[] args) throws ParseException { DefaultParser defaultParser = new DefaultParser(); Options options = createOptions();/* w w w .j a v a 2s . c om*/ CommandLine commandLine = defaultParser.parse(options, args); if (commandLine.hasOption("h")) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("Benchto driver", options); System.exit(0); } exposeArgumentsAsPropertiesForSpring(commandLine); checkState(commandLine.getArgList().isEmpty(), "Added extra non used arguments: %s", commandLine.getArgList()); return commandLine; }
From source file:com.partagames.imageresizetool.SimpleImageResizeTool.java
/** * Parses all command line arguments and prepares them. * * @param args Command line arguments. * @param options Apache CLI options/*from w w w . j a v a 2 s . co m*/ * @return True if arguments were prepared correctly and we can continue execution */ private static boolean parseAndPrepareArguments(String[] args, Options options) { // parse through arguments and prepare them appropriately final CommandLineParser parser = new DefaultParser(); final CommandLine cmd; try { cmd = parser.parse(options, args); } catch (MissingOptionException | MissingArgumentException e) { System.out.println(e.getMessage() + "\n"); printHelpAndUsage(); return false; } catch (ParseException e2) { System.out.println( "Error: There was a problem parsing the command line arguments, please check your command.\n"); printHelpAndUsage(); throw new RuntimeException(e2); } // show help if (cmd.hasOption(ARG_HELP)) { printHelpAndUsage(); return false; } if (cmd.getArgList().isEmpty()) { System.out.println("Error: Missing argument: comma-separated list of images!\n"); printHelpAndUsage(); return false; } else { imageFileStrings = cmd.getArgList().get(0).split(","); } // prepare mandatory arguments if (cmd.hasOption(ARG_DIMENSIONS)) { final String[] dimensionStrings = cmd.getOptionValue(ARG_DIMENSIONS).split("x"); try { dimensions = new Dimensions(Integer.parseInt(dimensionStrings[0]), Integer.parseInt(dimensionStrings[1])); } catch (Exception e) { System.out.println("Error: Dimension argument was not correct!\n"); printHelpAndUsage(); return false; } } // prepare optional arguments if (cmd.hasOption(ARG_OUTPUT)) { outputFolder = Paths.get(cmd.getOptionValue(ARG_OUTPUT)); } if (cmd.hasOption(ARG_FORMAT)) { final String outputFormatString = cmd.getOptionValue("format").toLowerCase(); if (Constants.OUTPUT_IMAGE_FORMATS.contains(outputFormatString)) { format = outputFormatString; } else { System.out.println("Error: Wrong output image format!\n"); printHelpAndUsage(); return false; } } if (cmd.hasOption(ARG_HINT)) { final String scalingHintString = cmd.getOptionValue(ARG_HINT); if (SUPPORTED_SCALING_HINTS.contains(scalingHintString)) { scalingHint = scalingHintString; } else { System.out.println("Error: Wrong scaling hint!\n"); printHelpAndUsage(); return false; } } return true; }
From source file:com.google.cloud.solutions.rtdp.MqttOptions.java
/** Construct an MqttExampleOptions class from command line flags. */ public static MqttOptions fromFlags(String[] args) { Options options = new Options(); // Required arguments options.addOption(Option.builder().type(String.class).longOpt("project_id").hasArg() .desc("GCP cloud project name.").required().build()); options.addOption(Option.builder().type(String.class).longOpt("registry_id").hasArg() .desc("Cloud IoT registry id.").required().build()); options.addOption(Option.builder().type(String.class).longOpt("device_id").hasArg() .desc("Cloud IoT device id.").required().build()); options.addOption(Option.builder().type(String.class).longOpt("private_key_file").hasArg() .desc("Path to private key file.").required().build()); options.addOption(Option.builder().type(String.class).longOpt("algorithm").hasArg() .desc("Encryption algorithm to use to generate the JWT. Either 'RS256' or 'ES256'.").required() .build());/*w w w . j a v a2s. c o m*/ options.addOption(Option.builder().type(String.class).longOpt("lat").hasArg().desc("Base lattitude") .required().build()); options.addOption(Option.builder().type(String.class).longOpt("lng").hasArg().desc("Base longitude") .required().build()); // Optional arguments. options.addOption(Option.builder().type(String.class).longOpt("cloud_region").hasArg() .desc("GCP cloud region.").build()); options.addOption(Option.builder().type(Number.class).longOpt("num_messages").hasArg() .desc("Number of messages to publish.").build()); options.addOption(Option.builder().type(String.class).longOpt("mqtt_bridge_hostname").hasArg() .desc("MQTT bridge hostname.").build()); options.addOption(Option.builder().type(Number.class).longOpt("mqtt_bridge_port").hasArg() .desc("MQTT bridge port.").build()); CommandLineParser parser = new DefaultParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); MqttOptions opts = new MqttOptions(); opts.projectId = commandLine.getOptionValue("project_id"); opts.registryId = commandLine.getOptionValue("registry_id"); opts.deviceId = commandLine.getOptionValue("device_id"); opts.privateKeyFile = commandLine.getOptionValue("private_key_file"); opts.algorithm = commandLine.getOptionValue("algorithm"); opts.lat = commandLine.getOptionValue("lat"); opts.lng = commandLine.getOptionValue("lng"); if (commandLine.hasOption("cloud_region")) { opts.cloudRegion = commandLine.getOptionValue("cloud_region"); } if (commandLine.hasOption("num_messages")) { opts.numMessages = ((Number) commandLine.getParsedOptionValue("num_messages")).intValue(); } if (commandLine.hasOption("mqtt_bridge_hostname")) { opts.mqttBridgeHostname = commandLine.getOptionValue("mqtt_bridge_hostname"); } if (commandLine.hasOption("mqtt_bridge_port")) { opts.mqttBridgePort = ((Number) commandLine.getParsedOptionValue("mqtt_bridge_port")).shortValue(); } return opts; } catch (ParseException e) { System.err.println(e.getMessage()); return null; } }
From source file:fr.ortolang.diffusion.client.cmd.ImportWorkspaceCommand.java
@Override public void execute(String[] args) { CommandLineParser parser = new DefaultParser(); CommandLine cmd;// w w w .j a v a2 s. co m Map<String, String> params = new HashMap<>(); Map<String, File> files = new HashMap<>(); try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) { help(); } String[] credentials = getCredentials(cmd); String username = credentials[0]; String password = credentials[1]; if (cmd.hasOption("f")) { if (cmd.hasOption("upload")) { files.put("bagpath", new File(cmd.getOptionValue("f"))); } else { params.put("bagpath", cmd.getOptionValue("f")); } } else { help(); } OrtolangClient client = OrtolangClient.getInstance(); if (username.length() > 0) { client.getAccountManager().setCredentials(username, password); client.login(username); } System.out.println("Connected as user: " + client.connectedProfile()); String pkey = client.createProcess("import-workspace", "Import Workspace '" + cmd.getOptionValue("f").substring(cmd.getOptionValue("f").lastIndexOf("/") + 1) + "'", params, files); System.out.println("Import-Workspace process created with key : " + pkey); client.logout(); client.close(); } catch (ParseException e) { System.out.println("Failed to parse command line properties " + e.getMessage()); help(); } catch (OrtolangClientException | OrtolangClientAccountException e) { System.out.println("Unexpected error !!"); e.printStackTrace(); } }
From source file:jp.igapyon.diary.v3.md2html.IgapyonMd2HtmlCli.java
public void process(final String[] args) throws IOException { final Options options = new Options(); options.addOption("s", true, "source directory which contains .md file."); options.addOption("t", true, "target directory which will contains .html file."); options.addOption("r", false, "treat directory recursive."); options.addOption("h", false, "show help."); final CommandLineParser parser = new DefaultParser(); CommandLine commandLine;//from ww w .j a v a2 s . c o m try { commandLine = parser.parse(options, args); } catch (ParseException e) { System.err.println(e.toString()); return; } if (commandLine.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("md2html", options); return; } if (commandLine.hasOption("s") == false) { throw new IllegalArgumentException("-s must be set."); } if (commandLine.hasOption("t") == false) { throw new IllegalArgumentException("-t must be set."); } final String source = commandLine.getOptionValue("s"); final String target = commandLine.getOptionValue("t"); final boolean recursivedir = commandLine.hasOption("r"); System.out .println(IgapyonMd2HtmlConstants.PROGRAM_DISPLAY_NAME + " ver:" + IgapyonMd2HtmlConstants.VERSION); System.out.println(" source:[" + source + "]"); System.out.println(" target:[" + target + "]"); System.out.println(" recursivedir=" + recursivedir); new IgapyonMd2Html().processDir(source, target, recursivedir); }
From source file:de.neofonie.aiko.Runner.java
/** * Parses the given arguments, starts all tests and returns an exit code. If all tests were successful 0 is returned * otherwise 2.// w w w.j a v a 2s.c o m * * @param args command line arguments that specify the configuration file * @return 0 - all tests successful | 2 - at least one test failed * @throws ParseException * @throws IOException */ private static int startTests(final String... args) throws ParseException, IOException { final CommandLineParser parser = new DefaultParser(); final CommandLine cmd = parser.parse(AIKO_OPTIONS, args); final String configurationFile = cmd.getOptionValue("f"); final Context context = new Context(System.getProperty("user.dir"), configurationFile); int exitCode = 0; System.out.println(context); System.out.println("Starting tests"); if (!Runner.runAllTests(context)) { exitCode = 2; } return exitCode; }
From source file:com.ibm.crail.storage.rdma.RdmaStorageTier.java
public void init(CrailConfiguration conf, String[] args) throws Exception { if (args != null) { Option interfaceOption = Option.builder("i").desc("interface to start server on").hasArg().build(); Option portOption = Option.builder("p").desc("port to start server on").hasArg().build(); Options options = new Options(); options.addOption(interfaceOption); options.addOption(portOption);//w w w. ja va2 s . c o m CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, args.length)); if (line.hasOption(interfaceOption.getOpt())) { String ifname = line.getOptionValue(interfaceOption.getOpt()); LOG.info("using custom interface " + ifname); conf.set(RdmaConstants.STORAGE_RDMA_INTERFACE_KEY, ifname); } if (line.hasOption(portOption.getOpt())) { String port = line.getOptionValue(portOption.getOpt()); LOG.info("using custom port " + port); conf.set(RdmaConstants.STORAGE_RDMA_PORT_KEY, port); } } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("RDMA storage tier", options); System.exit(-1); } } RdmaConstants.updateConstants(conf); RdmaConstants.verify(); }