|
1 | | -# Java_ArgParser |
| 1 | +# About This Project |
| 2 | +I have needed an argument parser for some java projects. There are some libraries available, but I wanted something tailor-made. Maybe it could be useful for others, too, so I decided to publish it. The documentation is a bit lean, if you need more detailed descriptions, let me know. |
| 3 | +# Table Of Contents |
| 4 | +- [Scope Of Functions](#scope_of_functions) |
| 5 | +- [How to use it](#how_to_use_it) |
| 6 | + - [Create The Main Object](#create_the_main_object) |
| 7 | + - [Definition Simple Arguments](#definition_simple_arguments) |
| 8 | + - [Definition Arguments With Rules](#definition_arguments_with_rules) |
| 9 | + - [Add Autogenerated Help Argument](#add_autogenerated_help_argument) |
| 10 | + - [Parse The Arguments](#parse_the_arguments) |
| 11 | + - [Get Argument Values ](#get_argument_values ) |
| 12 | + - [Put All Together](#put_all_together) |
| 13 | + - [Further Examples](#further_examples) |
| 14 | +## Scope Of Functions |
| 15 | +<a name="scope_of_functions"></a> |
| 16 | +- Define arguments needed for your console applications |
| 17 | + - Integer Arguments |
| 18 | + - Double Arguments |
| 19 | + - String Arguments |
| 20 | + - Flag Arguments |
| 21 | +- Define whether an argument is required |
| 22 | +- Define a default value |
| 23 | +- Define different rules for this argument |
| 24 | +## How To Use It |
| 25 | +<a name="how_to_use_it"></a> |
| 26 | +It's that simple: Import the JAR file (`from 'release/ArgParser_X.X'`) or the packages and classes into your project. Now you can create an `ArgumentParser` object and define your arguments. Finally, you call the parse method and pass the arguments and get the result. A more detailed description of how to use ArgParser can be found in the following sections. |
| 27 | +### Create The Main Object |
| 28 | +<a name="create_the_main_object"></a> |
| 29 | +Before the arguments are defined, a `ArgumentParser` object is required. Here `bool1` defines whether the program should be terminated if the user uses a help argument. `bool2` defines whether an exception should be thrown if a required argument is not given. `bool3` defines whether an exception should be thrown if the user enters an undefined argument. |
| 30 | +``` |
| 31 | +ArgumentParser argumentParser = new ArgumentParser(bool1, bool2, bool3); |
| 32 | +``` |
| 33 | +### Definition Simple Arguments |
| 34 | +<a name="definition_simple_arguments"></a> |
| 35 | +The arguments are then defined. In the following example a `StringArgumentDefinition` is created. It could also be an `IntegerArgumentDefinition`, `DoubleArgumentDefinition` or `FlagArgumentDefinition`. The parameters are the same for all four. The respective argument is assigned one or more prefixes in the first parameter, e.g. `new String[]{"-s", "-src", "-source"}`. In `argumentDescription` a string can be set which describes the argument e.g. `"The image source."`. `isRequired` specifies whether this argument must be set by the user or is optional. In `defaultValue` is deposited which value is valid for this argument by default. |
| 36 | +``` |
| 37 | +StringArgumentDefinition sad = new StringArgumentDefinition(prefixes, argumentDescription, isRequired, defaultValue) |
| 38 | +``` |
| 39 | +Then the argument definition can be added to the argument parser. |
| 40 | +``` |
| 41 | +argumentParser.add(sad); |
| 42 | +``` |
| 43 | +### Definition Arguments With Rules |
| 44 | +<a name="definition_arguments_with_rules"></a> |
| 45 | +Let's assume that we want to add rules to the previously created argument definition. In this example we want an argument for a PNG image. Then we could change the instantiation as follows. As an additional parameter we set an array with the type `StringArgumentRule`. The first added rule checks if the image has the extension `.png | .PNG`. The second rule checks if the file exists and is really a file. |
| 46 | +``` |
| 47 | +StringArgumentDefinition sad = new StringArgumentDefinition( |
| 48 | + new String[]{"-s", "-src", "-source"}, // With prefixes implied the argument |
| 49 | + "Image source", // What is the argument for |
| 50 | + true, // This Argument is required |
| 51 | + "", // Set nothing as default, since this argument is tagged as required |
| 52 | + new StringArgumentRule[] { |
| 53 | + new StringArgumentRegularExpressionRule("^.*(.png|.PNG){1}$", "File is PNG"), // Is it a PNG image |
| 54 | + new StringArgumentFileExistsRule() // Does this file exists |
| 55 | + } |
| 56 | +); |
| 57 | +``` |
| 58 | +For the `IntegerArgumentDefinition` use `IntegerArgumentRule` and for `DoubleArgumentDefinition` `DoubleArgumentRule`. There are no rules for `FlagArgumentDefinition` because it is a bit assignment (`true, false`) without variance. |
| 59 | +### Add Autogenerated Help Argument |
| 60 | +<a name="add_autogenerated_help_argument"></a> |
| 61 | +Now an automatically generated help argument can be created. As with the previous argument definitions, a prefix is defined for this. In addition, a title is defined for the output. The following example shows an instantiation of this help argument. |
| 62 | +``` |
| 63 | +argumentParser.addHelpArgument(new String[] {"-h", "-help"}, "This arguments are available:"); |
| 64 | +``` |
| 65 | +The output would look like this once the user enters `-h` or `-help`: |
| 66 | +``` |
| 67 | +This arguments are available: |
| 68 | +{-s,-src,-source} Required: yes Image source |
| 69 | +``` |
| 70 | +### Parse The Arguments |
| 71 | +<a name="parse_the_arguments"></a> |
| 72 | +Now the arguments from the main `(String[] args)` can be passed to the parser. |
| 73 | +``` |
| 74 | +argumentParser.parse(args); |
| 75 | +``` |
| 76 | +### Get Argument Values |
| 77 | +<a name="get_argument_values "></a> |
| 78 | +To get the value after parsing, simply read the value from the respective definition object as follows. |
| 79 | +``` |
| 80 | +System.out.println(iad.getValue()); |
| 81 | +``` |
| 82 | +### Put All Together |
| 83 | +<a name="put_all_together"></a> |
| 84 | +Now everything together and with an error handling. |
| 85 | +``` |
| 86 | +public class Main { |
| 87 | + public static void main(String[] args) { |
| 88 | + ArgumentParser argumentParser = new ArgumentParser(true, true, true); // Create first and ArgumentParser object |
| 89 | + try { // Catch the exceptions |
| 90 | + StringArgumentDefinition sad = new StringArgumentDefinition( // Create a argument definition for an image source |
| 91 | + new String[]{"-s", "-src", "-source"}, // This argument can be addressed with the following prefixes |
| 92 | + "Image source", // What is the argument for |
| 93 | + true, // This Argument is required |
| 94 | + "", // Set nothing as default, since this argument is tagged as required |
| 95 | + new StringArgumentRule[] { // Add some rules |
| 96 | + new StringArgumentRegularExpressionRule("^.*(.png|.PNG){1}$", "File is PNG"), // Is it a PNG image |
| 97 | + new StringArgumentFileExistsRule() // Does this file exists |
| 98 | + } |
| 99 | + ); |
| 100 | + |
| 101 | + argumentParser.addHelpArgument(new String[] {"-h", "-help"}, "This arguments are available:"); |
| 102 | + argumentParser.add(sad); // Add this argument definition to the parser |
| 103 | + argumentParser.parse(args); // Parse the users input |
| 104 | + |
| 105 | + System.out.println("Load image from " + sad.getValue()); // Get the users input for image source |
| 106 | + // Do something with the image path like loading and displaying |
| 107 | + } catch (NonUniquePrefixException | NotSupportedInThisVersionException e) { // If that happens, you have a bug in the code |
| 108 | + e.printStackTrace(); |
| 109 | + } |
| 110 | + catch (UnknownArgumentException | MissingArgumentException | ValueParseException | RuleNotObservedException e) { // This eception can be provoke by the users input |
| 111 | + System.err.println(e.getMessage()); // Print the exception for the user |
| 112 | + } |
| 113 | + } |
| 114 | +} |
| 115 | +``` |
| 116 | +## Further Examples |
| 117 | +<a name="further_examples"></a> |
| 118 | +In the following example, a temperature is written to the database. As argument we want the username, the password and the table name of the database. Additionally we need the IP and a port. We also offer the user the option to disable encrypted communication. Last but not least we want a valid temperature. We assume that we have tempreatures in the range of -40 to 120 degrees. |
| 119 | +``` |
| 120 | +public class Main2 { |
| 121 | + public static void main(String[] args) { |
| 122 | + ArgumentParser argumentParser = new ArgumentParser(true, true, true); // Create first and ArgumentParser object |
| 123 | + try { // Catch the exceptions |
| 124 | + StringArgumentDefinition mysqlUser = new StringArgumentDefinition(new String[] {"-u", "-user"}, "MySql username", true, "", new StringArgumentRule[] { |
| 125 | + new StringArgumentRegularExpressionRule("^[a-zA-Z0-9]{4,}$") |
| 126 | + }); |
| 127 | + StringArgumentDefinition mysqlPassword = new StringArgumentDefinition(new String[] {"-p", "-pw"}, "MySql password", true, "", new StringArgumentRule[] { |
| 128 | + new StringArgumentRegularExpressionRule("^[a-zA-Z0-9]{4,}$") |
| 129 | + }); |
| 130 | + StringArgumentDefinition mysqlTable = new StringArgumentDefinition(new String[] {"-t", "-table"}, "MySql table", false, "temperature_log", new StringArgumentRule[] { |
| 131 | + new StringArgumentRegularExpressionRule("^[a-zA-Z0-9_]{4,}$") |
| 132 | + }); |
| 133 | + StringArgumentDefinition mysqlIp = new StringArgumentDefinition(new String[] {"-ip"}, "MySql server IP", true, "temperature_log", new StringArgumentRule[] { |
| 134 | + new StringArgumentRegularExpressionRule(RegularExpressionCollection.IP_FORMAT(), "Valid IP address"), // Check if the IP is in the correct format. Uses a template from the Regular expression collection. |
| 135 | + new StringArgumentIpAddressReachableRule(2500) // Check if the give IP is reachable |
| 136 | + }); |
| 137 | + IntegerArgumentDefinition mysqlPort = new IntegerArgumentDefinition(new String[] {"-port"}, "MySql server port", false, 3306, new IntegerArgumentRule[] { |
| 138 | + new IntegerArgumentRegularExpressionRule("^(3306|33060|389|){1}$", "Port out of {3306|33060|389}") // Just example ports for illustration |
| 139 | + }); |
| 140 | + FlagArgumentDefinition encryptedCommunication = new FlagArgumentDefinition(new String[] {"-c", "-crypt"}, "Encrypted communication", false, true); // A flag can be triggered by the prefix like 'aplication -c' |
| 141 | + DoubleArgumentDefinition temperature = new DoubleArgumentDefinition(new String[] {"-temp", "-temperature"}, "Temperature to log", true, 0.0, new DoubleArgumentRule[] { |
| 142 | + new DoubleArgumentProportionRule(NumberProportionRuleType.GREATER_EQUAL, -40.0), |
| 143 | + new DoubleArgumentProportionRule(NumberProportionRuleType.LESS_EQUAL, 120.0) |
| 144 | + }); |
| 145 | + |
| 146 | + argumentParser.addHelpArgument(new String[] {"-h", "-help"}, "This arguments are available:"); |
| 147 | + argumentParser.add(mysqlUser); |
| 148 | + argumentParser.add(mysqlPassword); |
| 149 | + argumentParser.add(mysqlTable); |
| 150 | + argumentParser.add(mysqlIp); |
| 151 | + argumentParser.add(mysqlPort); |
| 152 | + argumentParser.add(encryptedCommunication); |
| 153 | + argumentParser.add(temperature); |
| 154 | + argumentParser.parse(args); |
| 155 | + |
| 156 | + System.out.println("Connect to " + mysqlIp.getValue() + ":" + mysqlPort.getValue() + (encryptedCommunication.getValue()?" with a secure connection":" with an unsafe connection")); |
| 157 | + System.out.println("Use credentials Username:[" + mysqlUser.getValue() + "] Password:[" + mysqlPassword.getValue() + "]"); |
| 158 | + System.out.println("Insert [" + temperature.getValue() + "]°C into table [" + mysqlTable.getValue() + "]"); |
| 159 | + |
| 160 | + } catch (NonUniquePrefixException e) { // If that happens, you have a bug in the code |
| 161 | + e.printStackTrace(); |
| 162 | + } |
| 163 | + catch (UnknownArgumentException | MissingArgumentException | ValueParseException | RuleNotObservedException e) { // This eception can be provoke by the users input |
| 164 | + System.err.println(e.getMessage()); // Print the exception for the user |
| 165 | + } |
| 166 | + } |
| 167 | +} |
| 168 | +``` |
| 169 | +If the application is executed with help argument (`-h`), the following is output: |
| 170 | +``` |
| 171 | +This arguments are available: |
| 172 | +{-u,-user} Required: yes MySql username |
| 173 | +{-p,-pw} Required: yes MySql password |
| 174 | +{-t,-table} Required: no MySql table (default 'temperature_log') |
| 175 | +{-ip} Required: yes MySql server IP |
| 176 | +{-port} Required: no MySql server port (default '3306') |
| 177 | +{-c,-crypt} Required: no Encrypted communication (default 'yes') |
| 178 | +{-temp,-temperature} Required: yes Temperature to log |
| 179 | +``` |
| 180 | +If the arguments are given `-u root -p Tutorial19 -ip 127.0.0.1 -c -temp 22.3`. Then the output is as follows: |
| 181 | +``` |
| 182 | +Connect to 127.0.0.1:3306 with an unsafe connection |
| 183 | +Use credentials Username:[root] Password:[Tutorial19] |
| 184 | +Insert [22.3]°C into table [temperature_log] |
| 185 | +``` |
| 186 | +If an unallowed port is specified `-u root -p Tutorial19 -ip 127.0.0.1 -port 42 -c -temp 22.3`, then the output is: |
| 187 | +``` |
| 188 | +The rule 'Port out of {3306|33060|389}' for argument {-port} is not observed with the argument '42'. |
| 189 | +``` |
| 190 | +If the temperature argument is not given, the output is: |
| 191 | +``` |
| 192 | +Missing argument: |
| 193 | +{-temp,-temperature} Temperature to log |
| 194 | +``` |
0 commit comments