http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/a8a7e7c9/log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java index a4cc8d2..f61d216 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java @@ -139,11 +139,11 @@ public class CommandLine { private String commandName = Help.DEFAULT_COMMAND_NAME; private boolean overwrittenOptionsAllowed = false; private boolean unmatchedArgumentsAllowed = false; - private List<String> unmatchedArguments = new ArrayList<String>(); + private final List<String> unmatchedArguments = new ArrayList<String>(); private CommandLine parent; private boolean usageHelpRequested; private boolean versionHelpRequested; - private List<String> versionLines = new ArrayList<String>(); + private final List<String> versionLines = new ArrayList<String>(); /** * Constructs a new {@code CommandLine} interpreter with the specified annotated object. @@ -152,7 +152,7 @@ public class CommandLine { * @param command the object to initialize from the command line arguments * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation */ - public CommandLine(Object command) { + public CommandLine(final Object command) { interpreter = new Interpreter(command); } @@ -197,8 +197,8 @@ public class CommandLine { * @since 0.9.7 * @see Command#subcommands() */ - public CommandLine addSubcommand(String name, Object command) { - CommandLine commandLine = toCommandLine(command); + public CommandLine addSubcommand(final String name, final Object command) { + final CommandLine commandLine = toCommandLine(command); commandLine.parent = this; interpreter.commands.put(name, commandLine); return this; @@ -259,9 +259,9 @@ public class CommandLine { * @return this {@code CommandLine} object, to allow method chaining * @since 0.9.7 */ - public CommandLine setOverwrittenOptionsAllowed(boolean newValue) { + public CommandLine setOverwrittenOptionsAllowed(final boolean newValue) { this.overwrittenOptionsAllowed = newValue; - for (CommandLine command : interpreter.commands.values()) { + for (final CommandLine command : interpreter.commands.values()) { command.setOverwrittenOptionsAllowed(newValue); } return this; @@ -288,9 +288,9 @@ public class CommandLine { * @since 0.9.7 * @see #getUnmatchedArguments() */ - public CommandLine setUnmatchedArgumentsAllowed(boolean newValue) { + public CommandLine setUnmatchedArgumentsAllowed(final boolean newValue) { this.unmatchedArgumentsAllowed = newValue; - for (CommandLine command : interpreter.commands.values()) { + for (final CommandLine command : interpreter.commands.values()) { command.setUnmatchedArgumentsAllowed(newValue); } return this; @@ -325,8 +325,8 @@ public class CommandLine { * @throws ParameterException if the specified command line arguments are invalid * @since 0.9.7 */ - public static <T> T populateCommand(T command, String... args) { - CommandLine cli = toCommandLine(command); + public static <T> T populateCommand(final T command, final String... args) { + final CommandLine cli = toCommandLine(command); cli.parse(args); return command; } @@ -345,7 +345,7 @@ public class CommandLine { * @throws ParameterException if the specified command line arguments are invalid; use * {@link ParameterException#getCommandLine()} to get the command or subcommand whose user input was invalid */ - public List<CommandLine> parse(String... args) { + public List<CommandLine> parse(final String... args) { return interpreter.parse(args); } /** @@ -407,7 +407,7 @@ public class CommandLine { * @since 2.0 */ public static class DefaultExceptionHandler implements IExceptionHandler { @Override - public List<Object> handleException(ParameterException ex, PrintStream out, Help.Ansi ansi, String... args) { + public List<Object> handleException(final ParameterException ex, final PrintStream out, final Help.Ansi ansi, final String... args) { out.println(ex.getMessage()); ex.getCommandLine().usage(out, ansi); return Collections.emptyList(); @@ -429,8 +429,8 @@ public class CommandLine { * @param ansi for printing help messages using ANSI styles and colors * @return {@code true} if help was printed, {@code false} otherwise * @since 2.0 */ - public static boolean printHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, Help.Ansi ansi) { - for (CommandLine parsed : parsedCommands) { + public static boolean printHelpIfRequested(final List<CommandLine> parsedCommands, final PrintStream out, final Help.Ansi ansi) { + for (final CommandLine parsed : parsedCommands) { if (parsed.isUsageHelpRequested()) { parsed.usage(out, ansi); return true; @@ -441,19 +441,19 @@ public class CommandLine { } return false; } - private static Object execute(CommandLine parsed) { - Object command = parsed.getCommand(); + private static Object execute(final CommandLine parsed) { + final Object command = parsed.getCommand(); if (command instanceof Runnable) { try { ((Runnable) command).run(); return null; - } catch (Exception ex) { + } catch (final Exception ex) { throw new ExecutionException(parsed, "Error while running command (" + command + ")", ex); } } else if (command instanceof Callable) { try { return ((Callable<Object>) command).call(); - } catch (Exception ex) { + } catch (final Exception ex) { throw new ExecutionException(parsed, "Error while calling command (" + command + ")", ex); } } @@ -482,7 +482,7 @@ public class CommandLine { * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed */ @Override - public List<Object> handleParseResult(List<CommandLine> parsedCommands, PrintStream out, Help.Ansi ansi) { + public List<Object> handleParseResult(final List<CommandLine> parsedCommands, final PrintStream out, final Help.Ansi ansi) { if (printHelpIfRequested(parsedCommands, out, ansi)) { return Collections.emptyList(); } return Arrays.asList(execute(parsedCommands.get(0))); } @@ -533,9 +533,9 @@ public class CommandLine { * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed */ @Override - public List<Object> handleParseResult(List<CommandLine> parsedCommands, PrintStream out, Help.Ansi ansi) { + public List<Object> handleParseResult(final List<CommandLine> parsedCommands, final PrintStream out, final Help.Ansi ansi) { if (printHelpIfRequested(parsedCommands, out, ansi)) { return Collections.emptyList(); } - CommandLine last = parsedCommands.get(parsedCommands.size() - 1); + final CommandLine last = parsedCommands.get(parsedCommands.size() - 1); return Arrays.asList(execute(last)); } } @@ -559,12 +559,12 @@ public class CommandLine { * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed */ @Override - public List<Object> handleParseResult(List<CommandLine> parsedCommands, PrintStream out, Help.Ansi ansi) { + public List<Object> handleParseResult(final List<CommandLine> parsedCommands, final PrintStream out, final Help.Ansi ansi) { if (printHelpIfRequested(parsedCommands, out, ansi)) { return null; } - List<Object> result = new ArrayList<Object>(); - for (CommandLine parsed : parsedCommands) { + final List<Object> result = new ArrayList<Object>(); + for (final CommandLine parsed : parsedCommands) { result.add(execute(parsed)); } return result; @@ -607,7 +607,7 @@ public class CommandLine { * @see RunLast * @see RunAll * @since 2.0 */ - public List<Object> parseWithHandler(IParseResultHandler handler, PrintStream out, String... args) { + public List<Object> parseWithHandler(final IParseResultHandler handler, final PrintStream out, final String... args) { return parseWithHandlers(handler, out, Help.Ansi.AUTO, new DefaultExceptionHandler(), args); } /** @@ -652,11 +652,11 @@ public class CommandLine { * @see RunAll * @see DefaultExceptionHandler * @since 2.0 */ - public List<Object> parseWithHandlers(IParseResultHandler handler, PrintStream out, Help.Ansi ansi, IExceptionHandler exceptionHandler, String... args) { + public List<Object> parseWithHandlers(final IParseResultHandler handler, final PrintStream out, final Help.Ansi ansi, final IExceptionHandler exceptionHandler, final String... args) { try { - List<CommandLine> result = parse(args); + final List<CommandLine> result = parse(args); return handler.handleParseResult(result, out, ansi); - } catch (ParameterException ex) { + } catch (final ParameterException ex) { return exceptionHandler.handleException(ex, out, ansi, args); } } @@ -666,7 +666,7 @@ public class CommandLine { * @param out the print stream to print the help message to * @throws IllegalArgumentException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation */ - public static void usage(Object command, PrintStream out) { + public static void usage(final Object command, final PrintStream out) { toCommandLine(command).usage(out); } @@ -678,7 +678,7 @@ public class CommandLine { * @param ansi whether the usage message should contain ANSI escape codes or not * @throws IllegalArgumentException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation */ - public static void usage(Object command, PrintStream out, Help.Ansi ansi) { + public static void usage(final Object command, final PrintStream out, final Help.Ansi ansi) { toCommandLine(command).usage(out, ansi); } @@ -690,7 +690,7 @@ public class CommandLine { * @param colorScheme the {@code ColorScheme} defining the styles for options, parameters and commands when ANSI is enabled * @throws IllegalArgumentException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation */ - public static void usage(Object command, PrintStream out, Help.ColorScheme colorScheme) { + public static void usage(final Object command, final PrintStream out, final Help.ColorScheme colorScheme) { toCommandLine(command).usage(out, colorScheme); } @@ -699,7 +699,7 @@ public class CommandLine { * @param out the printStream to print to * @see #usage(PrintStream, Help.ColorScheme) */ - public void usage(PrintStream out) { + public void usage(final PrintStream out) { usage(out, Help.Ansi.AUTO); } @@ -709,7 +709,7 @@ public class CommandLine { * @param ansi whether the usage message should include ANSI escape codes or not * @see #usage(PrintStream, Help.ColorScheme) */ - public void usage(PrintStream out, Help.Ansi ansi) { + public void usage(final PrintStream out, final Help.Ansi ansi) { usage(out, Help.defaultColorScheme(ansi)); } /** @@ -744,8 +744,8 @@ public class CommandLine { * @param out the {@code PrintStream} to print the usage help message to * @param colorScheme the {@code ColorScheme} defining the styles for options, parameters and commands when ANSI is enabled */ - public void usage(PrintStream out, Help.ColorScheme colorScheme) { - Help help = new Help(interpreter.command, colorScheme).addAllSubcommands(getSubcommands()); + public void usage(final PrintStream out, final Help.ColorScheme colorScheme) { + final Help help = new Help(interpreter.command, colorScheme).addAllSubcommands(getSubcommands()); if (!Help.DEFAULT_SEPARATOR.equals(getSeparator())) { help.separator = getSeparator(); help.parameterLabelRenderer = help.createDefaultParamLabelRenderer(); // update for new separator @@ -753,7 +753,7 @@ public class CommandLine { if (!Help.DEFAULT_COMMAND_NAME.equals(getCommandName())) { help.commandName = getCommandName(); } - StringBuilder sb = new StringBuilder() + final StringBuilder sb = new StringBuilder() .append(help.headerHeading()) .append(help.header()) .append(help.synopsisHeading()) //e.g. Usage: @@ -777,7 +777,7 @@ public class CommandLine { * @see #printVersionHelp(PrintStream, Help.Ansi) * @since 0.9.8 */ - public void printVersionHelp(PrintStream out) { printVersionHelp(out, Help.Ansi.AUTO); } + public void printVersionHelp(final PrintStream out) { printVersionHelp(out, Help.Ansi.AUTO); } /** * Prints version information from the {@link Command#version()} annotation to the specified {@code PrintStream}. @@ -790,8 +790,8 @@ public class CommandLine { * @see #isVersionHelpRequested() * @since 0.9.8 */ - public void printVersionHelp(PrintStream out, Help.Ansi ansi) { - for (String versionInfo : versionLines) { + public void printVersionHelp(final PrintStream out, final Help.Ansi ansi) { + for (final String versionInfo : versionLines) { out.println(ansi.new Text(versionInfo)); } } @@ -808,8 +808,8 @@ public class CommandLine { * @see #isVersionHelpRequested() * @since 1.0.0 */ - public void printVersionHelp(PrintStream out, Help.Ansi ansi, Object... params) { - for (String versionInfo : versionLines) { + public void printVersionHelp(final PrintStream out, final Help.Ansi ansi, final Object... params) { + for (final String versionInfo : versionLines) { out.println(ansi.new Text(String.format(versionInfo, params))); } } @@ -832,7 +832,7 @@ public class CommandLine { * @see #parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...) * @see RunFirst */ - public static <C extends Callable<T>, T> T call(C callable, PrintStream out, String... args) { + public static <C extends Callable<T>, T> T call(final C callable, final PrintStream out, final String... args) { return call(callable, out, Help.Ansi.AUTO, args); } /** @@ -880,9 +880,9 @@ public class CommandLine { * @see #parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...) * @see RunLast */ - public static <C extends Callable<T>, T> T call(C callable, PrintStream out, Help.Ansi ansi, String... args) { - CommandLine cmd = new CommandLine(callable); // validate command outside of try-catch - List<Object> results = cmd.parseWithHandlers(new RunLast(), out, ansi, new DefaultExceptionHandler(), args); + public static <C extends Callable<T>, T> T call(final C callable, final PrintStream out, final Help.Ansi ansi, final String... args) { + final CommandLine cmd = new CommandLine(callable); // validate command outside of try-catch + final List<Object> results = cmd.parseWithHandlers(new RunLast(), out, ansi, new DefaultExceptionHandler(), args); return results == null || results.isEmpty() ? null : (T) results.get(0); } @@ -902,7 +902,7 @@ public class CommandLine { * @see #parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...) * @see RunFirst */ - public static <R extends Runnable> void run(R runnable, PrintStream out, String... args) { + public static <R extends Runnable> void run(final R runnable, final PrintStream out, final String... args) { run(runnable, out, Help.Ansi.AUTO, args); } /** @@ -948,8 +948,8 @@ public class CommandLine { * @see #parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...) * @see RunLast */ - public static <R extends Runnable> void run(R runnable, PrintStream out, Help.Ansi ansi, String... args) { - CommandLine cmd = new CommandLine(runnable); // validate command outside of try-catch + public static <R extends Runnable> void run(final R runnable, final PrintStream out, final Help.Ansi ansi, final String... args) { + final CommandLine cmd = new CommandLine(runnable); // validate command outside of try-catch cmd.parseWithHandlers(new RunLast(), out, ansi, new DefaultExceptionHandler(), args); } @@ -996,9 +996,9 @@ public class CommandLine { * @return this CommandLine object, to allow method chaining * @see #addSubcommand(String, Object) */ - public <K> CommandLine registerConverter(Class<K> cls, ITypeConverter<K> converter) { + public <K> CommandLine registerConverter(final Class<K> cls, final ITypeConverter<K> converter) { interpreter.converterRegistry.put(Assert.notNull(cls, "class"), Assert.notNull(converter, "converter")); - for (CommandLine command : interpreter.commands.values()) { + for (final CommandLine command : interpreter.commands.values()) { command.registerConverter(cls, converter); } return this; @@ -1014,7 +1014,7 @@ public class CommandLine { * The separator may also be set declaratively with the {@link CommandLine.Command#separator()} annotation attribute. * @param separator the String that separates option names from option values * @return this {@code CommandLine} object, to allow method chaining */ - public CommandLine setSeparator(String separator) { + public CommandLine setSeparator(final String separator) { interpreter.separator = Assert.notNull(separator, "separator"); return this; } @@ -1030,35 +1030,35 @@ public class CommandLine { * The command name may also be set declaratively with the {@link CommandLine.Command#name()} annotation attribute. * @param commandName command name (also called program name) displayed in the usage help synopsis * @return this {@code CommandLine} object, to allow method chaining */ - public CommandLine setCommandName(String commandName) { + public CommandLine setCommandName(final String commandName) { this.commandName = Assert.notNull(commandName, "commandName"); return this; } - private static boolean empty(String str) { return str == null || str.trim().length() == 0; } - private static boolean empty(Object[] array) { return array == null || array.length == 0; } - private static boolean empty(Text txt) { return txt == null || txt.plain.toString().trim().length() == 0; } - private static String str(String[] arr, int i) { return (arr == null || arr.length == 0) ? "" : arr[i]; } - private static boolean isBoolean(Class<?> type) { return type == Boolean.class || type == Boolean.TYPE; } - private static CommandLine toCommandLine(Object obj) { return obj instanceof CommandLine ? (CommandLine) obj : new CommandLine(obj);} - private static boolean isMultiValue(Field field) { return isMultiValue(field.getType()); } - private static boolean isMultiValue(Class<?> cls) { return cls.isArray() || Collection.class.isAssignableFrom(cls) || Map.class.isAssignableFrom(cls); } - private static Class<?>[] getTypeAttribute(Field field) { - Class<?>[] explicit = field.isAnnotationPresent(Parameters.class) ? field.getAnnotation(Parameters.class).type() : field.getAnnotation(Option.class).type(); + private static boolean empty(final String str) { return str == null || str.trim().length() == 0; } + private static boolean empty(final Object[] array) { return array == null || array.length == 0; } + private static boolean empty(final Text txt) { return txt == null || txt.plain.toString().trim().length() == 0; } + private static String str(final String[] arr, final int i) { return (arr == null || arr.length == 0) ? "" : arr[i]; } + private static boolean isBoolean(final Class<?> type) { return type == Boolean.class || type == Boolean.TYPE; } + private static CommandLine toCommandLine(final Object obj) { return obj instanceof CommandLine ? (CommandLine) obj : new CommandLine(obj);} + private static boolean isMultiValue(final Field field) { return isMultiValue(field.getType()); } + private static boolean isMultiValue(final Class<?> cls) { return cls.isArray() || Collection.class.isAssignableFrom(cls) || Map.class.isAssignableFrom(cls); } + private static Class<?>[] getTypeAttribute(final Field field) { + final Class<?>[] explicit = field.isAnnotationPresent(Parameters.class) ? field.getAnnotation(Parameters.class).type() : field.getAnnotation(Option.class).type(); if (explicit.length > 0) { return explicit; } if (field.getType().isArray()) { return new Class<?>[] { field.getType().getComponentType() }; } if (isMultiValue(field)) { - Type type = field.getGenericType(); // e.g. Map<Long, ? extends Number> + final Type type = field.getGenericType(); // e.g. Map<Long, ? extends Number> if (type instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) type; - Type[] paramTypes = parameterizedType.getActualTypeArguments(); // e.g. ? extends Number - Class<?>[] result = new Class<?>[paramTypes.length]; + final ParameterizedType parameterizedType = (ParameterizedType) type; + final Type[] paramTypes = parameterizedType.getActualTypeArguments(); // e.g. ? extends Number + final Class<?>[] result = new Class<?>[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { if (paramTypes[i] instanceof Class) { result[i] = (Class<?>) paramTypes[i]; continue; } // e.g. Long if (paramTypes[i] instanceof WildcardType) { // e.g. ? extends Number - WildcardType wildcardType = (WildcardType) paramTypes[i]; - Type[] lower = wildcardType.getLowerBounds(); // e.g. [] + final WildcardType wildcardType = (WildcardType) paramTypes[i]; + final Type[] lower = wildcardType.getLowerBounds(); // e.g. [] if (lower.length > 0 && lower[0] instanceof Class) { result[i] = (Class<?>) lower[0]; continue; } - Type[] upper = wildcardType.getUpperBounds(); // e.g. Number + final Type[] upper = wildcardType.getUpperBounds(); // e.g. Number if (upper.length > 0 && upper[0] instanceof Class) { result[i] = (Class<?>) upper[0]; continue; } } Arrays.fill(result, String.class); return result; // too convoluted generic type, giving up @@ -1656,7 +1656,7 @@ public class CommandLine { * @param unspecified {@code true} if no arity was specified on the option/parameter (value is based on type) * @param originalValue the original value that was specified on the option or parameter */ - public Range(int min, int max, boolean variable, boolean unspecified, String originalValue) { + public Range(final int min, final int max, final boolean variable, final boolean unspecified, final String originalValue) { this.min = min; this.max = max; this.isVariable = variable; @@ -1667,7 +1667,7 @@ public class CommandLine { * or the field type's default arity if no arity was specified. * @param field the field whose Option annotation to inspect * @return a new {@code Range} based on the Option arity annotation on the specified field */ - public static Range optionArity(Field field) { + public static Range optionArity(final Field field) { return field.isAnnotationPresent(Option.class) ? adjustForType(Range.valueOf(field.getAnnotation(Option.class).arity()), field) : new Range(0, 0, false, true, "0"); @@ -1676,7 +1676,7 @@ public class CommandLine { * or the field type's default arity if no arity was specified. * @param field the field whose Parameters annotation to inspect * @return a new {@code Range} based on the Parameters arity annotation on the specified field */ - public static Range parameterArity(Field field) { + public static Range parameterArity(final Field field) { return field.isAnnotationPresent(Parameters.class) ? adjustForType(Range.valueOf(field.getAnnotation(Parameters.class).arity()), field) : new Range(0, 0, false, true, "0"); @@ -1684,12 +1684,12 @@ public class CommandLine { /** Returns a new {@code Range} based on the {@link Parameters#index()} annotation on the specified field. * @param field the field whose Parameters annotation to inspect * @return a new {@code Range} based on the Parameters index annotation on the specified field */ - public static Range parameterIndex(Field field) { + public static Range parameterIndex(final Field field) { return field.isAnnotationPresent(Parameters.class) ? Range.valueOf(field.getAnnotation(Parameters.class).index()) : new Range(0, 0, false, true, "0"); } - static Range adjustForType(Range result, Field field) { + static Range adjustForType(final Range result, final Field field) { return result.isUnspecified ? defaultArity(field) : result; } /** Returns the default arity {@code Range}: for {@link Option options} this is 0 for booleans and 1 for @@ -1698,8 +1698,8 @@ public class CommandLine { * @param field the field whose default arity to return * @return a new {@code Range} indicating the default arity of the specified field * @since 2.0 */ - public static Range defaultArity(Field field) { - Class<?> type = field.getType(); + public static Range defaultArity(final Field field) { + final Class<?> type = field.getType(); if (field.isAnnotationPresent(Option.class)) { return defaultArity(type); } @@ -1711,14 +1711,14 @@ public class CommandLine { /** Returns the default arity {@code Range} for {@link Option options}: booleans have arity 0, other types have arity 1. * @param type the type whose default arity to return * @return a new {@code Range} indicating the default arity of the specified type */ - public static Range defaultArity(Class<?> type) { + public static Range defaultArity(final Class<?> type) { return isBoolean(type) ? Range.valueOf("0") : Range.valueOf("1"); } private int size() { return 1 + max - min; } - static Range parameterCapacity(Field field) { - Range arity = parameterArity(field); + static Range parameterCapacity(final Field field) { + final Range arity = parameterArity(field); if (!isMultiValue(field)) { return arity; } - Range index = parameterIndex(field); + final Range index = parameterIndex(field); if (arity.max == 0) { return arity; } if (index.size() == 1) { return arity; } if (index.isVariable) { return Range.valueOf(arity.min + "..*"); } @@ -1734,7 +1734,7 @@ public class CommandLine { * @return a new {@code Range} value */ public static Range valueOf(String range) { range = range.trim(); - boolean unspecified = range.length() == 0 || range.startsWith(".."); // || range.endsWith(".."); + final boolean unspecified = range.length() == 0 || range.startsWith(".."); // || range.endsWith(".."); int min = -1, max = -1; boolean variable = false; int dots = -1; @@ -1747,13 +1747,13 @@ public class CommandLine { variable = max == Integer.MAX_VALUE; min = variable ? 0 : max; } - Range result = new Range(min, max, variable, unspecified, range); + final Range result = new Range(min, max, variable, unspecified, range); return result; } - private static int parseInt(String str, int defaultValue) { + private static int parseInt(final String str, final int defaultValue) { try { return Integer.parseInt(str); - } catch (Exception ex) { + } catch (final Exception ex) { return defaultValue; } } @@ -1761,25 +1761,25 @@ public class CommandLine { * The {@code max} of the returned Range is guaranteed not to be less than the new {@code min} value. * @param newMin the {@code min} value of the returned Range object * @return a new Range object with the specified {@code min} value */ - public Range min(int newMin) { return new Range(newMin, Math.max(newMin, max), isVariable, isUnspecified, originalValue); } + public Range min(final int newMin) { return new Range(newMin, Math.max(newMin, max), isVariable, isUnspecified, originalValue); } /** Returns a new Range object with the {@code max} value replaced by the specified value. * The {@code min} of the returned Range is guaranteed not to be greater than the new {@code max} value. * @param newMax the {@code max} value of the returned Range object * @return a new Range object with the specified {@code max} value */ - public Range max(int newMax) { return new Range(Math.min(min, newMax), newMax, isVariable, isUnspecified, originalValue); } + public Range max(final int newMax) { return new Range(Math.min(min, newMax), newMax, isVariable, isUnspecified, originalValue); } /** * Returns {@code true} if this Range includes the specified value, {@code false} otherwise. * @param value the value to check * @return {@code true} if the specified value is not less than the minimum and not greater than the maximum of this Range */ - public boolean contains(int value) { return min <= value && max >= value; } + public boolean contains(final int value) { return min <= value && max >= value; } @Override - public boolean equals(Object object) { + public boolean equals(final Object object) { if (!(object instanceof Range)) { return false; } - Range other = (Range) object; + final Range other = (Range) object; return other.max == this.max && other.min == this.min && other.isVariable == this.isVariable; } @Override @@ -1791,32 +1791,32 @@ public class CommandLine { return min == max ? String.valueOf(min) : min + ".." + (isVariable ? "*" : max); } @Override - public int compareTo(Range other) { - int result = min - other.min; + public int compareTo(final Range other) { + final int result = min - other.min; return (result == 0) ? max - other.max : result; } } - static void init(Class<?> cls, - List<Field> requiredFields, - Map<String, Field> optionName2Field, - Map<Character, Field> singleCharOption2Field, - List<Field> positionalParametersFields) { - Field[] declaredFields = cls.getDeclaredFields(); - for (Field field : declaredFields) { + static void init(final Class<?> cls, + final List<Field> requiredFields, + final Map<String, Field> optionName2Field, + final Map<Character, Field> singleCharOption2Field, + final List<Field> positionalParametersFields) { + final Field[] declaredFields = cls.getDeclaredFields(); + for (final Field field : declaredFields) { field.setAccessible(true); if (field.isAnnotationPresent(Option.class)) { - Option option = field.getAnnotation(Option.class); + final Option option = field.getAnnotation(Option.class); if (option.required()) { requiredFields.add(field); } - for (String name : option.names()) { // cannot be null or empty - Field existing = optionName2Field.put(name, field); + for (final String name : option.names()) { // cannot be null or empty + final Field existing = optionName2Field.put(name, field); if (existing != null && existing != field) { throw DuplicateOptionAnnotationsException.create(name, field, existing); } if (name.length() == 2 && name.startsWith("-")) { - char flag = name.charAt(1); - Field existing2 = singleCharOption2Field.put(flag, field); + final char flag = name.charAt(1); + final Field existing2 = singleCharOption2Field.put(flag, field); if (existing2 != null && existing2 != field) { throw DuplicateOptionAnnotationsException.create(name, field, existing2); } @@ -1829,17 +1829,17 @@ public class CommandLine { + field.getName() + "' is both."); } positionalParametersFields.add(field); - Range arity = Range.parameterArity(field); + final Range arity = Range.parameterArity(field); if (arity.min > 0) { requiredFields.add(field); } } } } - static void validatePositionalParameters(List<Field> positionalParametersFields) { + static void validatePositionalParameters(final List<Field> positionalParametersFields) { int min = 0; - for (Field field : positionalParametersFields) { - Range index = Range.parameterIndex(field); + for (final Field field : positionalParametersFields) { + final Range index = Range.parameterIndex(field); if (index.min > min) { throw new ParameterIndexGapException("Missing field annotated with @Parameter(index=" + min + "). Nearest field '" + field.getName() + "' has index=" + index.min); @@ -1848,7 +1848,7 @@ public class CommandLine { min = min == Integer.MAX_VALUE ? min : min + 1; } } - private static <T> Stack<T> reverse(Stack<T> stack) { + private static <T> Stack<T> reverse(final Stack<T> stack) { Collections.reverse(stack); return stack; } @@ -1867,7 +1867,7 @@ public class CommandLine { private String separator = Help.DEFAULT_SEPARATOR; private int position; - Interpreter(Object command) { + Interpreter(final Object command) { converterRegistry.put(Path.class, new BuiltIn.PathConverter()); converterRegistry.put(Object.class, new BuiltIn.StringConverter()); converterRegistry.put(String.class, new BuiltIn.StringConverter()); @@ -1910,28 +1910,28 @@ public class CommandLine { init(cls, requiredFields, optionName2Field, singleCharOption2Field, positionalParametersFields); if (cls.isAnnotationPresent(Command.class)) { hasCommandAnnotation = true; - Command cmd = cls.getAnnotation(Command.class); + final Command cmd = cls.getAnnotation(Command.class); declaredSeparator = (declaredSeparator == null) ? cmd.separator() : declaredSeparator; declaredName = (declaredName == null) ? cmd.name() : declaredName; CommandLine.this.versionLines.addAll(Arrays.asList(cmd.version())); - for (Class<?> sub : cmd.subcommands()) { - Command subCommand = sub.getAnnotation(Command.class); + for (final Class<?> sub : cmd.subcommands()) { + final Command subCommand = sub.getAnnotation(Command.class); if (subCommand == null || Help.DEFAULT_COMMAND_NAME.equals(subCommand.name())) { throw new InitializationException("Subcommand " + sub.getName() + " is missing the mandatory @Command annotation with a 'name' attribute"); } try { - Constructor<?> constructor = sub.getDeclaredConstructor(); + final Constructor<?> constructor = sub.getDeclaredConstructor(); constructor.setAccessible(true); - CommandLine commandLine = toCommandLine(constructor.newInstance()); + final CommandLine commandLine = toCommandLine(constructor.newInstance()); commandLine.parent = CommandLine.this; commands.put(subCommand.name(), commandLine); } - catch (InitializationException ex) { throw ex; } - catch (NoSuchMethodException ex) { throw new InitializationException("Cannot instantiate subcommand " + + catch (final InitializationException ex) { throw ex; } + catch (final NoSuchMethodException ex) { throw new InitializationException("Cannot instantiate subcommand " + sub.getName() + ": the class has no constructor", ex); } - catch (Exception ex) { + catch (final Exception ex) { throw new InitializationException("Could not instantiate and add subcommand " + sub.getName() + ": " + ex, ex); } @@ -1956,41 +1956,41 @@ public class CommandLine { * @return a list with all commands and subcommands initialized by this method * @throws ParameterException if the specified command line arguments are invalid */ - List<CommandLine> parse(String... args) { + List<CommandLine> parse(final String... args) { Assert.notNull(args, "argument array"); if (tracer.isInfo()) {tracer.info("Parsing %d command line args %s%n", args.length, Arrays.toString(args));} - Stack<String> arguments = new Stack<String>(); + final Stack<String> arguments = new Stack<String>(); for (int i = args.length - 1; i >= 0; i--) { arguments.push(args[i]); } - List<CommandLine> result = new ArrayList<CommandLine>(); + final List<CommandLine> result = new ArrayList<CommandLine>(); parse(result, arguments, args); return result; } - private void parse(List<CommandLine> parsedCommands, Stack<String> argumentStack, String[] originalArgs) { + private void parse(final List<CommandLine> parsedCommands, final Stack<String> argumentStack, final String[] originalArgs) { // first reset any state in case this CommandLine instance is being reused isHelpRequested = false; CommandLine.this.versionHelpRequested = false; CommandLine.this.usageHelpRequested = false; - Class<?> cmdClass = this.command.getClass(); + final Class<?> cmdClass = this.command.getClass(); if (tracer.isDebug()) {tracer.debug("Initializing %s: %d options, %d positional parameters, %d required, %d subcommands.%n", cmdClass.getName(), new HashSet<Field>(optionName2Field.values()).size(), positionalParametersFields.size(), requiredFields.size(), commands.size());} parsedCommands.add(CommandLine.this); - List<Field> required = new ArrayList<Field>(requiredFields); - Set<Field> initialized = new HashSet<Field>(); + final List<Field> required = new ArrayList<Field>(requiredFields); + final Set<Field> initialized = new HashSet<Field>(); Collections.sort(required, new PositionalParametersSorter()); try { processArguments(parsedCommands, argumentStack, required, initialized, originalArgs); - } catch (ParameterException ex) { + } catch (final ParameterException ex) { throw ex; - } catch (Exception ex) { - int offendingArgIndex = originalArgs.length - argumentStack.size() - 1; - String arg = offendingArgIndex >= 0 && offendingArgIndex < originalArgs.length ? originalArgs[offendingArgIndex] : "?"; + } catch (final Exception ex) { + final int offendingArgIndex = originalArgs.length - argumentStack.size() - 1; + final String arg = offendingArgIndex >= 0 && offendingArgIndex < originalArgs.length ? originalArgs[offendingArgIndex] : "?"; throw ParameterException.create(CommandLine.this, ex, arg, offendingArgIndex, originalArgs); } if (!isAnyHelpRequested() && !required.isEmpty()) { - for (Field missing : required) { + for (final Field missing : required) { if (missing.isAnnotationPresent(Option.class)) { throw MissingParameterException.create(CommandLine.this, required, separator); } else { @@ -2004,11 +2004,11 @@ public class CommandLine { } } - private void processArguments(List<CommandLine> parsedCommands, - Stack<String> args, - Collection<Field> required, - Set<Field> initialized, - String[] originalArgs) throws Exception { + private void processArguments(final List<CommandLine> parsedCommands, + final Stack<String> args, + final Collection<Field> required, + final Set<Field> initialized, + final String[] originalArgs) throws Exception { // arg must be one of: // 1. the "--" double dash separating options from positional arguments // 1. a stand-alone flag, like "-v" or "--verbose": no value required, must map to boolean or Boolean field @@ -2045,13 +2045,13 @@ public class CommandLine { // or an option may have one or more option parameters. // A parameter may be attached to the option. boolean paramAttachedToOption = false; - int separatorIndex = arg.indexOf(separator); + final int separatorIndex = arg.indexOf(separator); if (separatorIndex > 0) { - String key = arg.substring(0, separatorIndex); + final String key = arg.substring(0, separatorIndex); // be greedy. Consume the whole arg as an option if possible. if (optionName2Field.containsKey(key) && !optionName2Field.containsKey(arg)) { paramAttachedToOption = true; - String optionParam = arg.substring(separatorIndex + separator.length()); + final String optionParam = arg.substring(separatorIndex + separator.length()); args.push(optionParam); arg = key; if (tracer.isDebug()) {tracer.debug("Separated '%s' option from '%s' option parameter%n", key, optionParam);} @@ -2081,43 +2081,44 @@ public class CommandLine { } } } - private boolean resemblesOption(String arg) { + private boolean resemblesOption(final String arg) { int count = 0; - for (String optionName : optionName2Field.keySet()) { + for (final String optionName : optionName2Field.keySet()) { for (int i = 0; i < arg.length(); i++) { if (optionName.length() > i && arg.charAt(i) == optionName.charAt(i)) { count++; } else { break; } } } - boolean result = count > 0 && count * 10 >= optionName2Field.size() * 9; // at least one prefix char in common with 9 out of 10 options + final boolean result = count > 0 && count * 10 >= optionName2Field.size() * 9; // at least one prefix char in common with 9 out of 10 options if (tracer.isDebug()) {tracer.debug("%s %s an option: %d matching prefix chars out of %d option names%n", arg, (result ? "resembles" : "doesn't resemble"), count, optionName2Field.size());} return result; } - private void handleUnmatchedArguments(String arg) {Stack<String> args = new Stack<String>(); args.add(arg); handleUnmatchedArguments(args);} - private void handleUnmatchedArguments(Stack<String> args) { + private void handleUnmatchedArguments(final String arg) {final Stack<String> args = new Stack<String>(); args.add(arg); handleUnmatchedArguments(args);} + private void handleUnmatchedArguments(final Stack<String> args) { while (!args.isEmpty()) { unmatchedArguments.add(args.pop()); } // addAll would give args in reverse order } - private void processRemainderAsPositionalParameters(Collection<Field> required, Set<Field> initialized, Stack<String> args) throws Exception { + private void processRemainderAsPositionalParameters(final Collection<Field> required, final Set<Field> initialized, final Stack<String> args) throws Exception { while (!args.empty()) { processPositionalParameter(required, initialized, args); } } - private void processPositionalParameter(Collection<Field> required, Set<Field> initialized, Stack<String> args) throws Exception { + private void processPositionalParameter(final Collection<Field> required, final Set<Field> initialized, final Stack<String> args) throws Exception { if (tracer.isDebug()) {tracer.debug("Processing next arg as a positional parameter at index=%d. Remainder=%s%n", position, reverse((Stack<String>) args.clone()));} int consumed = 0; - for (Field positionalParam : positionalParametersFields) { - Range indexRange = Range.parameterIndex(positionalParam); + for (final Field positionalParam : positionalParametersFields) { + final Range indexRange = Range.parameterIndex(positionalParam); if (!indexRange.contains(position)) { continue; } @SuppressWarnings("unchecked") + final Stack<String> argsCopy = (Stack<String>) args.clone(); - Range arity = Range.parameterArity(positionalParam); + final Range arity = Range.parameterArity(positionalParam); if (tracer.isDebug()) {tracer.debug("Position %d is in index range %s. Trying to assign args to %s, arity=%s%n", position, indexRange, positionalParam, arity);} assertNoMissingParameters(positionalParam, arity.min, argsCopy); - int originalSize = argsCopy.size(); + final int originalSize = argsCopy.size(); applyOption(positionalParam, Parameters.class, arity, false, argsCopy, initialized, "args[" + indexRange + "] at position " + position); - int count = originalSize - argsCopy.size(); + final int count = originalSize - argsCopy.size(); if (count > 0) { required.remove(positionalParam); } consumed = Math.max(consumed, count); } @@ -2130,12 +2131,12 @@ public class CommandLine { } } - private void processStandaloneOption(Collection<Field> required, - Set<Field> initialized, - String arg, - Stack<String> args, - boolean paramAttachedToKey) throws Exception { - Field field = optionName2Field.get(arg); + private void processStandaloneOption(final Collection<Field> required, + final Set<Field> initialized, + final String arg, + final Stack<String> args, + final boolean paramAttachedToKey) throws Exception { + final Field field = optionName2Field.get(arg); required.remove(field); Range arity = Range.optionArity(field); if (paramAttachedToKey) { @@ -2145,19 +2146,19 @@ public class CommandLine { applyOption(field, Option.class, arity, paramAttachedToKey, args, initialized, "option " + arg); } - private void processClusteredShortOptions(Collection<Field> required, - Set<Field> initialized, - String arg, - Stack<String> args) + private void processClusteredShortOptions(final Collection<Field> required, + final Set<Field> initialized, + final String arg, + final Stack<String> args) throws Exception { - String prefix = arg.substring(0, 1); + final String prefix = arg.substring(0, 1); String cluster = arg.substring(1); boolean paramAttachedToOption = true; do { if (cluster.length() > 0 && singleCharOption2Field.containsKey(cluster.charAt(0))) { - Field field = singleCharOption2Field.get(cluster.charAt(0)); + final Field field = singleCharOption2Field.get(cluster.charAt(0)); Range arity = Range.optionArity(field); - String argDescription = "option " + prefix + cluster.charAt(0); + final String argDescription = "option " + prefix + cluster.charAt(0); if (tracer.isDebug()) {tracer.debug("Found option '%s%s' in %s: field %s, arity=%s%n", prefix, cluster.charAt(0), arg, field, arity);} required.remove(field); cluster = cluster.length() > 0 ? cluster.substring(1) : ""; @@ -2175,7 +2176,7 @@ public class CommandLine { if (!empty(cluster)) { args.push(cluster); // interpret remainder as option parameter } - int consumed = applyOption(field, Option.class, arity, paramAttachedToOption, args, initialized, argDescription); + final int consumed = applyOption(field, Option.class, arity, paramAttachedToOption, args, initialized, argDescription); // only return if cluster (and maybe more) was consumed, otherwise continue do-while loop if (empty(cluster) || consumed > 0 || args.isEmpty()) { return; @@ -2208,15 +2209,15 @@ public class CommandLine { } while (true); } - private int applyOption(Field field, - Class<?> annotation, - Range arity, - boolean valueAttachedToOption, - Stack<String> args, - Set<Field> initialized, - String argDescription) throws Exception { + private int applyOption(final Field field, + final Class<?> annotation, + final Range arity, + final boolean valueAttachedToOption, + final Stack<String> args, + final Set<Field> initialized, + final String argDescription) throws Exception { updateHelpRequested(field); - int length = args.size(); + final int length = args.size(); assertNoMissingParameters(field, arity.min, args); Class<?> cls = field.getType(); @@ -2233,13 +2234,13 @@ public class CommandLine { return applyValueToSingleValuedField(field, arity, args, cls, initialized, argDescription); } - private int applyValueToSingleValuedField(Field field, - Range arity, - Stack<String> args, - Class<?> cls, - Set<Field> initialized, - String argDescription) throws Exception { - boolean noMoreValues = args.isEmpty(); + private int applyValueToSingleValuedField(final Field field, + final Range arity, + final Stack<String> args, + final Class<?> cls, + final Set<Field> initialized, + final String argDescription) throws Exception { + final boolean noMoreValues = args.isEmpty(); String value = args.isEmpty() ? null : trim(args.pop()); // unquote the value int result = arity.min; // the number or args we need to consume @@ -2253,16 +2254,16 @@ public class CommandLine { if (value != null) { args.push(value); // we don't consume the value } - Boolean currentValue = (Boolean) field.get(command); + final Boolean currentValue = (Boolean) field.get(command); value = String.valueOf(currentValue == null ? true : !currentValue); // #147 toggle existing boolean value } } if (noMoreValues && value == null) { return 0; } - ITypeConverter<?> converter = getTypeConverter(cls, field); - Object newValue = tryConvert(field, -1, converter, value, cls); - Object oldValue = field.get(command); + final ITypeConverter<?> converter = getTypeConverter(cls, field); + final Object newValue = tryConvert(field, -1, converter, value, cls); + final Object oldValue = field.get(command); TraceLevel level = TraceLevel.INFO; String traceMessage = "Setting %s field '%s.%s' to '%5$s' (was '%4$s') for %6$s%n"; if (initialized != null) { @@ -2281,34 +2282,34 @@ public class CommandLine { field.set(command, newValue); return result; } - private int applyValuesToMapField(Field field, - Class<?> annotation, - Range arity, - Stack<String> args, - Class<?> cls, - String argDescription) throws Exception { - Class<?>[] classes = getTypeAttribute(field); + private int applyValuesToMapField(final Field field, + final Class<?> annotation, + final Range arity, + final Stack<String> args, + final Class<?> cls, + final String argDescription) throws Exception { + final Class<?>[] classes = getTypeAttribute(field); if (classes.length < 2) { throw new ParameterException(CommandLine.this, "Field " + field + " needs two types (one for the map key, one for the value) but only has " + classes.length + " types configured."); } - ITypeConverter<?> keyConverter = getTypeConverter(classes[0], field); - ITypeConverter<?> valueConverter = getTypeConverter(classes[1], field); + final ITypeConverter<?> keyConverter = getTypeConverter(classes[0], field); + final ITypeConverter<?> valueConverter = getTypeConverter(classes[1], field); Map<Object, Object> result = (Map<Object, Object>) field.get(command); if (result == null) { result = createMap(cls); field.set(command, result); } - int originalSize = result.size(); + final int originalSize = result.size(); consumeMapArguments(field, arity, args, classes, keyConverter, valueConverter, result, argDescription); return result.size() - originalSize; } - private void consumeMapArguments(Field field, - Range arity, - Stack<String> args, - Class<?>[] classes, - ITypeConverter<?> keyConverter, - ITypeConverter<?> valueConverter, - Map<Object, Object> result, - String argDescription) throws Exception { + private void consumeMapArguments(final Field field, + final Range arity, + final Stack<String> args, + final Class<?>[] classes, + final ITypeConverter<?> keyConverter, + final ITypeConverter<?> valueConverter, + final Map<Object, Object> result, + final String argDescription) throws Exception { // first do the arity.min mandatory parameters for (int i = 0; i < arity.min; i++) { consumeOneMapArgument(field, arity, args, classes, keyConverter, valueConverter, result, i, argDescription); @@ -2324,19 +2325,19 @@ public class CommandLine { } } - private void consumeOneMapArgument(Field field, - Range arity, - Stack<String> args, - Class<?>[] classes, - ITypeConverter<?> keyConverter, ITypeConverter<?> valueConverter, - Map<Object, Object> result, - int index, - String argDescription) throws Exception { - String[] values = split(trim(args.pop()), field); - for (String value : values) { - String[] keyValue = value.split("="); + private void consumeOneMapArgument(final Field field, + final Range arity, + final Stack<String> args, + final Class<?>[] classes, + final ITypeConverter<?> keyConverter, final ITypeConverter<?> valueConverter, + final Map<Object, Object> result, + final int index, + final String argDescription) throws Exception { + final String[] values = split(trim(args.pop()), field); + for (final String value : values) { + final String[] keyValue = value.split("="); if (keyValue.length < 2) { - String splitRegex = splitRegex(field); + final String splitRegex = splitRegex(field); if (splitRegex.length() == 0) { throw new ParameterException(CommandLine.this, "Value for option " + optionDescription("", field, 0) + " should be in KEY=VALUE format but was " + value); @@ -2345,44 +2346,44 @@ public class CommandLine { 0) + " should be in KEY=VALUE[" + splitRegex + "KEY=VALUE]... format but was " + value); } } - Object mapKey = tryConvert(field, index, keyConverter, keyValue[0], classes[0]); - Object mapValue = tryConvert(field, index, valueConverter, keyValue[1], classes[1]); + final Object mapKey = tryConvert(field, index, keyConverter, keyValue[0], classes[0]); + final Object mapValue = tryConvert(field, index, valueConverter, keyValue[1], classes[1]); result.put(mapKey, mapValue); if (tracer.isInfo()) {tracer.info("Putting [%s : %s] in %s<%s, %s> field '%s.%s' for %s%n", String.valueOf(mapKey), String.valueOf(mapValue), result.getClass().getSimpleName(), classes[0].getSimpleName(), classes[1].getSimpleName(), field.getDeclaringClass().getSimpleName(), field.getName(), argDescription);} } } - private void checkMaxArityExceeded(Range arity, int remainder, Field field, String[] values) { + private void checkMaxArityExceeded(final Range arity, final int remainder, final Field field, final String[] values) { if (values.length <= remainder) { return; } - String desc = arity.max == remainder ? "" + remainder : arity + ", remainder=" + remainder; + final String desc = arity.max == remainder ? "" + remainder : arity + ", remainder=" + remainder; throw new MaxValuesforFieldExceededException(CommandLine.this, optionDescription("", field, -1) + " max number of values (" + arity.max + ") exceeded: remainder is " + remainder + " but " + values.length + " values were specified: " + Arrays.toString(values)); } - private int applyValuesToArrayField(Field field, - Class<?> annotation, - Range arity, - Stack<String> args, - Class<?> cls, - String argDescription) throws Exception { - Object existing = field.get(command); - int length = existing == null ? 0 : Array.getLength(existing); - Class<?> type = getTypeAttribute(field)[0]; - List<Object> converted = consumeArguments(field, annotation, arity, args, type, length, argDescription); - List<Object> newValues = new ArrayList<Object>(); + private int applyValuesToArrayField(final Field field, + final Class<?> annotation, + final Range arity, + final Stack<String> args, + final Class<?> cls, + final String argDescription) throws Exception { + final Object existing = field.get(command); + final int length = existing == null ? 0 : Array.getLength(existing); + final Class<?> type = getTypeAttribute(field)[0]; + final List<Object> converted = consumeArguments(field, annotation, arity, args, type, length, argDescription); + final List<Object> newValues = new ArrayList<Object>(); for (int i = 0; i < length; i++) { newValues.add(Array.get(existing, i)); } - for (Object obj : converted) { + for (final Object obj : converted) { if (obj instanceof Collection<?>) { newValues.addAll((Collection<?>) obj); } else { newValues.add(obj); } } - Object array = Array.newInstance(type, newValues.size()); + final Object array = Array.newInstance(type, newValues.size()); field.set(command, array); for (int i = 0; i < newValues.size(); i++) { Array.set(array, i, newValues.get(i)); @@ -2391,21 +2392,21 @@ public class CommandLine { } @SuppressWarnings("unchecked") - private int applyValuesToCollectionField(Field field, - Class<?> annotation, - Range arity, - Stack<String> args, - Class<?> cls, - String argDescription) throws Exception { + private int applyValuesToCollectionField(final Field field, + final Class<?> annotation, + final Range arity, + final Stack<String> args, + final Class<?> cls, + final String argDescription) throws Exception { Collection<Object> collection = (Collection<Object>) field.get(command); - Class<?> type = getTypeAttribute(field)[0]; - int length = collection == null ? 0 : collection.size(); - List<Object> converted = consumeArguments(field, annotation, arity, args, type, length, argDescription); + final Class<?> type = getTypeAttribute(field)[0]; + final int length = collection == null ? 0 : collection.size(); + final List<Object> converted = consumeArguments(field, annotation, arity, args, type, length, argDescription); if (collection == null) { collection = createCollection(cls); field.set(command, collection); } - for (Object element : converted) { + for (final Object element : converted) { if (element instanceof Collection<?>) { collection.addAll((Collection<?>) element); } else { @@ -2415,14 +2416,14 @@ public class CommandLine { return converted.size(); } - private List<Object> consumeArguments(Field field, - Class<?> annotation, - Range arity, - Stack<String> args, - Class<?> type, - int originalSize, - String argDescription) throws Exception { - List<Object> result = new ArrayList<Object>(); + private List<Object> consumeArguments(final Field field, + final Class<?> annotation, + final Range arity, + final Stack<String> args, + final Class<?> type, + final int originalSize, + final String argDescription) throws Exception { + final List<Object> result = new ArrayList<Object>(); // first do the arity.min mandatory parameters for (int i = 0; i < arity.min; i++) { @@ -2440,16 +2441,16 @@ public class CommandLine { return result; } - private int consumeOneArgument(Field field, - Range arity, - Stack<String> args, - Class<?> type, - List<Object> result, + private int consumeOneArgument(final Field field, + final Range arity, + final Stack<String> args, + final Class<?> type, + final List<Object> result, int index, - int originalSize, - String argDescription) throws Exception { - String[] values = split(trim(args.pop()), field); - ITypeConverter<?> converter = getTypeConverter(type, field); + final int originalSize, + final String argDescription) throws Exception { + final String[] values = split(trim(args.pop()), field); + final ITypeConverter<?> converter = getTypeConverter(type, field); for (int j = 0; j < values.length; j++) { result.add(tryConvert(field, index, converter, values[j], type)); @@ -2465,13 +2466,13 @@ public class CommandLine { return ++index; } - private String splitRegex(Field field) { + private String splitRegex(final Field field) { if (field.isAnnotationPresent(Option.class)) { return field.getAnnotation(Option.class).split(); } if (field.isAnnotationPresent(Parameters.class)) { return field.getAnnotation(Parameters.class).split(); } return ""; } - private String[] split(String value, Field field) { - String regex = splitRegex(field); + private String[] split(final String value, final Field field) { + final String regex = splitRegex(field); return regex.length() == 0 ? new String[] {value} : value.split(regex); } @@ -2481,7 +2482,7 @@ public class CommandLine { * @param arg the string to determine whether it is an option or not * @return true if it is an option, false otherwise */ - private boolean isOption(String arg) { + private boolean isOption(final String arg) { if ("--".equals(arg)) { return true; } @@ -2489,7 +2490,7 @@ public class CommandLine { if (optionName2Field.containsKey(arg)) { // -v or -f or --file (not attached to param or other option) return true; } - int separatorIndex = arg.indexOf(separator); + final int separatorIndex = arg.indexOf(separator); if (separatorIndex > 0) { // -f=FILE or --file==FILE (attached to param via separator) if (optionName2Field.containsKey(arg.substring(0, separatorIndex))) { return true; @@ -2497,33 +2498,33 @@ public class CommandLine { } return (arg.length() > 2 && arg.startsWith("-") && singleCharOption2Field.containsKey(arg.charAt(1))); } - private Object tryConvert(Field field, int index, ITypeConverter<?> converter, String value, Class<?> type) + private Object tryConvert(final Field field, final int index, final ITypeConverter<?> converter, final String value, final Class<?> type) throws Exception { try { return converter.convert(value); - } catch (TypeConversionException ex) { + } catch (final TypeConversionException ex) { throw new ParameterException(CommandLine.this, ex.getMessage() + optionDescription(" for ", field, index)); - } catch (Exception other) { - String desc = optionDescription(" for ", field, index) + ": " + other; + } catch (final Exception other) { + final String desc = optionDescription(" for ", field, index) + ": " + other; throw new ParameterException(CommandLine.this, "Could not convert '" + value + "' to " + type.getSimpleName() + desc, other); } } - private String optionDescription(String prefix, Field field, int index) { - Help.IParamLabelRenderer labelRenderer = Help.createMinimalParamLabelRenderer(); + private String optionDescription(final String prefix, final Field field, final int index) { + final Help.IParamLabelRenderer labelRenderer = Help.createMinimalParamLabelRenderer(); String desc = ""; if (field.isAnnotationPresent(Option.class)) { desc = prefix + "option '" + field.getAnnotation(Option.class).names()[0] + "'"; if (index >= 0) { - Range arity = Range.optionArity(field); + final Range arity = Range.optionArity(field); if (arity.max > 1) { desc += " at index " + index; } desc += " (" + labelRenderer.renderParameterLabel(field, Help.Ansi.OFF, Collections.<IStyle>emptyList()) + ")"; } } else if (field.isAnnotationPresent(Parameters.class)) { - Range indexRange = Range.parameterIndex(field); - Text label = labelRenderer.renderParameterLabel(field, Help.Ansi.OFF, Collections.<IStyle>emptyList()); + final Range indexRange = Range.parameterIndex(field); + final Text label = labelRenderer.renderParameterLabel(field, Help.Ansi.OFF, Collections.<IStyle>emptyList()); desc = prefix + "positional parameter at index " + indexRange + " (" + label + ")"; } return desc; @@ -2531,19 +2532,19 @@ public class CommandLine { private boolean isAnyHelpRequested() { return isHelpRequested || versionHelpRequested || usageHelpRequested; } - private void updateHelpRequested(Field field) { + private void updateHelpRequested(final Field field) { if (field.isAnnotationPresent(Option.class)) { isHelpRequested |= is(field, "help", field.getAnnotation(Option.class).help()); CommandLine.this.versionHelpRequested |= is(field, "versionHelp", field.getAnnotation(Option.class).versionHelp()); CommandLine.this.usageHelpRequested |= is(field, "usageHelp", field.getAnnotation(Option.class).usageHelp()); } } - private boolean is(Field f, String description, boolean value) { + private boolean is(final Field f, final String description, final boolean value) { if (value) { if (tracer.isInfo()) {tracer.info("Field '%s.%s' has '%s' annotation: not validating required fields%n", f.getDeclaringClass().getSimpleName(), f.getName(), description); }} return value; } @SuppressWarnings("unchecked") - private Collection<Object> createCollection(Class<?> collectionClass) throws Exception { + private Collection<Object> createCollection(final Class<?> collectionClass) throws Exception { if (collectionClass.isInterface()) { if (List.class.isAssignableFrom(collectionClass)) { return new ArrayList<Object>(); @@ -2559,14 +2560,14 @@ public class CommandLine { // custom Collection implementation class must have default constructor return (Collection<Object>) collectionClass.newInstance(); } - private Map<Object, Object> createMap(Class<?> mapClass) throws Exception { + private Map<Object, Object> createMap(final Class<?> mapClass) throws Exception { try { // if it is an implementation class, instantiate it return (Map<Object, Object>) mapClass.newInstance(); - } catch (Exception ignored) {} + } catch (final Exception ignored) {} return new LinkedHashMap<Object, Object>(); } - private ITypeConverter<?> getTypeConverter(final Class<?> type, Field field) { - ITypeConverter<?> result = converterRegistry.get(type); + private ITypeConverter<?> getTypeConverter(final Class<?> type, final Field field) { + final ITypeConverter<?> result = converterRegistry.get(type); if (result != null) { return result; } @@ -2574,7 +2575,7 @@ public class CommandLine { return new ITypeConverter<Object>() { @Override @SuppressWarnings("unchecked") - public Object convert(String value) throws Exception { + public Object convert(final String value) throws Exception { return Enum.valueOf((Class<Enum>) type, value); } }; @@ -2582,15 +2583,15 @@ public class CommandLine { throw new MissingTypeConverterException(CommandLine.this, "No TypeConverter registered for " + type.getName() + " of field " + field); } - private void assertNoMissingParameters(Field field, int arity, Stack<String> args) { + private void assertNoMissingParameters(final Field field, final int arity, final Stack<String> args) { if (arity > args.size()) { if (arity == 1) { if (field.isAnnotationPresent(Option.class)) { throw new MissingParameterException(CommandLine.this, "Missing required parameter for " + optionDescription("", field, 0)); } - Range indexRange = Range.parameterIndex(field); - Help.IParamLabelRenderer labelRenderer = Help.createMinimalParamLabelRenderer(); + final Range indexRange = Range.parameterIndex(field); + final Help.IParamLabelRenderer labelRenderer = Help.createMinimalParamLabelRenderer(); String sep = ""; String names = ""; int count = 0; @@ -2603,7 +2604,7 @@ public class CommandLine { } } String msg = "Missing required parameter"; - Range paramArity = Range.parameterArity(field); + final Range paramArity = Range.parameterArity(field); if (paramArity.isVariable) { msg += "s at positions " + indexRange + ": "; } else { @@ -2619,11 +2620,11 @@ public class CommandLine { " requires at least " + arity + " values, but only " + args.size() + " were specified: " + reverse(args)); } } - private String trim(String value) { + private String trim(final String value) { return unquote(value); } - private String unquote(String value) { + private String unquote(final String value) { return value == null ? null : (value.length() > 1 && value.startsWith("\"") && value.endsWith("\"")) @@ -2633,8 +2634,8 @@ public class CommandLine { } private static class PositionalParametersSorter implements Comparator<Field> { @Override - public int compare(Field o1, Field o2) { - int result = Range.parameterIndex(o1).compareTo(Range.parameterIndex(o2)); + public int compare(final Field o1, final Field o2) { + final int result = Range.parameterIndex(o1).compareTo(Range.parameterIndex(o2)); return (result == 0) ? Range.parameterArity(o1).compareTo(Range.parameterArity(o2)) : result; } } @@ -2647,25 +2648,25 @@ public class CommandLine { } static class StringConverter implements ITypeConverter<String> { @Override - public String convert(String value) { return value; } + public String convert(final String value) { return value; } } static class StringBuilderConverter implements ITypeConverter<StringBuilder> { @Override - public StringBuilder convert(String value) { return new StringBuilder(value); } + public StringBuilder convert(final String value) { return new StringBuilder(value); } } static class CharSequenceConverter implements ITypeConverter<CharSequence> { @Override - public String convert(String value) { return value; } + public String convert(final String value) { return value; } } /** Converts text to a {@code Byte} by delegating to {@link Byte#valueOf(String)}.*/ static class ByteConverter implements ITypeConverter<Byte> { @Override - public Byte convert(String value) { return Byte.valueOf(value); } + public Byte convert(final String value) { return Byte.valueOf(value); } } /** Converts {@code "true"} or {@code "false"} to a {@code Boolean}. Other values result in a ParameterException.*/ static class BooleanConverter implements ITypeConverter<Boolean> { @Override - public Boolean convert(String value) { + public Boolean convert(final String value) { if ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) { return Boolean.parseBoolean(value); } else { @@ -2675,7 +2676,7 @@ public class CommandLine { } static class CharacterConverter implements ITypeConverter<Character> { @Override - public Character convert(String value) { + public Character convert(final String value) { if (value.length() > 1) { throw new TypeConversionException("'" + value + "' is not a single character"); } @@ -2685,45 +2686,45 @@ public class CommandLine { /** Converts text to a {@code Short} by delegating to {@link Short#valueOf(String)}.*/ static class ShortConverter implements ITypeConverter<Short> { @Override - public Short convert(String value) { return Short.valueOf(value); } + public Short convert(final String value) { return Short.valueOf(value); } } /** Converts text to an {@code Integer} by delegating to {@link Integer#valueOf(String)}.*/ static class IntegerConverter implements ITypeConverter<Integer> { @Override - public Integer convert(String value) { return Integer.valueOf(value); } + public Integer convert(final String value) { return Integer.valueOf(value); } } /** Converts text to a {@code Long} by delegating to {@link Long#valueOf(String)}.*/ static class LongConverter implements ITypeConverter<Long> { @Override - public Long convert(String value) { return Long.valueOf(value); } + public Long convert(final String value) { return Long.valueOf(value); } } static class FloatConverter implements ITypeConverter<Float> { @Override - public Float convert(String value) { return Float.valueOf(value); } + public Float convert(final String value) { return Float.valueOf(value); } } static class DoubleConverter implements ITypeConverter<Double> { @Override - public Double convert(String value) { return Double.valueOf(value); } + public Double convert(final String value) { return Double.valueOf(value); } } static class FileConverter implements ITypeConverter<File> { @Override - public File convert(String value) { return new File(value); } + public File convert(final String value) { return new File(value); } } static class URLConverter implements ITypeConverter<URL> { @Override - public URL convert(String value) throws MalformedURLException { return new URL(value); } + public URL convert(final String value) throws MalformedURLException { return new URL(value); } } static class URIConverter implements ITypeConverter<URI> { @Override - public URI convert(String value) throws URISyntaxException { return new URI(value); } + public URI convert(final String value) throws URISyntaxException { return new URI(value); } } /** Converts text in {@code yyyy-mm-dd} format to a {@code java.util.Date}. ParameterException on failure. */ static class ISO8601DateConverter implements ITypeConverter<Date> { @Override - public Date convert(String value) { + public Date convert(final String value) { try { return new SimpleDateFormat("yyyy-MM-dd").parse(value); - } catch (ParseException e) { + } catch (final ParseException e) { throw new TypeConversionException("'" + value + "' is not a yyyy-MM-dd date"); } } @@ -2732,7 +2733,7 @@ public class CommandLine { * {@code HH:mm:ss.SSS}, {@code HH:mm:ss,SSS}. Other formats result in a ParameterException. */ static class ISO8601TimeConverter implements ITypeConverter<Time> { @Override - public Time convert(String value) { + public Time convert(final String value) { try { if (value.length() <= 5) { return new Time(new SimpleDateFormat("HH:mm").parse(value).getTime()); @@ -2741,11 +2742,11 @@ public class CommandLine { } else if (value.length() <= 12) { try { return new Time(new SimpleDateFormat("HH:mm:ss.SSS").parse(value).getTime()); - } catch (ParseException e2) { + } catch (final ParseException e2) { return new Time(new SimpleDateFormat("HH:mm:ss,SSS").parse(value).getTime()); } } - } catch (ParseException ignored) { + } catch (final ParseException ignored) { // ignored because we throw a ParameterException below } throw new TypeConversionException("'" + value + "' is not a HH:mm[:ss[.SSS]] time"); @@ -2753,28 +2754,28 @@ public class CommandLine { } static class BigDecimalConverter implements ITypeConverter<BigDecimal> { @Override - public BigDecimal convert(String value) { return new BigDecimal(value); } + public BigDecimal convert(final String value) { return new BigDecimal(value); } } static class BigIntegerConverter implements ITypeConverter<BigIntege
<TRUNCATED>