The Apache Commons CLI are the components of the Apache Commons which are derived from Java API and provides an API to parse command line arguments/options which are passed to the programs. This API also enables to print help related to options available.
Command line processing comprises of three stages. These stages are explained below −
Definition Stage
In definition stage, we define the options that an application can take and act accordingly. Commons CLI provides Options class, which is a container for Option objects.
Here we have added an option flag a, while false as second parameter, signifies that option is not mandatory and third parameter states the description of option.
Parsing Stage
In parsing stage, we parse the options passed using command line arguments after creating a parser instance.
Interrogation Stage
In Interrogation stage, we check if a particular option is present or not and then, process the command accordingly.
In this chapter, we will learn about the local environment setup of Apache Commons CLI and how to set up the path of Commons CLI for Windows 2000/XP, Windows 95/98/ME etc. We will also understand about some popular java editors and how to download Commons CLI archive.
Local Environment Setup
If you are still willing to set up your environment for Java programming language, then this chapter will guide you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment.
Java SE is freely available from the link https://www.oracle.com/java/technologies/oracle-java-archive-downloads.html. So you can download a version based on your operating system.
Path for Windows 2000/XP
We are assuming that you have installed Java in c:\Program Files\java\jdk directory.
Right-click on ‘My Computer’ and select ‘Properties’.
Click on the ‘Environment variables’ button under the ‘Advanced’ tab.
Now, alter the ‘Path’ variable, so that it also contains the path to the Java executable. Example, if the path is currently set to ‘C:\WINDOWS\SYSTEM32’, then change your path to read ‘C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin’.
Path for Windows 95/98/ME
We are assuming that you have installed Java in c:\Program Files\java\jdk directory.
Edit the ‘C:\autoexec.bat’ file and add the following line at the end − ‘SET PATH=%PATH%;C:\Program Files\java\jdk\bin’.
Path for Linux, UNIX, Solaris, FreeBSD
Environment variable PATH should be set to point, where the Java binaries have been installed. Refer to your shell documentation, if you have trouble doing this.
Example, if you use bash as your shell, then you would add the following line to the end of your ‘.bashrc: export PATH=/path/to/java:$PATH’
Popular Java Editors
To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −
Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.
Download Common CLI Archive
Download the latest version of Apache Common CLI jar file from commons-cli-1.4-bin.zip. At the time of writing this tutorial, we have downloaded commons-cli-1.4-bin.zip and copied it into C:\>Apache folder.
| OS | Archive name |
|---|---|
| Windows | commons-cli-1.4-bin.zip |
| Linux | commons-cli-1.4-bin.tar.gz |
| Mac | commons-cli-1.4-bin.tar.gz |
Apache Common CLI Environment
Set the APACHE_HOME environment variable to point to the base directory location where, Apache jar is stored on your machine. Assume that we have extracted commonscollections4-4.1-bin.zip in Apache folder on various Operating Systems as follows −
| OS | Output |
|---|---|
| Windows | Set the environment variable APACHE_HOME to C:\Apache |
| Linux | export APACHE_HOME = /usr/local/Apache |
| Mac | export APACHE_HOME = /Library/Apache |
CLASSPATH Variable
Set the CLASSPATH environment variable to point to the Common CLI jar location. Assume that you have stored commons-cli-1.4.jar in Apache folder on various Operating Systems as follows −
Работа с commons-cli 1.2
В процессе работы на одним проектом, возникла необходимость разработать консольное приложение для удаленного доступа к системе. За подобное взялся впервые в таких масштабах, раньше все было на окошках или если консоль, то точно известно число, тип и порядок передаваемых параметров. А здесь возникла необходимость в большом количестве команд, каждая со своими параметрами, или вовсе без них, соответственно для обеспечения гибкости возникла потребность в парсере, переданных параметров.
Дабы не изобретать велосипед, решил взять готовую библиотеку. Выбор остановил на commons-cli, для нее удалось найти пару примеров и использование ее казалось не очень уж сложны.
Как оказалось примеров не так уж много и покрывают они только базовые потребности разработчика. Попробую заполнить этот пробел своими пояснениями.
Итак, начнем. В основе Commons-cli лежит понятие опции. Чтобы сразу внести ясность, попробуем определиться с терминологией. Рассмотрим такую строчку:
Text.exe –l login ––password 123456
Происходит вызов программы test.exe с использованием опции l, которая в качестве аргумента принимает строку «login» и с использованием опции password, с аргументом в виде строки «123456». Нетрудно догадаться, что программа требует аутентификации, опция l отвечает за логин, а опция password само собой за пароль. Для простоты можно пару «опция, аргумент» рассматривать классичским способом «параметр=значение».
Кстати, форма записи со знаком «=» вполне допустима при использовании commons-cli.
Опции могут быть без аргументов вовсе или аргументов может быть больше одного. Если имя опции состоит из 1 буквы, то ей предшествует «-» (назовем это, по простому «тире»). Если имя опции состоит из 2 и более букв то необходимо удваивать «тире», как с опцией password.
С терминологией разобрались, можно переходить непосредственно к коду. Итак, все начинается с опций. Создаем опцию:
Коснтруктор в данном случае принимает 4 параметра: короткую форму опции (однобуквенная опция), длинную форму опции, флаг обозночающий наличие параметров и текстовое пояснение данной опции. Мы могли указать только однобуквнное предствления опции или только расширенное представлении опции, в каждом из этих случае конструктор принимал бы 3 параметра, но не указывать ни многобуквенной ни однобуквенной опции нельзя, необходимо указать хотя бы одну. Затем необходимо определить, как данная опция будет работать с аругментами. Примерно так:
Вроде бы из комментариев к коду все должно быть понятно. Если нам необходима опция без аргументов (опция-флаг), то ставим setArgs(0). После создания опции необходимо добавить ее в объект Options.
Теперь необходимо создать парсер командной строки и снабдить его необходимой информацией для работы:
Для начала создаем парсер, полновесных парсера в commons-cli 2 – Posix парсер и GNU парсер. Скажу честно, в их различия не вникал, но по беглому осмотру мне приглянулся Posix-парсер (регламентируется Posix стандартом, соотвественно будет работать на всех система поддерживающих этот стандарт).Затем запускаем парсер, в качестве параметров метод parse принимает коллекцию опций в виде объекта Options, и собственно строку с параметрами которые были переданны вашей программе при запуске (само собой что стандартный массив args[] перед использованием необходимо объекденить в одну строку разделяя элементы пробелами). Разультат разбора будет возвращен в объект commandLine.
Теперь необходимо выполнить полученные команды, делается это вот так:
Как видно, работа с commons-cli довольно просто. К тому же данная библеотека возьмет на себя заботы по выводу справки по использованию программы, не полностью, но многое облегчит:
Чтобы все стало ясно, приведу пример вызова данного метода:
Пожалуй здесь все понятно, кроме термина «строка usage». Приведу пример пример, из которого станет ясно как использовать данный параметр. При значении true вывод будет примерно такой:
usage: java test.jar [-l ] [-h]
При значении false, вывод будет таким:
usage: java test.jar
Думаю разница понятна.
Тоже все довольно просто.
В общем бибилиотека оставила неплохие впечатления по использованию, но очень быстро ее стало не хватать. Текущая версия бибилиотеки 1.2, при этом идет развитие абсолютно новой версии 2.0 – собственно, по описанию api версии 2.0 можно сказать, что эта версия должна удовлетворить большинство потребностей предъявляемых к библиотекам cli.
UPD. По подсказке nord_ua исправил ссылку на Posix стандарт командной строки.
Исправил опечатки и добавил ссылку на commons-cli. Спасибо nik_lazarev и FractalizeR.
Что такое java cli
Using Apache Commons CLI
The following sections describe some example scenarios on how to use CLI in applications.
Using a boolean option
Creating the Options
An Options object must be created and the Option must be added to it.
The addOption method has three parameters. The first parameter is a java.lang.String that represents the option. The second parameter is a boolean that specifies whether the option requires an argument or not. In the case of a boolean option (sometimes referred to as a flag) an argument value is not present so false is passed. The third parameter is the description of the option. This description will be used in the usage text of the application.
Parsing the command line arguments
International Time
The second parameter is true this time. This specifies that the c option requires an argument value. If the required option argument value is specified on the command line it is returned, otherwise null is returned.
Retrieving the argument value
The getOptionValue methods of CommandLine are used to retrieve the argument values of options.
Using Ant as an Example
Ant will be used here to illustrate how to create the Options required. The following is the help output for Ant.
Defining Boolean Options
Lets create the boolean options for the application as they are the easiest to create. For clarity the constructors for Option are used here.
Defining Argument Options
Defining Java Property Option
The last option to create is the Java property and it is also created using the OptionBuilder.
Creating the Options
All the preperation is now complete and we are now ready to parse the command line arguments.
Creating the Parser
Querying the commandline
To see if an option has been passed the hasOption method is used. The argument value can be retrieved using the getOptionValue method.
Displaying Usage and Help
CLI also provides the means to automatically generate usage and help information. This is achieved with the HelpFormatter class.
When executed the following output is produced:
If you also require to have a usage statement printed then calling formatter.printHelp(«ant», options, true) will generate a usage statment as well as the help information.
Creating an ls Example
The following is the code that is used to create the Options for this example.
Copyright © 2002-2021 The Apache Software Foundation. All Rights Reserved.
Apache Commons CLI
Introduction
The Apache Commons CLI is a library that provides API for parsing command-line options which we pass to programs. In this post, we will learn about the Apache Commons CLI to parse the command line arguments.
Command line options and arguments
We have been using command line arguments a lot, especially when using Unix commands.
After compiling Application.java and running it, we pass two command line options a and b with values 1 and 2, respectively.
Different forms of command line arguments
Usually the command line arguments can be passed using its short form or long form (representation).
The above option (-a/–all) did not accept any arguments because the argument was a boolean.
Maven dependency on Apache Commons CLI
If you are using a Maven project, you can depend on Apache Commons CLI by adding the below dependency.
Replace the version 1.4 with the latest available.
Apache Commons CLI – Terminologies
Let us look into the various steps or stages in processing a command line argument. There are three stages:
Definition Stage
A command line option has a set of option + (optional) values for them. In the definition stage, we define what the allowed options are.
The Options class represents a collection of Option objects. We will look at ways to create an Option instance.
Parsing Stage
In this stage, we parse the command line arguments passed to the application with the above created Options instance. We use a CommandLineParser for this. The parse method of the CommandLineParser takes the Options and the command line arguments and returns a CommandLine object.
If there is a problem parsing the command line options, this step fails with an exception.
Interrogation Stage
Now we have a CommandLine instance and the application uses this to query the argument values for the options.
Apache Commons CLI – A complete example
Let us look at using the Commons CLI library. The rest of the post dives deep into the various options for configuring the Option and building a CommandLine.
Definition Stage – Defining the Options
We create two command line options called t1 and t2.
Parsing Stage – Parsing the CL options into a CommandLine
Now, let us create a DefaultParser and parse command line arguments (String[] arguments). Calling the parse method on the built command line parser gives us a CommandLine object.
Interrogation Stage – Querying the command line
We query the CommandLine object and check for the presence of command line options. If they are present, we can get the command line argument values for them.
We can see that the second command line option can be queried by either the short representation or using the long form.
Creating Option instances using constructor
An Option is a single command-line option (example t1 in above example). It has a short name, long name, description of the option and a flag that describes if an argument is required for the option (an argument is not required for a boolean option). An option must either have a short or a long name.
To reduce the verboseness, I have created an utility method called process that accepts a String array of command line arguments (CL options and values) and an var-args of Options.
We used Arrays#stream to create a stream out of the array.
Creating a boolean option
Let us create an option called c that represents whether to cache application data or not.
We used the two argument version of the Option constructor and passed the short name and the description of the option. By default the flag hasArg will be false, which means this option does not require an argument.
Since the command line option c was a boolean option, it did not have any argument and hence it prints null for the getOptionValue() call.
Option with arguments
There is an overloaded constructor which accepts a flag to denote whether the option takes an argument or not. We create an option named k (the key) and pass the value as “value”.
Option with long name
In addition, we could also pass a long option name (–key).
Multiple Options
Below, we create two options k1 and k2, pass values for both, parse and query them.
Option – Setter methods
The Option class has some setter methods using which we can set some properties.
Setting argument name and required flag
Using Option#setRequired, we say that the command line option is mandatory. The setArgName sets a display name for the argument.
Setting an optional argument
For options that accept an argument value, there might be scenarios where the value must be optional (say when the application can resort to a default value). We set it using setOptionalArg setter method.
Even though the option k requires an argument, the parsing succeeds since we have set the optionalArg to true.
Setting the type of Option
This is one of the most useful parameters we can set. When creating an Option, we can specify the type of that Option. In the below example, when creating the key option, we make the type of that Option as a Number.
The getOptionValue always returns the string representation of the passed argument value. To get the option value converted to the right type, call the getParsedOptionValue method. But it could throw a ParseException if the option value cannot be converted to the configured type.
If we pass any other type other than a number for the k option, it will throw a ParseException.
Option with more than one argument
By default, when we create an option with arguments, the number of arguments is default to one. There is a setter method called setArgs to which we can specify the number of arguments the option must take. This is useful for multi-valued command line options.
The valueSeparator specifies how to extract the argument values from the string.
Let us create an option called v which must accept three values by using the value separator as a comma.
To get the values, call the getOptionValues method.
If we pass less than three values, it throws a MissingArgumentException.
If we pass more than three values, the rest of the values would be part of the last value and will not be split.
Note that the last value is “value,value4”.
Options constructor
The Options class has addOption methods that that mirror the Option class’s constructor. Hence, we can pass the values directly to the addOption method.
The disadvantage is that the other setter methods we saw are not accessible via this.
Option builder
The Option class has builder to build an Option instance. This is preferred over using a constructor and the setter methods. Some examples are shown below:
Exceptions in processing command line arguments
Let us look at a few scenarios where exceptions could be thrown when processing the command line arguments.
Unrecognized Option
If we pass an option that is not defined, it throws an UnrecognizedOptionException.
Missing a mandatory option
Here we create two command line options k1 and k2; k2 is mandatory. But the command line arguments do not have k2 in it. It throws a MissingOptionException.
CommandLineParser
We saw that if the command line parser encounters an unrecognized option it fails by throwing an UnrecognizedOptionException. The parse method accepts a boolean flag called stopAtNonOption. If we pass true, then when it sees an unrecognized argument it stops the parsing and returns immediately. The remaining arguments (even if valid) are not processed.
Let us create two options k1 and k2. But in the command line argument we pass k1, k3 and k2 (in that order). By default, the parse method of the command line parser throws an UnrecognizedOptionException.
Let us pass true for the flag stopAtNonOption.
It has successfully processed the command line option k1. But when it encountered k3, it returned without processing k2 (a valid option).
Other CommandLine methods
We already saw a few methods of the CommandLine class. Let us look at a few more.
getArgList and getArgs
The getArgList method returns any left-over options and arguments. This happens in the above case when we passed true to stop and return the processing when it encounters a bad/unrecognized option.
The getArgs method does the same but returns as a String array (rather than a List).
Default Option Value
The getOptionValue has an overload where we can pass a default option value in case the passed option does not have any parsed argument value. This can be used along with the three argument parse method of the command line parser.
Conclusion
We started by looking at the various stages of command line parsing involved with the Apache Commons CLI. We saw an end to end example of defining options, parsing command line arguments and retrieving the option values. Then, we saw various ways to create Option instances and methods on the CommandLine object.
Apache Commons CLI — Краткое руководство
CLI Apache Commons — это компоненты Apache Commons, которые являются производными от Java API и предоставляют API для анализа аргументов / опций командной строки, передаваемых программам. Этот API также позволяет распечатать справку, связанную с доступными опциями.
Обработка командной строки состоит из трех этапов.
Этап определения
На этапе определения мы определяем параметры, которые приложение может принять и действовать соответственно. CLI Commons предоставляет класс Options, который является контейнером для объектов Option.
Здесь мы добавили флаг опции a, в то время как false в качестве второго параметра означает, что опция не является обязательной, а третий параметр содержит описание опции.
Этап разбора
На этапе синтаксического анализа мы анализируем параметры, переданные с использованием аргументов командной строки после создания экземпляра анализатора.
Этап допроса
На этапе опроса мы проверяем, присутствует ли конкретная опция или нет, и соответствующим образом обрабатываем команду.
Apache Commons CLI — настройка среды
Настройка локальной среды
Если вы все еще хотите настроить свою среду для языка программирования Java, то в этом разделе вы узнаете, как загрузить и настроить Java на вашем компьютере. Пожалуйста, следуйте инструкциям ниже, чтобы настроить среду.
Следуйте инструкциям для загрузки Java и запуска .exe для установки Java на вашем компьютере. После того, как вы установили Java на свой компьютер, вам нужно будет установить переменные окружения, чтобы они указывали на правильные каталоги установки —
Настройка пути для Windows 2000 / XP
Мы предполагаем, что вы установили Java в каталог c: \ Program Files \ java \ jdk —
Щелкните правой кнопкой мыши «Мой компьютер» и выберите «Свойства».
Нажмите кнопку «Переменные среды» на вкладке «Дополнительно».
Теперь измените переменную Path, чтобы она также содержала путь к исполняемому файлу Java. Например, если в настоящий момент путь задан как «C: \ WINDOWS \ SYSTEM32», измените ваш путь на «C: \ WINDOWS \ SYSTEM32; c: \ Program Files \ java \ jdk \ bin».
Щелкните правой кнопкой мыши «Мой компьютер» и выберите «Свойства».
Нажмите кнопку «Переменные среды» на вкладке «Дополнительно».
Теперь измените переменную Path, чтобы она также содержала путь к исполняемому файлу Java. Например, если в настоящий момент путь задан как «C: \ WINDOWS \ SYSTEM32», измените ваш путь на «C: \ WINDOWS \ SYSTEM32; c: \ Program Files \ java \ jdk \ bin».
Настройка пути для Windows 95/98 / ME
Мы предполагаем, что вы установили Java в каталог c: \ Program Files \ java \ jdk —
Отредактируйте файл «C: \ autoexec.bat» и добавьте в конце следующую строку: «SET PATH =% PATH%; C: \ Program Files \ java \ jdk \ bin»
Отредактируйте файл «C: \ autoexec.bat» и добавьте в конце следующую строку: «SET PATH =% PATH%; C: \ Program Files \ java \ jdk \ bin»
Настройка пути для Linux, UNIX, Solaris, FreeBSD
Переменная среды PATH должна указывать на то, где установлены двоичные файлы Java. Обратитесь к документации по вашей оболочке, если у вас возникли проблемы с этим.
Популярные редакторы Java
Для написания ваших программ на Java вам нужен текстовый редактор. Есть много сложных IDE, доступных на рынке. Но сейчас вы можете рассмотреть один из следующих —
Блокнот — на компьютере с Windows вы можете использовать любой простой текстовый редактор, например Блокнот (рекомендуется для этого урока), TextPad.
Блокнот — на компьютере с Windows вы можете использовать любой простой текстовый редактор, например Блокнот (рекомендуется для этого урока), TextPad.
Скачать Common CLI Archive
| Операционные системы | Название архива |
|---|---|
| Windows | commons-cli-1.4-bin.zip |
| Linux | Обще-кли-1,4-bin.tar.gz |
| макинтош | Обще-кли-1,4-bin.tar.gz |
Установить Apache Common CLI Environment
Установите переменную окружения APACHE_HOME, чтобы она указывала на местоположение базовой директории, где на вашем компьютере хранится jar-файл Apache. Предполагая, что мы извлекли commons-collections4-4.1-bin.zip в папку Apache в различных операционных системах следующим образом.
| Операционные системы | Выход |
|---|---|
| Windows | Установите переменную окружения APACHE_HOME в C: \ Apache |
| Linux | экспорт APACHE_HOME = / usr / local / Apache |
| макинтош | экспорт APACHE_HOME = / Библиотека / Apache |
Установить переменную CLASSPATH
Задайте переменную среды CLASSPATH, чтобы она указывала на расположение JAR Common CLI. Предполагается, что вы сохранили commons-cli-1.4.jar в папке Apache в различных операционных системах следующим образом.
Apache Commons CLI — первое приложение
Давайте создадим пример консольного приложения, целью которого является получение либо суммы пропущенных чисел, либо умножения пропущенных чисел на основе используемых опций.
Создайте Java-класс с именем CLITester.
пример
Выход
Apache Commons CLI — свойства опций
Объект Option используется для представления опции, переданной в программу командной строки. Ниже приведены различные свойства, которыми обладает объект Option.
| Sr.No. | Имя (Тип) и Описание |
|---|---|
| 1 |



