2 * Svjatoslav Commons - shared library of common functionality. Author: Svjatoslav Agejenko.
3 * This project is released under Creative Commons Zero (CC0) license.
5 package eu.svjatoslav.commons.commandline.parameterparser;
7 import java.util.ArrayList;
11 * Single commandline parameter can have any amount of arguments.
16 private final ArrayList<Parameter<?, ? extends Parameter>> parameters = new ArrayList<>();
18 public <E extends Parameter> E add(final E parameter) {
19 parameters.add(parameter);
24 * @return <code>true</code> if no errors were found. <code>false</code>
27 private boolean checkMandatoryArgumentsPresent() {
29 for (final Parameter parameter : parameters)
30 if (parameter.isMandatory() && (!parameter.isSpecified())) {
31 System.out.println("Error! Mandatory parameter ("
32 + parameter.getAliases() + ") is not specified.");
40 * Return parameter by given alias or <code>null</code> if no parameter
41 * exists for given alias.
43 * @param alias parameter alias
44 * @return found parameter or <code>null</code> if parameter was not found.
46 public Parameter findParameterByAlias(final String alias) {
48 for (final Parameter parameter : parameters)
49 if (parameter.matchesAlias(alias))
56 * @param args commandline arguments
57 * @return <code>true</code> if no errors were found. <code>false</code>
60 public boolean parse(final String[] args) {
62 Parameter currentParameter = null;
64 for (final String argument : args) {
66 final Parameter parameterForAlias = findParameterByAlias(argument);
67 if (parameterForAlias == null) {
68 if (currentParameter == null) {
69 System.out.println("Unknown commandline parameter: "
74 if (!currentParameter.addArgument(argument))
78 if (currentParameter != null)
79 if (!currentParameter.noMoreArguments())
82 parameterForAlias.setSpecified(true);
83 currentParameter = parameterForAlias;
88 return checkMandatoryArgumentsPresent();
91 public void showHelp() {
92 System.out.println("Available commandline arguments:");
93 for (final Parameter parameter : parameters)
94 System.out.println(parameter.getHelp());