
com.crabshue.commons.args.CommandLineArgumentsParser Maven / Gradle / Ivy
package com.crabshue.commons.args;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.lang3.Validate;
import com.crabshue.commons.args.exceptions.ArgumentsErrorContext;
import com.crabshue.commons.args.exceptions.ArgumentsErrorType;
import com.crabshue.commons.args.option.OptionsBuilder;
import com.crabshue.commons.args.parser.TolerantGnuParser;
import com.crabshue.commons.exceptions.ApplicationException;
import com.crabshue.commons.exceptions.SystemException;
/**
* Command line arguments parser.
*/
public class CommandLineArgumentsParser {
/**
* Parse command line arguments wrt a list of {@link Argument argument definitions}
*
* @param args the command line arguments
* @param arguments the argument definitions.
* @return the map of parsed arguments.
*/
public Map parseArguments(final String[] args, T... arguments) {
Validate.notNull(args);
final Options options = OptionsBuilder.buildOptions(arguments);
final CommandLine commandLine = parseCommandLine(args, options);
final Map ret = new HashMap<>();
Arrays.stream(arguments)
.forEach(argument ->
ret.put(
argument,
argument.isArgumentExpected() ?
commandLine.getOptionValue(argument.getOptionName(), argument.getDefaultValue()) :
commandLine.hasOption(argument.getOptionName())
)
);
return ret;
}
private CommandLine parseCommandLine(final String[] args, final Options options) {
final CommandLineParser commandLineParser = new TolerantGnuParser(true);
try {
return commandLineParser.parse(options, args);
} catch (MissingOptionException e) {
System.out.println(e.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("Help", options);
throw new ApplicationException(ArgumentsErrorType.MISSING_ARGUMENT, e)
.addContextValue(ArgumentsErrorContext.REQUIRED, options.getRequiredOptions());
} catch (ParseException e) {
throw new SystemException(ArgumentsErrorType.COMMAND_LINE_ARGUMENTS, e);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy