2 * Svjatoslav Commons - shared library of common functionality.
3 * Copyright ©2012-2019, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of version 3 of the GNU Lesser General Public License
7 * or later as published by the Free Software Foundation.
10 package eu.svjatoslav.commons.commandline.parameterparser;
12 import java.util.ArrayList;
16 * Single commandline parameter can have any amount of arguments.
21 private final ArrayList<Parameter<?, ? extends Parameter>> parameters = new ArrayList<>();
23 public <E extends Parameter> E add(final E parameter) {
24 parameters.add(parameter);
29 * @return <code>true</code> if no errors were found. <code>false</code>
32 private boolean checkMandatoryArgumentsPresent() {
34 for (final Parameter parameter : parameters)
35 if (parameter.isMandatory() && (!parameter.isSpecified())) {
36 System.out.println("Error! Mandatory parameter ("
37 + parameter.getAliases() + ") is not specified.");
45 * Return parameter by given alias or <code>null</code> if no parameter
46 * exists for given alias.
48 * @param alias parameter alias
49 * @return found parameter or <code>null</code> if parameter was not found.
51 public Parameter findParameterByAlias(final String alias) {
53 for (final Parameter parameter : parameters)
54 if (parameter.matchesAlias(alias))
61 * @param args commandline arguments
62 * @return <code>true</code> if no errors were found. <code>false</code>
65 public boolean parse(final String[] args) {
67 Parameter currentParameter = null;
69 for (final String argument : args) {
71 final Parameter parameterForAlias = findParameterByAlias(argument);
72 if (parameterForAlias == null) {
73 if (currentParameter == null) {
74 System.out.println("Unknown commandline parameter: "
79 if (!currentParameter.addArgument(argument))
83 if (currentParameter != null)
84 if (!currentParameter.noMoreArguments())
87 parameterForAlias.setSpecified(true);
88 currentParameter = parameterForAlias;
93 return checkMandatoryArgumentsPresent();
96 public void showHelp() {
97 System.out.println("Available commandline arguments:");
98 for (final Parameter parameter : parameters)
99 System.out.println(parameter.getHelp());