Thread: [Japi-cvs] SF.net SVN: japi: [168] libs/argparser/trunk/src
Status: Beta
Brought to you by:
christianhujer
From: <chr...@us...> - 2006-09-24 22:23:33
|
Revision: 168 http://svn.sourceforge.net/japi/?rev=168&view=rev Author: christianhujer Date: 2006-09-24 15:23:20 -0700 (Sun, 24 Sep 2006) Log Message: ----------- Adding first test case. Added Paths: ----------- libs/argparser/trunk/src/test/ libs/argparser/trunk/src/test/net/ libs/argparser/trunk/src/test/net/sf/ libs/argparser/trunk/src/test/net/sf/japi/ libs/argparser/trunk/src/test/net/sf/japi/io/ libs/argparser/trunk/src/test/net/sf/japi/io/args/ libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTestCase.java Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTestCase.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTestCase.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTestCase.java 2006-09-24 22:23:20 UTC (rev 168) @@ -0,0 +1,22 @@ +package test.net.sf.japi.io.args; + +import static org.junit.Assert.assertEquals; +import net.sf.japi.io.args.StringJoiner; +import org.junit.Test; + +/** + * TestCase for {@link StringJoiner}. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class StringJoinerTestCase { + + /** + * Tests whether {@link StringJoiner#join(CharSequence, CharSequence...)} works. + */ + @Test public void testJoinCSCS() { + final String expected = "foo, bar, buzz"; + final String actual = StringJoiner.join(", ", "foo", "bar", "buzz"); + assertEquals(expected, actual); + } + +} // class StringJoinerTestCase Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTestCase.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2006-09-25 09:36:36
|
Revision: 170 http://svn.sourceforge.net/japi/?rev=170&view=rev Author: christianhujer Date: 2006-09-25 02:36:21 -0700 (Mon, 25 Sep 2006) Log Message: ----------- Added test cases. Added handling of = in long options. Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java libs/argparser/trunk/src/net/sf/japi/io/args/Option.java Added Paths: ----------- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2006-09-24 22:37:21 UTC (rev 169) +++ libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2006-09-25 09:36:21 UTC (rev 170) @@ -45,7 +45,7 @@ private final Set<Method> requiredMethods = new HashSet<Method>(); /** The iterator for the arguments. */ - private final Iterator<String> argIterator; + private final ListIterator<String> argIterator; /** The currently used option. */ private String currentOption; @@ -63,7 +63,7 @@ commandClass = command.getClass(); initMethods(); final List<String> argList = new ArrayList<String>(Arrays.asList(args)); - argIterator = argList.iterator(); + argIterator = argList.listIterator(); try { parse(); } catch (final NoSuchElementException e) { @@ -84,7 +84,7 @@ for (final Method requiredMethod : requiredMethods) { final Option option = requiredMethod.getAnnotation(Option.class); assert option != null; - missingOptions.add(option.value()[0]); + missingOptions.add(option.name()[0]); } throw new RequiredOptionsMissingException(missingOptions.toArray(new String[missingOptions.size()])); } @@ -99,8 +99,7 @@ for (final Method method : commandClass.getMethods()) { final Option option = method.getAnnotation(Option.class); if (option != null) { - for (final String optionString : option.value()) { - final String optionName = optionString.length() > 1 ? '-' + optionString : optionString; + for (final String optionName : option.name()) { if (argumentMethods.containsKey(optionName)) { throw new IllegalArgumentException(commandClass.getName() + " declared option " + optionName + " twice."); } @@ -129,12 +128,20 @@ break; } if (arg.charAt(1) == '-') { - currentOption = arg.substring(1); + currentOption = arg.substring(2); + final int indexOfEq = currentOption.indexOf('='); + if (indexOfEq != -1) { + argIterator.add(currentOption.substring(indexOfEq + 1)); + argIterator.previous(); + currentOption = currentOption.substring(0, indexOfEq); + } invokeMethod(); } else { for (final String co : arg.substring(1).split("")) { - currentOption = co; - invokeMethod(); + if (co.length() == 1) { + currentOption = co; + invokeMethod(); + } } } } @@ -156,7 +163,16 @@ } requiredMethods.remove(method); try { - method.invoke(command); + final Class<?>[] parameterTypes = method.getParameterTypes(); + final int parameterCount = parameterTypes.length; + if (parameterCount == 1) { + final String arg = argIterator.next(); + method.invoke(command, arg); + argIterator.remove(); + } else { + assert parameterCount == 0; + method.invoke(command); + } } catch (final IllegalAccessException e) { System.err.println(e); } catch (final InvocationTargetException e) { Modified: libs/argparser/trunk/src/net/sf/japi/io/args/Option.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/Option.java 2006-09-24 22:37:21 UTC (rev 169) +++ libs/argparser/trunk/src/net/sf/japi/io/args/Option.java 2006-09-25 09:36:21 UTC (rev 170) @@ -48,6 +48,6 @@ * @note the supplied string values MUST consist of ASCII-letters only (match regex <code>[a-zA-Z]+</code>). * @return option names */ - String[] value(); + String[] name(); } // @interface Option Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-09-25 09:36:21 UTC (rev 170) @@ -0,0 +1,75 @@ +package test.net.sf.japi.io.args; + +import net.sf.japi.io.args.Command; +import net.sf.japi.io.args.ArgParser; +import net.sf.japi.io.args.Option; +import net.sf.japi.io.args.OptionType; +import java.util.List; +import org.junit.Test; +import org.junit.Assert; + +/** + * Test for {@link ArgParser}. + */ +public class ArgParserTest { + + public static class MockCommand1 implements Command { + + /** The input option value. */ + private String input; + + /** The command line arguments received from the parser. */ + private List<String> args; + + /** {@inheritDoc} */ + @SuppressWarnings({"InstanceMethodNamingConvention"}) + public void run(final List<String> args) { + this.args = args; + } + + /** + * Get the command line arguments. + * @return Command line arguments. + */ + public List<String> getArgs() { + return args; + } + + /** + * Set the value of the input option. + * @return Value of the input option. + */ + @Option(type = OptionType.REQUIRED, name = {"i", "input"}) + public void setInput(final String input) { + this.input = input; + } + + /** + * Get the value of the input option. + * @return Value of the input option. + */ + public String getInput() { + return input; + } + + } // class MockCommand1 + + @Test public void testCommand1A() { + final MockCommand1 command = new MockCommand1(); + ArgParser.parseAndRun(command, "-i", "fooInput"); + Assert.assertEquals("Option value must be stored.", "fooInput", command.getInput()); + } + + @Test public void testCommand1B() { + final MockCommand1 command = new MockCommand1(); + ArgParser.parseAndRun(command, "--input", "fooInput"); + Assert.assertEquals("Option value must be stored.", "fooInput", command.getInput()); + } + + @Test public void testCommand1C() { + final MockCommand1 command = new MockCommand1(); + ArgParser.parseAndRun(command, "--input=fooInput"); + Assert.assertEquals("Option value must be stored.", "fooInput", command.getInput()); + } + +} // class ArgParserTest Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2006-09-25 10:04:23
|
Revision: 171 http://svn.sourceforge.net/japi/?rev=171&view=rev Author: christianhujer Date: 2006-09-25 03:04:00 -0700 (Mon, 25 Sep 2006) Log Message: ----------- Added proper handling of unknown options and missing option arguments. Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java libs/argparser/trunk/src/net/sf/japi/io/args/RequiredOptionsMissingException.java libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java Added Paths: ----------- libs/argparser/trunk/src/net/sf/japi/io/args/MissingArgumentException.java libs/argparser/trunk/src/net/sf/japi/io/args/UnknownOptionException.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2006-09-25 09:36:21 UTC (rev 170) +++ libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2006-09-25 10:04:00 UTC (rev 171) @@ -57,19 +57,15 @@ * @param args Arguments to parse * @throws RequiredOptionsMissingException in case an option is missing * @throws TerminalException in case argument parsing was stopped + * @throws MissingArgumentException in the required argument for an option was missing */ - private ArgParser(final Command command, final String... args) throws TerminalException, RequiredOptionsMissingException { + private ArgParser(final Command command, final String... args) throws TerminalException, RequiredOptionsMissingException, UnknownOptionException, MissingArgumentException { this.command = command; commandClass = command.getClass(); initMethods(); final List<String> argList = new ArrayList<String>(Arrays.asList(args)); argIterator = argList.listIterator(); - try { - parse(); - } catch (final NoSuchElementException e) { - System.err.println("Missing argument for option " + currentOption); - return; - } + parse(); checkRequiredMethods(); command.run(argList); } @@ -117,7 +113,7 @@ * Parses arguments into an arguments container and invokes the Command's {@link Command#run(List<String>)} method. * @throws TerminalException in case argument parsing was stopped */ - private void parse() throws TerminalException { + private void parse() throws TerminalException, UnknownOptionException, MissingArgumentException { try { for (; argIterator.hasNext(); ) { final String arg = argIterator.next(); @@ -148,7 +144,7 @@ // empty arguments are intentionally not removed. } } catch (final NoSuchElementException e) { - System.err.println("Missing argument for option " + currentOption); + throw new MissingArgumentException(currentOption); } } @@ -156,10 +152,10 @@ * Invoke the argument method for the current option. * @throws TerminalException in case the invoked exception was terminal */ - private void invokeMethod() throws TerminalException { + private void invokeMethod() throws TerminalException, UnknownOptionException { final Method method = argumentMethods.get(currentOption); if (method == null) { - throw new RuntimeException("Unknown argument Exception"); + throw new UnknownOptionException(currentOption); } requiredMethods.remove(method); try { @@ -192,14 +188,31 @@ * @param command Command to run * @param args Arguments to parse */ - public static void parseAndRun(final Command command, final String... args) { + public static void simpleParseAndRun(final Command command, final String... args) { try { - new ArgParser(command, args); + parseAndRun(command, args); } catch (final TerminalException e) { /* ignore, nothing serious has happend. */ } catch (final RequiredOptionsMissingException e) { System.err.println(e); + } catch (final UnknownOptionException e) { + System.err.println(e); + } catch (final MissingArgumentException e) { + System.err.println(e); } } + /** + * Parses arguments of a command and runs that command. + * @param command Command to run + * @param args Arguments to parse + * @throws RequiredOptionsMissingException in case one or more required options were missing. + * @throws TerminalException in case a terminal option was encountered. + * @throws UnknownOptionException in case an option given was not known. + * @throws MissingArgumentException in case an option was missing its argument + */ + public static void parseAndRun(final Command command, final String... args) throws RequiredOptionsMissingException, TerminalException, UnknownOptionException, MissingArgumentException { + new ArgParser(command, args); + } + } // class ArgParser Added: libs/argparser/trunk/src/net/sf/japi/io/args/MissingArgumentException.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/MissingArgumentException.java (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/MissingArgumentException.java 2006-09-25 10:04:00 UTC (rev 171) @@ -0,0 +1,31 @@ +package net.sf.japi.io.args; + +import org.jetbrains.annotations.NotNull; + +/** + * This exception is thrown in case a required argument for an option is missing. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class MissingArgumentException extends Exception { + + /** The option that was missing its argument. */ + @NotNull private final String option; + + /** + * Create a RequiredOptionsMissingException. + * @param option that was missing its argument + */ + public MissingArgumentException(@NotNull final String option) { + super("Argument missing for option " + option); + this.option = option; + } + + /** + * Get the option that is missing its argument. + * @return option that is missing its argument. + */ + public String getOption() { + return option; + } + +} // class MissingArgumentException Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/MissingArgumentException.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/net/sf/japi/io/args/RequiredOptionsMissingException.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/RequiredOptionsMissingException.java 2006-09-25 09:36:21 UTC (rev 170) +++ libs/argparser/trunk/src/net/sf/japi/io/args/RequiredOptionsMissingException.java 2006-09-25 10:04:00 UTC (rev 171) @@ -36,7 +36,7 @@ * @param missingOptions options that were missing. * @throws IllegalArgumentException in case <var>missingOptions</var> was null or of zero length */ - public RequiredOptionsMissingException(@NotNull final String[] missingOptions) { + public RequiredOptionsMissingException(@NotNull final String... missingOptions) { super(createMessage(missingOptions)); this.missingOptions = missingOptions.clone(); } @@ -47,7 +47,7 @@ * @return message string * @throws IllegalArgumentException in case <var>missingOptions</var> was null or of zero length */ - private static String createMessage(final String[] missingOptions) { + private static String createMessage(final String... missingOptions) { if (missingOptions == null || missingOptions.length < 1) { throw new IllegalArgumentException("RequiredOptionsMissingException created but no missing options given."); } Added: libs/argparser/trunk/src/net/sf/japi/io/args/UnknownOptionException.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/UnknownOptionException.java (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/UnknownOptionException.java 2006-09-25 10:04:00 UTC (rev 171) @@ -0,0 +1,66 @@ +/* + * JAPI - (Yet another (hopefully) useful) Java API + * + * Copyright (C) 2006 Christian Hujer + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + */ +package net.sf.japi.io.args; + +import org.jetbrains.annotations.NotNull; + +/** + * This exception is thrown in case one or more unknown options were encountered. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class UnknownOptionException extends Exception { + + /** The list of options that were unknown. */ + @NotNull + private final String[] unknownOptions; + + /** + * Create a RequiredOptionsMissingException. + * @param unknownOptions options that were missing. + * @throws IllegalArgumentException in case <var>unknownOptions</var> was null or of zero length + */ + public UnknownOptionException(@NotNull final String... unknownOptions) { + super(createMessage(unknownOptions)); + this.unknownOptions = unknownOptions.clone(); + } + + /** + * Creates the message. + * @param unknownOptions options that were missing + * @return message string + * @throws IllegalArgumentException in case <var>unknownOptions</var> was null or of zero length + */ + private static String createMessage(final String... unknownOptions) { + if (unknownOptions == null || unknownOptions.length < 1) { + throw new IllegalArgumentException("UnknownOptionException created but no unknown options given."); + } + return StringJoiner.join(new StringBuilder("unknown options: "), ", ", unknownOptions).toString(); + } + + /** + * Get the options that were missing. + * @return options that were missing + */ + public String[] getUnknownOptions() { + return unknownOptions.clone(); + } + +} // class UnknownOptionException Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/UnknownOptionException.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-09-25 09:36:21 UTC (rev 170) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-09-25 10:04:00 UTC (rev 171) @@ -1,9 +1,6 @@ package test.net.sf.japi.io.args; -import net.sf.japi.io.args.Command; -import net.sf.japi.io.args.ArgParser; -import net.sf.japi.io.args.Option; -import net.sf.japi.io.args.OptionType; +import net.sf.japi.io.args.*; import java.util.List; import org.junit.Test; import org.junit.Assert; @@ -54,22 +51,42 @@ } // class MockCommand1 - @Test public void testCommand1A() { + @Test + public void testCommand1A() { final MockCommand1 command = new MockCommand1(); - ArgParser.parseAndRun(command, "-i", "fooInput"); + ArgParser.simpleParseAndRun(command, "-i", "fooInput"); Assert.assertEquals("Option value must be stored.", "fooInput", command.getInput()); } - @Test public void testCommand1B() { + @Test + public void testCommand1B() { final MockCommand1 command = new MockCommand1(); - ArgParser.parseAndRun(command, "--input", "fooInput"); + ArgParser.simpleParseAndRun(command, "--input", "fooInput"); Assert.assertEquals("Option value must be stored.", "fooInput", command.getInput()); } - @Test public void testCommand1C() { + @Test + public void testCommand1C() { final MockCommand1 command = new MockCommand1(); - ArgParser.parseAndRun(command, "--input=fooInput"); + ArgParser.simpleParseAndRun(command, "--input=fooInput"); Assert.assertEquals("Option value must be stored.", "fooInput", command.getInput()); } + @Test(expected=RequiredOptionsMissingException.class) + public void testCommand1D() throws RequiredOptionsMissingException, TerminalException, UnknownOptionException, MissingArgumentException { + final MockCommand1 command = new MockCommand1(); + ArgParser.parseAndRun(command); + } + + @Test(expected=UnknownOptionException.class) + public void testCommand1E() throws RequiredOptionsMissingException, TerminalException, UnknownOptionException, MissingArgumentException { + final MockCommand1 command = new MockCommand1(); + ArgParser.parseAndRun(command, "--output"); + } + + @Test(expected=MissingArgumentException.class) + public void testCommand1F() throws RequiredOptionsMissingException, TerminalException, UnknownOptionException, MissingArgumentException { + final MockCommand1 command = new MockCommand1(); + ArgParser.parseAndRun(command, "--input"); + } } // class ArgParserTest This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2006-10-03 23:32:18
|
Revision: 179 http://svn.sourceforge.net/japi/?rev=179&view=rev Author: christianhujer Date: 2006-10-03 16:31:53 -0700 (Tue, 03 Oct 2006) Log Message: ----------- Adding new feature: BasicCommand which handles --help and --version, i18n/l10n for --help output. Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java libs/argparser/trunk/src/net/sf/japi/io/args/Command.java libs/argparser/trunk/src/net/sf/japi/io/args/Option.java libs/argparser/trunk/src/net/sf/japi/io/args/OptionType.java libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java Added Paths: ----------- libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java libs/argparser/trunk/src/net/sf/japi/io/args/messages.properties libs/argparser/trunk/src/net/sf/japi/io/args/messages_de.properties Modified: libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2006-09-25 22:42:46 UTC (rev 178) +++ libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2006-10-03 23:31:53 UTC (rev 179) @@ -28,10 +28,11 @@ /** * Parser for command line arguments. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> - * TODO: automatic argument conversion for option method invokation. + * TODO: automatic argument conversion for option method invocation. * TODO: Handling of --help * TODO: Handling of --version - * TODO: Handling of - for STDIN as input argument filestrea + * TODO: Handling of - for STDIN as input argument filestream + * TODO: Support for I18N/L10N */ public class ArgParser { @@ -83,7 +84,7 @@ for (final Method requiredMethod : requiredMethods) { final Option option = requiredMethod.getAnnotation(Option.class); assert option != null; - missingOptions.add(option.name()[0]); + missingOptions.add(option.names()[0]); } throw new RequiredOptionsMissingException(missingOptions.toArray(new String[missingOptions.size()])); } @@ -95,24 +96,48 @@ * All required methods are additionally stored in {@link #requiredMethods}. */ private void initMethods() { - for (final Method method : commandClass.getMethods()) { + for (final Method method : getOptionMethods(commandClass)) { final Option option = method.getAnnotation(Option.class); - if (option != null) { - for (final String optionName : option.name()) { - if (argumentMethods.containsKey(optionName)) { - throw new IllegalArgumentException(commandClass.getName() + " declared option " + optionName + " twice."); - } - argumentMethods.put(optionName, method); + assert option != null; + for (final String optionName : option.names()) { + if (argumentMethods.containsKey(optionName)) { + throw new IllegalArgumentException(commandClass.getName() + " declared option " + optionName + " twice."); } - final OptionType type = option.type(); - if (type == OptionType.REQUIRED) { - requiredMethods.add(method); - } + argumentMethods.put(optionName, method); } + final OptionType type = option.type(); + if (type == OptionType.REQUIRED) { + requiredMethods.add(method); + } } } /** + * Get all option methods from a command. + * @param command Command to get option methods for + * @return option methods for the command. + */ + public static Set<Method> getOptionMethods(final Command command) { + return getOptionMethods(command.getClass()); + } + + /** + * Get all option methods from a command class. + * @param commandClass Class of the Command to get option methods for + * @return Option methods for the command class. + */ + public static Set<Method> getOptionMethods(final Class<? extends Command> commandClass) { + final Method[] methods = commandClass.getMethods(); + final Set<Method> optionMethods = new HashSet<Method>(); + for (final Method method : methods) { + if (method.isAnnotationPresent(Option.class)) { + optionMethods.add(method); + } + } + return optionMethods; + } + + /** * Parses arguments into an arguments container and invokes the Command's {@link Command#run(List<String>)} method. * @throws TerminalException in case argument parsing was stopped */ Added: libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java 2006-10-03 23:31:53 UTC (rev 179) @@ -0,0 +1,100 @@ +package net.sf.japi.io.args; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Formatter; +import java.util.HashSet; +import java.util.List; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.Set; + +/** + * BasicCommand is a base class for commands that provides the options --help and --version. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public abstract class BasicCommand implements Command { + + /** The ResourceBundle for locale-specific output. */ + private final ResourceBundle resourceBundle = ResourceBundle.getBundle("net.sf.japi.io.args.messages"); + + /** The maximum width of the option type field. */ + private final int maxOptionTypeWidth; + + /** Create a BasicCommand. */ + protected BasicCommand() { + int tmpMaxOptionTypeWidth = 0; + for (final OptionType optionType : OptionType.values()) { + tmpMaxOptionTypeWidth = Math.max(tmpMaxOptionTypeWidth, optionType.toString().length()); + } + maxOptionTypeWidth = tmpMaxOptionTypeWidth; + } + + /** Version Option. */ + @Option(type = OptionType.TERMINAL, names = {"v", "version"}) + public void version() { + // TODO + } + + /** Help Option. */ + @Option(type = OptionType.TERMINAL, names = {"h", "help"}) + public void help() { + final Set<Method> optionMethods = ArgParser.getOptionMethods(this); + final Set<Class<?>> parameterTypes = new HashSet<Class<?>>(); + int maxLong = 0; + int maxShort = 0; + for (final Method optionMethod : optionMethods) { + final Option option = optionMethod.getAnnotation(Option.class); + final String[] names = option.names(); + int currentLong = 0; + int currentShort = 0; + for (final String name : names) { + if (name.length() > 1) { + currentLong += name.length() + ", --".length(); + } else { + currentShort += name.length() + ", -".length(); + } + } + maxLong = Math.max(maxLong, currentLong - ", ".length()); + maxShort = Math.max(maxShort, currentShort - ", ".length()); + for (final Class<?> parameterType : optionMethod.getParameterTypes()) { + parameterTypes.add(parameterType); + } + } + final String formatString = "%-" + maxShort + "s%s%-" + maxLong + "s: (%-" + maxOptionTypeWidth + "s) %s%n"; + final Formatter format = new Formatter(System.err); + for (final Method optionMethod : optionMethods) { + final Option option = optionMethod.getAnnotation(Option.class); + final OptionType optionType = option.type(); + final String[] names = option.names(); + final List<String> shortNames = new ArrayList<String>(); + final List<String> longNames = new ArrayList<String>(); + for (final String name : names) { + if (name.length() > 1) { + longNames.add("--" + name); + } else { + shortNames.add("-" + name); + } + } + final String delim = shortNames.size() > 0 && longNames.size() > 0 ? ", " : " "; + String description; + try { + final String optionKey = option.key().equals("") ? optionMethod.getName() : option.key(); + description = getBundle().getString(optionKey); + } catch (final MissingResourceException ignore) { + description = ""; + } + format.format(formatString, StringJoiner.join(", ", shortNames), delim, StringJoiner.join(", ", longNames), optionType.toString(), description); + } + format.flush(); + } + + /** + * Get the ResourceBundle for the default locale. + * If you override this method be sure to declare the bundle returned by the overridden method as parent of your bundle. + */ + public ResourceBundle getBundle() { + return resourceBundle; + } + +} // class BasicCommand Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/net/sf/japi/io/args/Command.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/Command.java 2006-09-25 22:42:46 UTC (rev 178) +++ libs/argparser/trunk/src/net/sf/japi/io/args/Command.java 2006-10-03 23:31:53 UTC (rev 179) @@ -22,6 +22,7 @@ package net.sf.japi.io.args; import java.util.List; +import org.jetbrains.annotations.NotNull; /** * Shell commands can implement this interface and make use of ArgParser. @@ -30,11 +31,11 @@ public interface Command { /** - * Run the command. + * Run this command. * This method is invoked by {@link ArgParser} once it is finnished with parsing the arguments. * @param args the argument strings that were not parsed away by {@link ArgParser}. */ @SuppressWarnings({"InstanceMethodNamingConvention"}) - void run(List<String> args); + void run(@NotNull List<String> args); } // interface Command Modified: libs/argparser/trunk/src/net/sf/japi/io/args/Option.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/Option.java 2006-09-25 22:42:46 UTC (rev 178) +++ libs/argparser/trunk/src/net/sf/japi/io/args/Option.java 2006-10-03 23:31:53 UTC (rev 179) @@ -48,6 +48,13 @@ * @note the supplied string values MUST consist of ASCII-letters only (match regex <code>[a-zA-Z]+</code>). * @return option names */ - String[] name(); + String[] names(); + /** + * The option key, used for i18n/l10n. + * Default is <code>""</code> (empty String) which is interpreted as the associated method's name being the key. + * @return option key + */ + String key() default ""; + } // @interface Option Modified: libs/argparser/trunk/src/net/sf/japi/io/args/OptionType.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/OptionType.java 2006-09-25 22:42:46 UTC (rev 178) +++ libs/argparser/trunk/src/net/sf/japi/io/args/OptionType.java 2006-10-03 23:31:53 UTC (rev 179) @@ -20,6 +20,10 @@ */ package net.sf.japi.io.args; +import java.util.ResourceBundle; +import java.util.MissingResourceException; +import java.util.Locale; + /** * The type of an option. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> @@ -33,6 +37,43 @@ OPTIONAL, /** Terminal options terminate argument parsing, no matter what happens. */ - TERMINAL + TERMINAL; + /** + * Returns the localized name of this OptionType in the default locale if available, otherwise the lowercase enum constant name. + * @return The localized name of this OptionType. + */ + public String getName() { + String name; + try { + name = ResourceBundle.getBundle("net.sf.japi.io.args.messages").getString(getClass().getName() + "." + name()); + } catch (final MissingResourceException e) { + name = name(); + } + return name; + } + + /** + * Returns the localized name of this OptionType in the specified locale if available, otherwise the lowercase enum constant name. + * @param locale Locale + * @return The localized name of this OptionType. + */ + public String getName(final Locale locale) { + String name; + try { + name = ResourceBundle.getBundle("net.sf.japi.io.args.messages", locale).getString(getClass().getName() + "." + name()); + } catch (final MissingResourceException e) { + name = name(); + } + return name; + } + + /** + * {@inheritDoc} + * Returns the same as {@link #getName()}. + */ + @Override public String toString() { + return getName(); + } + } // OptionType Added: libs/argparser/trunk/src/net/sf/japi/io/args/messages.properties =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/messages.properties (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/messages.properties 2006-10-03 23:31:53 UTC (rev 179) @@ -0,0 +1,5 @@ +net.sf.japi.io.args.OptionType.REQUIRED=required +net.sf.japi.io.args.OptionType.OPTIONAL=optional +net.sf.japi.io.args.OptionType.TERMINAL=terminal +help=Display this help and exit. +version=Display version information and exit. \ No newline at end of file Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/messages.properties ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/net/sf/japi/io/args/messages_de.properties =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/messages_de.properties (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/messages_de.properties 2006-10-03 23:31:53 UTC (rev 179) @@ -0,0 +1,5 @@ +net.sf.japi.io.args.OptionType.REQUIRED=erforderlich +net.sf.japi.io.args.OptionType.OPTIONAL=optional +net.sf.japi.io.args.OptionType.TERMINAL=abbrechend +help=Diese Hilfe anzeigen und beenden. +version=Versionsinformation anzeigen und beenden. \ No newline at end of file Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/messages_de.properties ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-09-25 22:42:46 UTC (rev 178) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-10-03 23:31:53 UTC (rev 179) @@ -1,7 +1,7 @@ package test.net.sf.japi.io.args; import net.sf.japi.io.args.ArgParser; -import net.sf.japi.io.args.Command; +import net.sf.japi.io.args.BasicCommand; import net.sf.japi.io.args.MissingArgumentException; import net.sf.japi.io.args.Option; import net.sf.japi.io.args.OptionType; @@ -22,7 +22,7 @@ * This MockCommand serves as a command for performing simple tests. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ - public static class MockCommand implements Command { + public static class MockCommand extends BasicCommand { /** The input option value. */ private String input; @@ -52,12 +52,21 @@ * Set the value of the input option. * @param input Value of the input option. */ - @Option(type = OptionType.REQUIRED, name = {"i", "input"}) + @Option(type = OptionType.REQUIRED, names = {"i", "input"}) public void setInput(final String input) { this.input = input; } /** + * Set the value of the foo option. + * @param foo Value of the foo option. + */ + @Option(names = {"f", "b", "foo", "bar", "buzz"}) + public void setFoo(final String foo) { + // ignored + } + + /** * Get the value of the input option. * @return Value of the input option. */ @@ -190,4 +199,17 @@ Assert.assertEquals("Argument list for invocation without arguments must be empty.", 0, command.getArgs().size()); } + /** + * Tests whether help works. + * @throws RequiredOptionsMissingException + * @throws TerminalException + * @throws UnknownOptionException + * @throws MissingArgumentException + */ + @Test(expected = TerminalException.class) + public void testHelp() throws RequiredOptionsMissingException, MissingArgumentException, TerminalException, UnknownOptionException { + final MockCommand command = new MockCommand(); + ArgParser.parseAndRun(command, "-h"); + } + } // class ArgParserTest This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2006-11-06 22:28:16
|
Revision: 194 http://svn.sourceforge.net/japi/?rev=194&view=rev Author: christianhujer Date: 2006-11-06 14:27:57 -0800 (Mon, 06 Nov 2006) Log Message: ----------- Added isExiting and changed run() signature of Command. Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java libs/argparser/trunk/src/net/sf/japi/io/args/Command.java libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2006-11-06 22:26:24 UTC (rev 193) +++ libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2006-11-06 22:27:57 UTC (rev 194) @@ -29,8 +29,7 @@ * Parser for command line arguments. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> * TODO: automatic argument conversion for option method invocation. - * TODO: Handling of --help - * TODO: Handling of --version + * TODO: better handling of boolean arguments * TODO: Handling of - for STDIN as input argument filestream * TODO: Support for I18N/L10N */ @@ -71,7 +70,16 @@ argIterator = argList.listIterator(); parse(); checkRequiredMethods(); - command.run(argList); + int returnCode = 0; + try { + returnCode = command.run(argList); + } catch (final Exception e) { + System.err.println(e); + returnCode = 1; + } + if (command.isExiting()) { + System.exit(returnCode); + } } /** Modified: libs/argparser/trunk/src/net/sf/japi/io/args/Command.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/Command.java 2006-11-06 22:26:24 UTC (rev 193) +++ libs/argparser/trunk/src/net/sf/japi/io/args/Command.java 2006-11-06 22:27:57 UTC (rev 194) @@ -34,8 +34,16 @@ * Run this command. * This method is invoked by {@link ArgParser} once it is finnished with parsing the arguments. * @param args the argument strings that were not parsed away by {@link ArgParser}. + * @return return code suitable for passing to {@link System#exit(int)} (whether {@link System#exit(int)} is really invoked depends on the configuration of the {@link ArgParser}.) + * @throws Exception in case of problems during command execution. */ @SuppressWarnings({"InstanceMethodNamingConvention"}) - void run(@NotNull List<String> args); + int run(@NotNull List<String> args) throws Exception; + /** + * Return whether after running this Command, {@link System#exit(int)} should be invoked. + * @return <code>true</code> if {@link ArgParser} should invoke {@link System#exit(int)} after this command, otherwise <code>false</code>. + */ + boolean isExiting(); + } // interface Command Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-11-06 22:26:24 UTC (rev 193) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-11-06 22:27:57 UTC (rev 194) @@ -35,9 +35,10 @@ /** {@inheritDoc} */ @SuppressWarnings({"InstanceMethodNamingConvention"}) - public void run(final List<String> args) { + public int run(final List<String> args) { runCalled = true; this.args = args; + return 0; } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2006-11-06 22:30:01
|
Revision: 195 http://svn.sourceforge.net/japi/?rev=195&view=rev Author: christianhujer Date: 2006-11-06 14:29:50 -0800 (Mon, 06 Nov 2006) Log Message: ----------- Added some examples. Added Paths: ----------- libs/argparser/trunk/src/doc/ libs/argparser/trunk/src/doc/examples/ libs/argparser/trunk/src/doc/examples/Cat.java libs/argparser/trunk/src/doc/examples/Head.java libs/argparser/trunk/src/doc/examples/Tail.java Added: libs/argparser/trunk/src/doc/examples/Cat.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Cat.java (rev 0) +++ libs/argparser/trunk/src/doc/examples/Cat.java 2006-11-06 22:29:50 UTC (rev 195) @@ -0,0 +1,67 @@ +package examples; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import net.sf.japi.io.args.ArgParser; +import net.sf.japi.io.args.BasicCommand; +import net.sf.japi.io.args.MissingArgumentException; +import net.sf.japi.io.args.RequiredOptionsMissingException; +import net.sf.japi.io.args.TerminalException; +import net.sf.japi.io.args.UnknownOptionException; +import org.jetbrains.annotations.NotNull; + +/** + * Java implementation of the UNIX command <q>cat</q> to demonstrate how to use the argparser library. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class Cat extends BasicCommand { + + /** {@inheritDoc} */ + @SuppressWarnings({"InstanceMethodNamingConvention"}) + public int run(@NotNull final List<String> args) throws Exception { + int returnCode = 0; + if (args.size() == 0) { + copy(System.in, System.out); + } else { + for (final String arg : args) { + try { + final InputStream in = new FileInputStream(arg); + try { + copy(in, System.out); + } finally { + in.close(); + } + } catch (final IOException e) { + returnCode = 1; + System.err.println(e); + } + } + } + return returnCode; + } + + /** + * Copies data from one input stream to another. + * @param in InputStream to read from. + * @param out InputStream to write to. + * @throws IOException in case of I/O problems. + */ + private void copy(final InputStream in, final OutputStream out) throws IOException { + final byte[] buf = new byte[4096]; + for (int bytesRead; (bytesRead = in.read(buf)) != -1;) { + out.write(buf, 0, bytesRead); + } + } + + /** + * Main method. + * @param args Command line arguments + */ + public static void main(final String... args) throws RequiredOptionsMissingException, MissingArgumentException, TerminalException, UnknownOptionException { + ArgParser.parseAndRun(new Head(), args); + } + +} // class Cat Property changes on: libs/argparser/trunk/src/doc/examples/Cat.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/doc/examples/Head.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Head.java (rev 0) +++ libs/argparser/trunk/src/doc/examples/Head.java 2006-11-06 22:29:50 UTC (rev 195) @@ -0,0 +1,135 @@ +package examples; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.List; +import net.sf.japi.io.args.ArgParser; +import net.sf.japi.io.args.BasicCommand; +import net.sf.japi.io.args.MissingArgumentException; +import net.sf.japi.io.args.Option; +import net.sf.japi.io.args.RequiredOptionsMissingException; +import net.sf.japi.io.args.TerminalException; +import net.sf.japi.io.args.UnknownOptionException; +import org.jetbrains.annotations.NotNull; + +/** + * Java implementation of the UNIX command <q>head</q> to demonstrate how to use the argparser library. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class Head extends BasicCommand { + + /** The number of items to print. */ + private int numItems = 10; + + /** + * The kind of items to print. + * <code>false</code>: print lines. + * <code>true</code>: print bytes. + */ + private boolean printBytes; + + /** + * Quiety / Verbosity. + * 0 = never print filenames. + * 1 = print filenames if more than one file. + * 2 = always print filenames. + */ + private int verbose = 1; + + /** + * Sets the number of lines to print. + * @param lines number of lines to print + */ + @Option(names = {"n", "lines"}) + public void setLines(final String lines) { + numItems = Integer.parseInt(lines); + printBytes = false; + } + + /** + * Sets the number of bytes to print. + * @param bytes number of bytes to print. + */ + @Option(names = {"c", "bytes"}) + public void setBytes(final String bytes) { + numItems = Integer.parseInt(bytes); + printBytes = true; + } + + /** + * Sets the command to be quiet. + */ + @Option(names = {"q", "quiet", "silent"}) + public void setQuiet() { + verbose = 0; + } + + /** + * Sets the command to be verbose. + */ + @Option(names = {"v", "verbose"}) + public void setVerbose() { + verbose = 2; + } + + /** + * {@inheritDoc} + */ + public int run(@NotNull final List<String> args) throws IOException { + int returnCode = 0; + if (args.size() == 0) { + if (verbose == 2) { + System.out.println("==> STDIN <=="); + } + copyItems(System.in); + } else { + for (final String arg : args) { + if (verbose == 2 || verbose == 1 && args.size() > 1) { + System.out.println("==> " + arg + " <=="); + } + try { + final InputStream in = new FileInputStream(arg); + try { + copyItems(in); + } finally { + in.close(); + } + } catch (final IOException e) { + System.err.println(e); + returnCode = 1; + } + } + } + return returnCode; + } + + /** + * Copies the configured number of items from the specified InputStream to System.out. + * @param in InputStream to run on + */ + private void copyItems(final InputStream in) throws IOException { + if (printBytes) { + for (int i = 0, b; i < numItems && (b = in.read()) != -1; i++) { + System.out.write(b); + } + } else { + BufferedReader lin = new BufferedReader(new InputStreamReader(in)); + String line; + for (int i = 0; i < numItems && (line = lin.readLine()) != null; i++) { + System.out.println(line); + } + } + } + + /** + * Main method. + * @param args Command line arguments + */ + public static void main(final String... args) throws RequiredOptionsMissingException, MissingArgumentException, TerminalException, UnknownOptionException { + ArgParser.parseAndRun(new Head(), args); + } + +} // class Head Property changes on: libs/argparser/trunk/src/doc/examples/Head.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/doc/examples/Tail.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Tail.java (rev 0) +++ libs/argparser/trunk/src/doc/examples/Tail.java 2006-11-06 22:29:50 UTC (rev 195) @@ -0,0 +1,143 @@ +package examples; + +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.List; +import net.sf.japi.io.args.ArgParser; +import net.sf.japi.io.args.BasicCommand; +import net.sf.japi.io.args.MissingArgumentException; +import net.sf.japi.io.args.Option; +import net.sf.japi.io.args.RequiredOptionsMissingException; +import net.sf.japi.io.args.TerminalException; +import net.sf.japi.io.args.UnknownOptionException; +import org.jetbrains.annotations.NotNull; + +/** + * Java implementation of the UNIX command <q>tail</q> to demonstrate how to use the argparser library. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class Tail extends BasicCommand { + + /** The number of items to print. */ + private int numItems = 10; + + /** + * The kind of items to print. + * <code>false</code>: print lines. + * <code>true</code>: print bytes. + */ + private boolean printBytes; + + /** + * Quiety / Verbosity. + * 0 = never print filenames. + * 1 = print filenames if more than one file. + * 2 = always print filenames. + */ + private int verbose = 1; + + /** + * Sets the number of lines to print. + * @param lines number of lines to print + */ + @Option(names = {"n", "lines"}) + public void setLines(final String lines) { + numItems = Integer.parseInt(lines); + printBytes = false; + } + + /** + * Sets the number of bytes to print. + * @param bytes number of bytes to print. + */ + @Option(names = {"c", "bytes"}) + public void setBytes(final String bytes) { + numItems = Integer.parseInt(bytes); + printBytes = true; + } + + /** + * Sets the command to be quiet. + */ + @Option(names = {"q", "quiet", "silent"}) + public void setQuiet() { + verbose = 0; + } + + /** + * Sets the command to be verbose. + */ + @Option(names = {"v", "verbose"}) + public void setVerbose() { + verbose = 2; + } + + /** {@inheritDoc} */ + @SuppressWarnings({"InstanceMethodNamingConvention"}) + public int run(@NotNull List<String> args) throws Exception { + int returnCode = 0; + for (final String arg : args) { + try { + final InputStream in = new BufferedInputStream(new FileInputStream(arg)); + try { + copy(in); + } finally { + in.close(); + } + } catch (final IOException e) { + returnCode = 1; + System.err.println(e); + } + } + return returnCode; + } + + private void copy(final InputStream in) throws IOException { + if (printBytes) { + copyBytes(in); + } else { + copyLines(in); + } + } + private void copyBytes(final InputStream in) throws IOException { + final InputStream lin = in instanceof BufferedInputStream ? in : new BufferedInputStream(in); + final byte[] buf = new byte[numItems]; + int bytesRead; + int loop = 0; + while ((bytesRead = lin.read(buf)) != -1) { + loop++; + } + if (loop >= 2) { + System.out.write(buf, bytesRead, buf.length - bytesRead); + } + System.out.write(buf, 0, bytesRead); + } + + private void copyLines(final InputStream in) throws IOException { + final String[] buf = new String[numItems]; + final BufferedReader lin = new BufferedReader(new InputStreamReader(in)); + int num = 0; + while ((buf[num++ % numItems] = lin.readLine()) != null); + if (num >= numItems) { + for (int i = num % numItems; i < numItems; i++) { + System.out.println(buf[i]); + } + } + for (int i = 0; i < num % numItems; i++) { + System.out.println(buf[i]); + } + } + + /** + * Main method. + * @param args Command line arguments + */ + public static void main(final String... args) throws RequiredOptionsMissingException, MissingArgumentException, TerminalException, UnknownOptionException { + ArgParser.parseAndRun(new Head(), args); + } + +} // class Tail Property changes on: libs/argparser/trunk/src/doc/examples/Tail.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2006-11-29 21:17:06
|
Revision: 238 http://svn.sourceforge.net/japi/?rev=238&view=rev Author: christianhujer Date: 2006-11-29 13:17:00 -0800 (Wed, 29 Nov 2006) Log Message: ----------- Improved converter feature. Integrated converter with ArgParser. Changed option names to value so it's default annotation argument. Modified Paths: -------------- libs/argparser/trunk/src/doc/examples/Head.java libs/argparser/trunk/src/doc/examples/Tail.java libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java libs/argparser/trunk/src/net/sf/japi/io/args/Command.java libs/argparser/trunk/src/net/sf/japi/io/args/Option.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/BooleanConverter.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/InputStreamConverter.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/StringConverter.java libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java Added Paths: ----------- libs/argparser/trunk/src/META-INF/ libs/argparser/trunk/src/META-INF/services/ libs/argparser/trunk/src/META-INF/services/net.sf.japi.io.args.converter.Converter libs/argparser/trunk/src/doc/examples/Uniq.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/IntegerConverter.java Added: libs/argparser/trunk/src/META-INF/services/net.sf.japi.io.args.converter.Converter =================================================================== --- libs/argparser/trunk/src/META-INF/services/net.sf.japi.io.args.converter.Converter (rev 0) +++ libs/argparser/trunk/src/META-INF/services/net.sf.japi.io.args.converter.Converter 2006-11-29 21:17:00 UTC (rev 238) @@ -0,0 +1,4 @@ +net.sf.japi.io.args.converter.BooleanConverter +net.sf.japi.io.args.converter.InputStreamConverter +net.sf.japi.io.args.converter.IntegerConverter +net.sf.japi.io.args.converter.StringConverter Property changes on: libs/argparser/trunk/src/META-INF/services/net.sf.japi.io.args.converter.Converter ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/doc/examples/Head.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Head.java 2006-11-26 23:47:21 UTC (rev 237) +++ libs/argparser/trunk/src/doc/examples/Head.java 2006-11-29 21:17:00 UTC (rev 238) @@ -43,9 +43,9 @@ * Sets the number of lines to print. * @param lines number of lines to print */ - @Option(names = {"n", "lines"}) - public void setLines(final String lines) { - numItems = Integer.parseInt(lines); + @Option({"n", "lines"}) + public void setLines(final Integer lines) { + numItems = lines; printBytes = false; } @@ -53,16 +53,16 @@ * Sets the number of bytes to print. * @param bytes number of bytes to print. */ - @Option(names = {"c", "bytes"}) - public void setBytes(final String bytes) { - numItems = Integer.parseInt(bytes); + @Option({"c", "bytes"}) + public void setBytes(final Integer bytes) { + numItems = bytes; printBytes = true; } /** * Sets the command to be quiet. */ - @Option(names = {"q", "quiet", "silent"}) + @Option({"q", "quiet", "silent"}) public void setQuiet() { verbose = 0; } @@ -70,7 +70,7 @@ /** * Sets the command to be verbose. */ - @Option(names = {"v", "verbose"}) + @Option({"v", "verbose"}) public void setVerbose() { verbose = 2; } Modified: libs/argparser/trunk/src/doc/examples/Tail.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Tail.java 2006-11-26 23:47:21 UTC (rev 237) +++ libs/argparser/trunk/src/doc/examples/Tail.java 2006-11-29 21:17:00 UTC (rev 238) @@ -40,9 +40,9 @@ * Sets the number of lines to print. * @param lines number of lines to print */ - @Option(names = {"n", "lines"}) - public void setLines(final String lines) { - numItems = Integer.parseInt(lines); + @Option({"n", "lines"}) + public void setLines(final Integer lines) { + numItems = lines; printBytes = false; } @@ -50,16 +50,16 @@ * Sets the number of bytes to print. * @param bytes number of bytes to print. */ - @Option(names = {"c", "bytes"}) - public void setBytes(final String bytes) { - numItems = Integer.parseInt(bytes); + @Option({"c", "bytes"}) + public void setBytes(final Integer bytes) { + numItems = bytes; printBytes = true; } /** * Sets the command to be quiet. */ - @Option(names = {"q", "quiet", "silent"}) + @Option({"q", "quiet", "silent"}) public void setQuiet() { verbose = 0; } @@ -67,7 +67,7 @@ /** * Sets the command to be verbose. */ - @Option(names = {"v", "verbose"}) + @Option({"v", "verbose"}) public void setVerbose() { verbose = 2; } Added: libs/argparser/trunk/src/doc/examples/Uniq.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Uniq.java (rev 0) +++ libs/argparser/trunk/src/doc/examples/Uniq.java 2006-11-29 21:17:00 UTC (rev 238) @@ -0,0 +1,110 @@ +package examples; + +import net.sf.japi.io.args.BasicCommand; +import net.sf.japi.io.args.Option; +import org.jetbrains.annotations.NotNull; +import java.util.List; +import java.io.InputStream; +import java.io.FileInputStream; +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.BufferedReader; + +/** + * Java implementation of the UNIX command <q>uniq</q> to demonstrate how to use the argparser library. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class Uniq extends BasicCommand { + + /** Whether to prefix lines with the count of their occurrence. */ + private boolean count; + + /** Whether to only print lines that occurred more than once. */ + private boolean repeated; + + /** Whether to ignore case. */ + private boolean ignoreCase; + + /** + * Sets that lines should prefixed with the count of their occurrence. + */ + @Option({"c", "count"}) + public void setCount() { + count = true; + } + + /** + * Sets that only lines that occurred more than once will be printed. + */ + @Option({"d", "repeated"}) + public void setRepeated() { + repeated = true; + } + + /** + * Sets that the case should be ignored. + */ + @Option({"i", "ignore-case"}) + public void setIgnoreCase() { + ignoreCase = true; + } + + /** {@inheritDoc} */ + @SuppressWarnings({"InstanceMethodNamingConvention"}) + public int run(final @NotNull List<String> args) throws Exception { + int returnCode = 0; + for (final String arg : args) { + try { + final InputStream in = new BufferedInputStream(new FileInputStream(arg)); + try { + uniq(in); + } finally { + in.close(); + } + } catch (final IOException e) { + returnCode = 1; + System.err.println(e); + } + } + return returnCode; + } + + /** + * Prints unique lines from the specified InputStream. + * @param in InputStream to print unique lines from. + * @throws IOException In case of I/O problems. + */ + private void uniq(@NotNull final InputStream in) throws IOException { + uniq(new InputStreamReader(in)); + } + + /** + * Prints unique lines from the specified Reader. + * @param in Reader to print unique lines from. + * @throws IOException In case of I/O problems. + */ + private void uniq(@NotNull final Reader in) throws IOException { + final BufferedReader bin = in instanceof BufferedReader ? (BufferedReader) in : new BufferedReader(in); + String previousLine = bin.readLine(); + if (previousLine != null) { + String line; + int lineCount = 1; + do { + line = bin.readLine(); + if (!(ignoreCase ? previousLine.equalsIgnoreCase(line) : previousLine.equals(line)) && (!repeated || lineCount > 1)) { + if (count) { + System.out.format("%7d %s%n", lineCount, previousLine); + } else { + System.out.println(previousLine); + } + lineCount = 0; + } + previousLine = line; + lineCount++; + } while (line != null); + } + } + +} // class Uniq Property changes on: libs/argparser/trunk/src/doc/examples/Uniq.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2006-11-26 23:47:21 UTC (rev 237) +++ libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2006-11-29 21:17:00 UTC (rev 238) @@ -25,6 +25,7 @@ import java.lang.reflect.Method; import java.util.*; import java.io.Closeable; +import net.sf.japi.io.args.converter.ConverterRegistry; /** * Parser for command line arguments. @@ -97,7 +98,7 @@ for (final Method requiredMethod : requiredMethods) { final Option option = requiredMethod.getAnnotation(Option.class); assert option != null; - missingOptions.add(option.names()[0]); + missingOptions.add(option.value()[0]); } throw new RequiredOptionsMissingException(missingOptions.toArray(new String[missingOptions.size()])); } @@ -112,7 +113,7 @@ for (final Method method : getOptionMethods(commandClass)) { final Option option = method.getAnnotation(Option.class); assert option != null; - for (final String optionName : option.names()) { + for (final String optionName : option.value()) { if (argumentMethods.containsKey(optionName)) { throw new IllegalArgumentException(commandClass.getName() + " declared option " + optionName + " twice."); } @@ -207,8 +208,8 @@ final int parameterCount = parameterTypes.length; if (parameterCount == 1) { final String arg = argIterator.next(); - method.invoke(command, arg); argIterator.remove(); + method.invoke(command, ConverterRegistry.convert(parameterTypes[0], arg)); } else if (parameterCount == 0) { method.invoke(command); } else { @@ -222,6 +223,8 @@ throw (TerminalException) cause; } System.err.println(e.getCause()); + } catch (final Exception e) { + e.printStackTrace(); } if (method.getAnnotation(Option.class).type() == OptionType.TERMINAL) { throw new TerminalException(); Modified: libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java 2006-11-26 23:47:21 UTC (rev 237) +++ libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java 2006-11-29 21:17:00 UTC (rev 238) @@ -8,6 +8,7 @@ import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; +import org.jetbrains.annotations.NotNull; /** * BasicCommand is a base class for commands that provides the options --help, --exit and --noexit. @@ -34,24 +35,18 @@ } /** Exit Option. */ - @Option(names = {"exit"}) - public void setExiting() { - exiting = true; + @Option(value = {"exit"}) + public void setExiting(@NotNull final Boolean exiting) { + this.exiting = exiting; } - /** No Exit Option. */ - @Option(names = {"noexit"}) - public void setNotExiting() { - exiting = false; - } - /** {@inheritDoc} */ - public boolean isExiting() { + public Boolean isExiting() { return exiting; } /** Help Option. */ - @Option(type = OptionType.TERMINAL, names = {"h", "help"}) + @Option(type = OptionType.TERMINAL, value = {"h", "help"}) public void help() { final Set<Method> optionMethods = ArgParser.getOptionMethods(this); final Set<Class<?>> parameterTypes = new HashSet<Class<?>>(); @@ -59,7 +54,7 @@ int maxShort = 0; for (final Method optionMethod : optionMethods) { final Option option = optionMethod.getAnnotation(Option.class); - final String[] names = option.names(); + final String[] names = option.value(); int currentLong = 0; int currentShort = 0; for (final String name : names) { @@ -80,7 +75,7 @@ for (final Method optionMethod : optionMethods) { final Option option = optionMethod.getAnnotation(Option.class); final OptionType optionType = option.type(); - final String[] names = option.names(); + final String[] names = option.value(); final List<String> shortNames = new ArrayList<String>(); final List<String> longNames = new ArrayList<String>(); for (final String name : names) { Modified: libs/argparser/trunk/src/net/sf/japi/io/args/Command.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/Command.java 2006-11-26 23:47:21 UTC (rev 237) +++ libs/argparser/trunk/src/net/sf/japi/io/args/Command.java 2006-11-29 21:17:00 UTC (rev 238) @@ -45,6 +45,6 @@ * Return whether after running this Command, {@link System#exit(int)} should be invoked. * @return <code>true</code> if {@link ArgParser} should invoke {@link System#exit(int)} after this command, otherwise <code>false</code>. */ - boolean isExiting(); + Boolean isExiting(); } // interface Command Modified: libs/argparser/trunk/src/net/sf/japi/io/args/Option.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/Option.java 2006-11-26 23:47:21 UTC (rev 237) +++ libs/argparser/trunk/src/net/sf/japi/io/args/Option.java 2006-11-29 21:17:00 UTC (rev 238) @@ -48,7 +48,7 @@ * @note the supplied string values MUST consist of ASCII-letters only (match regex <code>[a-zA-Z]+</code>). * @return option names */ - String[] names(); + String[] value(); /** * The option key, used for i18n/l10n. Added: libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java 2006-11-29 21:17:00 UTC (rev 238) @@ -0,0 +1,38 @@ +package net.sf.japi.io.args.converter; + +import java.util.Locale; +import java.util.ResourceBundle; + +/** + * Base class for the default converters. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +abstract class AbstractConverter<T> implements Converter<T> { + + /** The target class. */ + private final Class<T> targetClass; + + /** + * Create an AbstractConverter. + * @param targetClass TargetClass + */ + AbstractConverter(final Class<T> targetClass) { + this.targetClass = targetClass; + } + + /** {@inheritDoc} */ + public final Class<T> getTargetClass() { + return targetClass; + } + + /** {@inheritDoc} */ + public final String getDisplayName() { + return ResourceBundle.getBundle("net.sf.japi.io.args.converter.names").getString(targetClass.getName()); + } + + /** {@inheritDoc} */ + public final String getDisplayName(final Locale locale) { + return ResourceBundle.getBundle("net.sf.japi.io.args.converter.names", locale).getString(targetClass.getName()); + } + +} // class AbstractConverter Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/BooleanConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/BooleanConverter.java 2006-11-26 23:47:21 UTC (rev 237) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/BooleanConverter.java 2006-11-29 21:17:00 UTC (rev 238) @@ -4,8 +4,15 @@ * Converter which converts a String into a Boolean. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ -public class BooleanConverter implements Converter<Boolean> { +public class BooleanConverter extends AbstractConverter<Boolean> { + /** + * Create a BooleanConverter. + */ + public BooleanConverter() { + super(Boolean.class); + } + /** {@inheritDoc} */ public Boolean convert(final String arg) throws Exception { return Boolean.valueOf(arg); Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.java 2006-11-26 23:47:21 UTC (rev 237) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.java 2006-11-29 21:17:00 UTC (rev 238) @@ -1,5 +1,7 @@ package net.sf.japi.io.args.converter; +import java.util.Locale; + /** * The Converter interface is used for converters that convert Strings into other types. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> @@ -14,4 +16,23 @@ */ T convert(final String arg) throws Exception; + /** + * Returns the Class this Converter is for. + * @return The Class this Converter is for. + */ + Class<T> getTargetClass(); + + /** + * Returns a display name for the type of this Converter. + * @return A display name for the type of this Converter. + */ + String getDisplayName(); + + /** + * Returns a display name for the type of this Converter. + * @param locale Locale to get display name for. + * @return A display name for the type of this Converter in the specified locale. + */ + String getDisplayName(final Locale locale); + } // interface Convert Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java 2006-11-26 23:47:21 UTC (rev 237) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java 2006-11-29 21:17:00 UTC (rev 238) @@ -1,10 +1,9 @@ package net.sf.japi.io.args.converter; +import java.util.HashMap; +import java.util.Iterator; import java.util.Map; -import java.util.HashMap; -import java.util.Enumeration; -import java.net.URL; -import java.io.IOException; +import sun.misc.Service; /** * Registry for Converters. @@ -32,14 +31,8 @@ */ private static ConverterRegistry createSingletonInstance() { final ConverterRegistry instance = new ConverterRegistry(); - try { - for (final Enumeration<URL> urls = ConverterRegistry.class.getClassLoader().getResources("META-INF/services/net.sf.japi.io.args.ConverterRegistry"); urls.hasMoreElements() ; ) { - final URL url = urls.nextElement(); - // TODO - } - } catch (final IOException e) { - // TODO - e.printStackTrace(); + for (final Iterator<Converter<?>> converters = Service.providers(Converter.class); converters.hasNext();) { + instance.register(converters.next()); } return instance; } @@ -63,21 +56,31 @@ /** * Register a Converter for a specific class. - * @param clazz Class Class to register converter for * @param converter Converter to register */ - public <T> void register(final Class<T> clazz, final Converter<T> converter) { - converters.put(clazz, converter); - for (Class<?> superClass = clazz; (superClass = superClass.getSuperclass()) != null;) { + public <T> void register(final Converter<T> converter) { + converters.put(converter.getTargetClass(), converter); + for (Class<?> superClass = converter.getTargetClass(); (superClass = superClass.getSuperclass()) != null;) { if (!converters.containsKey(superClass)) { converters.put(superClass, converter); } } - for (final Class<?> interf : clazz.getInterfaces()) { + for (final Class<?> interf : converter.getTargetClass().getInterfaces()) { if (!converters.containsKey(interf)) { converters.put(interf, converter); } } } + /** + * Convenience method to convert a String to the desired target type using the default ConverterRegistry. + * @param targetType target type to convert to. + * @param s String to convert + * @return Converted String in the desired target type. + * @throws Exception in case the conversion failed. + */ + public static <T> T convert(final Class<T> targetType, final String s) throws Exception { + return getInstance().getConverter(targetType).convert(s); + } + } // class ConverterRegistry Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/InputStreamConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/InputStreamConverter.java 2006-11-26 23:47:21 UTC (rev 237) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/InputStreamConverter.java 2006-11-29 21:17:00 UTC (rev 238) @@ -10,8 +10,15 @@ * Converter that converts a String into an InputStream. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ -public class InputStreamConverter implements Converter<InputStream> { +public class InputStreamConverter extends AbstractConverter<InputStream> { + /** + * Create an InputStreamConverter. + */ + public InputStreamConverter() { + super(InputStream.class); + } + /** {@inheritDoc} */ public InputStream convert(final String arg) throws FileNotFoundException { try { Added: libs/argparser/trunk/src/net/sf/japi/io/args/converter/IntegerConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/IntegerConverter.java (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/IntegerConverter.java 2006-11-29 21:17:00 UTC (rev 238) @@ -0,0 +1,21 @@ +package net.sf.japi.io.args.converter; + +/** + * Converter which converts a String into a an Integer. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class IntegerConverter extends AbstractConverter<Integer> { + + /** + * Create an IntegerConverter. + */ + public IntegerConverter() { + super(Integer.class); + } + + /** {@inheritDoc} */ + public Integer convert(final String arg) throws Exception { + return Integer.valueOf(arg); + } + +} // class IntegerConverter Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/converter/IntegerConverter.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/StringConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/StringConverter.java 2006-11-26 23:47:21 UTC (rev 237) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/StringConverter.java 2006-11-29 21:17:00 UTC (rev 238) @@ -4,8 +4,15 @@ * Dummy Converter which "converts" a String into a String by simply returning it. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ -public class StringConverter implements Converter<String> { +public class StringConverter extends AbstractConverter<String> { + /** + * Create a StringConverter. + */ + public StringConverter() { + super(String.class); + } + /** {@inheritDoc} */ public String convert(final String arg) throws Exception { return arg; Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-11-26 23:47:21 UTC (rev 237) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-11-29 21:17:00 UTC (rev 238) @@ -53,7 +53,7 @@ * Set the value of the input option. * @param input Value of the input option. */ - @Option(type = OptionType.REQUIRED, names = {"i", "input"}) + @Option(type = OptionType.REQUIRED, value = {"i", "input"}) public void setInput(final String input) { this.input = input; } @@ -62,7 +62,7 @@ * Set the value of the foo option. * @param foo Value of the foo option. */ - @Option(names = {"f", "b", "foo", "bar", "buzz"}) + @Option(value = {"f", "b", "foo", "bar", "buzz"}) public void setFoo(final String foo) { // ignored } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2006-12-02 16:15:13
|
Revision: 242 http://svn.sourceforge.net/japi/?rev=242&view=rev Author: christianhujer Date: 2006-12-02 08:15:10 -0800 (Sat, 02 Dec 2006) Log Message: ----------- Improved converters, added some test cases. Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/Option.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/BooleanConverter.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/InputStreamConverter.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/IntegerConverter.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/StringConverter.java libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java Added Paths: ----------- libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter_de.properties libs/argparser/trunk/src/net/sf/japi/io/args/converter/NoConverterFoundException.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/OututStreamConverter.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/StringConverterTest.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/Option.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/Option.java 2006-11-29 23:09:22 UTC (rev 241) +++ libs/argparser/trunk/src/net/sf/japi/io/args/Option.java 2006-12-02 16:15:10 UTC (rev 242) @@ -37,6 +37,7 @@ /** * The option type. * Default is {@link OptionType#OPTIONAL}. + * Normally you wouldn't change this. * @return option type */ OptionType type() default OptionType.OPTIONAL; Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java 2006-11-29 23:09:22 UTC (rev 241) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java 2006-12-02 16:15:10 UTC (rev 242) @@ -2,37 +2,53 @@ import java.util.Locale; import java.util.ResourceBundle; +import org.jetbrains.annotations.NotNull; /** * Base class for the default converters. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ -abstract class AbstractConverter<T> implements Converter<T> { +public abstract class AbstractConverter<T> implements Converter<T> { /** The target class. */ - private final Class<T> targetClass; + @NotNull private final Class<T> targetClass; /** * Create an AbstractConverter. * @param targetClass TargetClass */ - AbstractConverter(final Class<T> targetClass) { + AbstractConverter(@NotNull final Class<T> targetClass) { this.targetClass = targetClass; } /** {@inheritDoc} */ - public final Class<T> getTargetClass() { + @NotNull public final Class<T> getTargetClass() { return targetClass; } /** {@inheritDoc} */ - public final String getDisplayName() { - return ResourceBundle.getBundle("net.sf.japi.io.args.converter.names").getString(targetClass.getName()); + @NotNull public final T convert(@NotNull final String arg) throws Exception { + return convert(Locale.getDefault(), arg); } /** {@inheritDoc} */ - public final String getDisplayName(final Locale locale) { - return ResourceBundle.getBundle("net.sf.japi.io.args.converter.names", locale).getString(targetClass.getName()); + @NotNull public final String getDisplayName() { + return getDisplayName(Locale.getDefault()); } + /** {@inheritDoc} */ + @NotNull public final String getDisplayName(@NotNull final Locale locale) { + return ResourceBundle.getBundle("net.sf.japi.io.args.converter.Converter", locale).getString(targetClass.getName() + ".displayName"); + } + + /** {@inheritDoc} */ + @NotNull public final String getDescription() { + return getDescription(Locale.getDefault()); + } + + /** {@inheritDoc} */ + @NotNull public final String getDescription(@NotNull final Locale locale) { + return ResourceBundle.getBundle("net.sf.japi.io.args.converter.Converter", locale).getString(targetClass.getName() + ".description"); + } + } // class AbstractConverter Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/BooleanConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/BooleanConverter.java 2006-11-29 23:09:22 UTC (rev 241) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/BooleanConverter.java 2006-12-02 16:15:10 UTC (rev 242) @@ -1,11 +1,21 @@ package net.sf.japi.io.args.converter; +import org.jetbrains.annotations.NotNull; +import java.util.Locale; +import java.util.ResourceBundle; + /** * Converter which converts a String into a Boolean. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ public class BooleanConverter extends AbstractConverter<Boolean> { + /** Strings for true. */ + private static final String[] TRUE_STRINGS = { "true", "yes", "on", "1" }; + + /** Strings for true. */ + private static final String[] FALSE_STRINGS = { "false", "no", "off", "0" }; + /** * Create a BooleanConverter. */ @@ -14,8 +24,29 @@ } /** {@inheritDoc} */ - public Boolean convert(final String arg) throws Exception { - return Boolean.valueOf(arg); + @NotNull + public Boolean convert(@NotNull final Locale locale, @NotNull final String arg) throws Exception { + for (final String s : TRUE_STRINGS) { + if (s.equalsIgnoreCase(arg)) { + return Boolean.TRUE; + } + } + for (final String s : FALSE_STRINGS) { + if (s.equalsIgnoreCase(arg)) { + return Boolean.FALSE; + } + } + for (final String s : ResourceBundle.getBundle("net.sf.japi.io.args.converter.Converter", locale).getString("java.lang.Boolean.true").split("\\s+")) { + if (s.equalsIgnoreCase(arg)) { + return Boolean.TRUE; + } + } + for (final String s : ResourceBundle.getBundle("net.sf.japi.io.args.converter.Converter", locale).getString("java.lang.Boolean.false").split("\\s+")) { + if (s.equalsIgnoreCase(arg)) { + return Boolean.TRUE; + } + } + throw new IllegalArgumentException(arg + " is not a valid String for a boolean."); } } // class BooleanConverter Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.java 2006-11-29 23:09:22 UTC (rev 241) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.java 2006-12-02 16:15:10 UTC (rev 242) @@ -1,6 +1,7 @@ package net.sf.japi.io.args.converter; import java.util.Locale; +import org.jetbrains.annotations.NotNull; /** * The Converter interface is used for converters that convert Strings into other types. @@ -13,26 +14,50 @@ * @param arg Argument to convert * @return Argument converted to T. * @throws Exception In case of conversion failure. + * @throws NullPointerException In case <code><var>arg</var> == null</code>. */ - T convert(final String arg) throws Exception; + @NotNull T convert(@NotNull final String arg) throws Exception; /** + * Convert the given argument to the desired return type. + * @param arg Argument to convert + * @param locale Locale to get perform conversion for. + * @return Argument converted to T. + * @throws Exception In case of conversion failure. + * @throws NullPointerException In case <code><var>arg</var> == null</code>. + */ + @NotNull T convert(@NotNull final Locale locale, @NotNull final String arg) throws Exception; + + /** * Returns the Class this Converter is for. * @return The Class this Converter is for. */ - Class<T> getTargetClass(); + @NotNull Class<T> getTargetClass(); /** * Returns a display name for the type of this Converter. * @return A display name for the type of this Converter. */ - String getDisplayName(); + @NotNull String getDisplayName(); /** * Returns a display name for the type of this Converter. * @param locale Locale to get display name for. * @return A display name for the type of this Converter in the specified locale. */ - String getDisplayName(final Locale locale); + @NotNull String getDisplayName(@NotNull final Locale locale); + /** + * Returns a description for this Converter. + * @return A description for this Converter. + */ + @NotNull String getDescription(); + + /** + * Returns a description for this Converter. + * @param locale Locale to get the description for. + * @return A description for this Converter in the specified locale. + */ + @NotNull String getDescription(@NotNull final Locale locale); + } // interface Convert Added: libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties 2006-12-02 16:15:10 UTC (rev 242) @@ -0,0 +1,12 @@ +java.io.InputStream.displayName=uri|filename|- +java.io.InputStream.description=Input file (URI, filename or - for STDIN). +java.io.OutputStream.displayName=filename|- +java.io.OutputStream.description=Output file (filename or - for STDOUT). +java.lang.Boolean.displayName=boolean +java.lang.Boolean.description=Valid values are: {0} for true and {1} for false. +java.lang.Boolean.true= +java.lang.Boolean.false= +java.lang.Integer.displayName=integer +java.lang.Integer.description=Integer number (decimal, 0... octal, 0x... 0X... #... hexadecimal) +java.lang.String.displayName=string +java.lang.String.description=Simple text \ No newline at end of file Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java 2006-11-29 23:09:22 UTC (rev 241) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java 2006-12-02 16:15:10 UTC (rev 242) @@ -3,7 +3,10 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import java.util.Locale; import sun.misc.Service; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * Registry for Converters. @@ -11,15 +14,15 @@ */ public class ConverterRegistry { - /** Singleton instance. */ - private static final ConverterRegistry instance = createSingletonInstance(); + /** Singleton INSTANCE. */ + private static final ConverterRegistry INSTANCE = createSingletonInstance(); /** Map for converters. */ private final Map<Class<?>, Converter<?>> converters = new HashMap<Class<?>, Converter<?>>(); /** * Creates a ConverterRegistry. - * Usually you want a shared global ConverterRegistry and use {@link #getInstance()} instead of creating your own ConverterRegistry instance. + * Usually you want a shared global ConverterRegistry and use {@link #getInstance()} instead of creating your own ConverterRegistry INSTANCE. * @see #getInstance() */ public ConverterRegistry() { @@ -29,6 +32,7 @@ * Creates the global shared instance of ConverterRegistry. * @return The global shared instance of ConverterRegistry. */ + @SuppressWarnings({"unchecked"}) private static ConverterRegistry createSingletonInstance() { final ConverterRegistry instance = new ConverterRegistry(); for (final Iterator<Converter<?>> converters = Service.providers(Converter.class); converters.hasNext();) { @@ -42,7 +46,7 @@ * @return The global shared instance of ConverterRegistry. */ public static ConverterRegistry getInstance() { - return instance; + return INSTANCE; } /** @@ -50,7 +54,8 @@ * @param clazz Class to get Converter for. * @return <code>null</code> if no suited converter was found. */ - public <T> Converter<T> getConverter(final Class<T> clazz) { + @Nullable public <T> Converter<T> getConverter(@NotNull final Class<T> clazz) { + //noinspection unchecked return (Converter<T>) converters.get(clazz); } @@ -58,7 +63,7 @@ * Register a Converter for a specific class. * @param converter Converter to register */ - public <T> void register(final Converter<T> converter) { + public <T> void register(@NotNull final Converter<T> converter) { converters.put(converter.getTargetClass(), converter); for (Class<?> superClass = converter.getTargetClass(); (superClass = superClass.getSuperclass()) != null;) { if (!converters.containsKey(superClass)) { @@ -79,8 +84,30 @@ * @return Converted String in the desired target type. * @throws Exception in case the conversion failed. */ - public static <T> T convert(final Class<T> targetType, final String s) throws Exception { - return getInstance().getConverter(targetType).convert(s); + @NotNull public static <T> T convert(@NotNull final Class<T> targetType, @NotNull final String s) throws Exception { + final Converter<T> converter = getInstance().getConverter(targetType); + if (converter != null) { + return converter.convert(s); + } else { + throw new NoConverterFoundException(targetType); + } } + /** + * Convenience method to convert a String to the desired target type using the default ConverterRegistry. + * @param targetType target type to convert to. + * @param locale Locale to perform the conversion in. + * @param s String to convert. + * @return Converted String in the desired target type. + * @throws Exception in case the conversion failed. + */ + @NotNull public static <T> T convert(@NotNull final Class<T> targetType, @NotNull final Locale locale, @NotNull final String s) throws Exception { + final Converter<T> converter = getInstance().getConverter(targetType); + if (converter != null) { + return converter.convert(locale, s); + } else { + throw new NoConverterFoundException(targetType); + } + } + } // class ConverterRegistry Added: libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter_de.properties =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter_de.properties (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter_de.properties 2006-12-02 16:15:10 UTC (rev 242) @@ -0,0 +1,7 @@ +java.io.InputStream.description=Eingabedatei (als URI, Dateiname oder - f\xFCr STDIN). +java.io.OutputStream.description=Ausgabedatei (Dateiname oder - f\xFCr STDOUT). +java.lang.Boolean.description=G\xFCltige Werte: {0} f\xFCr wahr und {1} f\xFCr falsch. +java.lang.Boolean.true=wahr ja an +java.lang.Boolean.false=falsch nein aus +java.lang.Integer.description=Ganzzahl (dezimal, 0... oktal, 0x... 0X... #... hexadezimal) +java.lang.String.description=Einfacher Text. Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter_de.properties ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/InputStreamConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/InputStreamConverter.java 2006-11-29 23:09:22 UTC (rev 241) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/InputStreamConverter.java 2006-12-02 16:15:10 UTC (rev 242) @@ -5,12 +5,16 @@ import java.io.IOException; import java.io.InputStream; import java.net.URL; +import java.util.Locale; +import org.jetbrains.annotations.NotNull; /** * Converter that converts a String into an InputStream. + * @note This converter always behaves the same independently of the {@link Locale}. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + * @deprecated The concept of this class is not yet mature. Please don't use it. */ -public class InputStreamConverter extends AbstractConverter<InputStream> { +@Deprecated public class InputStreamConverter extends AbstractConverter<InputStream> { /** * Create an InputStreamConverter. @@ -20,11 +24,19 @@ } /** {@inheritDoc} */ - public InputStream convert(final String arg) throws FileNotFoundException { + @NotNull public InputStream convert(@NotNull final Locale locale, @NotNull final String arg) throws FileNotFoundException { try { return new URL(arg).openStream(); } catch (final IOException ignore) { - return new FileInputStream(arg); + try { + return new FileInputStream(arg); + } catch (final FileNotFoundException e) { + if ("-".equals(arg)) { + return System.in; + } else { + throw e; + } + } } } Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/IntegerConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/IntegerConverter.java 2006-11-29 23:09:22 UTC (rev 241) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/IntegerConverter.java 2006-12-02 16:15:10 UTC (rev 242) @@ -1,8 +1,15 @@ package net.sf.japi.io.args.converter; +import org.jetbrains.annotations.NotNull; +import java.util.Locale; + /** * Converter which converts a String into a an Integer. + * The Converter uses a method that at minimum supports the same conversions as {@link Integer#decode(String)}. + * That means the following formats are supported: + * @note This converter always behaves the same independently of the {@link Locale}. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + * @see Integer#decode(String) Minimum grammar supported. */ public class IntegerConverter extends AbstractConverter<Integer> { @@ -14,8 +21,8 @@ } /** {@inheritDoc} */ - public Integer convert(final String arg) throws Exception { - return Integer.valueOf(arg); + @NotNull public Integer convert(@NotNull final Locale locale, @NotNull final String arg) throws NumberFormatException { + return Integer.decode(arg); } } // class IntegerConverter Added: libs/argparser/trunk/src/net/sf/japi/io/args/converter/NoConverterFoundException.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/NoConverterFoundException.java (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/NoConverterFoundException.java 2006-12-02 16:15:10 UTC (rev 242) @@ -0,0 +1,30 @@ +package net.sf.japi.io.args.converter; + +/** + * Exception that is thrown in case no matching converter for a conversion was found. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class NoConverterFoundException extends Exception { + + /** + * The type for that no Converter was found. + */ + private final Class<?> targetType; + + /** + * Create a NoConverterFoundException. + * @param targetType Type for that no Converter was found. + */ + public NoConverterFoundException(final Class<?> targetType) { + this.targetType = targetType; + } + + /** + * Returns the type for that no Converter was found. + * @return The type for that no Converter was found. + */ + public Class<?> getTargetType() { + return targetType; + } + +} // class NoConverterFoundException Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/converter/NoConverterFoundException.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/net/sf/japi/io/args/converter/OututStreamConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/OututStreamConverter.java (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/OututStreamConverter.java 2006-12-02 16:15:10 UTC (rev 242) @@ -0,0 +1,34 @@ +package net.sf.japi.io.args.converter; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.Locale; +import org.jetbrains.annotations.NotNull; + +/** + * Converter that converts a String into an InputStream. + * @note This converter always behaves the same independently of the {@link Locale}. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + * @deprecated The concept of this class is not yet mature. Please don't use it. + */ +@Deprecated public class OututStreamConverter extends AbstractConverter<OutputStream> { + + /** + * Create an InputStreamConverter. + */ + public OututStreamConverter() { + super(OutputStream.class); + } + + /** {@inheritDoc} */ + @NotNull public OutputStream convert(@NotNull final Locale locale, @NotNull final String arg) throws FileNotFoundException { + if ("-".equals(arg) && !new File("-").exists()) { + return System.out; + } else { + return new FileOutputStream(arg); + } + } + +} // class InputStreamConverter Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/converter/OututStreamConverter.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/StringConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/StringConverter.java 2006-11-29 23:09:22 UTC (rev 241) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/StringConverter.java 2006-12-02 16:15:10 UTC (rev 242) @@ -1,7 +1,12 @@ package net.sf.japi.io.args.converter; +import org.jetbrains.annotations.NotNull; +import java.util.Locale; + /** - * Dummy Converter which "converts" a String into a String by simply returning it. + * Simple Converter which "converts" a String into a String by simply returning it. + * It exists to be able to apply the same conversion pattern for all types including Strings. + * @note This converter always behaves the same independently of the {@link Locale}. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ public class StringConverter extends AbstractConverter<String> { @@ -14,7 +19,7 @@ } /** {@inheritDoc} */ - public String convert(final String arg) throws Exception { + @NotNull public String convert(@NotNull final Locale locale, @NotNull final String arg) throws Exception { return arg; } Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-11-29 23:09:22 UTC (rev 241) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-12-02 16:15:10 UTC (rev 242) @@ -54,7 +54,7 @@ * Set the value of the input option. * @param input Value of the input option. */ - @Option(type = OptionType.REQUIRED, value = {"i", "input"}) + @Option(value = {"i", "input"}, type = OptionType.REQUIRED) public void setInput(final String input) { this.input = input; } @@ -63,7 +63,7 @@ * Set the value of the foo option. * @param foo Value of the foo option. */ - @Option(value = {"f", "b", "foo", "bar", "buzz"}) + @Option({"f", "b", "foo", "bar", "buzz"}) public void setFoo(final String foo) { // ignored } Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java 2006-12-02 16:15:10 UTC (rev 242) @@ -0,0 +1,76 @@ +package test.net.sf.japi.io.args.converter; + +import java.util.Locale; +import net.sf.japi.io.args.converter.Converter; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; +import org.junit.Test; + +/** + * Base class for tests for Converters. + * Provides some basic testing methods. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public abstract class AbstractConverterTest<V, T extends Converter<V>> { + + /** The target class. */ + private Class<V> targetClass; + + /** The converter testling. */ + protected T converter; + + /** + * Create an AbstractConverterTest. + * @param targetClass Class of the Converter's target to test. + * @param converterClass Class of the Converter to test. + * @throws Exception in case of setup problems. + */ + protected AbstractConverterTest(@NotNull final Class<V> targetClass, @NotNull final Class<T> converterClass) throws Exception { + this.targetClass = targetClass; + converter = converterClass.newInstance(); + } + + /** + * Tests whether convert throws a NullPointerException if invoked with <code>null</code> + * @throws NullPointerException Expected exception that's thrown if the test case is successful. + * @throws Exception In case of test problems. + */ + @SuppressWarnings({"ConstantConditions"}) + @Test(expected=NullPointerException.class) + public void testThrowsNPE() throws Exception { + converter.convert(null); + } + /** + * Tests whether getting the target class works. + * @throws Exception In case of test problems. + */ + @Test + public void testGetTargetClass() throws Exception { + Assert.assertSame(targetClass, converter.getTargetClass()); + } + + /** + * Tests whether the testling has a proper description for the default locale. + * @throws Exception In case of unexpected errors. + */ + @Test + public void testDescription() throws Exception { + final String description = converter.getDescription(); + Assert.assertNotNull(description); + Assert.assertTrue(description.length() > 0); + Assert.assertEquals(description, converter.getDescription(Locale.getDefault())); + } + + /** + * Tests whether the testling has a proper display name. + * @throws Exception In case of unexpected errors. + */ + @Test + public void testDisplayName() throws Exception { + final String displayName = converter.getDisplayName(); + Assert.assertNotNull(displayName); + Assert.assertTrue(displayName.length() > 0); + Assert.assertEquals(displayName, converter.getDisplayName(Locale.getDefault())); + } + +} // class AbstractConverterTest \ No newline at end of file Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java 2006-12-02 16:15:10 UTC (rev 242) @@ -0,0 +1,55 @@ +package test.net.sf.japi.io.args.converter; + +import net.sf.japi.io.args.converter.BooleanConverter; +import org.junit.Test; +import org.junit.Assert; + +/** + * Tests for {@link BooleanConverter}. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class BooleanConverterTest extends AbstractConverterTest<Boolean, BooleanConverter> { + + /* + * Create an BooleanConverterTest. + * @throws Exception in case of setup problems. + */ + public BooleanConverterTest() throws Exception { + super(Boolean.class, BooleanConverter.class); + } + + /** + * Tests whether convert works for true. + * @throws Exception In case of unexpected errors. + */ + @Test + public void testConvertTrue() throws Exception { + Assert.assertTrue(converter.convert("tr... [truncated message content] |
From: <chr...@us...> - 2006-12-02 22:52:54
|
Revision: 244 http://svn.sourceforge.net/japi/?rev=244&view=rev Author: christianhujer Date: 2006-12-02 14:52:52 -0800 (Sat, 02 Dec 2006) Log Message: ----------- Added some more tests. Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/OptionType.java libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java Added Paths: ----------- libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/CommandDummy.java libs/argparser/trunk/src/test/net/sf/japi/io/args/MissingArgumentExceptionTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/OptionTypeTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/RequiredOptionsMissingExceptionTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/TerminalExceptionTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/UnknownOptionExceptionTest.java Removed Paths: ------------- libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTestCase.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/OptionType.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/OptionType.java 2006-12-02 19:01:29 UTC (rev 243) +++ libs/argparser/trunk/src/net/sf/japi/io/args/OptionType.java 2006-12-02 22:52:52 UTC (rev 244) @@ -23,6 +23,7 @@ import java.util.ResourceBundle; import java.util.MissingResourceException; import java.util.Locale; +import org.jetbrains.annotations.NotNull; /** * The type of an option. @@ -54,7 +55,7 @@ * Returns the localized name of this OptionType in the default locale if available, otherwise the lowercase enum constant name. * @return The localized name of this OptionType. */ - public String getName() { + @NotNull public String getName() { String name; try { name = ResourceBundle.getBundle("net.sf.japi.io.args.messages").getString(getClass().getName() + "." + name()); @@ -69,7 +70,7 @@ * @param locale Locale * @return The localized name of this OptionType. */ - public String getName(final Locale locale) { + @NotNull public String getName(@NotNull final Locale locale) { String name; try { name = ResourceBundle.getBundle("net.sf.japi.io.args.messages", locale).getString(getClass().getName() + "." + name()); @@ -83,7 +84,7 @@ * {@inheritDoc} * Returns the same as {@link #getName()}. */ - @Override public String toString() { + @NotNull @Override public String toString() { return getName(); } @@ -91,7 +92,7 @@ * Returns the command line description of this option type. * @return The command line description of this option type. */ - public String getDescription() { + @NotNull public String getDescription() { String description; try { description = ResourceBundle.getBundle("net.sf.japi.io.args.messages").getString(getClass().getName() + "." + name() + ".description"); @@ -101,4 +102,19 @@ return description.length() == 0 ? description : " (" + description + ")"; } + /** + * Returns the command line description of this option type. + * @param locale Locale + * @return The command line description of this option type. + */ + @NotNull public String getDescription(@NotNull final Locale locale) { + String description; + try { + description = ResourceBundle.getBundle("net.sf.japi.io.args.messages", locale).getString(getClass().getName() + "." + name() + ".description"); + } catch (final MissingResourceException e) { + description = name(); + } + return description.length() == 0 ? description : " (" + description + ")"; + } + } // OptionType Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-12-02 19:01:29 UTC (rev 243) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2006-12-02 22:52:52 UTC (rev 244) @@ -1,5 +1,8 @@ package test.net.sf.japi.io.args; +import java.util.List; +import java.util.Set; +import java.lang.reflect.Method; import net.sf.japi.io.args.ArgParser; import net.sf.japi.io.args.BasicCommand; import net.sf.japi.io.args.MissingArgumentException; @@ -8,10 +11,10 @@ import net.sf.japi.io.args.RequiredOptionsMissingException; import net.sf.japi.io.args.TerminalException; import net.sf.japi.io.args.UnknownOptionException; -import java.util.List; +import net.sf.japi.io.args.Command; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; import org.junit.Test; -import org.junit.Assert; -import org.jetbrains.annotations.NotNull; /** * Test for {@link ArgParser}. @@ -20,72 +23,46 @@ public class ArgParserTest { /** - * This MockCommand serves as a command for performing simple tests. - * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + * Tests whether {@link ArgParser#getOptionMethods(Command)} works. + * @throws Exception (unexpected) */ - public static class MockCommand extends BasicCommand { + @Test + public void testGetOptionMethodsCommand() throws Exception { + final CommandDummy commandDummy = new CommandDummy(); + final Set<Method> optionMethods = ArgParser.getOptionMethods(commandDummy); + Assert.assertFalse(optionMethods.isEmpty()); + } - /** The input option value. */ - private String input; + /** + * Tests whether {@link ArgParser#getOptionMethods(Class)} works. + * @throws Exception (unexpected) + */ + @Test + public void testGetOptionMethodsClass() throws Exception { + final Set<Method> optionMethods = ArgParser.getOptionMethods(CommandDummy.class); + Assert.assertFalse(optionMethods.isEmpty()); + } - /** Remembers whether {@link #run(java.util.List<java.lang.String>)} was called. */ - private boolean runCalled; + /** + * Tests whether {@link ArgParser#simpleParseAndRun(Command, String[])} works. + * @throws Exception (unexpected) + */ + @Test + public void testSimpleParseAndRun() throws Exception { + final CommandDummy commandDummy = new CommandDummy(); + ArgParser.simpleParseAndRun(commandDummy); + } - /** The command line arguments received from the parser. */ - private List<String> args; + /** + * Tests whether {@link ArgParser#parseAndRun(Command, String[])} works. + * @throws Exception (unexpected) + */ + @Test + public void testParseAndRun() throws Exception { + final CommandDummy commandDummy = new CommandDummy(); + ArgParser.parseAndRun(commandDummy); + } - /** {@inheritDoc} */ - @SuppressWarnings({"InstanceMethodNamingConvention"}) - public int run(@NotNull final List<String> args) { - runCalled = true; - this.args = args; - return 0; - } - - /** - * Get the command line arguments. - * @return Command line arguments. - */ - private List<String> getArgs() { - return args; - } - - /** - * Set the value of the input option. - * @param input Value of the input option. - */ - @Option(value = {"i", "input"}, type = OptionType.REQUIRED) - public void setInput(final String input) { - this.input = input; - } - - /** - * Set the value of the foo option. - * @param foo Value of the foo option. - */ - @Option({"f", "b", "foo", "bar", "buzz"}) - public void setFoo(final String foo) { - // ignored - } - - /** - * Get the value of the input option. - * @return Value of the input option. - */ - private String getInput() { - return input; - } - - /** - * Return whether run was called. - * @return whether run was called. - */ - private boolean isRunCalled() { - return runCalled; - } - - } // class MockCommand - /** * Tests whether supplying a required option with argument in short form works. * @throws RequiredOptionsMissingException (unexpected) @@ -141,7 +118,7 @@ * @throws UnknownOptionException (unexpected) * @throws MissingArgumentException (unexpected) */ - @Test(expected=RequiredOptionsMissingException.class) + @Test(expected = RequiredOptionsMissingException.class) public void testCommandRequiredOptionMissing() throws RequiredOptionsMissingException, TerminalException, UnknownOptionException, MissingArgumentException { final MockCommand command = new MockCommand(); try { @@ -158,7 +135,7 @@ * @throws UnknownOptionException (expected) * @throws MissingArgumentException (unexpected) */ - @Test(expected=UnknownOptionException.class) + @Test(expected = UnknownOptionException.class) public void testCommandUnknownOption() throws RequiredOptionsMissingException, TerminalException, UnknownOptionException, MissingArgumentException { final MockCommand command = new MockCommand(); try { @@ -175,7 +152,7 @@ * @throws UnknownOptionException (unexpected) * @throws MissingArgumentException (expected) */ - @Test(expected=MissingArgumentException.class) + @Test(expected = MissingArgumentException.class) public void testCommandMissingArgument() throws RequiredOptionsMissingException, TerminalException, UnknownOptionException, MissingArgumentException { final MockCommand command = new MockCommand(); try { @@ -214,4 +191,71 @@ ArgParser.parseAndRun(command, "-h"); } + /** + * This MockCommand serves as a command for performing simple tests. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ + public static class MockCommand extends BasicCommand { + + /** The input option value. */ + private String input; + + /** Remembers whether {@link #run(java.util.List<java.lang.String>)} was called. */ + private boolean runCalled; + + /** The command line arguments received from the parser. */ + private List<String> args; + + /** {@inheritDoc} */ + @SuppressWarnings({"InstanceMethodNamingConvention"}) + public int run(@NotNull final List<String> args) { + runCalled = true; + this.args = args; + return 0; + } + + /** + * Get the command line arguments. + * @return Command line arguments. + */ + private List<String> getArgs() { + return args; + } + + /** + * Set the value of the input option. + * @param input Value of the input option. + */ + @Option(value = {"i", "input"}, type = OptionType.REQUIRED) + public void setInput(final String input) { + this.input = input; + } + + /** + * Set the value of the foo option. + * @param foo Value of the foo option. + */ + @Option({"f", "b", "foo", "bar", "buzz"}) + public void setFoo(final String foo) { + // ignored + } + + /** + * Get the value of the input option. + * @return Value of the input option. + */ + private String getInput() { + return input; + } + + /** + * Return whether run was called. + * @return whether run was called. + */ + private boolean isRunCalled() { + return runCalled; + } + + } // class MockCommand + } // class ArgParserTest Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java 2006-12-02 22:52:52 UTC (rev 244) @@ -0,0 +1,69 @@ +package test.net.sf.japi.io.args; + +import net.sf.japi.io.args.BasicCommand; +import org.junit.Assert; +import org.junit.Test; +import java.util.ArrayList; +import java.util.ResourceBundle; + +/** + * Test for {@link BasicCommand}. + * + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class BasicCommandTest { + + /** + * Tests whether {@link BasicCommand#BasicCommand()} works. + * @throws Exception (unexpected) + */ + @Test + public void testBasicCommand() throws Exception { + final BasicCommand basicCommand = new CommandDummy(); + Assert.assertEquals(0, basicCommand.run(new ArrayList<String>())); + } + + /** + * Tests whether {@link BasicCommand#setExiting(Boolean)} works. + * @throws Exception (unexpected) + */ + @Test + public void testSetExiting() throws Exception { + final BasicCommand basicCommand = new CommandDummy(); + basicCommand.setExiting(false); + Assert.assertFalse(basicCommand.isExiting()); + basicCommand.setExiting(true); + Assert.assertTrue(basicCommand.isExiting()); + } + + /** + * Tests whether {@link BasicCommand#isExiting()} works. + * @throws Exception (unexpected) + */ + @Test + public void testIsExiting() throws Exception { + testSetExiting(); + } + + /** + * Tests whether {@link BasicCommand#help()} works. + * @throws Exception (unexpected) + */ + @Test + public void testHelp() throws Exception { + final BasicCommand basicCommand = new CommandDummy(); + basicCommand.help(); + } + + /** + * Tests whether {@link BasicCommand#getBundle()} works. + * @throws Exception (unexpected) + */ + @Test + public void testGetBundle() throws Exception { + final BasicCommand basicCommand = new CommandDummy(); + final ResourceBundle bundle = basicCommand.getBundle(); + Assert.assertNotNull(bundle); + } + +} // class BasicCommandTest \ No newline at end of file Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/CommandDummy.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/CommandDummy.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/CommandDummy.java 2006-12-02 22:52:52 UTC (rev 244) @@ -0,0 +1,19 @@ +package test.net.sf.japi.io.args; + +import net.sf.japi.io.args.BasicCommand; +import org.jetbrains.annotations.NotNull; +import java.util.List; + +/** + * A simple BasicCommand implementation as a test mock. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +class CommandDummy extends BasicCommand { + + /** {@inheritDoc} */ + @SuppressWarnings({"InstanceMethodNamingConvention"}) + public int run(@NotNull List<String> args) throws Exception { + return 0; + } + +} // class CommandDummy Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/CommandDummy.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/MissingArgumentExceptionTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/MissingArgumentExceptionTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/MissingArgumentExceptionTest.java 2006-12-02 22:52:52 UTC (rev 244) @@ -0,0 +1,33 @@ +package test.net.sf.japi.io.args; + +import net.sf.japi.io.args.MissingArgumentException; +import org.junit.Assert; +import org.junit.Test; + +/** + * Test for {@link MissingArgumentException}. + * + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class MissingArgumentExceptionTest { + + /** + * Tests whether {@link MissingArgumentException#MissingArgumentException(String)} works. + * @throws Exception (unexpected) + */ + @Test + public void testMissingArgumentException() throws Exception { + final MissingArgumentException exception = new MissingArgumentException("foo"); + Assert.assertEquals(exception.getOption(), "foo"); + } + + /** + * Tests whether {@link MissingArgumentException#getOption()} works. + * @throws Exception (unexpected) + */ + @Test + public void testGetOption() throws Exception { + testMissingArgumentException(); + } + +} // class MissingArgumentExceptionTest \ No newline at end of file Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/MissingArgumentExceptionTest.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/OptionTypeTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/OptionTypeTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/OptionTypeTest.java 2006-12-02 22:52:52 UTC (rev 244) @@ -0,0 +1,54 @@ +package test.net.sf.japi.io.args; + +import net.sf.japi.io.args.OptionType; +import org.junit.Assert; +import org.junit.Test; +import java.util.Locale; + +/** + * Test for {@link OptionType}. + * + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class OptionTypeTest { + + /** + * Tests whether {@link OptionType#getName()} and {@link OptionType#getName(Locale)} work. + * @throws Exception (unexpected) + */ + @Test + public void testGetName() throws Exception { + for (final OptionType optionType : OptionType.values()) { + Assert.assertNotNull(optionType.getName()); + } + for (final OptionType optionType : OptionType.values()) { + Assert.assertNotNull(optionType.getName(Locale.getDefault())); + } + } + + /** + * Tests whether {@link OptionType#toString()} works. + * @throws Exception (unexpected) + */ + @Test + public void testToString() throws Exception { + for (final OptionType optionType : OptionType.values()) { + Assert.assertNotNull(optionType.toString()); + } + } + + /** + * Tests whether {@link OptionType#getDescription()} and {@link OptionType#getDescription(Locale)} work. + * @throws Exception (unexpected) + */ + @Test + public void testGetDescription() throws Exception { + for (final OptionType optionType : OptionType.values()) { + Assert.assertNotNull(optionType.getDescription()); + } + for (final OptionType optionType : OptionType.values()) { + Assert.assertNotNull(optionType.getDescription(Locale.getDefault())); + } + } + +} // class OptionTypeTest \ No newline at end of file Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/OptionTypeTest.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/RequiredOptionsMissingExceptionTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/RequiredOptionsMissingExceptionTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/RequiredOptionsMissingExceptionTest.java 2006-12-02 22:52:52 UTC (rev 244) @@ -0,0 +1,35 @@ +package test.net.sf.japi.io.args; + +import net.sf.japi.io.args.RequiredOptionsMissingException; +import org.junit.Assert; +import org.junit.Test; +import java.util.Arrays; + +/** + * Test for {@link RequiredOptionsMissingException}. + * + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class RequiredOptionsMissingExceptionTest { + + /** + * Tests whether {@link RequiredOptionsMissingException#RequiredOptionsMissingException(String[])} works. + * @throws Exception (unexpected) + */ + @Test + public void testRequiredOptionsMissingException() throws Exception { + final String[] options = { "foo", "bar" }; + final RequiredOptionsMissingException exception = new RequiredOptionsMissingException(options.clone()); + Assert.assertTrue(Arrays.equals(exception.getMissingOptions(), options)); + } + + /** + * Tests whether {@link RequiredOptionsMissingException#getMissingOptions()} works. + * @throws Exception (unexpected) + */ + @Test + public void testGetMissingOptions() throws Exception { + testRequiredOptionsMissingException(); + } + +} // class RequiredOptionsMissingExceptionTest \ No newline at end of file Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/RequiredOptionsMissingExceptionTest.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTest.java 2006-12-02 22:52:52 UTC (rev 244) @@ -0,0 +1,59 @@ +package test.net.sf.japi.io.args; + +import java.util.Arrays; +import net.sf.japi.io.args.StringJoiner; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +/** + * Test for {@link StringJoiner}. + * + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class StringJoinerTest { + + /** + * Expected String. + */ + private static final String EXPECTED = "foo, bar, buzz"; + + /** + * Argument values. + */ + private static final String[] ARGS = {"foo", "bar", "buzz"}; + + /** + * Tests whether {@link StringJoiner#join(CharSequence,CharSequence...)} works. + */ + @Test + public void testJoinCSCS() { + final String[] nargs = ARGS.clone(); + final String actual = StringJoiner.join(", ", nargs); + assertEquals("arguments must be joined correctly.", EXPECTED, actual); + assertTrue("arguments must not be changed by join().", Arrays.equals(ARGS, nargs)); + } + + /** + * Tests whether {@link StringJoiner#join(CharSequence,Iterable<? extends java.lang.CharSequence>)} works. + */ + @Test + public void testJoinCSIe() { + final String[] nargs = ARGS.clone(); + final String actual = StringJoiner.join(", ", Arrays.asList(nargs)); + assertEquals("arguments must be joined correctly.", EXPECTED, actual); + assertTrue("arguments must not be changed by join().", Arrays.equals(ARGS, nargs)); + } + + /** + * Tests whether {@link StringJoiner#join(CharSequence,java.util.Iterator<? extends java.lang.CharSequence>)} works. + */ + @Test + public void testJoinCSIr() { + final String[] nargs = ARGS.clone(); + final String actual = StringJoiner.join(", ", Arrays.asList(nargs).iterator()); + assertEquals("arguments must be joined correctly.", EXPECTED, actual); + assertTrue("arguments must not be changed by join().", Arrays.equals(ARGS, nargs)); + } + +} // class StringJoinerTest Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTest.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Deleted: libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTestCase.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTestCase.java 2006-12-02 19:01:29 UTC (rev 243) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/StringJoinerTestCase.java 2006-12-02 22:52:52 UTC (rev 244) @@ -1,58 +0,0 @@ -package test.net.sf.japi.io.args; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; -import net.sf.japi.io.args.StringJoiner; -import org.junit.Test; - -import java.util.Arrays; - -/** - * TestCase for {@link StringJoiner}. - * @author <a href="mailto:ch...@ri...">Christian Hujer</a> - */ -public class StringJoinerTestCase { - - /** Expected String. */ - private static final String EXPECTED = "foo, bar, buzz"; - - /** Argument values. */ - private static final String[] ARGS = { "foo", "bar", "buzz" }; - - /** - * Empty constructor for JUnit. - */ - public StringJoinerTestCase() { - } - - /** - * Tests whether {@link StringJoiner#join(CharSequence, CharSequence...)} works. - */ - @Test public void testJoinCSCS() { - final String[] nargs = ARGS.clone(); - final String actual = StringJoiner.join(", ", nargs); - assertEquals("arguments must be joined correctly.", EXPECTED, actual); - assertTrue("arguments must not be changed by join().", Arrays.equals(ARGS, nargs)); - } - - /** - * Tests whether {@link StringJoiner#join(CharSequence, Iterable<? extends java.lang.CharSequence>)} works. - */ - @Test public void testJoinCSIe() { - final String[] nargs = ARGS.clone(); - final String actual = StringJoiner.join(", ", Arrays.asList(nargs)); - assertEquals("arguments must be joined correctly.", EXPECTED, actual); - assertTrue("arguments must not be changed by join().", Arrays.equals(ARGS, nargs)); - } - - /** - * Tests whether {@link StringJoiner#join(CharSequence, java.util.Iterator<? extends java.lang.CharSequence>)} works. - */ - @Test public void testJoinCSIr() { - final String[] nargs = ARGS.clone(); - final String actual = StringJoiner.join(", ", Arrays.asList(nargs).iterator()); - assertEquals("arguments must be joined correctly.", EXPECTED, actual); - assertTrue("arguments must not be changed by join().", Arrays.equals(ARGS, nargs)); - } - -} // class StringJoinerTestCase Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/TerminalExceptionTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/TerminalExceptionTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/TerminalExceptionTest.java 2006-12-02 22:52:52 UTC (rev 244) @@ -0,0 +1,34 @@ +package test.net.sf.japi.io.args; + +import net.sf.japi.io.args.TerminalException; +import org.junit.Assert; +import org.junit.Test; + +/** + * Test for {@link TerminalException}. + * + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class TerminalExceptionTest { + + /** + * Tests whether {@link TerminalException#TerminalException()} works. + * @throws Exception (unexpected) + */ + @Test + public void testTerminalException() throws Exception { + final TerminalException exception = new TerminalException(); + Assert.assertEquals(exception.getReturnCode(), 0); + } + + /** + * Tests whether {@link TerminalException#getReturnCode()} works. + * @throws Exception (unexpected) + */ + @Test + public void testGetReturnCode() throws Exception { + final TerminalException exception = new TerminalException(1); + Assert.assertEquals(exception.getReturnCode(), 1); + } + +} // class TerminalExceptionTest \ No newline at end of file Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/TerminalExceptionTest.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/UnknownOptionExceptionTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/UnknownOptionExceptionTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/UnknownOptionExceptionTest.java 2006-12-02 22:52:52 UTC (rev 244) @@ -0,0 +1,35 @@ +package test.net.sf.japi.io.args; + +import net.sf.japi.io.args.UnknownOptionException; +import org.junit.Assert; +import org.junit.Test; +import java.util.Arrays; + +/** + * Test for {@link UnknownOptionException}. + * + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class UnknownOptionExceptionTest { + + /** + * Tests whether {@link UnknownOptionException#UnknownOptionException(String[])} works. + * @throws Exception (unexpected) + */ + @Test + public void testUnknownOptionException() throws Exception { + final String[] options = { "foo", "bar" }; + final UnknownOptionException exception = new UnknownOptionException(options.clone()); + Assert.assertTrue(Arrays.equals(options, exception.getUnknownOptions())); + } + + /** + * Tests whether {@link UnknownOptionException#getUnknownOptions()} works. + * @throws Exception (unexpected) + */ + @Test + public void testGetUnknownOptions() throws Exception { + testUnknownOptionException(); + } + +} // class UnknownOptionExceptionTest \ No newline at end of file Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/UnknownOptionExceptionTest.java ___________________________________________________________________ Name: svn:mime-type + text/pl... [truncated message content] |
From: <chr...@us...> - 2006-12-02 23:27:45
|
Revision: 245 http://svn.sourceforge.net/japi/?rev=245&view=rev Author: christianhujer Date: 2006-12-02 15:27:43 -0800 (Sat, 02 Dec 2006) Log Message: ----------- Fixed Javadoc issues. Modified Paths: -------------- libs/argparser/trunk/src/doc/examples/Head.java libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java libs/argparser/trunk/src/net/sf/japi/io/args/StringJoiner.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/NoConverterFoundExceptionTest.java Modified: libs/argparser/trunk/src/doc/examples/Head.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Head.java 2006-12-02 22:52:52 UTC (rev 244) +++ libs/argparser/trunk/src/doc/examples/Head.java 2006-12-02 23:27:43 UTC (rev 245) @@ -109,6 +109,7 @@ /** * Copies the configured number of items from the specified InputStream to System.out. * @param in InputStream to run on + * @throws IOException In case of I/O problems. */ private void copyItems(final InputStream in) throws IOException { if (printBytes) { Modified: libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java 2006-12-02 22:52:52 UTC (rev 244) +++ libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java 2006-12-02 23:27:43 UTC (rev 245) @@ -22,7 +22,10 @@ /** The maximum width of the option type field. */ private final int maxOptionTypeWidth; - /** @see Command#isExiting() */ + /** + * Whether to exit or not. + * @see Command#isExiting() + */ private boolean exiting; /** Create a BasicCommand. */ @@ -34,7 +37,10 @@ maxOptionTypeWidth = tmpMaxOptionTypeWidth; } - /** Exit Option. */ + /** + * Exit Option. + * @param exiting <code>true</code> if {@link System#exit(int)} should be invoked, otherwise <code>false</code>. + */ @Option(value = {"exit"}) public void setExiting(@NotNull final Boolean exiting) { this.exiting = exiting; Modified: libs/argparser/trunk/src/net/sf/japi/io/args/StringJoiner.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/StringJoiner.java 2006-12-02 22:52:52 UTC (rev 244) +++ libs/argparser/trunk/src/net/sf/japi/io/args/StringJoiner.java 2006-12-02 23:27:43 UTC (rev 245) @@ -57,6 +57,7 @@ * @param delim delimiter to use for joining the strings * @param strings Strings to join * @return Appendable + * @throws IOException In case of I/O problems on <var>dest</var>. */ public static Appendable join(final Appendable dest, final CharSequence delim, final CharSequence... strings) throws IOException { for (int i = 0; i < strings.length; i++) { @@ -74,6 +75,7 @@ * @param delim delimiter to use for joining the strings * @param strings Strings to join * @return Appendable + * @throws IOException In case of I/O problems on <var>dest</var>. */ public static Appendable join(final Appendable dest, final CharSequence delim, final Iterable<? extends CharSequence> strings) throws IOException { return join(dest, delim, strings.iterator()); @@ -85,6 +87,7 @@ * @param delim delimiter to use for joining the strings * @param strings Strings to join * @return Appendable + * @throws IOException In case of I/O problems on <var>dest</var>. */ public static Appendable join(final Appendable dest, final CharSequence delim, final Iterator<? extends CharSequence> strings) throws IOException { if (strings.hasNext()) { Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java 2006-12-02 22:52:52 UTC (rev 244) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java 2006-12-02 23:27:43 UTC (rev 245) @@ -39,7 +39,7 @@ } /** - * Tests whether convert throws a NullPointerException if invoked with <code>null</code> + * Tests whether convert throws a NullPointerException if invoked with <code>null</code>. * @throws Exception In case of test problems. */ @SuppressWarnings({"ConstantConditions"}) Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java 2006-12-02 22:52:52 UTC (rev 244) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java 2006-12-02 23:27:43 UTC (rev 245) @@ -12,7 +12,6 @@ * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ public class ConverterRegistryTest { - ConverterRegistry converterRegistry; /** * Tests that creating a new ConverterRegistry works. @@ -20,6 +19,7 @@ */ @Test public void testConverterRegistry() throws Exception { + //noinspection UnusedDeclaration final ConverterRegistry converterRegistry = new ConverterRegistry(); } Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/NoConverterFoundExceptionTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/NoConverterFoundExceptionTest.java 2006-12-02 22:52:52 UTC (rev 244) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/NoConverterFoundExceptionTest.java 2006-12-02 23:27:43 UTC (rev 245) @@ -6,6 +6,7 @@ /** * Test for {@link NoConverterFoundException}. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ public class NoConverterFoundExceptionTest { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2006-12-16 21:48:02
|
Revision: 264 http://svn.sourceforge.net/japi/?rev=264&view=rev Author: christianhujer Date: 2006-12-16 13:47:59 -0800 (Sat, 16 Dec 2006) Log Message: ----------- Improved ResourceBundle handling. Modified Paths: -------------- libs/argparser/trunk/src/doc/examples/Head.java libs/argparser/trunk/src/doc/examples/Recode.java libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java libs/argparser/trunk/src/net/sf/japi/io/args/package.html Added Paths: ----------- libs/argparser/trunk/src/doc/examples/Head.properties libs/argparser/trunk/src/doc/examples/Head_de.properties Removed Paths: ------------- libs/argparser/trunk/src/doc/examples/head.properties libs/argparser/trunk/src/doc/examples/head_de.properties Modified: libs/argparser/trunk/src/doc/examples/Head.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Head.java 2006-12-15 21:05:19 UTC (rev 263) +++ libs/argparser/trunk/src/doc/examples/Head.java 2006-12-16 21:47:59 UTC (rev 264) @@ -6,7 +6,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; -import java.util.ResourceBundle; import net.sf.japi.io.args.ArgParser; import net.sf.japi.io.args.BasicCommand; import net.sf.japi.io.args.Option; @@ -18,9 +17,6 @@ */ public class Head extends BasicCommand { - /** The ResourceBundle for locale-specific output. */ - private final ResourceBundle resourceBundle = ResourceBundle.getBundle("examples.head"); - /** The number of items to print. */ private int numItems = 10; @@ -133,9 +129,4 @@ ArgParser.simpleParseAndRun(new Head(), args); } - /** {@inheritDoc} */ - @Override public ResourceBundle getBundle() { - return resourceBundle; - } - } // class Head Added: libs/argparser/trunk/src/doc/examples/Head.properties =================================================================== --- libs/argparser/trunk/src/doc/examples/Head.properties (rev 0) +++ libs/argparser/trunk/src/doc/examples/Head.properties 2006-12-16 21:47:59 UTC (rev 264) @@ -0,0 +1,7 @@ +net.sf.japi.io.args.OptionType.REQUIRED=required +net.sf.japi.io.args.OptionType.OPTIONAL=optional +net.sf.japi.io.args.OptionType.TERMINAL=terminal +setBytes=Print the first N bytes of each file. +setLines=Print the first N lines of each file (default: 10). +setQuiet=Never print headers giving file names. +setVerbose=Always print headers giving file names. Property changes on: libs/argparser/trunk/src/doc/examples/Head.properties ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/doc/examples/Head_de.properties =================================================================== --- libs/argparser/trunk/src/doc/examples/Head_de.properties (rev 0) +++ libs/argparser/trunk/src/doc/examples/Head_de.properties 2006-12-16 21:47:59 UTC (rev 264) @@ -0,0 +1,7 @@ +net.sf.japi.io.args.OptionType.REQUIRED=erforderlich +net.sf.japi.io.args.OptionType.OPTIONAL=optional +net.sf.japi.io.args.OptionType.TERMINAL=abbrechend +setBytes=Die ersten N Bytes jeder Datei ausgeben. +setLines=Die ersten N Zeilen jeder Datei ausgeben (Voreinstellung: 10). +setQuiet=Niemals Dateinamen vorab ausgeben. +setVerbose=Immer Dateinamen vorab ausgeben. Property changes on: libs/argparser/trunk/src/doc/examples/Head_de.properties ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/doc/examples/Recode.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Recode.java 2006-12-15 21:05:19 UTC (rev 263) +++ libs/argparser/trunk/src/doc/examples/Recode.java 2006-12-16 21:47:59 UTC (rev 264) @@ -2,7 +2,6 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -12,6 +11,8 @@ import java.io.Reader; import java.io.Writer; import java.util.List; +import java.nio.channels.FileChannel; +import net.sf.japi.io.args.ArgParser; import net.sf.japi.io.args.BasicCommand; import net.sf.japi.io.args.Option; import static net.sf.japi.io.args.OptionType.REQUIRED; @@ -83,13 +84,14 @@ } finally { out.close(); } - if (!tmpFile.renameTo(file)) { - tmpFile.delete(); - throw new FileNotFoundException("Couldn't open " + file + " for writing."); - } } finally { in.close(); } + try { + copy(tmpFile, file); + } finally { + tmpFile.delete(); + } } /** @@ -107,4 +109,34 @@ cout.flush(); } + /** + * Copies form one file to another. + * @param source File to copy. + * @param dest File to copy to. + * @throws IOException In case of I/O problems. + */ + public void copy(final File source, final File dest) throws IOException { + final FileInputStream in = new FileInputStream(source); + try { + final FileOutputStream out = new FileOutputStream(dest); + try { + final FileChannel inChannel = in.getChannel(); + final FileChannel outChannel = out.getChannel(); + inChannel.transferTo(0, inChannel.size(), outChannel); + } finally { + out.close(); + } + } finally { + in.close(); + } + } + + /** + * Main method. + * @param args Command line arguments + */ + public static void main(final String... args) { + ArgParser.simpleParseAndRun(new Recode(), args); + } + } // class Recode Deleted: libs/argparser/trunk/src/doc/examples/head.properties =================================================================== --- libs/argparser/trunk/src/doc/examples/head.properties 2006-12-15 21:05:19 UTC (rev 263) +++ libs/argparser/trunk/src/doc/examples/head.properties 2006-12-16 21:47:59 UTC (rev 264) @@ -1,7 +0,0 @@ -net.sf.japi.io.args.OptionType.REQUIRED=required -net.sf.japi.io.args.OptionType.OPTIONAL=optional -net.sf.japi.io.args.OptionType.TERMINAL=terminal -setBytes=Print the first N bytes of each file. -setLines=Print the first N lines of each file (default: 10). -setQuiet=Never print headers giving file names. -setVerbose=Always print headers giving file names. Deleted: libs/argparser/trunk/src/doc/examples/head_de.properties =================================================================== --- libs/argparser/trunk/src/doc/examples/head_de.properties 2006-12-15 21:05:19 UTC (rev 263) +++ libs/argparser/trunk/src/doc/examples/head_de.properties 2006-12-16 21:47:59 UTC (rev 264) @@ -1,7 +0,0 @@ -net.sf.japi.io.args.OptionType.REQUIRED=erforderlich -net.sf.japi.io.args.OptionType.OPTIONAL=optional -net.sf.japi.io.args.OptionType.TERMINAL=abbrechend -setBytes=Die ersten N Bytes jeder Datei ausgeben. -setLines=Die ersten N Zeilen jeder Datei ausgeben (Voreinstellung: 10). -setQuiet=Niemals Dateinamen vorab ausgeben. -setVerbose=Immer Dateinamen vorab ausgeben. Modified: libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java 2006-12-15 21:05:19 UTC (rev 263) +++ libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java 2006-12-16 21:47:59 UTC (rev 264) @@ -16,8 +16,8 @@ */ public abstract class BasicCommand implements Command { - /** The ResourceBundle for locale-specific output. */ - private final ResourceBundle resourceBundle = ResourceBundle.getBundle("net.sf.japi.io.args.messages"); + /** The ResourceBundle for locale-specific output of this class. */ + @NotNull private final ResourceBundle ownBundle = ResourceBundle.getBundle("net.sf.japi.io.args.messages"); /** * Whether to exit or not. @@ -116,7 +116,7 @@ * @return ResourceBundle for default locale. */ public ResourceBundle getBundle() { - return resourceBundle; + return ownBundle; } /** @@ -152,8 +152,12 @@ private String getString(final String key) throws MissingResourceException { try { return getBundle().getString(key); - } catch (MissingResourceException e) { - return resourceBundle.getString(key); + } catch (final MissingResourceException e) { + try { + return ResourceBundle.getBundle(getClass().getName()).getString(key); + } catch (final MissingResourceException e2) { + return ownBundle.getString(key); + } } } Modified: libs/argparser/trunk/src/net/sf/japi/io/args/package.html =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/package.html 2006-12-15 21:05:19 UTC (rev 263) +++ libs/argparser/trunk/src/net/sf/japi/io/args/package.html 2006-12-16 21:47:59 UTC (rev 264) @@ -50,5 +50,9 @@ The special option <code>--</code> will stop argument parsing. All strings that follow the <code>--</code>-option are treated as command arguments, not options, even if they start with <code>-</code>. </p> + <p> + The ArgParser library is built upon the JavaBeans concept. + A command is a JavaBean, the command's options are bean properties. + </p> </body> </html> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-06-25 12:21:41
|
Revision: 425 http://svn.sourceforge.net/japi/?rev=425&view=rev Author: christianhujer Date: 2007-06-25 05:21:40 -0700 (Mon, 25 Jun 2007) Log Message: ----------- Added missing newlines at end of files. Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/MissingArgumentExceptionTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/OptionTypeTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/RequiredOptionsMissingExceptionTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/TerminalExceptionTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/UnknownOptionExceptionTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/NoConverterFoundExceptionTest.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties 2007-06-25 12:07:16 UTC (rev 424) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties 2007-06-25 12:21:40 UTC (rev 425) @@ -28,4 +28,4 @@ java.lang.Integer.displayName=integer java.lang.Integer.description=Integer number (decimal, 0... octal, 0x... 0X... #... hexadecimal) java.lang.String.displayName=string -java.lang.String.description=Simple text \ No newline at end of file +java.lang.String.description=Simple text Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java 2007-06-25 12:07:16 UTC (rev 424) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java 2007-06-25 12:21:40 UTC (rev 425) @@ -85,4 +85,4 @@ Assert.assertNotNull(bundle); } -} // class BasicCommandTest \ No newline at end of file +} // class BasicCommandTest Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/MissingArgumentExceptionTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/MissingArgumentExceptionTest.java 2007-06-25 12:07:16 UTC (rev 424) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/MissingArgumentExceptionTest.java 2007-06-25 12:21:40 UTC (rev 425) @@ -49,4 +49,4 @@ testMissingArgumentException(); } -} // class MissingArgumentExceptionTest \ No newline at end of file +} // class MissingArgumentExceptionTest Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/OptionTypeTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/OptionTypeTest.java 2007-06-25 12:07:16 UTC (rev 424) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/OptionTypeTest.java 2007-06-25 12:21:40 UTC (rev 425) @@ -70,4 +70,4 @@ } } -} // class OptionTypeTest \ No newline at end of file +} // class OptionTypeTest Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/RequiredOptionsMissingExceptionTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/RequiredOptionsMissingExceptionTest.java 2007-06-25 12:07:16 UTC (rev 424) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/RequiredOptionsMissingExceptionTest.java 2007-06-25 12:21:40 UTC (rev 425) @@ -51,4 +51,4 @@ testRequiredOptionsMissingException(); } -} // class RequiredOptionsMissingExceptionTest \ No newline at end of file +} // class RequiredOptionsMissingExceptionTest Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/TerminalExceptionTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/TerminalExceptionTest.java 2007-06-25 12:07:16 UTC (rev 424) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/TerminalExceptionTest.java 2007-06-25 12:21:40 UTC (rev 425) @@ -50,4 +50,4 @@ Assert.assertEquals(exception.getReturnCode(), 1); } -} // class TerminalExceptionTest \ No newline at end of file +} // class TerminalExceptionTest Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/UnknownOptionExceptionTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/UnknownOptionExceptionTest.java 2007-06-25 12:07:16 UTC (rev 424) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/UnknownOptionExceptionTest.java 2007-06-25 12:21:40 UTC (rev 425) @@ -51,4 +51,4 @@ testUnknownOptionException(); } -} // class UnknownOptionExceptionTest \ No newline at end of file +} // class UnknownOptionExceptionTest Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java 2007-06-25 12:07:16 UTC (rev 424) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java 2007-06-25 12:21:40 UTC (rev 425) @@ -106,4 +106,4 @@ Assert.assertEquals(displayName, converter.getDisplayName(Locale.getDefault())); } -} // class AbstractConverterTest \ No newline at end of file +} // class AbstractConverterTest Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java 2007-06-25 12:07:16 UTC (rev 424) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java 2007-06-25 12:21:40 UTC (rev 425) @@ -145,4 +145,4 @@ } // class DummyConverter -} // class ConverterRegistryTest \ No newline at end of file +} // class ConverterRegistryTest Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java 2007-06-25 12:07:16 UTC (rev 424) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java 2007-06-25 12:21:40 UTC (rev 425) @@ -86,4 +86,4 @@ Assert.assertEquals(0x1ff, converter.convert("0777")); } -} // class IntegerConverterTest \ No newline at end of file +} // class IntegerConverterTest Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/NoConverterFoundExceptionTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/NoConverterFoundExceptionTest.java 2007-06-25 12:07:16 UTC (rev 424) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/NoConverterFoundExceptionTest.java 2007-06-25 12:21:40 UTC (rev 425) @@ -48,4 +48,4 @@ testGetTargetType(); } -} // class NoConverterFoundExceptionTest \ No newline at end of file +} // class NoConverterFoundExceptionTest This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-06-25 12:44:41
|
Revision: 428 http://svn.sourceforge.net/japi/?rev=428&view=rev Author: christianhujer Date: 2007-06-25 05:44:40 -0700 (Mon, 25 Jun 2007) Log Message: ----------- Fixed several javadoc issues. Modified Paths: -------------- libs/argparser/trunk/src/doc/examples/Head.java libs/argparser/trunk/src/doc/examples/Tail.java libs/argparser/trunk/src/net/sf/japi/io/args/RequiredOptionsMissingException.java libs/argparser/trunk/src/net/sf/japi/io/args/UnknownOptionException.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java Modified: libs/argparser/trunk/src/doc/examples/Head.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Head.java 2007-06-25 12:34:24 UTC (rev 427) +++ libs/argparser/trunk/src/doc/examples/Head.java 2007-06-25 12:44:40 UTC (rev 428) @@ -123,6 +123,10 @@ } } + /** Copies the first {@link #numItems} bytes from the supplied input stream to {@link System#out}. + * @param in InputStream to copy bytes from. + * @throws IOException in case of I/O errors. + */ private void copyBytes(@NotNull final InputStream in) throws IOException { final InputStream lin = in instanceof BufferedInputStream ? in : new BufferedInputStream(in); final byte[] buf = new byte[numItems]; @@ -130,6 +134,10 @@ System.out.write(buf, 0, bytesRead); } + /** Copies the first {@link #numItems} lines from the supplied input stream to {@link System#out}. + * @param in InputStream to copy lines from. + * @throws IOException in case of I/O errors. + */ private void copyLines(@NotNull final InputStream in) throws IOException { BufferedReader lin = new BufferedReader(new InputStreamReader(in)); String line; Modified: libs/argparser/trunk/src/doc/examples/Tail.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Tail.java 2007-06-25 12:34:24 UTC (rev 427) +++ libs/argparser/trunk/src/doc/examples/Tail.java 2007-06-25 12:44:40 UTC (rev 428) @@ -123,6 +123,10 @@ } } + /** Copies the last {@link #numItems} bytes from the supplied input stream to {@link System#out}. + * @param in InputStream to copy bytes from. + * @throws IOException in case of I/O errors. + */ private void copyBytes(@NotNull final InputStream in) throws IOException { final InputStream lin = in instanceof BufferedInputStream ? in : new BufferedInputStream(in); final byte[] buf = new byte[numItems]; @@ -137,6 +141,10 @@ System.out.write(buf, 0, bytesRead); } + /** Copies the last {@link #numItems} lines from the supplied input stream to {@link System#out}. + * @param in InputStream to copy lines from. + * @throws IOException in case of I/O errors. + */ private void copyLines(@NotNull final InputStream in) throws IOException { final String[] buf = new String[numItems]; final BufferedReader lin = new BufferedReader(new InputStreamReader(in)); Modified: libs/argparser/trunk/src/net/sf/japi/io/args/RequiredOptionsMissingException.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/RequiredOptionsMissingException.java 2007-06-25 12:34:24 UTC (rev 427) +++ libs/argparser/trunk/src/net/sf/japi/io/args/RequiredOptionsMissingException.java 2007-06-25 12:44:40 UTC (rev 428) @@ -36,7 +36,7 @@ * @param missingOptions options that were missing. * @throws IllegalArgumentException in case <var>missingOptions</var> was null or of zero length */ - public RequiredOptionsMissingException(@NotNull final String... missingOptions) { + public RequiredOptionsMissingException(@NotNull final String... missingOptions) throws IllegalArgumentException { super(createMessage(missingOptions)); this.missingOptions = missingOptions.clone(); } @@ -47,7 +47,7 @@ * @return message string * @throws IllegalArgumentException in case <var>missingOptions</var> was null or of zero length */ - private static String createMessage(final String... missingOptions) { + private static String createMessage(final String... missingOptions) throws IllegalArgumentException { if (missingOptions == null || missingOptions.length < 1) { throw new IllegalArgumentException("RequiredOptionsMissingException created but no missing options given."); } Modified: libs/argparser/trunk/src/net/sf/japi/io/args/UnknownOptionException.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/UnknownOptionException.java 2007-06-25 12:34:24 UTC (rev 427) +++ libs/argparser/trunk/src/net/sf/japi/io/args/UnknownOptionException.java 2007-06-25 12:44:40 UTC (rev 428) @@ -36,7 +36,7 @@ * @param unknownOptions options that were missing. * @throws IllegalArgumentException in case <var>unknownOptions</var> was null or of zero length */ - public UnknownOptionException(@NotNull final String... unknownOptions) { + public UnknownOptionException(@NotNull final String... unknownOptions) throws IllegalArgumentException { super(createMessage(unknownOptions)); this.unknownOptions = unknownOptions.clone(); } @@ -47,7 +47,7 @@ * @return message string * @throws IllegalArgumentException in case <var>unknownOptions</var> was null or of zero length */ - private static String createMessage(final String... unknownOptions) { + private static String createMessage(final String... unknownOptions) throws IllegalArgumentException { if (unknownOptions == null || unknownOptions.length < 1) { throw new IllegalArgumentException("UnknownOptionException created but no unknown options given."); } Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java 2007-06-25 12:34:24 UTC (rev 427) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java 2007-06-25 12:44:40 UTC (rev 428) @@ -70,6 +70,7 @@ /** * Get the Converter for a specific class. + * @param <T> target type of the class to get a converter for. * @param clazz Class to get Converter for. * @return <code>null</code> if no suited converter was found. */ @@ -80,6 +81,7 @@ /** * Register a Converter for a specific class. + * @param <T> target type of the class to register a converter for. * @param converter Converter to register */ public <T> void register(@NotNull final Converter<T> converter) { @@ -98,6 +100,7 @@ /** * Convenience method to convert a String to the desired target type using the default ConverterRegistry. + * @param <T> target type of the class to converter to. * @param targetType target type to convert to. * @param s String to convert * @return Converted String in the desired target type. @@ -114,6 +117,7 @@ /** * Convenience method to convert a String to the desired target type using the default ConverterRegistry. + * @param <T> target type of the class to converter to. * @param targetType target type to convert to. * @param locale Locale to perform the conversion in. * @param s String to convert. Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java 2007-06-25 12:34:24 UTC (rev 427) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java 2007-06-25 12:44:40 UTC (rev 428) @@ -29,7 +29,7 @@ */ public class BooleanConverterTest extends AbstractConverterTest<Boolean, BooleanConverter> { - /* + /** * Create an BooleanConverterTest. * @throws Exception in case of setup problems. */ Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java 2007-06-25 12:34:24 UTC (rev 427) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java 2007-06-25 12:44:40 UTC (rev 428) @@ -49,6 +49,7 @@ /** * Tests whether converting an arbitrary text throws a NumberFormatException. * @throws NumberFormatException Expected exception that's thrown if the test case is successful. + * @throws Exception In case of unexpected errors. */ @Test(expected=NumberFormatException.class) public void testConvertWithText() throws Exception { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-06-25 12:46:47
|
Revision: 429 http://svn.sourceforge.net/japi/?rev=429&view=rev Author: christianhujer Date: 2007-06-25 05:46:45 -0700 (Mon, 25 Jun 2007) Log Message: ----------- Fixed type javadoc issues. Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java 2007-06-25 12:44:40 UTC (rev 428) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/AbstractConverter.java 2007-06-25 12:46:45 UTC (rev 429) @@ -25,6 +25,7 @@ /** * Base class for the default converters. + * @param <T> target type to convert to. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ public abstract class AbstractConverter<T> implements Converter<T> { Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.java 2007-06-25 12:44:40 UTC (rev 428) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.java 2007-06-25 12:46:45 UTC (rev 429) @@ -24,6 +24,7 @@ /** * The Converter interface is used for converters that convert Strings into other types. + * @param <T> target type to convert to. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ public interface Converter<T> { Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java 2007-06-25 12:44:40 UTC (rev 428) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java 2007-06-25 12:46:45 UTC (rev 429) @@ -28,6 +28,8 @@ /** * Base class for tests for Converters. * Provides some basic testing methods. + * @param <V> target type to convert to. + * @param <T> converter type to test * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ public abstract class AbstractConverterTest<V, T extends Converter<V>> { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-06-25 13:42:55
|
Revision: 432 http://svn.sourceforge.net/japi/?rev=432&view=rev Author: christianhujer Date: 2007-06-25 06:42:52 -0700 (Mon, 25 Jun 2007) Log Message: ----------- Fixed all warnings that arise with our current checkstyle configuration. Modified Paths: -------------- libs/argparser/trunk/src/doc/examples/Cat.java libs/argparser/trunk/src/doc/examples/Head.java libs/argparser/trunk/src/doc/examples/Recode.java libs/argparser/trunk/src/doc/examples/Tail.java libs/argparser/trunk/src/doc/examples/Uniq.java libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java libs/argparser/trunk/src/test/net/sf/japi/io/args/CommandDummy.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/StringConverterTest.java Modified: libs/argparser/trunk/src/doc/examples/Cat.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Cat.java 2007-06-25 13:42:15 UTC (rev 431) +++ libs/argparser/trunk/src/doc/examples/Cat.java 2007-06-25 13:42:52 UTC (rev 432) @@ -33,8 +33,11 @@ */ public class Cat extends BasicCommand { + /** Size of the internal buffer for performing the Cat. */ + private static final int BUF_SIZE = 4096; + /** {@inheritDoc} */ - @SuppressWarnings({"InstanceMethodNamingConvention"}) + @SuppressWarnings({ "InstanceMethodNamingConvention" }) public int run(@NotNull final List<String> args) throws Exception { int returnCode = 0; if (args.size() == 0) { @@ -63,7 +66,7 @@ * @throws IOException in case of I/O problems. */ private void copy(@NotNull final InputStream in, @NotNull final OutputStream out) throws IOException { - final byte[] buf = new byte[4096]; + final byte[] buf = new byte[BUF_SIZE]; for (int bytesRead; (bytesRead = in.read(buf)) != -1;) { out.write(buf, 0, bytesRead); } Modified: libs/argparser/trunk/src/doc/examples/Head.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Head.java 2007-06-25 13:42:15 UTC (rev 431) +++ libs/argparser/trunk/src/doc/examples/Head.java 2007-06-25 13:42:52 UTC (rev 432) @@ -36,8 +36,11 @@ */ public class Head extends BasicCommand { + /** Default number of items to print. */ + private static final int DEFAULT_NUM_ITEMS = 10; + /** The number of items to print. */ - private int numItems = 10; + private int numItems = DEFAULT_NUM_ITEMS; /** The kind of items to print. * <code>false</code>: print lines. Modified: libs/argparser/trunk/src/doc/examples/Recode.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Recode.java 2007-06-25 13:42:15 UTC (rev 431) +++ libs/argparser/trunk/src/doc/examples/Recode.java 2007-06-25 13:42:52 UTC (rev 432) @@ -45,6 +45,9 @@ */ public class Recode extends BasicCommand { + /** Size of the internal buffer for performing the Recode. */ + private static final int BUF_SIZE = 4096; + /** The InputEncoding to use. */ private String inputEncoding; @@ -73,7 +76,7 @@ /** {@inheritDoc} */ @SuppressWarnings({"InstanceMethodNamingConvention"}) - public int run(@NotNull List<String> args) throws Exception { + public int run(@NotNull final List<String> args) throws Exception { int returnCode = 0; if (args.size() == 0) { recode(System.in, System.out); @@ -125,9 +128,11 @@ public void recode(final InputStream in, final OutputStream out) throws IOException { final Reader cin = new InputStreamReader(in, inputEncoding); final Writer cout = new OutputStreamWriter(out, outputEncoding); - final char[] buf = new char[4096]; + final char[] buf = new char[BUF_SIZE]; //noinspection StatementWithEmptyBody - for (int charsRead; (charsRead = cin.read(buf)) != -1; cout.write(buf, 0, charsRead)); + for (int charsRead; (charsRead = cin.read(buf)) != -1;) { + cout.write(buf, 0, charsRead); + } cout.flush(); } Modified: libs/argparser/trunk/src/doc/examples/Tail.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Tail.java 2007-06-25 13:42:15 UTC (rev 431) +++ libs/argparser/trunk/src/doc/examples/Tail.java 2007-06-25 13:42:52 UTC (rev 432) @@ -36,8 +36,11 @@ */ public class Tail extends BasicCommand { + /** Default number of items to print. */ + private static final int DEFAULT_NUM_ITEMS = 10; + /** The number of items to print. */ - private int numItems = 10; + private int numItems = DEFAULT_NUM_ITEMS; /** The kind of items to print. * <code>false</code>: print lines. @@ -150,7 +153,9 @@ final BufferedReader lin = new BufferedReader(new InputStreamReader(in)); int num = 0; //noinspection StatementWithEmptyBody - while ((buf[num++ % numItems] = lin.readLine()) != null); + while ((buf[num++ % numItems] = lin.readLine()) != null) { + // nothing to do, it's all in the condition. + } if (num >= numItems) { for (int i = num % numItems; i < numItems; i++) { System.out.println(buf[i]); Modified: libs/argparser/trunk/src/doc/examples/Uniq.java =================================================================== --- libs/argparser/trunk/src/doc/examples/Uniq.java 2007-06-25 13:42:15 UTC (rev 431) +++ libs/argparser/trunk/src/doc/examples/Uniq.java 2007-06-25 13:42:52 UTC (rev 432) @@ -66,7 +66,7 @@ /** {@inheritDoc} */ @SuppressWarnings({"InstanceMethodNamingConvention"}) - public int run(final @NotNull List<String> args) throws Exception { + public int run(@NotNull final List<String> args) throws Exception { int returnCode = 0; for (final String arg : args) { try { Modified: libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2007-06-25 13:42:15 UTC (rev 431) +++ libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2007-06-25 13:42:52 UTC (rev 432) @@ -39,7 +39,7 @@ * @todo Handling of - for STDIN as input argument filestream * @todo automatic printout of default values if property getter available. */ -public class ArgParser { +public final class ArgParser { /** The command to parse arguments to. */ private final Command command; Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/CommandDummy.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/CommandDummy.java 2007-06-25 13:42:15 UTC (rev 431) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/CommandDummy.java 2007-06-25 13:42:52 UTC (rev 432) @@ -31,7 +31,7 @@ /** {@inheritDoc} */ @SuppressWarnings({"InstanceMethodNamingConvention"}) - public int run(@NotNull List<String> args) throws Exception { + public int run(@NotNull final List<String> args) throws Exception { return 0; } Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java 2007-06-25 13:42:15 UTC (rev 431) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/AbstractConverterTest.java 2007-06-25 13:42:52 UTC (rev 432) @@ -38,7 +38,7 @@ private Class<V> targetClass; /** The converter testling. */ - protected T converter; + private T converter; /** * Create an AbstractConverterTest. @@ -108,4 +108,11 @@ Assert.assertEquals(displayName, converter.getDisplayName(Locale.getDefault())); } + /** Returns the converter that's being tested. + * @return The converter that's being tested. + */ + protected T getConverter() { + return converter; + } + } // class AbstractConverterTest Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java 2007-06-25 13:42:15 UTC (rev 431) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java 2007-06-25 13:42:52 UTC (rev 432) @@ -52,10 +52,10 @@ */ @Test public void testConvertTrue() throws Exception { - Assert.assertTrue(converter.convert("true")); - Assert.assertTrue(converter.convert("TRUE")); - Assert.assertTrue(converter.convert("True")); - Assert.assertTrue(converter.convert("1")); + Assert.assertTrue(getConverter().convert("true")); + Assert.assertTrue(getConverter().convert("TRUE")); + Assert.assertTrue(getConverter().convert("True")); + Assert.assertTrue(getConverter().convert("1")); } /** @@ -64,10 +64,10 @@ */ @Test public void testConvertFalse() throws Exception { - Assert.assertFalse(converter.convert("false")); - Assert.assertFalse(converter.convert("FALSE")); - Assert.assertFalse(converter.convert("False")); - Assert.assertFalse(converter.convert("0")); + Assert.assertFalse(getConverter().convert("false")); + Assert.assertFalse(getConverter().convert("FALSE")); + Assert.assertFalse(getConverter().convert("False")); + Assert.assertFalse(getConverter().convert("0")); } /** @@ -75,9 +75,9 @@ * @throws IllegalArgumentException Expected exception that's thrown if the test case is successful. * @throws Exception In case of unexpected errors. */ - @Test(expected=IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) public void testConvertOther() throws Exception { - converter.convert("foobarbuzz"); + getConverter().convert("foobarbuzz"); } } // class BooleanConverterTest Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java 2007-06-25 13:42:15 UTC (rev 431) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java 2007-06-25 13:42:52 UTC (rev 432) @@ -88,7 +88,7 @@ * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ @SuppressWarnings({"ConstantConditions"}) - private static class DummyConverter<T> implements Converter<T> { + private static final class DummyConverter<T> implements Converter<T> { /** Class for this converter. */ private final Class<T> targetClass; @@ -103,13 +103,13 @@ /** {@inheritDoc} */ @NotNull - public T convert(@NotNull String arg) throws Exception { + public T convert(@NotNull final String arg) throws Exception { return null; } /** {@inheritDoc} */ @NotNull - public T convert(@NotNull Locale locale, @NotNull String arg) throws Exception { + public T convert(@NotNull final Locale locale, @NotNull final String arg) throws Exception { return null; } @@ -127,7 +127,7 @@ /** {@inheritDoc} */ @NotNull - public String getDisplayName(@NotNull Locale locale) { + public String getDisplayName(@NotNull final Locale locale) { return null; } @@ -139,7 +139,7 @@ /** {@inheritDoc} */ @NotNull - public String getDescription(@NotNull Locale locale) { + public String getDescription(@NotNull final Locale locale) { return null; } Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java 2007-06-25 13:42:15 UTC (rev 431) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/IntegerConverterTest.java 2007-06-25 13:42:52 UTC (rev 432) @@ -51,9 +51,9 @@ * @throws NumberFormatException Expected exception that's thrown if the test case is successful. * @throws Exception In case of unexpected errors. */ - @Test(expected=NumberFormatException.class) + @Test(expected = NumberFormatException.class) public void testConvertWithText() throws Exception { - converter.convert("foo"); + getConverter().convert("foo"); } /** @@ -63,7 +63,7 @@ @Test public void testConvertDecimalNumbers() throws Exception { for (final int number : new int[] { Integer.MIN_VALUE, -100, -1, 0, 1, 100, Integer.MAX_VALUE }) { - Assert.assertEquals(number, converter.convert(Integer.toString(number))); + Assert.assertEquals(number, getConverter().convert(Integer.toString(number))); } } @@ -73,9 +73,9 @@ */ @Test public void testConvertHexadecimalNumbers() throws Exception { - Assert.assertEquals(0x50000, converter.convert("0x50000")); - Assert.assertEquals(0x50000, converter.convert("0X50000")); - Assert.assertEquals(0x50000, converter.convert("#50000")); + Assert.assertEquals(0x50000, getConverter().convert("0x50000")); + Assert.assertEquals(0x50000, getConverter().convert("0X50000")); + Assert.assertEquals(0x50000, getConverter().convert("#50000")); } /** @@ -84,7 +84,7 @@ */ @Test public void testConvertOctalNumbers() throws Exception { - Assert.assertEquals(0x1ff, converter.convert("0777")); + Assert.assertEquals(0x1ff, getConverter().convert("0777")); } } // class IntegerConverterTest Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/StringConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/StringConverterTest.java 2007-06-25 13:42:15 UTC (rev 431) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/StringConverterTest.java 2007-06-25 13:42:52 UTC (rev 432) @@ -52,7 +52,7 @@ */ @Test public void testConvert() throws Exception { - final String foo = converter.convert("foo"); + final String foo = getConverter().convert("foo"); Assert.assertEquals("StringConverter.convert(\"foo\") must return \"foo\".", "foo", foo); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-06-25 13:51:25
|
Revision: 433 http://svn.sourceforge.net/japi/?rev=433&view=rev Author: christianhujer Date: 2007-06-25 06:51:23 -0700 (Mon, 25 Jun 2007) Log Message: ----------- Cosmetic: reformatted code to use @NotNull in modifier annotation style always. Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/converter/BooleanConverter.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/BooleanConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/BooleanConverter.java 2007-06-25 13:42:52 UTC (rev 432) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/BooleanConverter.java 2007-06-25 13:51:23 UTC (rev 433) @@ -43,8 +43,7 @@ } /** {@inheritDoc} */ - @NotNull - public Boolean convert(@NotNull final Locale locale, @NotNull final String arg) throws Exception { + @NotNull public Boolean convert(@NotNull final Locale locale, @NotNull final String arg) throws Exception { for (final String s : TRUE_STRINGS) { if (s.equalsIgnoreCase(arg)) { return Boolean.TRUE; Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java 2007-06-25 13:42:52 UTC (rev 432) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java 2007-06-25 13:51:23 UTC (rev 433) @@ -102,44 +102,37 @@ } /** {@inheritDoc} */ - @NotNull - public T convert(@NotNull final String arg) throws Exception { + @NotNull public T convert(@NotNull final String arg) throws Exception { return null; } /** {@inheritDoc} */ - @NotNull - public T convert(@NotNull final Locale locale, @NotNull final String arg) throws Exception { + @NotNull public T convert(@NotNull final Locale locale, @NotNull final String arg) throws Exception { return null; } /** {@inheritDoc} */ - @NotNull - public Class<T> getTargetClass() { + @NotNull public Class<T> getTargetClass() { return targetClass; } /** {@inheritDoc} */ - @NotNull - public String getDisplayName() { + @NotNull public String getDisplayName() { return null; } /** {@inheritDoc} */ - @NotNull - public String getDisplayName(@NotNull final Locale locale) { + @NotNull public String getDisplayName(@NotNull final Locale locale) { return null; } /** {@inheritDoc} */ - @NotNull - public String getDescription() { + @NotNull public String getDescription() { return null; } /** {@inheritDoc} */ - @NotNull - public String getDescription(@NotNull final Locale locale) { + @NotNull public String getDescription(@NotNull final Locale locale) { return null; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-06-30 21:33:57
|
Revision: 488 http://svn.sourceforge.net/japi/?rev=488&view=rev Author: christianhujer Date: 2007-06-30 14:33:51 -0700 (Sat, 30 Jun 2007) Log Message: ----------- Improved automatic constructor invocation for types that don't have a specific converter configured. Added unit tests to cover that feature. Improved existing unit tests and increased test coverage. Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java Added Paths: ----------- libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConstructorConverter.java libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConstructorConverterTest.java Added: libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConstructorConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConstructorConverter.java (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConstructorConverter.java 2007-06-30 21:33:51 UTC (rev 488) @@ -0,0 +1,72 @@ +/* + * JAPI libs-argparser is a library for parsing command line arguments. + * Copyright (C) 2007 Christian Hujer. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.sf.japi.io.args.converter; + +import java.lang.reflect.Constructor; +import java.util.Locale; +import org.jetbrains.annotations.NotNull; + +/** + * Converter that performs a conversion by + * Created by IntelliJ IDEA. + * + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class ConstructorConverter<T> extends AbstractConverter<T> { + + /** The Constructor to invoke. */ + @NotNull private final Constructor<T> constructor; + + /** + * Create an AbstractConverter. + * @param targetClass TargetClass + * @throws NoSuchMethodException in case the target class does not supply a matching constructor. + */ + public ConstructorConverter(@NotNull final Class<T> targetClass) throws NoSuchMethodException { + super(targetClass); + constructor = getConstructor(targetClass); + } + + @NotNull public T convert(@NotNull final Locale locale, @NotNull final String arg) throws Exception { + return constructor.newInstance(arg); + } + + /** Returns a constructor that takes a single String argument for the target type. + * @param targetType type to get constructor for. + * @return Constructor for <var>targetType</var> + * @throws NoSuchMethodException in case the conversion failed. + */ + @NotNull public static <T> Constructor<T> getConstructor(@NotNull final Class<T> targetType) throws NoSuchMethodException { + return targetType.getConstructor(String.class); + } + + /** {@inheritDoc} */ + @Override + public boolean equals(final Object o) { + return o != null && o instanceof ConstructorConverter && constructor.equals(((ConstructorConverter) o).constructor); + } + + /** {@inheritDoc} */ + @Override + public int hashCode() { + return constructor.hashCode(); + } + +} // class ConstructorConverter Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConstructorConverter.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java 2007-06-30 20:34:36 UTC (rev 487) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConverterRegistry.java 2007-06-30 21:33:51 UTC (rev 488) @@ -21,12 +21,11 @@ import java.util.HashMap; import java.util.Iterator; -import java.util.Map; import java.util.Locale; -import java.lang.reflect.Constructor; -import sun.misc.Service; +import java.util.Map; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import sun.misc.Service; /** * Registry for Converters. @@ -74,11 +73,17 @@ * @param <T> target type of the class to get a converter for. * @param clazz Class to get Converter for. * @return <code>null</code> if no suited converter was found. - * @todo create a constructor converter if this is called from client code. */ @Nullable public <T> Converter<T> getConverter(@NotNull final Class<T> clazz) { //noinspection unchecked - return (Converter<T>) converters.get(clazz); + @Nullable Converter<T> converter = (Converter<T>) converters.get(clazz); + if (converter == null) { + converter = getConstructorConverter(clazz); + if (converter != null) { + register(converter); + } + } + return converter; } /** @@ -110,7 +115,10 @@ */ @NotNull public static <T> T convert(@NotNull final Class<T> targetType, @NotNull final String s) throws Exception { final Converter<T> converter = getInstance().getConverter(targetType); - return converter != null ? converter.convert(s) : construct(targetType, s); + if (converter != null) { + return converter.convert(s); + } + throw new NoConverterFoundException(targetType); } /** @@ -124,31 +132,22 @@ */ @NotNull public static <T> T convert(@NotNull final Class<T> targetType, @NotNull final Locale locale, @NotNull final String s) throws Exception { final Converter<T> converter = getInstance().getConverter(targetType); - return converter != null ? converter.convert(locale, s) : construct(targetType, s); + if (converter != null) { + return converter.convert(locale, s); + } + throw new NoConverterFoundException(targetType); } - /** Returns a constructor that takes a single String argument for the target type. - * @param targetType type to get constructor for. - * @return Constructor for <var>targetType</var> - * @throws NoConverterFoundException in case the conversion failed. - * @todo check whether the constructor is public. + /** Returns a constructor converter for the target type. + * @param targetType target type to convert to. + * @return ConstructorConverter for the target type. */ - @NotNull public static <T> Constructor<T> getConstructor(@NotNull final Class<T> targetType) throws NoConverterFoundException { + @Nullable public static <T> ConstructorConverter<T> getConstructorConverter(@NotNull final Class<T> targetType) { try { - return targetType.getConstructor(String.class); - } catch (final NoSuchMethodException e) { - throw new NoConverterFoundException(targetType); + return new ConstructorConverter<T>(targetType); + } catch (final Exception e) { + return null; } } - /** Performs a conversion by invoking a constructor. - * @param targetType target type to convert to. - * @param s String to convert. - * @return Converted String in the desired target type. - * @throws Exception in case the conversion failed. - */ - @NotNull public static <T> T construct(@NotNull final Class<T> targetType, @NotNull final String s) throws Exception { - return getConstructor(targetType).newInstance(s); - } - } // class ConverterRegistry Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2007-06-30 20:34:36 UTC (rev 487) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2007-06-30 21:33:51 UTC (rev 488) @@ -229,6 +229,8 @@ @SuppressWarnings({"InstanceMethodNamingConvention"}) public int run(@NotNull final List<String> args) { runCalled = true; + // okay, we won't change it. + //noinspection AssignmentToCollectionOrArrayFieldFromParameter this.args = args; return 0; } Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java 2007-06-30 20:34:36 UTC (rev 487) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/BooleanConverterTest.java 2007-06-30 21:33:51 UTC (rev 488) @@ -22,6 +22,7 @@ import net.sf.japi.io.args.converter.BooleanConverter; import org.junit.Test; import org.junit.Assert; +import java.util.Locale; /** * Tests for {@link BooleanConverter}. @@ -38,7 +39,7 @@ } /** - * Tests whether instanciating a BooleanConverter works. + * Tests that instanciating a BooleanConverter works. * @throws Exception (unexpected) */ @Test @@ -47,7 +48,7 @@ } /** - * Tests whether convert works for true. + * Tests that convert works for true. * @throws Exception In case of unexpected errors. */ @Test @@ -59,7 +60,7 @@ } /** - * Tests whether convert works for true. + * Tests that convert works for true. * @throws Exception In case of unexpected errors. */ @Test @@ -71,7 +72,35 @@ } /** - * Tests whether convert works for other Strings (IllegalArgumentException must be thrown). + * Tests that convert works for true. + * @throws Exception In case of unexpected errors. + */ + @Test + public void testLocalizedConvertTrue() throws Exception { + Assert.assertTrue(getConverter().convert(Locale.GERMANY, "true")); + Assert.assertTrue(getConverter().convert(Locale.GERMANY, "TRUE")); + Assert.assertTrue(getConverter().convert(Locale.GERMANY, "True")); + Assert.assertTrue(getConverter().convert(Locale.GERMANY, "1")); + Assert.assertTrue(getConverter().convert(Locale.GERMANY, "wahr")); + Assert.assertTrue(getConverter().convert(Locale.GERMANY, "ja")); + } + + /** + * Tests that convert works for true. + * @throws Exception In case of unexpected errors. + */ + @Test + public void testLocalizedConvertFalse() throws Exception { + Assert.assertFalse(getConverter().convert(Locale.GERMANY, "false")); + Assert.assertFalse(getConverter().convert(Locale.GERMANY, "FALSE")); + Assert.assertFalse(getConverter().convert(Locale.GERMANY, "False")); + Assert.assertFalse(getConverter().convert(Locale.GERMANY, "0")); + Assert.assertFalse(getConverter().convert(Locale.GERMANY, "falsch")); + Assert.assertFalse(getConverter().convert(Locale.GERMANY, "nein")); + } + + /** + * Tests that convert works for other Strings (IllegalArgumentException must be thrown). * @throws IllegalArgumentException Expected exception that's thrown if the test case is successful. * @throws Exception In case of unexpected errors. */ Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConstructorConverterTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConstructorConverterTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConstructorConverterTest.java 2007-06-30 21:33:51 UTC (rev 488) @@ -0,0 +1,118 @@ +/* + * JAPI libs-argparser is a library for parsing command line arguments. + * Copyright (C) 2007 Christian Hujer. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package test.net.sf.japi.io.args.converter; + +import java.io.File; +import java.lang.reflect.Constructor; +import java.util.Locale; +import net.sf.japi.io.args.converter.ConstructorConverter; +import org.junit.Assert; +import org.junit.Test; + +/** + * Test for {@link ConstructorConverter}. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class ConstructorConverterTest { + + /** Tests that creating a ConstructorConverter works. + * @throws Exception (unexpected) + */ + @Test + public void testConstructorConverter() throws Exception { + final ConstructorConverter<String> conv = new ConstructorConverter<String>(String.class); + Assert.assertEquals("foo", conv.convert("foo")); + Assert.assertEquals("foo", conv.convert(Locale.GERMANY, "foo")); + } + + /** Tests that creating a ConstructorConverter works. + * @throws Exception (unexpected) + */ + @Test + public void testConstructorConverter2() throws Exception { + final ConstructorConverter<File> conv = new ConstructorConverter<File>(File.class); + Assert.assertEquals(new File("foo"), conv.convert("foo")); + Assert.assertEquals(new File("foo"), conv.convert(Locale.GERMANY, "foo")); + } + + /** Tests that creating a ConstructorConverter for non-public constructors fails. + * @throws Exception (unexpected) + */ + @Test(expected = NoSuchMethodException.class) + public void testConstructorConverter3() throws Exception { + new ConstructorConverter<NonPublicConverter>(NonPublicConverter.class); + } + + /** Tests that {@link ConstructorConverter#equals(Object)} works. + * @throws Exception (unexpected) + */ + @Test + public void testEquals() throws Exception { + final ConstructorConverter<String> conv1 = new ConstructorConverter<String>(String.class); + final ConstructorConverter<String> conv2 = new ConstructorConverter<String>(String.class); + final ConstructorConverter<File> conv3 = new ConstructorConverter<File>(File.class); + Assert.assertTrue(conv1.equals(conv2)); + Assert.assertFalse(conv1.equals(new Object())); + //noinspection ObjectEqualsNull + Assert.assertFalse(conv1.equals(null)); + //noinspection EqualsBetweenInconvertibleTypes + Assert.assertFalse(conv1.equals(conv3)); + } + + /** Tests that {@link ConstructorConverter#hashCode()} works. + * @throws Exception (unexpected) + */ + @Test + public void testHashCode() throws Exception { + final ConstructorConverter<File> conv = new ConstructorConverter<File>(File.class); + final Constructor<File> constructor = File.class.getConstructor(String.class); + Assert.assertEquals(conv.hashCode(), constructor.hashCode()); + } + + /** Tests that {@link ConstructorConverter#getConstructor(Class)} works. + * @throws Exception (unexpected) + */ + @Test + public void testGetConstructor() throws Exception { + final Constructor<File> constructor = ConstructorConverter.getConstructor(File.class); + Assert.assertEquals(File.class.getConstructor(String.class), constructor); + } + + /** Tests that {@link ConstructorConverter#getConstructor(Class)} throws an Exception for non-public constructors. + * @throws Exception (unexpected) + */ + @Test(expected = NoSuchMethodException.class) + public void testGetConstructor2() throws Exception { + ConstructorConverter.getConstructor(NonPublicConverter.class); + } + + /** Dummy that represents a converter with a non-public constructor. */ + public static class NonPublicConverter { + + /** Non-public constructor for test. + * @param arg String argument. + */ + @SuppressWarnings({"UnusedDeclaration"}) + NonPublicConverter(final String arg) { + } + + } // class NonPublicConverter + +} // class ConstructorConverterTest Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConstructorConverterTest.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java 2007-06-30 20:34:36 UTC (rev 487) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/converter/ConverterRegistryTest.java 2007-06-30 21:33:51 UTC (rev 488) @@ -21,10 +21,13 @@ import net.sf.japi.io.args.converter.ConverterRegistry; import net.sf.japi.io.args.converter.Converter; +import net.sf.japi.io.args.converter.NoConverterFoundException; +import net.sf.japi.io.args.converter.ConstructorConverter; import org.junit.Test; import org.junit.Assert; import org.jetbrains.annotations.NotNull; import java.util.Locale; +import java.io.File; /** * Test for {@link ConverterRegistry}. @@ -84,6 +87,44 @@ } /** + * Tests whether {@link ConverterRegistry#convert(Class, String)} will automatically create a converter with a constructor. + * @throws Exception (unexpected) + */ + @Test + public void testConstruct() throws Exception { + Assert.assertEquals(new File("foo"), ConverterRegistry.convert(File.class, "foo")); + Assert.assertEquals(new File("foo"), ConverterRegistry.convert(File.class, Locale.GERMANY, "foo")); + } + + /** + * Tests whether {@link ConverterRegistry#convert(Class, String)} will throw the appropriate exception if no constructor converter is available. + * @throws Exception (unexpected) + */ + @Test(expected = NoConverterFoundException.class) + public void testConstructException() throws Exception { + ConverterRegistry.convert(System.class, "foo"); + } + + /** + * Tests whether {@link ConverterRegistry#convert(Class, Locale, String)} will throw the appropriate exception if no constructor converter is available. + * @throws Exception (unexpected) + */ + @Test(expected = NoConverterFoundException.class) + public void testConstructException2() throws Exception { + ConverterRegistry.convert(System.class, Locale.GERMANY, "foo"); + } + + /** + * Tests whether {@link ConverterRegistry#getConstructorConverter(Class)} returns appropriate values. + * @throws Exception (unexpected) + */ + @Test + public void testGetConstructorConverter() throws Exception { + Assert.assertEquals(new ConstructorConverter<String>(String.class), ConverterRegistry.getConstructorConverter(String.class)); + Assert.assertEquals(null, ConverterRegistry.getConstructorConverter(System.class)); + } + + /** * Dummy Converter. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-07-04 18:26:51
|
Revision: 493 http://svn.sourceforge.net/japi/?rev=493&view=rev Author: christianhujer Date: 2007-07-04 11:26:50 -0700 (Wed, 04 Jul 2007) Log Message: ----------- Test and fix for [ 1747891 ] helpHeader and helpFooter not read from classname bundle Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java Added Paths: ----------- libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommand.java libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommand.properties libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommandMyBundle.properties Modified: libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java 2007-07-01 17:22:38 UTC (rev 492) +++ libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java 2007-07-04 18:26:50 UTC (rev 493) @@ -170,16 +170,20 @@ * @return String from the ResourceBundles. * @throws MissingResourceException In case all tries for retrieving a value for <var>key</var> failed. */ - @NotNull private String getString(@NotNull final String key) throws MissingResourceException { - try { - return getBundle().getString(key); - } catch (final MissingResourceException e) { + @NotNull public String getString(@NotNull final String key) throws MissingResourceException { + final ResourceBundle bundle = getBundle(); + if (bundle != ownBundle) { try { - return ResourceBundle.getBundle(getClass().getName()).getString(key); - } catch (final MissingResourceException e2) { - return ownBundle.getString(key); + return getBundle().getString(key); + } catch (final MissingResourceException ignore) { + // not serious } } + try { + return ResourceBundle.getBundle(getClass().getName()).getString(key); + } catch (final MissingResourceException e2) { + return ownBundle.getString(key); + } } } // class BasicCommand Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java 2007-07-01 17:22:38 UTC (rev 492) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/BasicCommandTest.java 2007-07-04 18:26:50 UTC (rev 493) @@ -85,4 +85,34 @@ Assert.assertNotNull(bundle); } + /** + * Tests whether {@link BasicCommand#getString(String)} returns the value from the correct bundle. + * testGetString1 must be defined in RBMockCommand.properties with value String1FromDefaultBundle. + * testGetString1 must be defined in RBMockCommandMyBundle.properties with value String1FromMyBundle. + * testGetString2 must be defined in RBMockCommand.properties with value String2FromDefaultBundle. + * testGetString2 must not be defined in RBMockCommandMyBundle.properties. + */ + @Test + public void testGetString() { + final RBMockCommand mock = new RBMockCommand(); + mock.setReturnOwnBundle(false); + Assert.assertEquals("String1FromDefaultBundle", mock.getString("testGetString1")); + Assert.assertEquals("String2FromDefaultBundle", mock.getString("testGetString2")); + mock.setReturnOwnBundle(true); + Assert.assertEquals("String1FromMyBundle", mock.getString("testGetString1")); + Assert.assertEquals("String2FromDefaultBundle", mock.getString("testGetString2")); + } + + /** + * Tests whether {@link BasicCommand#getHelpHeader()} returns the value from the correct bundle. + */ + @Test + public void testGetHelpHeader() { + final RBMockCommand mock = new RBMockCommand(); + mock.setReturnOwnBundle(false); + Assert.assertEquals("HelpHeaderFromDefaultBundle", mock.getString("helpHeader")); + mock.setReturnOwnBundle(true); + Assert.assertEquals("HelpHeaderFromMyBundle", mock.getString("helpHeader")); + } + } // class BasicCommandTest Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommand.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommand.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommand.java 2007-07-04 18:26:50 UTC (rev 493) @@ -0,0 +1,58 @@ +/* + * JAPI libs-argparser is a library for parsing command line arguments. + * Copyright (C) 2007 Christian Hujer. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package test.net.sf.japi.io.args; + +import net.sf.japi.io.args.BasicCommand; +import java.util.ResourceBundle; +import java.util.List; +import org.jetbrains.annotations.NotNull; + +/** + * Mock Command for {@link ResourceBundle} related tests of {@link BasicCommand}. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class RBMockCommand extends BasicCommand { + + /** My own ResourceBundle. */ + private ResourceBundle myBundle = ResourceBundle.getBundle("test.net.sf.japi.io.args.RBMockCommandMyBundle"); + + /** Whether to return its own ResourceBundle. */ + private boolean returnOwnBundle; + + /** {@inheritDoc} */ + @SuppressWarnings({"InstanceMethodNamingConvention"}) + public int run(@NotNull final List<String> args) throws Exception { + return 0; + } + + /** {@inheritDoc} */ + @Override @NotNull public ResourceBundle getBundle() { + return returnOwnBundle ? myBundle : super.getBundle(); //To change body of overridden methods use File | Settings | File Templates. + } + + /** + * Sets whether {@link #getBundle()} should return the mock's own bundle or the superclass' bundle. + * @param returnOwnBundle <code>true</code> if {@link #getBundle()} should return the mock's own bundle, otherwise <code>false</code>. + */ + public void setReturnOwnBundle(final boolean returnOwnBundle) { + this.returnOwnBundle = returnOwnBundle; + } + +} // class RBMockCommand Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommand.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommand.properties =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommand.properties (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommand.properties 2007-07-04 18:26:50 UTC (rev 493) @@ -0,0 +1,21 @@ +# +# JAPI libs-argparser is a library for parsing command line arguments. +# Copyright (C) 2007 Christian Hujer. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +# +testGetString1=String1FromDefaultBundle +testGetString2=String2FromDefaultBundle +helpHeader=HelpHeaderFromDefaultBundle Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommand.properties ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommandMyBundle.properties =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommandMyBundle.properties (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommandMyBundle.properties 2007-07-04 18:26:50 UTC (rev 493) @@ -0,0 +1,20 @@ +# +# JAPI libs-argparser is a library for parsing command line arguments. +# Copyright (C) 2007 Christian Hujer. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +# +testGetString1=String1FromMyBundle +helpHeader=HelpHeaderFromMyBundle Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/RBMockCommandMyBundle.properties ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-07-04 18:45:22
|
Revision: 494 http://svn.sourceforge.net/japi/?rev=494&view=rev Author: christianhujer Date: 2007-07-04 11:45:20 -0700 (Wed, 04 Jul 2007) Log Message: ----------- Test and fix for [ 1747898 ] Option list in --help should be sorted case insensitive Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/MethodOptionComparator.java Added Paths: ----------- libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/MethodOptionComparator.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/MethodOptionComparator.java 2007-07-04 18:26:50 UTC (rev 493) +++ libs/argparser/trunk/src/net/sf/japi/io/args/MethodOptionComparator.java 2007-07-04 18:45:20 UTC (rev 494) @@ -40,7 +40,7 @@ final String[] names2 = option2.value(); Arrays.sort(names1); Arrays.sort(names2); - return names1[0].compareTo(names2[0]); + return String.CASE_INSENSITIVE_ORDER.compare(names1[0], names2[0]); } } // class MethodOptionComparator Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java 2007-07-04 18:45:20 UTC (rev 494) @@ -0,0 +1,89 @@ +/* + * JAPI libs-argparser is a library for parsing command line arguments. + * Copyright (C) 2007 Christian Hujer. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package test.net.sf.japi.io.args; + +import net.sf.japi.io.args.MethodOptionComparator; +import net.sf.japi.io.args.BasicCommand; +import net.sf.japi.io.args.Option; +import org.junit.Test; +import org.junit.Assert; +import org.jetbrains.annotations.NotNull; +import java.lang.reflect.Method; +import java.util.Comparator; +import java.util.List; + +/** + * Test for {@link MethodOptionComparator}. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class MethodOptionComparatorTest { + + /** Tests whether comparing two methods yields the expected result. + * @throws NoSuchMethodException (unexpected) + */ + @Test + public void testCompare() throws NoSuchMethodException { + final Comparator<Method> comparator = MethodOptionComparator.INSTANCE; + final Class<MockCommand> cmdClass = MockCommand.class; + final Method mFoo = cmdClass.getMethod("foo"); + final Method mBar = cmdClass.getMethod("bar"); + final Method mBuzz = cmdClass.getMethod("buzz"); + final Method mA = cmdClass.getMethod("a"); + final Method mZ = cmdClass.getMethod("Z"); + Assert.assertTrue("-a must be sorted before -b / --bar.", comparator.compare(mA, mBar) < 0); + Assert.assertTrue("-b / --bar must be sorted before --buzz.", comparator.compare(mBar, mBuzz) < 0); + Assert.assertTrue("--buzz must be sorted before -f / --foo.", comparator.compare(mBuzz, mFoo) < 0); + Assert.assertTrue("-f / --foo must be sorted before -Z.", comparator.compare(mFoo, mZ) < 0); + } + + /** Mock Command with methods that should be properly sorted. + * The sorting should be: + * a(), bar(), buzz(), foo(), Z(). + */ + private static class MockCommand extends BasicCommand { + + /** Dummy command method. */ + @Option({"f", "foo"}) + public void foo() {} + + /** Dummy command method. */ + @Option({"b", "bar"}) + public void bar() {} + + /** Dummy command method. */ + @Option({"buzz"}) + public void buzz() {} + + /** Dummy command method. */ + @Option({"Z"}) + public void Z() {} + + /** Dummy command method. */ + @Option({"a"}) + public void a() {} + + /** {@inheritDoc} */ + @SuppressWarnings({"InstanceMethodNamingConvention"}) + public int run(@NotNull final List<String> args) throws Exception { + return 0; + } + } + +} // class MethodOptionComparatorTest Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-07-04 20:06:01
|
Revision: 495 http://svn.sourceforge.net/japi/?rev=495&view=rev Author: christianhujer Date: 2007-07-04 13:05:59 -0700 (Wed, 04 Jul 2007) Log Message: ----------- Added LogCommand. Modified Paths: -------------- libs/argparser/trunk/src/META-INF/services/net.sf.japi.io.args.converter.Converter libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter_de.properties libs/argparser/trunk/src/net/sf/japi/io/args/messages.properties libs/argparser/trunk/src/net/sf/japi/io/args/messages_de.properties Added Paths: ----------- libs/argparser/trunk/src/net/sf/japi/io/args/LogCommand.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/LogLevelConverter.java Modified: libs/argparser/trunk/src/META-INF/services/net.sf.japi.io.args.converter.Converter =================================================================== --- libs/argparser/trunk/src/META-INF/services/net.sf.japi.io.args.converter.Converter 2007-07-04 18:45:20 UTC (rev 494) +++ libs/argparser/trunk/src/META-INF/services/net.sf.japi.io.args.converter.Converter 2007-07-04 20:05:59 UTC (rev 495) @@ -2,3 +2,4 @@ net.sf.japi.io.args.converter.InputStreamConverter net.sf.japi.io.args.converter.IntegerConverter net.sf.japi.io.args.converter.StringConverter +net.sf.japi.io.args.converter.LogLevelConverter Added: libs/argparser/trunk/src/net/sf/japi/io/args/LogCommand.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/LogCommand.java (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/LogCommand.java 2007-07-04 20:05:59 UTC (rev 495) @@ -0,0 +1,55 @@ +/* + * JAPI libs-argparser is a library for parsing command line arguments. + * Copyright (C) 2007 Christian Hujer. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.sf.japi.io.args; + +import org.jetbrains.annotations.NotNull; +import java.util.logging.Logger; +import java.util.logging.Level; + +/** + * Subclass of BasicCommand that provides logging through {@link java.util.logging}. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public abstract class LogCommand extends BasicCommand { + + /** The Logger to use. */ + protected final Logger log; + + /** Create a LogCommand with the specified log. + * @param log Logger to use + */ + protected LogCommand(@NotNull final Logger log) { + this.log = log; + } + + /** Create a LogCommand which automatically creates a log that matches the class name. */ + protected LogCommand() { + log = Logger.getLogger(getClass().getName(), getClass().getName()); + } + + /** Sets the log level to log. + * @param level LogLevel to log. + */ + @Option({"l", "level"}) + public void setLevel(@NotNull final Level level) { + log.setLevel(level); + } + +} // class LogCommand Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/LogCommand.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties 2007-07-04 18:45:20 UTC (rev 494) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter.properties 2007-07-04 20:05:59 UTC (rev 495) @@ -29,3 +29,5 @@ java.lang.Integer.description=Integer number (decimal, 0... octal, 0x... 0X... #... hexadecimal) java.lang.String.displayName=string java.lang.String.description=Simple text +java.util.logging.Level.displayName=level +java.util.logging.Level.description=Log Level Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter_de.properties =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter_de.properties 2007-07-04 18:45:20 UTC (rev 494) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/Converter_de.properties 2007-07-04 20:05:59 UTC (rev 495) @@ -29,3 +29,5 @@ java.lang.Integer.description=Ganzzahl (dezimal, 0... oktal, 0x... 0X... #... hexadezimal) java.lang.String.displayName=string java.lang.String.description=Einfacher Text. +java.util.logging.Level.displayName=level +java.util.logging.Level.description=Log Level Added: libs/argparser/trunk/src/net/sf/japi/io/args/converter/LogLevelConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/LogLevelConverter.java (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/LogLevelConverter.java 2007-07-04 20:05:59 UTC (rev 495) @@ -0,0 +1,43 @@ +/* + * JAPI libs-argparser is a library for parsing command line arguments. + * Copyright (C) 2007 Christian Hujer. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.sf.japi.io.args.converter; + +import java.util.logging.Level; +import java.util.Locale; +import org.jetbrains.annotations.NotNull; + +/** + * Created by IntelliJ IDEA. + * + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class LogLevelConverter extends AbstractConverter<Level> { + + /** Create a LogLevelConverter. */ + public LogLevelConverter() { + super(Level.class); + } + + /** {@inheritDoc} */ + @NotNull public Level convert(@NotNull final Locale locale, @NotNull final String arg) throws Exception { + return Level.parse(arg); + } + +} // class LogLevelConverter Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/converter/LogLevelConverter.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/net/sf/japi/io/args/messages.properties =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/messages.properties 2007-07-04 18:45:20 UTC (rev 494) +++ libs/argparser/trunk/src/net/sf/japi/io/args/messages.properties 2007-07-04 20:05:59 UTC (rev 495) @@ -28,3 +28,4 @@ setNotExiting=Don't quit Java VM (default). helpHeader= helpFooter= +setLevel=Sets the log level. Modified: libs/argparser/trunk/src/net/sf/japi/io/args/messages_de.properties =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/messages_de.properties 2007-07-04 18:45:20 UTC (rev 494) +++ libs/argparser/trunk/src/net/sf/japi/io/args/messages_de.properties 2007-07-04 20:05:59 UTC (rev 495) @@ -28,3 +28,4 @@ setNotExiting=Java VM nicht beenden (Voreinstellung). helpHeader= helpFooter= +setLevel=Legt den Log-Level fest. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-07-05 20:06:55
|
Revision: 497 http://svn.sourceforge.net/japi/?rev=497&view=rev Author: christianhujer Date: 2007-07-05 13:06:54 -0700 (Thu, 05 Jul 2007) Log Message: ----------- Fix: [ 1748308 ] Options that only differ in case are not listed in --help Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/MethodOptionComparator.java libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/MethodOptionComparator.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/MethodOptionComparator.java 2007-07-05 20:05:05 UTC (rev 496) +++ libs/argparser/trunk/src/net/sf/japi/io/args/MethodOptionComparator.java 2007-07-05 20:06:54 UTC (rev 497) @@ -20,8 +20,8 @@ package net.sf.japi.io.args; import java.lang.reflect.Method; +import java.util.Arrays; import java.util.Comparator; -import java.util.Arrays; import org.jetbrains.annotations.NotNull; /** Compares methods by their options. @@ -40,7 +40,11 @@ final String[] names2 = option2.value(); Arrays.sort(names1); Arrays.sort(names2); - return String.CASE_INSENSITIVE_ORDER.compare(names1[0], names2[0]); + int result = String.CASE_INSENSITIVE_ORDER.compare(names1[0], names2[0]); + if (result == 0) { + result = names1[0].compareTo(names2[0]); + } + return result; } } // class MethodOptionComparator Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java 2007-07-05 20:05:05 UTC (rev 496) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java 2007-07-05 20:06:54 UTC (rev 497) @@ -19,15 +19,15 @@ package test.net.sf.japi.io.args; +import java.lang.reflect.Method; +import java.util.Comparator; +import java.util.List; +import net.sf.japi.io.args.BasicCommand; import net.sf.japi.io.args.MethodOptionComparator; -import net.sf.japi.io.args.BasicCommand; import net.sf.japi.io.args.Option; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; import org.junit.Test; -import org.junit.Assert; -import org.jetbrains.annotations.NotNull; -import java.lang.reflect.Method; -import java.util.Comparator; -import java.util.List; /** * Test for {@link MethodOptionComparator}. @@ -53,6 +53,19 @@ Assert.assertTrue("-f / --foo must be sorted before -Z.", comparator.compare(mFoo, mZ) < 0); } + /** Tests whether comparing two methods that only differ in case yields the difference. + * Test for <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=1748308&group_id=149894&atid=776737">[ 1748308 ] Options that only differ in case are not listed in --help</a> + * @throws NoSuchMethodException (unexpected) + */ + @Test + public void testCompareCase() throws NoSuchMethodException { + final Comparator<Method> comparator = MethodOptionComparator.INSTANCE; + final Class<MockCommand> cmdClass = MockCommand.class; + final Method mC1 = cmdClass.getMethod("c"); + final Method mC2 = cmdClass.getMethod("C"); + Assert.assertTrue("-c and -C must not be the same.", comparator.compare(mC1, mC2) != 0); + } + /** Mock Command with methods that should be properly sorted. * The sorting should be: * a(), bar(), buzz(), foo(), Z(). @@ -79,6 +92,14 @@ @Option({"a"}) public void a() {} + /** Dummy command method. */ + @Option({"c"}) + public void c() {} + + /** Dummy command method. */ + @Option({"C"}) + public void C() {} + /** {@inheritDoc} */ @SuppressWarnings({"InstanceMethodNamingConvention"}) public int run(@NotNull final List<String> args) throws Exception { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-07-05 20:52:13
|
Revision: 500 http://svn.sourceforge.net/japi/?rev=500&view=rev Author: christianhujer Date: 2007-07-05 13:52:11 -0700 (Thu, 05 Jul 2007) Log Message: ----------- Fixed checkstyle issues. Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/LogCommand.java libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConstructorConverter.java libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/LogCommand.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/LogCommand.java 2007-07-05 20:48:04 UTC (rev 499) +++ libs/argparser/trunk/src/net/sf/japi/io/args/LogCommand.java 2007-07-05 20:52:11 UTC (rev 500) @@ -30,7 +30,7 @@ public abstract class LogCommand extends BasicCommand { /** The Logger to use. */ - protected final Logger log; + private final Logger log; /** Create a LogCommand with the specified log. * @param log Logger to use @@ -52,4 +52,11 @@ log.setLevel(level); } + /** Returns the logger. + * @return The Logger. + */ + public Logger getLog() { + return log; + } + } // class LogCommand Modified: libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConstructorConverter.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConstructorConverter.java 2007-07-05 20:48:04 UTC (rev 499) +++ libs/argparser/trunk/src/net/sf/japi/io/args/converter/ConstructorConverter.java 2007-07-05 20:52:11 UTC (rev 500) @@ -25,8 +25,7 @@ /** * Converter that performs a conversion by - * Created by IntelliJ IDEA. - * + * @param <T> target type to convert to. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ public class ConstructorConverter<T> extends AbstractConverter<T> { Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java 2007-07-05 20:48:04 UTC (rev 499) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/MethodOptionComparatorTest.java 2007-07-05 20:52:11 UTC (rev 500) @@ -46,7 +46,7 @@ final Method mBar = cmdClass.getMethod("bar"); final Method mBuzz = cmdClass.getMethod("buzz"); final Method mA = cmdClass.getMethod("a"); - final Method mZ = cmdClass.getMethod("Z"); + final Method mZ = cmdClass.getMethod("z"); Assert.assertTrue("-a must be sorted before -b / --bar.", comparator.compare(mA, mBar) < 0); Assert.assertTrue("-b / --bar must be sorted before --buzz.", comparator.compare(mBar, mBuzz) < 0); Assert.assertTrue("--buzz must be sorted before -f / --foo.", comparator.compare(mBuzz, mFoo) < 0); @@ -61,8 +61,8 @@ public void testCompareCase() throws NoSuchMethodException { final Comparator<Method> comparator = MethodOptionComparator.INSTANCE; final Class<MockCommand> cmdClass = MockCommand.class; - final Method mC1 = cmdClass.getMethod("c"); - final Method mC2 = cmdClass.getMethod("C"); + final Method mC1 = cmdClass.getMethod("c1"); + final Method mC2 = cmdClass.getMethod("c2"); Assert.assertTrue("-c and -C must not be the same.", comparator.compare(mC1, mC2) != 0); } @@ -74,31 +74,31 @@ /** Dummy command method. */ @Option({"f", "foo"}) - public void foo() {} + public void foo() { } /** Dummy command method. */ @Option({"b", "bar"}) - public void bar() {} + public void bar() { } /** Dummy command method. */ @Option({"buzz"}) - public void buzz() {} + public void buzz() { } /** Dummy command method. */ @Option({"Z"}) - public void Z() {} + public void z() { } /** Dummy command method. */ @Option({"a"}) - public void a() {} + public void a() { } /** Dummy command method. */ @Option({"c"}) - public void c() {} + public void c1() { } /** Dummy command method. */ @Option({"C"}) - public void C() {} + public void c2() { } /** {@inheritDoc} */ @SuppressWarnings({"InstanceMethodNamingConvention"}) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-07-09 20:54:34
|
Revision: 525 http://svn.sourceforge.net/japi/?rev=525&view=rev Author: christianhujer Date: 2007-07-09 13:54:31 -0700 (Mon, 09 Jul 2007) Log Message: ----------- [ 1750193 ] Partial read of command line arguments from a file Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java Added Paths: ----------- libs/argparser/trunk/src/net/sf/japi/io/args/TokenReader.java libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest_OptionsFileSingleLine libs/argparser/trunk/src/test/net/sf/japi/io/args/TokenReaderTest.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2007-07-09 19:27:05 UTC (rev 524) +++ libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2007-07-09 20:54:31 UTC (rev 525) @@ -30,6 +30,8 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; +import java.io.FileInputStream; +import java.io.FileNotFoundException; import net.sf.japi.io.args.converter.ConverterRegistry; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -75,7 +77,7 @@ this.command = command; commandClass = command.getClass(); initMethods(); - final List<String> argList = new ArrayList<String>(Arrays.asList(args)); + final List<String> argList = getAllArguments(Arrays.asList(args)); argIterator = argList.listIterator(); parse(); checkRequiredMethods(); @@ -92,6 +94,44 @@ } /** + * Returns a list of all arguments after parsing arguments files. + */ + public List<String> getAllArguments(@NotNull final List<String> args) { + final List<String> argList = new ArrayList<String>(args); + for (final ListIterator<String> iterator = argList.listIterator(); iterator.hasNext();) { + final String arg = iterator.next(); + if (arg.equals("--")) { + break; + } + if (arg.startsWith("@")) { + iterator.remove(); + for (final String insertArg : getAllArguments(readFromFile(arg.substring(1)))) { + iterator.add(insertArg); + } + } + } + return argList; + } + + /** + * Returns a tokenized unparsed list of arguments from an arguments file. + */ + public List<String> readFromFile(@NotNull final String filename) { + final List<String> args = new ArrayList<String>(); + final TokenReader in; + try { + in = new TokenReader(new FileInputStream(filename)); + } catch (FileNotFoundException e) { + // TODO TODO TODO TODO TODO + return args; + } + for (final String token : in) { + args.add(token); + } + return args; + } + + /** * Checks that all required methods have been invoked. * @throws RequiredOptionsMissingException in case a required command line argument was missing */ Added: libs/argparser/trunk/src/net/sf/japi/io/args/TokenReader.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/TokenReader.java (rev 0) +++ libs/argparser/trunk/src/net/sf/japi/io/args/TokenReader.java 2007-07-09 20:54:31 UTC (rev 525) @@ -0,0 +1,147 @@ +/* + * JAPI libs-argparser is a library for parsing command line arguments. + * Copyright (C) 2007 Christian Hujer. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.sf.japi.io.args; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.Iterator; +import java.util.NoSuchElementException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * A TokenReader reads arguments from a file, non-recursive. + * That means the arguments are read regarding a certain argument syntax, but remain otherwise unparsed. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class TokenReader implements Closeable, Iterable<String>, Iterator<String> { + + /** Reader to read from. */ + @NotNull private Reader in; + + /** The next token. */ + @Nullable String next; + + /** Creates a TokenReader. + * @param in InputStream to read from. + */ + public TokenReader(@NotNull final InputStream in) { + this.in = new InputStreamReader(in); + next = readNextToken(); + } + + /** {@inheritDoc} */ + public void close() throws IOException { + in.close(); + } + + /** {@inheritDoc} */ + @NotNull public Iterator<String> iterator() { + return this; + } + + /** {@inheritDoc} */ + public boolean hasNext() { + return next != null; + } + + /** {@inheritDoc} */ + @NotNull public String next() { + if (next == null) { + throw new NoSuchElementException(); + } + try { + return next; + } finally { + next = readNextToken(); + } + } + + /** {@inheritDoc} */ + public void remove() { + throw new UnsupportedOperationException(); + } + + /** Reads the next token from the underlying reader. + * @return Next token read from the underlying reader or <code>null</code> if no more tokens are available. + */ + @Nullable public String readNextToken() { + final StringBuilder nextToken = new StringBuilder(); + boolean tokenValid = false; + Mode mode = Mode.WHITESPACE; + try { + for (int rc; (rc = in.read()) != -1;) { + final char c = (char) rc; + switch (mode) { + case WHITESPACE: + if (Character.isWhitespace(c)) { + } else if (c == '"') { + mode = Mode.STRING; + tokenValid = true; + } else { + nextToken.append(c); + mode = Mode.NORMAL; + tokenValid = true; + } + break; + case NORMAL: + if (Character.isWhitespace(c)) { + assert tokenValid; + assert nextToken.length() != 0; + return nextToken.toString(); + } else if (c == '"') { + mode = Mode.STRING; + } else { + nextToken.append(c); + } + break; + case STRING: + if (c == '"') { + mode = Mode.NORMAL; + } else if (c == '\\') { + mode = Mode.STRING_ESCAPE; + } else { + nextToken.append(c); + } + break; + case STRING_ESCAPE: + nextToken.append(c); + mode = Mode.STRING; + break; + } + } + } catch (final IOException ignore) { + // ignore + } + return tokenValid ? nextToken.toString() : null; + } + + /** The mode of the tokenizer. */ + private enum Mode { + WHITESPACE, + NORMAL, + STRING, + STRING_ESCAPE + } + +} // class TokenReader Property changes on: libs/argparser/trunk/src/net/sf/japi/io/args/TokenReader.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2007-07-09 19:27:05 UTC (rev 524) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2007-07-09 20:54:31 UTC (rev 525) @@ -227,6 +227,25 @@ } /** + * Tests whether reading options from a file works. + * @throws RequiredOptionsMissingException (unexpected) + * @throws TerminalException (unexpected) + * @throws UnknownOptionException (unexpected) + * @throws MissingArgumentException (unexpected) + */ + @Test + public void testOptionsFromFileSingleLine() throws RequiredOptionsMissingException, MissingArgumentException, TerminalException, UnknownOptionException { + final MockCommand command = new MockCommand(); + ArgParser.parseAndRun(command, "@src/test/net/sf/japi/io/args/ArgParserTest_OptionsFileSingleLine"); + final List<String> args = command.getArgs(); + Assert.assertEquals("Option value must be stored.", "fooInput", command.getInput()); + Assert.assertTrue("Run must be called even with zero arguments.", command.isRunCalled()); + Assert.assertEquals("Arguments must be stored.", 2, args.size()); + Assert.assertEquals("Argument foo must be stored.", "foo", args.get(0)); + Assert.assertEquals("Argument bar must be stored.", "bar", args.get(1)); + } + + /** * This MockCommand serves as a command for performing simple tests. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest_OptionsFileSingleLine =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest_OptionsFileSingleLine (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest_OptionsFileSingleLine 2007-07-09 20:54:31 UTC (rev 525) @@ -0,0 +1 @@ +-i fooInput foo bar \ No newline at end of file Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest_OptionsFileSingleLine ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF Added: libs/argparser/trunk/src/test/net/sf/japi/io/args/TokenReaderTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/TokenReaderTest.java (rev 0) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/TokenReaderTest.java 2007-07-09 20:54:31 UTC (rev 525) @@ -0,0 +1,162 @@ +/* + * JAPI libs-argparser is a library for parsing command line arguments. + * Copyright (C) 2007 Christian Hujer. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package test.net.sf.japi.io.args; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.NoSuchElementException; +import net.sf.japi.io.args.TokenReader; +import org.jetbrains.annotations.NotNull; +import org.junit.Test; +import org.junit.Assert; + +/** + * Test for {@link TokenReader}. + * @author <a href="mailto:ch...@ri...">Christian Hujer</a> + */ +public class TokenReaderTest { + + /** Tests that a TokenReader on an empty file has no tokens. */ + @Test(expected = NoSuchElementException.class) + public void testTokenReaderEmpty() { + final TokenReader reader = new TokenReader(createStream("")); + Assert.assertFalse("On an empty file, hasNext() must return false.", reader.hasNext()); + reader.next(); + } + + /** Tests that a TokenReader on a file with whitespace only has no tokens. */ + @Test(expected = NoSuchElementException.class) + public void testTokenReaderWhitespace() { + final TokenReader reader = new TokenReader(createStream(" \n ")); + Assert.assertFalse("On whitespace only, hasNext() must return false.", reader.hasNext()); + reader.next(); + } + + /** Tests that a TokenReader on a file with a single token returns that token. */ + @Test(expected = NoSuchElementException.class) + public void testTokenSimple() { + final TokenReader reader = new TokenReader(createStream("foo")); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + final String token = reader.next(); + Assert.assertEquals("Token must be retrievable", "foo", token); + Assert.assertFalse("After reading the last token, hasNext() must return false.", reader.hasNext()); + reader.next(); + } + + /** Tests that a TokenReader on a file with preceeding whitespace returns the token without whitespace. */ + @Test(expected = NoSuchElementException.class) + public void testTokenWithPreceedingWhitespace() { + final TokenReader reader = new TokenReader(createStream(" foo")); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + final String token = reader.next(); + Assert.assertEquals("Token must be retrievable", "foo", token); + Assert.assertFalse("After reading the last token, hasNext() must return false.", reader.hasNext()); + reader.next(); + } + + /** Tests that a TokenReader on a file with trailing whitespace returns the token without whitespace. */ + @Test(expected = NoSuchElementException.class) + public void testTokenWithTrailingWhitespace() { + final TokenReader reader = new TokenReader(createStream("foo ")); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + final String token = reader.next(); + Assert.assertEquals("Token must be retrievable", "foo", token); + Assert.assertFalse("After reading the last token, hasNext() must return false.", reader.hasNext()); + reader.next(); + } + + /** Tests that a TokenReader on a file with surrounding whitespace returns the token without whitespace. */ + @Test(expected = NoSuchElementException.class) + public void testTokenWithSurroundingWhitespace() { + final TokenReader reader = new TokenReader(createStream(" foo ")); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + final String token = reader.next(); + Assert.assertEquals("Token must be retrievable", "foo", token); + Assert.assertFalse("After reading the last token, hasNext() must return false.", reader.hasNext()); + reader.next(); + } + + /** Tests that a TokenReader on a file with preceeding whitespace returns the token without whitespace. */ + @Test(expected = NoSuchElementException.class) + public void testTokensWithPreceedingWhitespace() { + final TokenReader reader = new TokenReader(createStream(" foo bar")); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Token must be retrievable", "foo", reader.next()); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Token must be retrievable", "bar", reader.next()); + Assert.assertFalse("After reading the last token, hasNext() must return false.", reader.hasNext()); + reader.next(); + } + + /** Tests that a TokenReader on a file with trailing whitespace returns the token without whitespace. */ + @Test(expected = NoSuchElementException.class) + public void testTokensWithTrailingWhitespace() { + final TokenReader reader = new TokenReader(createStream("foo bar ")); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Token must be retrievable", "foo", reader.next()); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Token must be retrievable", "bar", reader.next()); + Assert.assertFalse("After reading the last token, hasNext() must return false.", reader.hasNext()); + reader.next(); + } + + /** Tests that a TokenReader on a file with surrounding whitespace returns the token without whitespace. */ + @Test(expected = NoSuchElementException.class) + public void testTokensWithSurroundingWhitespace() { + final TokenReader reader = new TokenReader(createStream(" foo bar ")); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Token must be retrievable", "foo", reader.next()); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Token must be retrievable", "bar", reader.next()); + Assert.assertFalse("After reading the last token, hasNext() must return false.", reader.hasNext()); + reader.next(); + } + + /** Tests that a TokenReader on a file with String tokens returns them. */ + @Test(expected = NoSuchElementException.class) + public void testTokensComplex() { + final TokenReader reader = new TokenReader(createStream(" foo\nbar\nbuzz token\n\" Multiline\n\\\"String \" anotherFoo a\"n\"a")); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Expecting token", "foo", reader.next()); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Expecting token", "bar", reader.next()); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Expecting token", "buzz", reader.next()); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Expecting token", "token", reader.next()); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Expecting token", " Multiline\n\"String ", reader.next()); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Expecting token", "anotherFoo", reader.next()); + Assert.assertTrue("Before reading the last token, hasNext() must return true.", reader.hasNext()); + Assert.assertEquals("Expecting token", "ana", reader.next()); + Assert.assertFalse("After reading the last token, hasNext() must return false.", reader.hasNext()); + reader.next(); + } + + /** Creates an InputStream for reading from a String. + * @param s String to read from. + * @return InputStream created from s. + */ + @NotNull private static InputStream createStream(@NotNull final String s) { + return new ByteArrayInputStream(s.getBytes()); + } + +} // class TokenReaderTest Property changes on: libs/argparser/trunk/src/test/net/sf/japi/io/args/TokenReaderTest.java ___________________________________________________________________ Name: svn:mime-type + text/plain Name: svn:eol-style + LF This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-07-09 21:16:52
|
Revision: 526 http://svn.sourceforge.net/japi/?rev=526&view=rev Author: christianhujer Date: 2007-07-09 14:16:49 -0700 (Mon, 09 Jul 2007) Log Message: ----------- [ 1750198 ] Allow single dash instead of double dash Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2007-07-09 20:54:31 UTC (rev 525) +++ libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2007-07-09 21:16:49 UTC (rev 526) @@ -195,7 +195,7 @@ } /** - * Parses arguments into an arguments container and invokes the Command's {@link Command#run(List<String>)} method. + * Parses arguments into an arguments container. * @throws TerminalException in case argument parsing was stopped * @throws MissingArgumentException In case a required argument was missing. * @throws UnknownOptionException In case a given option is not known. @@ -206,24 +206,29 @@ final String arg = argIterator.next(); if (arg.length() > 1 && arg.charAt(0) == '-') { argIterator.remove(); - if ("--".equals(arg)) { + if ("--".equals(arg)) { // '--': stop parsing //noinspection BreakStatement break; } - if (arg.charAt(1) == '-') { - currentOption = arg.substring(2); - final int indexOfEq = currentOption.indexOf('='); - if (indexOfEq != -1) { - argIterator.add(currentOption.substring(indexOfEq + 1)); - argIterator.previous(); - currentOption = currentOption.substring(0, indexOfEq); - } + final boolean doubleDash = arg.charAt(1) == '-'; + currentOption = arg.substring(doubleDash ? 2 : 1); + final int indexOfEq = currentOption.indexOf('='); + if (indexOfEq != -1) { + argIterator.add(currentOption.substring(indexOfEq + 1)); + argIterator.previous(); + currentOption = currentOption.substring(0, indexOfEq); + } + if (doubleDash) { // '--foo' option invokeMethod(); - } else { - for (final String co : arg.substring(1).split("")) { - if (co.length() == 1) { - currentOption = co; - invokeMethod(); + } else { // '-xyz' + if (argumentMethods.get(currentOption) != null) { // '-foo' option + invokeMethod(); + } else { // '-abc' options + for (final String co : arg.substring(1).split("")) { + if (co.length() == 1) { + currentOption = co; + invokeMethod(); + } } } } Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2007-07-09 20:54:31 UTC (rev 525) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2007-07-09 21:16:49 UTC (rev 526) @@ -232,6 +232,7 @@ * @throws TerminalException (unexpected) * @throws UnknownOptionException (unexpected) * @throws MissingArgumentException (unexpected) + * @see <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=1750193&group_id=149894&atid=776740">[ 1750193 ] Partial read of command line arguments from a file</a> */ @Test public void testOptionsFromFileSingleLine() throws RequiredOptionsMissingException, MissingArgumentException, TerminalException, UnknownOptionException { @@ -246,6 +247,40 @@ } /** + * Tests that single dash options also work. + * @throws RequiredOptionsMissingException (unexpected) + * @throws TerminalException (unexpected) + * @throws UnknownOptionException (unexpected) + * @throws MissingArgumentException (unexpected) + * @see <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=1750198&group_id=149894&atid=776740">[ 1750198 ] Allow single dash instead of double dash</a> + */ + @Test + public void testSingleDashOption() throws RequiredOptionsMissingException, MissingArgumentException, TerminalException, UnknownOptionException { + final MockCommand command = new MockCommand(); + ArgParser.parseAndRun(command, "-input", "fooInput"); + Assert.assertEquals("Option value must be stored.", "fooInput", command.getInput()); + Assert.assertTrue("Run must be called even with zero arguments.", command.isRunCalled()); + Assert.assertEquals("Argument list for invocation without arguments must be empty.", 0, command.getArgs().size()); + } + + /** + * Tests that single dash options also work. + * @throws RequiredOptionsMissingException (unexpected) + * @throws TerminalException (unexpected) + * @throws UnknownOptionException (unexpected) + * @throws MissingArgumentException (unexpected) + * @see <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=1750198&group_id=149894&atid=776740">[ 1750198 ] Allow single dash instead of double dash</a> + */ + @Test + public void testSingleDashOptionWithEquals() throws RequiredOptionsMissingException, MissingArgumentException, TerminalException, UnknownOptionException { + final MockCommand command = new MockCommand(); + ArgParser.parseAndRun(command, "-input=fooInput"); + Assert.assertEquals("Option value must be stored.", "fooInput", command.getInput()); + Assert.assertTrue("Run must be called even with zero arguments.", command.isRunCalled()); + Assert.assertEquals("Argument list for invocation without arguments must be empty.", 0, command.getArgs().size()); + } + + /** * This MockCommand serves as a command for performing simple tests. * @author <a href="mailto:ch...@ri...">Christian Hujer</a> */ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <chr...@us...> - 2007-07-13 20:14:49
|
Revision: 532 http://svn.sourceforge.net/japi/?rev=532&view=rev Author: christianhujer Date: 2007-07-13 13:14:47 -0700 (Fri, 13 Jul 2007) Log Message: ----------- [ 1751332 ] Required options check should be optional / configurable Modified Paths: -------------- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java libs/argparser/trunk/src/net/sf/japi/io/args/Command.java libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java Modified: libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2007-07-10 19:13:49 UTC (rev 531) +++ libs/argparser/trunk/src/net/sf/japi/io/args/ArgParser.java 2007-07-13 20:14:47 UTC (rev 532) @@ -140,7 +140,7 @@ * @throws RequiredOptionsMissingException in case a required command line argument was missing */ private void checkRequiredMethods() throws RequiredOptionsMissingException { - if (requiredMethods.size() > 0) { + if (command.isCheckRequiredOptions() && requiredMethods.size() > 0) { final List<String> missingOptions = new ArrayList<String>(); for (final Method requiredMethod : requiredMethods) { final Option option = requiredMethod.getAnnotation(Option.class); Modified: libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java 2007-07-10 19:13:49 UTC (rev 531) +++ libs/argparser/trunk/src/net/sf/japi/io/args/BasicCommand.java 2007-07-13 20:14:47 UTC (rev 532) @@ -21,6 +21,7 @@ import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.Collections; import java.util.Formatter; import java.util.List; import java.util.MissingResourceException; @@ -28,7 +29,6 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; -import java.util.Collections; import org.jetbrains.annotations.NotNull; /** @@ -46,11 +46,26 @@ */ private boolean exiting; + /** + * Whether to check for required options. + * @see Command#isCheckRequiredOptions() + */ + private boolean checkRequiredOptions = true; + /** Create a BasicCommand. */ protected BasicCommand() { } /** + * {@inheritDoc} + * @see System#exit(int) + * @see #setExiting(Boolean) + */ + @NotNull public Boolean isExiting() { + return exiting; + } + + /** * Exit Option. * Normally you wouldn't override this method. * The default behaviour is to not exit. @@ -66,13 +81,16 @@ this.exiting = exiting; } - /** - * {@inheritDoc} - * @see System#exit(int) - * @see #setExiting(Boolean) + /** {@inheritDoc} */ + public boolean isCheckRequiredOptions() { + return checkRequiredOptions; + } + + /** Sets whether the check for required options should be performed. + * @param checkRequiredOptions <code>true</code> if the check for required options should be performed, otherwise <code>false</code>. */ - @NotNull public Boolean isExiting() { - return exiting; + public void setCheckRequiredOptions(final boolean checkRequiredOptions) { + this.checkRequiredOptions = checkRequiredOptions; } /** Help Option. */ Modified: libs/argparser/trunk/src/net/sf/japi/io/args/Command.java =================================================================== --- libs/argparser/trunk/src/net/sf/japi/io/args/Command.java 2007-07-10 19:13:49 UTC (rev 531) +++ libs/argparser/trunk/src/net/sf/japi/io/args/Command.java 2007-07-13 20:14:47 UTC (rev 532) @@ -45,4 +45,10 @@ */ Boolean isExiting(); + /** + * Return whether the check for required methods should be performed. + * @return <code>true</code> if {@link ArgParser} should perform a check on required methods on this command, otherwise <code>false</code>. + */ + boolean isCheckRequiredOptions(); + } // interface Command Modified: libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java =================================================================== --- libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2007-07-10 19:13:49 UTC (rev 531) +++ libs/argparser/trunk/src/test/net/sf/japi/io/args/ArgParserTest.java 2007-07-13 20:14:47 UTC (rev 532) @@ -148,6 +148,21 @@ } /** + * Tests whether it's not detected that a required option is missing if the command doesn't want it. + * @throws RequiredOptionsMissingException (unexpected) + * @throws TerminalException (unexpected) + * @throws UnknownOptionException (unexpected) + * @throws MissingArgumentException (unexpected) + * @see <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=1751332&group_id=149894&atid=776740">[ 1751332 ] Required options check should be optional / configurable</a> + */ + @Test + public void testCommandRequiredOptionMissingDisabled() throws RequiredOptionsMissingException, TerminalException, UnknownOptionException, MissingArgumentException { + final MockCommand command = new MockCommand(); + command.setCheckRequiredOptions(false); + ArgParser.parseAndRun(command); + } + + /** * Tests whether it's detected that an unknown option was given. * @throws RequiredOptionsMissingException (unexpected) * @throws TerminalException (unexpected) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |