com.opsbears.webcomponents.configuration.ArgvConfigurationLoader Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of configuration Show documentation
Show all versions of configuration Show documentation
Utilities for creating and reading configuration options
package com.opsbears.webcomponents.configuration;
import javax.annotation.ParametersAreNonnullByDefault;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
@ParametersAreNonnullByDefault
public class ArgvConfigurationLoader implements ConfigurationLoader {
private final static Pattern shortArgumentPattern = Pattern.compile("\\A-[a-zA-Z0-9]\\Z");
private final static Pattern longArgumentPattern = Pattern.compile("\\A--[a-zA-Z0-9]+((-[a-zA-Z0-9]+)*)\\Z");
private final String[] argv;
public ArgvConfigurationLoader(String[] argv) {
this.argv = argv;
}
@Override
public String getName() {
return "Command line arguments";
}
@Override
public String getDescription() {
return "Pass any arguments after the name of the JAR file of this application.";
}
@Override
public String formatConfigurationOption(ConfigurationOption option) {
return "--" + option.getLongOption().toLowerCase() + (option.getValueType().equals(Boolean.class)?"":" VALUE");
}
@Override
public Configuration load(Configuration configuration) throws InvalidParameterException, ConfigurationOptionNotFound {
List argvList = new ArrayList<>(Arrays.asList(argv));
while (argvList.size() > 0) {
String parameter = argvList.get(0);
ConfigurationOption option;
if (longArgumentPattern.matcher(parameter).matches()) {
parameter = parameter.replaceAll("\\A--", "");
option = configuration.getOption(parameter);
//noinspection unchecked
if (option.getValueType().isAssignableFrom(Boolean.class)) {
configuration = configuration.withOptionValue(parameter, true);
argvList.remove(0);
} else {
configuration = configuration.withOptionValue(parameter, argvList.get(1));
argvList.remove(0);
argvList.remove(0);
}
} else if (shortArgumentPattern.matcher(parameter).matches()) {
parameter = parameter.replaceAll("\\A-", "");
option = configuration.getOptionByShortOption(parameter);
//noinspection unchecked
if (option.getValueType().isAssignableFrom(Boolean.class)) {
configuration = configuration.withShortOptionValue(parameter, true);
argvList.remove(0);
} else {
configuration = configuration.withShortOptionValue(parameter, argvList.get(1));
argvList.remove(0);
argvList.remove(0);
}
} else {
throw new InvalidParameterException(parameter);
}
}
for (ConfigurationOptionGroupWithValues optionGroup : configuration.getConfigurationOptionGroups()) {
for (ConfigurationOptionWithValue option : optionGroup.getOptions()) {
if (option.getValueWithoutDefault() == null) {
configuration = configuration.withOptionValue(option.getLongOption(), false);
}
}
}
return configuration;
}
}