2 * Svjatoslav Commons - shared library of common functionality.
3 * Copyright ©2012-2014, 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<?>> parameters = new ArrayList<Parameter<?>>();
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.isParameterSpecified())) {
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.
50 * @return found parameter or <code>null</code> if parameter was not found.
52 public Parameter<?> findParameterByAlias(final String alias) {
54 for (final Parameter<?> parameter : parameters)
55 if (parameter.matchesAlias(alias))
63 * commandline arguments
64 * @return <code>true</code> if no errors were found. <code>false</code>
67 public boolean parse(final String[] args) {
69 Parameter<?> currentParameter = null;
71 for (final String argument : args) {
73 final Parameter<?> parameterForAlias = findParameterByAlias(argument);
74 if (parameterForAlias == null) {
75 if (currentParameter == null) {
76 System.out.println("Unknown commandline parameter: "
81 if (!currentParameter.addArgument(argument))
85 if (currentParameter != null)
86 if (!currentParameter.noMoreArguments())
89 parameterForAlias.setParameterSpecified(true);
90 currentParameter = parameterForAlias;
95 return checkMandatoryArgumentsPresent();
98 public void showHelp() {
99 for (final Parameter<?> parameter : parameters)
100 System.out.println(parameter.getHelp());