From 9747cf21b2d5cc782069aff5d43548a7f7437666 Mon Sep 17 00:00:00 2001 From: Emmanuel Bigeon Date: Sun, 5 Nov 2017 16:19:50 -0500 Subject: [PATCH] Add Code compliance Signed-off-by: Emmanuel Bigeon --- .../gclc/socket/ConsoleTestApplication.java | 3 +- .../bigeon/gclc/CommandRequestListener.java | 7 +- .../fr/bigeon/gclc/ConsoleApplication.java | 140 +++-- .../java/fr/bigeon/gclc/GCLCConstants.java | 66 +- .../java/fr/bigeon/gclc/command/Command.java | 26 +- .../gclc/command/CommandParameters.java | 148 +++-- .../bigeon/gclc/command/CommandProvider.java | 28 +- .../fr/bigeon/gclc/command/ExitCommand.java | 12 +- .../fr/bigeon/gclc/command/HelpExecutor.java | 52 +- .../bigeon/gclc/command/ICommandProvider.java | 6 +- .../fr/bigeon/gclc/command/MockCommand.java | 25 +- .../gclc/command/ParametrizedCommand.java | 170 ++++-- .../bigeon/gclc/command/ScriptExecution.java | 86 ++- .../fr/bigeon/gclc/command/SubedCommand.java | 83 +-- .../gclc/exception/CommandRunException.java | 48 +- .../java/fr/bigeon/gclc/i18n/Messages.java | 8 +- .../gclc/manager/PipedConsoleManager.java | 110 ++-- .../bigeon/gclc/manager/ReadingRunnable.java | 175 +++--- .../gclc/manager/SystemConsoleManager.java | 81 +-- .../bigeon/gclc/manager/WritingRunnable.java | 53 +- .../java/fr/bigeon/gclc/package-info.java | 42 ++ .../java/fr/bigeon/gclc/proc/ProcessKill.java | 20 +- .../java/fr/bigeon/gclc/proc/ProcessList.java | 34 +- .../main/java/fr/bigeon/gclc/proc/Task.java | 32 +- .../java/fr/bigeon/gclc/proc/TaskPool.java | 49 +- .../java/fr/bigeon/gclc/proc/TaskSpawner.java | 25 +- .../fr/bigeon/gclc/prompt/CLIPrompter.java | 192 +++--- .../gclc/prompt/CLIPrompterMessages.java | 4 +- .../gclc/tools/AOutputForwardRunnable.java | 68 +-- .../java/fr/bigeon/gclc/tools/PrintUtils.java | 22 +- .../bigeon/gclc/ConsoleApplicationTest.java | 34 +- .../bigeon/gclc/ConsoleTestApplication.java | 53 +- .../fr/bigeon/gclc/GCLCConstantsTest.java | 17 +- .../fr/bigeon/gclc/command/CommandTest.java | 94 +-- .../bigeon/gclc/command/HelpExecutorTest.java | 55 +- .../gclc/command/ParametrizedCommandTest.java | 398 +++++++----- .../gclc/command/ScriptExecutionTest.java | 42 +- .../bigeon/gclc/command/SubedCommandTest.java | 568 +++++++++--------- .../fr/bigeon/gclc/proc/ProcessListTest.java | 88 +-- .../fr/bigeon/gclc/proc/TaskPoolTest.java | 57 +- .../bigeon/gclc/prompt/CLIPrompterTest.java | 377 ++++++------ 41 files changed, 1919 insertions(+), 1679 deletions(-) create mode 100644 gclc/src/main/java/fr/bigeon/gclc/package-info.java diff --git a/gclc-socket/src/test/java/fr/bigeon/gclc/socket/ConsoleTestApplication.java b/gclc-socket/src/test/java/fr/bigeon/gclc/socket/ConsoleTestApplication.java index 2993853..5078bf8 100644 --- a/gclc-socket/src/test/java/fr/bigeon/gclc/socket/ConsoleTestApplication.java +++ b/gclc-socket/src/test/java/fr/bigeon/gclc/socket/ConsoleTestApplication.java @@ -52,7 +52,8 @@ public class ConsoleTestApplication { /** Exit command */ public static final String EXIT = "exit"; //$NON-NLS-1$ - /** @param manager the manager */ + /** @param manager the manager + * @return create the application */ @SuppressWarnings("nls") public static ConsoleApplication create(final ConsoleManager manager) { try { diff --git a/gclc/src/main/java/fr/bigeon/gclc/CommandRequestListener.java b/gclc/src/main/java/fr/bigeon/gclc/CommandRequestListener.java index 6917341..694cfb6 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/CommandRequestListener.java +++ b/gclc/src/main/java/fr/bigeon/gclc/CommandRequestListener.java @@ -38,13 +38,12 @@ */ package fr.bigeon.gclc; -/**

- * Command Request Listeners are listeners that are notified before a command is - * executed by the ConsoleApplication, +/** Command Request Listeners are listeners that are notified before a command + * is executed by the ConsoleApplication. * * @author Emmanuel Bigeon */ public interface CommandRequestListener { - /** Indicates that the given command was requested to the application + /** Indicates that the given command was requested to the application. * * @param command the command */ void commandRequest(String command); diff --git a/gclc/src/main/java/fr/bigeon/gclc/ConsoleApplication.java b/gclc/src/main/java/fr/bigeon/gclc/ConsoleApplication.java index dc17157..5192d58 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/ConsoleApplication.java +++ b/gclc/src/main/java/fr/bigeon/gclc/ConsoleApplication.java @@ -54,17 +54,18 @@ import fr.bigeon.gclc.exception.InvalidCommandName; import fr.bigeon.gclc.i18n.Messages; import fr.bigeon.gclc.manager.ConsoleManager; -/**

+/** + *

* A {@link ConsoleApplication} is an application that require the user to input * commands. *

* A typical use case is the following: * *

- * {@link ConsoleManager} manager = new {@link fr.bigeon.gclc.manager.SystemConsoleManager#SystemConsoleManager()}
- * {@link ConsoleApplication} app = new {@link ConsoleApplication#ConsoleApplication(ConsoleManager, String, String) ConsoleApplication(manager, "welcome", "see you latter")};
+ * {@link ConsoleManager} manager = new {@link fr.bigeon.gclc.manager.SystemConsoleManager SystemConsoleManager}();
+ * {@link ConsoleApplication} app = new {@link ConsoleApplication}(manager, "welcome", "see you latter")};
  * app.{@link ConsoleApplication#add(ICommand) add}("my_command", new {@link ICommand MyCommand()});
- * app.{@link ConsoleApplication#start start}();
+ * app.{@link ConsoleApplication#start() start()};
  * 
*

* That will launch in the console application that will display "welcome", @@ -75,40 +76,42 @@ import fr.bigeon.gclc.manager.ConsoleManager; * @author Emmanuel BIGEON */ public final class ConsoleApplication implements ICommandProvider { - /** The class logger */ + /** The class logger. */ private static final Logger LOGGER = Logger .getLogger(ConsoleApplication.class.getName()); - /** The welcome message */ + /** The welcome message. */ public final String header; - /** The good bye message */ + /** The good bye message. */ public final String footer; - /** The console manager */ + /** The console manager. */ public final ConsoleManager manager; - /** The container of commands */ + /** The container of commands. */ public final SubedCommand root; - /** The state of this application */ + /** The state of this application. */ private boolean running; - /** The listeners */ + /** The listeners. */ private final List listeners = new ArrayList<>(); - /** @param manager the manager + /** Create a console application. + * + * @param manager the manager * @param welcome the welcoming message * @param goodbye the goodbye message */ - public ConsoleApplication(ConsoleManager manager, String welcome, - String goodbye) { - this.header = welcome; - this.footer = goodbye; + public ConsoleApplication(final ConsoleManager manager, final String welcome, + final String goodbye) { + header = welcome; + footer = goodbye; this.manager = manager; root = new SubedCommand(""); //$NON-NLS-1$ } @Override - public final boolean add(ICommand cmd) throws InvalidCommandName { + public boolean add(final ICommand cmd) throws InvalidCommandName { return root.add(cmd); } /** @param listener the command listener */ - public final void addListener(CommandRequestListener listener) { + public void addListener(final CommandRequestListener listener) { listeners.add(listener); } @@ -116,13 +119,13 @@ public final class ConsoleApplication implements ICommandProvider { * @see fr.bigeon.gclc.command.ICommandProvider#executeSub(java.lang.String, * java.lang.String[]) */ @Override - public final void executeSub(String command, - String... args) throws CommandRunException { + public void executeSub(final String command, + final String... args) throws CommandRunException { root.executeSub(command, args); } /** Signify to the application that no command should be inputed anymore */ - public final void exit() { + public void exit() { LOGGER.fine("Request exiting application..."); //$NON-NLS-1$ running = false; manager.interruptPrompt(); @@ -131,17 +134,17 @@ public final class ConsoleApplication implements ICommandProvider { /* (non-Javadoc) * @see fr.bigeon.gclc.command.ICommandProvider#get(java.lang.String) */ @Override - public final ICommand get(String command) { + public ICommand get(final String command) { return root.get(command); } /** @param cmd the command * @throws IOException if the command could not be parsed */ - public final void interpretCommand(String cmd) throws IOException { + public void interpretCommand(final String cmd) throws IOException { List args; try { args = GCLCConstants.splitCommand(cmd); - } catch (CommandParsingException e1) { + } catch (final CommandParsingException e1) { manager.println("Command line cannot be parsed"); //$NON-NLS-1$ LOGGER.log(Level.FINE, "Invalid user command " + cmd, e1); //$NON-NLS-1$ return; @@ -162,50 +165,14 @@ public final class ConsoleApplication implements ICommandProvider { } } - /** @param listener the command listener to remove */ - public final void removeListener(CommandRequestListener listener) { - for (int i = 0; i < listeners.size(); i++) { - if (listeners.get(i) == listener) { - listeners.remove(i); - return; - } - } + /** @return the running status */ + public boolean isRunning() { + return running; } - /** Start the application */ - public final void start() { - try { - running = true; - if (header != null) { - manager.println(header); - } - } catch (IOException e) { - // The manager was closed - running = false; - LOGGER.warning( - "The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$ - LOGGER.log(Level.FINE, - "An exception caused the closing of the application", //$NON-NLS-1$ - e); - return; - } - do { - runLoop(); - } while (running); - if (footer != null) { - try { - manager.println(footer); - } catch (IOException e) { - // The manager was closed - running = false; - LOGGER.warning("The console manager was closed."); //$NON-NLS-1$ - LOGGER.log(Level.FINE, - "An exception occured when trying to print the good by e message... The application will still close.", //$NON-NLS-1$ - e); - } - } - running = false; - LOGGER.fine("Exiting application."); //$NON-NLS-1$ + /** @param listener the command listener to remove */ + public void removeListener(final CommandRequestListener listener) { + listeners.remove(listener); } /** The running loop content. @@ -222,12 +189,12 @@ public final class ConsoleApplication implements ICommandProvider { listener.commandRequest(cmd); } interpretCommand(cmd); - } catch (InterruptedIOException e) { + } catch (final InterruptedIOException e) { LOGGER.info( "Prompt interrupted. It is likely the application is closing."); //$NON-NLS-1$ LOGGER.log(Level.FINER, "Interruption of the prompt.", //$NON-NLS-1$ e); - } catch (IOException e) { + } catch (final IOException e) { // The manager was closed running = false; LOGGER.warning( @@ -238,8 +205,39 @@ public final class ConsoleApplication implements ICommandProvider { } } - /** @return the running status */ - public boolean isRunning() { - return running; + /** Start the application */ + public void start() { + try { + running = true; + if (header != null) { + manager.println(header); + } + } catch (final IOException e) { + // The manager was closed + running = false; + LOGGER.warning( + "The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$ + LOGGER.log(Level.FINE, + "An exception caused the closing of the application", //$NON-NLS-1$ + e); + return; + } + do { + runLoop(); + } while (running); + if (footer != null) { + try { + manager.println(footer); + } catch (final IOException e) { + // The manager was closed + running = false; + LOGGER.warning("Console manager alreaady closed."); //$NON-NLS-1$ + LOGGER.log(Level.FINE, + "Exception raised by goodbye message printing... Application will still close.", //$NON-NLS-1$ + e); + } + } + running = false; + LOGGER.fine("Exiting application."); //$NON-NLS-1$ } } diff --git a/gclc/src/main/java/fr/bigeon/gclc/GCLCConstants.java b/gclc/src/main/java/fr/bigeon/gclc/GCLCConstants.java index 5427897..87ff868 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/GCLCConstants.java +++ b/gclc/src/main/java/fr/bigeon/gclc/GCLCConstants.java @@ -49,7 +49,7 @@ import fr.bigeon.gclc.exception.CommandParsingException; * arguments. * * @author Emmanuel Bigeon */ -public class GCLCConstants { +public final class GCLCConstants { /** The escaping character */ private static final char ESCAPING_CHAR = getSystemEscapingChar(); @@ -59,17 +59,46 @@ public class GCLCConstants { // utility class } + /** @param cmd the command to parse + * @param startIndex the starting point of the parsing + * @param index the index of the current position + * @return the argument + * @throws CommandParsingException if the end of string does not mark end of + * command and is not followed by a space */ + private static String endOfString(final String cmd, final int startIndex, + final int index) throws CommandParsingException { + if (index < cmd.length() && cmd.charAt(index) != ' ') { + throw new CommandParsingException("Misplaced quote"); //$NON-NLS-1$ + } + return cmd.substring(startIndex + 1, index - 1); + } + /** @return the escaping character */ private static char getSystemEscapingChar() { return '\\'; } + /** @param arg the string to remove excaping character from + * @return the string without escape character */ + private static String removeEscaped(final String arg) { + final StringBuilder builder = new StringBuilder(); + int index = 0; + int endIndex = arg.indexOf(ESCAPING_CHAR); + while (endIndex != -1) { + builder.append(arg.subSequence(index, endIndex)); + index = endIndex + 1; + endIndex = arg.indexOf(ESCAPING_CHAR, index + 1); + } + builder.append(arg.substring(index)); + return builder.toString(); + } + /** Splits a command in the diferrent arguments - * + * * @param cmd the command to split in its parts * @return the list of argument preceded by the command name * @throws CommandParsingException if the parsing of the command failed */ - public static List splitCommand(String cmd) throws CommandParsingException { + public static List splitCommand(final String cmd) throws CommandParsingException { final List args = new ArrayList<>(); // parse the string to separate arguments int index = 0; @@ -77,7 +106,7 @@ public class GCLCConstants { boolean escaped = false; boolean inString = false; while (index < cmd.length()) { - char c = cmd.charAt(index); + final char c = cmd.charAt(index); index++; if (escaped || c == ESCAPING_CHAR) { escaped = !escaped; @@ -105,33 +134,4 @@ public class GCLCConstants { return args; } - /** @param arg the string to remove excaping character from - * @return the string without escape character */ - private static String removeEscaped(String arg) { - StringBuilder builder = new StringBuilder(); - int index = 0; - int endIndex = arg.indexOf(ESCAPING_CHAR); - while (endIndex != -1) { - builder.append(arg.subSequence(index, endIndex)); - index = endIndex + 1; - endIndex = arg.indexOf(ESCAPING_CHAR, index + 1); - } - builder.append(arg.substring(index)); - return builder.toString(); - } - - /** @param cmd the command to parse - * @param startIndex the starting point of the parsing - * @param index the index of the current position - * @return the argument - * @throws CommandParsingException if the end of string does not mark end of - * command and is not followed by a space */ - private static String endOfString(String cmd, int startIndex, - int index) throws CommandParsingException { - if (index < cmd.length() && cmd.charAt(index) != ' ') { - throw new CommandParsingException("Misplaced quote"); //$NON-NLS-1$ - } - return cmd.substring(startIndex + 1, index - 1); - } - } diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/Command.java b/gclc/src/main/java/fr/bigeon/gclc/command/Command.java index e7695b6..4f83255 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/Command.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/Command.java @@ -42,7 +42,8 @@ import java.io.IOException; import fr.bigeon.gclc.manager.ConsoleManager; -/**

+/** + *

* A command to execute. It is mandatory that it has a name and that name cannot * start with minus character or contain spaces. *

@@ -65,17 +66,13 @@ import fr.bigeon.gclc.manager.ConsoleManager; * @author Emmanuel BIGEON */ public abstract class Command implements ICommand { - /** - * - */ + /** The linux end of line character. */ private static final String EOL_LINUX = "\n"; //$NON-NLS-1$ - /** The empty string constant */ - private static final String EMPTY = ""; //$NON-NLS-1$ /** The name of the command */ protected final String name; /** @param name the command name */ - public Command(String name) { + public Command(final String name) { super(); this.name = name; } @@ -96,8 +93,8 @@ public abstract class Command implements ICommand { * @see fr.bigeon.gclc.command.ICommand#help(fr.bigeon.gclc.ConsoleManager, * java.lang.String) */ @Override - public final void help(ConsoleManager manager, - String... args) throws IOException { + public final void help(final ConsoleManager manager, + final String... args) throws IOException { manager.println(getCommandName()); manager.println(brief()); manager.println(); @@ -114,17 +111,16 @@ public abstract class Command implements ICommand { } } - /**

+ /** + *

* This method return the detail of the help. It immediatly follows the * {@link #usagePattern() usage pattern}. * * @return the detailed help (should end with end of line or be empty) */ - @SuppressWarnings("static-method") - protected String usageDetail() { - return EMPTY; - } + protected abstract String usageDetail(); - /**

+ /** + *

* This prints the usage pattern for the command. It follows the brief * introduction on the command ({@link #brief()}) * diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/CommandParameters.java b/gclc/src/main/java/fr/bigeon/gclc/command/CommandParameters.java index bad2c57..53bd545 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/CommandParameters.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/CommandParameters.java @@ -47,33 +47,32 @@ import java.util.Set; import fr.bigeon.gclc.exception.CommandParsingException; -/**

- * An object representing a collection of parameters. It is used for defaulting - * values. +/** An object representing a collection of parameters. + *

+ * It is used for defaulting values. * * @author Emmanuel BIGEON */ -public class CommandParameters { - /** - * - */ +public final class CommandParameters { + /** Number of element for a string argument. */ private static final int STRINGARG_NUMBER_OF_ELEMENTS = 2; - /** Boolean arguments */ + /** Boolean arguments. */ private final Map booleanArguments = new HashMap<>(); - /** String arguments */ + /** String arguments. */ private final Map stringArguments = new HashMap<>(); - /** Arguments restriction on the named ones */ + /** Arguments restriction on the named ones. */ private final boolean strict; - /** additional (unnamed) parameters */ + /** additional (unnamed) parameters. */ private final List additional = new ArrayList<>(); - /** @param bools the boolean parameters + /** Create a command parameter object. + * + * @param bools the boolean parameters * @param strings the string parameters * @param strict if the argument are restricted to the declared ones */ - @SuppressWarnings("boxing") - public CommandParameters(Set bools, Set strings, - boolean strict) { + public CommandParameters(final Set bools, final Set strings, + final boolean strict) { for (final String string : bools) { - booleanArguments.put(string, false); + booleanArguments.put(string, Boolean.FALSE); } for (final String string : strings) { stringArguments.put(string, null); @@ -81,56 +80,66 @@ public class CommandParameters { this.strict = strict; } - /** @param key the key + /** Get the value of a string argument. + * + * @param key the key * @return the associated value, null if it was not specified */ - public String get(String key) { + public String get(final String key) { return stringArguments.get(key); } - /** @return additional non parsed parameters */ + /** Get the additional (unrecognized) arguments. + * + * @return additional non parsed parameters */ public List getAdditionals() { return Collections.unmodifiableList(additional); } - /** @param key the key + /** Get the value of a boolean argument. + * + * @param key the key * @return if the key was specified */ - public boolean getBool(String key) { + public boolean getBool(final String key) { return booleanArguments.containsKey(key) && booleanArguments.get(key).booleanValue(); } - /** @param args the arguments to parse - * @throws CommandParsingException if the arguments parsing failed */ - public void parseArgs(String... args) throws CommandParsingException { - int i = 0; - while (i < args.length) { - String next = null; - if (i < args.length - 1) { - next = args[i + 1]; - } - int p = parseArg(args[i], next); - if (p == 0) { - throw new CommandParsingException( - "Invalid parameter " + args[i]); //$NON-NLS-1$ - } - i += p; - } + /** Get the boolean arguments. + * + * @return the boolean arguments */ + public Set getBooleanArgumentKeys() { + return booleanArguments.keySet(); + } + /** Get the string arguments. + * + * @return the boolean arguments */ + public Set getStringArgumentKeys() { + return stringArguments.keySet(); + } + + /** Test if an argument exists in this object. + * + * @param key the key + * @return if the key is present in string arguments or boolean ones. */ + public boolean hasArgument(final String key) { + return stringArguments.containsKey(key) || + booleanArguments.containsKey(key); } /** Attempt to parse an argument. *

* This method return 0 if the parsing was incorrect, or the number of * parsed elements. - * + * * @param arg the argument * @param next the next element * @return the number of element read */ - private int parseArg(String arg, String next) { + private int parseArg(final String arg, final String next) { if (!arg.startsWith("-")) { //$NON-NLS-1$ return strict ? 0 : 1; } - String name = arg.substring(1); + final String name = arg.substring(1); if (booleanArguments.containsKey(name)) { booleanArguments.put(name, Boolean.TRUE); return 1; @@ -145,12 +154,33 @@ public class CommandParameters { return 1; } - /** Add a string arg value - * + /** Parse arguments. + * + * @param args the arguments to parse + * @throws CommandParsingException if the arguments parsing failed */ + public void parseArgs(final String... args) throws CommandParsingException { + int i = 0; + while (i < args.length) { + String next = null; + if (i < args.length - 1) { + next = args[i + 1]; + } + final int p = parseArg(args[i], next); + if (p == 0) { + throw new CommandParsingException( + "Invalid parameter " + args[i]); //$NON-NLS-1$ + } + i += p; + } + + } + + /** Add a string arg value. + * * @param name the string arg name * @param next the string arg value * @return 2 or 0 if next is invalid */ - private int parseStringArg(String name, String next) { + private int parseStringArg(final String name, final String next) { if (next == null) { return 0; } @@ -158,37 +188,23 @@ public class CommandParameters { return STRINGARG_NUMBER_OF_ELEMENTS; } - /** @param string the key + /** Set a boolean parameter value. + * + * @param string the key * @param value the value */ - @SuppressWarnings("boxing") - public void set(String string, boolean value) { + public void set(final String string, final boolean value) { if (booleanArguments.containsKey(string)) { - booleanArguments.put(string, value); + booleanArguments.put(string, Boolean.valueOf(value)); } } - /** @param string the key + /** Set a string parameter value. + * + * @param string the key * @param value the value */ - public void set(String string, String value) { + public void set(final String string, final String value) { if (stringArguments.containsKey(string)) { stringArguments.put(string, value); } } - - /** @return the boolean arguments */ - public Set getBooleanArgumentKeys() { - return booleanArguments.keySet(); - } - - /** @return the boolean arguments */ - public Set getStringArgumentKeys() { - return stringArguments.keySet(); - } - - /** @param key the key - * @return if the key is present in string arguments or boolean ones. */ - public boolean hasArgument(String key) { - return stringArguments.containsKey(key) || - booleanArguments.containsKey(key); - } } diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/CommandProvider.java b/gclc/src/main/java/fr/bigeon/gclc/command/CommandProvider.java index 48e4ff8..7e0ddbe 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/CommandProvider.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/CommandProvider.java @@ -61,17 +61,26 @@ public class CommandProvider implements ICommandProvider { commands = new ArrayList<>(); } + /** @param name the command name + * @throws InvalidCommandName if the name is invalid */ + private static void testCommandName(final String name) throws InvalidCommandName { + if (name == null || name.isEmpty() || name.startsWith(MINUS) || + name.contains(SPACE)) { + throw new InvalidCommandName(); + } + } + /* (non-Javadoc) * @see fr.bigeon.gclc.command.ICommandProvider#add(java.lang.String, * fr.bigeon.gclc.command.Command) */ @Override - public boolean add(ICommand value) throws InvalidCommandName { + public final boolean add(final ICommand value) throws InvalidCommandName { final String name = value.getCommandName(); testCommandName(name); if (commands.contains(value)) { return true; } - for (ICommand iCommand : commands) { + for (final ICommand iCommand : commands) { if (iCommand.getCommandName().equals(value.getCommandName())) { throw new InvalidCommandName( "Name already used: " + value.getCommandName()); //$NON-NLS-1$ @@ -80,18 +89,9 @@ public class CommandProvider implements ICommandProvider { return commands.add(value); } - /** @param name the command name - * @throws InvalidCommandName if the name is invalid */ - private static void testCommandName(String name) throws InvalidCommandName { - if (name == null || name.isEmpty() || name.startsWith(MINUS) || - name.contains(SPACE)) { - throw new InvalidCommandName(); - } - } - @Override - public void executeSub(String cmd, - String... args) throws CommandRunException { + public final void executeSub(final String cmd, + final String... args) throws CommandRunException { for (final ICommand command : commands) { if (command.getCommandName().equals(cmd)) { command.execute(args); @@ -105,7 +105,7 @@ public class CommandProvider implements ICommandProvider { /* (non-Javadoc) * @see fr.bigeon.gclc.command.ICommandProvider#get(java.lang.String) */ @Override - public ICommand get(String commandName) { + public final ICommand get(final String commandName) { for (final ICommand command : commands) { if (command.getCommandName().equals(commandName)) { return command; diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/ExitCommand.java b/gclc/src/main/java/fr/bigeon/gclc/command/ExitCommand.java index 7a54eb6..1941c10 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/ExitCommand.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/ExitCommand.java @@ -48,7 +48,7 @@ import fr.bigeon.gclc.prompt.CLIPrompterMessages; * A command to exit a {@link ConsoleApplication}. * * @author Emmanuel BIGEON */ -public class ExitCommand implements ICommand { +public final class ExitCommand implements ICommand { /** The exit command manual message key */ private static final String EXIT_MAN = "exit.man"; //$NON-NLS-1$ /** The tip of the exit command */ @@ -60,7 +60,7 @@ public class ExitCommand implements ICommand { /** @param name the name of the command * @param app the application to exit */ - public ExitCommand(String name, ConsoleApplication app) { + public ExitCommand(final String name, final ConsoleApplication app) { this.name = name; this.app = app; } @@ -71,7 +71,7 @@ public class ExitCommand implements ICommand { } @Override - public final void execute(String... args) { + public void execute(final String... args) { beforeExit(); app.exit(); } @@ -79,13 +79,13 @@ public class ExitCommand implements ICommand { /* (non-Javadoc) * @see fr.bigeon.gclc.command.ICommand#getCommandName() */ @Override - public final String getCommandName() { + public String getCommandName() { return name; } @Override - public void help(ConsoleManager manager, - String... args) throws IOException { + public void help(final ConsoleManager manager, + final String... args) throws IOException { manager.println( CLIPrompterMessages.getString(EXIT_MAN, (Object[]) args)); } diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/HelpExecutor.java b/gclc/src/main/java/fr/bigeon/gclc/command/HelpExecutor.java index 4718752..bf0de55 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/HelpExecutor.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/HelpExecutor.java @@ -50,7 +50,7 @@ import fr.bigeon.gclc.prompt.CLIPrompterMessages; * This command will display the help of an other command * * @author Emmanuel BIGEON */ -public class HelpExecutor extends Command { +public final class HelpExecutor extends Command { /** The command to execute the help of */ private final ICommand cmd; @@ -60,29 +60,13 @@ public class HelpExecutor extends Command { /** @param cmdName the command name * @param consoleManager the manager for the console * @param cmd the command to execute the help of */ - public HelpExecutor(String cmdName, ConsoleManager consoleManager, - ICommand cmd) { + public HelpExecutor(final String cmdName, final ConsoleManager consoleManager, + final ICommand cmd) { super(cmdName); this.cmd = cmd; - if (consoleManager == null) { - throw new NullPointerException( - "Argument cannot be null: ConsoleManager"); //$NON-NLS-1$ - } this.consoleManager = consoleManager; } - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#execute(java.lang.String[]) */ - @Override - public void execute(String... args) throws CommandRunException { - try { - cmd.help(consoleManager, args); - } catch (IOException e) { - throw new CommandRunException(CommandRunExceptionType.INTERACTION, - "Console manager closed", e, this); //$NON-NLS-1$ - } - } - /* (non-Javadoc) * @see fr.bigeon.gclc.command.Command#brief() */ @Override @@ -94,13 +78,15 @@ public class HelpExecutor extends Command { } /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#usagePattern() */ + * @see fr.bigeon.gclc.command.Command#execute(java.lang.String[]) */ @Override - protected String usagePattern() { - if (cmd instanceof SubedCommand) { - return getCommandName() + " "; //$NON-NLS-1$ + public void execute(final String... args) throws CommandRunException { + try { + cmd.help(consoleManager, args); + } catch (final IOException e) { + throw new CommandRunException(CommandRunExceptionType.INTERACTION, + "Console manager closed", e, this); //$NON-NLS-1$ } - return getCommandName(); } /* (non-Javadoc) @@ -109,4 +95,22 @@ public class HelpExecutor extends Command { public String tip() { return CLIPrompterMessages.getString("help.cmd.tip"); //$NON-NLS-1$ } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#usageDetail() + */ + @Override + protected String usageDetail() { + return null; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#usagePattern() */ + @Override + protected String usagePattern() { + if (cmd instanceof SubedCommand) { + return getCommandName() + " "; //$NON-NLS-1$ + } + return getCommandName(); + } } diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/ICommandProvider.java b/gclc/src/main/java/fr/bigeon/gclc/command/ICommandProvider.java index 294a419..5eb0f54 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/ICommandProvider.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/ICommandProvider.java @@ -53,7 +53,7 @@ public interface ICommandProvider { * @param value the command to execute * @return if the command was added * @throws InvalidCommandName if the command name is invalid */ - public boolean add(ICommand value) throws InvalidCommandName; + boolean add(ICommand value) throws InvalidCommandName; /**

* This method executes the command with the given name found. If no command @@ -65,7 +65,7 @@ public interface ICommandProvider { * @param command the name of the command the user wishes to execute * @param args the arguments for the command * @throws CommandRunException if the command failed to run */ - public void executeSub(String command, + void executeSub(String command, String... args) throws CommandRunException; /**

@@ -77,6 +77,6 @@ public interface ICommandProvider { * * @param command the name of the command the user wishes to execute * @return the command to execute */ - public ICommand get(String command); + ICommand get(String command); } \ No newline at end of file diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/MockCommand.java b/gclc/src/main/java/fr/bigeon/gclc/command/MockCommand.java index 51e5165..de530b8 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/MockCommand.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/MockCommand.java @@ -38,9 +38,6 @@ */ package fr.bigeon.gclc.command; -import java.io.IOException; - -import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.manager.ConsoleManager; /** This implement a command that does nothing. @@ -54,24 +51,17 @@ public final class MockCommand implements ICommand { private final String name; /** @param name the command name */ - public MockCommand(String name) { + public MockCommand(final String name) { this.name = name; } /* (non-Javadoc) * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */ @Override - public void execute(String... args) throws CommandRunException { + public void execute(final String... args) { // } - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#tip() */ - @Override - public String tip() { - return null; - } - /* (non-Javadoc) * @see fr.bigeon.gclc.command.ICommand#getCommandName() */ @Override @@ -83,9 +73,16 @@ public final class MockCommand implements ICommand { * @see fr.bigeon.gclc.command.ICommand#help(fr.bigeon.gclc.manager. * ConsoleManager, java.lang.String[]) */ @Override - public void help(ConsoleManager manager, - String... args) throws IOException { + public void help(final ConsoleManager manager, + final String... args) { // } + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#tip() */ + @Override + public String tip() { + return null; + } + } diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/ParametrizedCommand.java b/gclc/src/main/java/fr/bigeon/gclc/command/ParametrizedCommand.java index 046f874..98a57e9 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/ParametrizedCommand.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/ParametrizedCommand.java @@ -55,77 +55,106 @@ import fr.bigeon.gclc.exception.CommandRunExceptionType; import fr.bigeon.gclc.exception.InvalidParameterException; import fr.bigeon.gclc.manager.ConsoleManager; -/**

- * A command relying on the {@link CommandParameters} to store parameters values +/** A command relying on the {@link CommandParameters} to store parameters + * values. * * @author Emmanuel BIGEON */ public abstract class ParametrizedCommand extends Command { /** If the command may use interactive prompting for required parameters - * that were not provided on execution */ + * that were not provided on execution. */ private boolean interactive = true; - /** The manager */ + /** The manager. */ protected final ConsoleManager manager; - /** The boolean parameters mandatory status */ + /** The boolean parameters mandatory status. */ private final Set boolParams = new HashSet<>(); - /** The string parameters mandatory status */ + /** The string parameters mandatory status. */ private final Map stringParams = new HashMap<>(); - /** The parameters mandatory status */ + /** The parameters mandatory status. */ private final Map params = new HashMap<>(); /** The restriction of provided parameters on execution to declared * paramters in the status maps. */ private final boolean strict; - /** @param manager the manager + /** Create a parametrized command. + *

+ * Implementation are supposed to call the + * {@link #addBooleanParameter(String)} and + * {@link #addStringParameter(String, boolean)} method to set the + * parameters. + * + * @param manager the manager * @param name the name */ - public ParametrizedCommand(ConsoleManager manager, String name) { + public ParametrizedCommand(final ConsoleManager manager, + final String name) { this(manager, name, true); } - /** @param name the name */ - public ParametrizedCommand(String name) { - this(null, name, true); - } - - /** @param manager the manager + /** Create a parametrized command. + *

+ * Implementation are supposed to call the + * {@link #addBooleanParameter(String)} and + * {@link #addStringParameter(String, boolean)} method to set the + * parameters. + * + * @param manager the manager * @param name the name * @param strict if the arguments are restricted to the declared ones */ - public ParametrizedCommand(ConsoleManager manager, String name, - boolean strict) { + public ParametrizedCommand(final ConsoleManager manager, final String name, + final boolean strict) { super(name); this.manager = manager; interactive = manager != null; this.strict = strict; } - /** @param name the name + /** Create a parametrized command. + *

+ * Implementation are supposed to call the + * {@link #addBooleanParameter(String)} and + * {@link #addStringParameter(String, boolean)} method to set the + * parameters. + * + * @param name the name */ + public ParametrizedCommand(final String name) { + this(null, name, true); + } + + /** Create a parametrized command. + *

+ * Implementation are supposed to call the + * {@link #addBooleanParameter(String)} and + * {@link #addStringParameter(String, boolean)} method to set the + * parameters. + * + * @param name the name * @param strict if the arguments are restricted to the declared ones */ - public ParametrizedCommand(String name, boolean strict) { + public ParametrizedCommand(final String name, final boolean strict) { this(null, name, strict); } /** Add a boolean parameter to defined parmaters. - * + * * @param flag the boolean flag * @throws InvalidParameterException if the parameter is already defined as * a string parameter */ - protected void addBooleanParameter(String flag) throws InvalidParameterException { + protected final void addBooleanParameter(final String flag) throws InvalidParameterException { if (params.containsKey(flag) && stringParams.containsKey(flag)) { throw new InvalidParameterException( "Parameter is already defined as string"); //$NON-NLS-1$ } boolParams.add(flag); - params.put(flag, Boolean.valueOf(false)); + params.put(flag, Boolean.FALSE); } /** Add a string parameter to defined parmaters. - * + * * @param flag the parameter flag * @param needed if the parameter's absence should cause an exception * @throws InvalidParameterException if the parameter is already defined as * a boolean parameter */ - protected void addStringParameter(String flag, - boolean needed) throws InvalidParameterException { + protected final void addStringParameter(final String flag, + final boolean needed) throws InvalidParameterException { if (params.containsKey(flag)) { checkParam(flag, needed); return; @@ -134,13 +163,15 @@ public abstract class ParametrizedCommand extends Command { params.put(flag, Boolean.valueOf(needed)); } - /** @param param the string parameter + /** Check a parameter. + * + * @param param the string parameter * @param needed if the parameter is needed * @throws InvalidParameterException if the new definition is invalid */ - private void checkParam(String param, - boolean needed) throws InvalidParameterException { + private void checkParam(final String param, + final boolean needed) throws InvalidParameterException { if (stringParams.containsKey(param)) { - Boolean need = Boolean + final Boolean need = Boolean .valueOf(needed || stringParams.get(param).booleanValue()); stringParams.put(param, need); params.put(param, need); @@ -150,26 +181,28 @@ public abstract class ParametrizedCommand extends Command { "Parameter is already defined as boolean"); //$NON-NLS-1$ } - /** @param parameters the command parameters + /** Actually performs the execution after parsing the parameters. + * + * @param parameters the command parameters * @throws CommandRunException if the command failed */ protected abstract void doExecute(CommandParameters parameters) throws CommandRunException; /* (non-Javadoc) * @see fr.bigeon.gclc.command.Command#execute(java.lang.String[]) */ - @SuppressWarnings("boxing") @Override - public final void execute(String... args) throws CommandRunException { + public final void execute(final String... args) throws CommandRunException { final CommandParameters parameters = new CommandParameters(boolParams, stringParams.keySet(), strict); try { parameters.parseArgs(args); - } catch (CommandParsingException e) { + } catch (final CommandParsingException e) { throw new CommandRunException(CommandRunExceptionType.USAGE, "Unable to read arguments", e, this); //$NON-NLS-1$ } final List toProvide = new ArrayList<>(); for (final Entry string : params.entrySet()) { - if (string.getValue() && parameters.get(string.getKey()) == null) { + if (string.getValue().booleanValue() && + parameters.get(string.getKey()) == null) { if (!interactive) { throw new CommandRunException( CommandRunExceptionType.INTERACTION, @@ -184,23 +217,26 @@ public abstract class ParametrizedCommand extends Command { doExecute(parameters); } - /** @param parameters the parameter list to complete + /** Fill the undefined parameters. + *

+ * This method prompts the user to fill the needed parameters. + * + * @param parameters the parameter list to complete * @param toProvide the parameters to ask for * @throws CommandRunException if the manager was closed */ - private void fillParameters(List toProvide, - CommandParameters parameters) throws CommandRunException { + private final void fillParameters(final List toProvide, + final CommandParameters parameters) throws CommandRunException { for (final String string : toProvide) { String value; try { value = manager .prompt(MessageFormat.format("value of {0}? ", string)); //$NON-NLS-1$ while (value.isEmpty()) { - value = manager.prompt( - MessageFormat.format( - "value of {0}? (cannot be empty) ", //$NON-NLS-1$ - string)); + value = manager.prompt(MessageFormat.format( + "value of {0}? (cannot be empty) ", //$NON-NLS-1$ + string)); } - } catch (IOException e) { + } catch (final IOException e) { throw new CommandRunException( CommandRunExceptionType.INTERACTION, "Interactive command but manager closed...", e, this); //$NON-NLS-1$ @@ -209,34 +245,48 @@ public abstract class ParametrizedCommand extends Command { } } - /** @return the set of boolean parameters */ - public Set getBooleanParameters() { + /** Retrieve the boolean parameters (aka flags). + * + * @return the set of boolean parameters */ + public final Set getBooleanParameters() { return Collections.unmodifiableSet(boolParams); } - /** @return the stringParams */ - public Set getStringParameters() { - return stringParams.keySet(); - } - - /** @return the stringParams */ - public Set getParameters() { + /** Retrieve the parameter names. + * + * @return the stringParams */ + public final Set getParameters() { return params.keySet(); } - /** @param param the parameter name + /** Get the string parameters names. + * + * @return the stringParams */ + public final Set getStringParameters() { + return stringParams.keySet(); + } + + /** If the command is interactive. + *

+ * An interactive command will prompt the user for missing parameters. + * + * @return the interactive */ + public final boolean isInteractive() { + return interactive; + } + + /** Test if a parameter is needed. + * + * @param param the parameter name * @return if the parameter is needed */ - public boolean isNeeded(String param) { + public final boolean isNeeded(final String param) { return params.containsKey(param) && params.get(param).booleanValue(); } - /** @return the strict */ - public boolean isStrict() { + /** If the command refuse unrecognized parameters. + * + * @return the strict */ + public final boolean isStrict() { return strict; } - - /** @return the interactive */ - public boolean isInteractive() { - return interactive; - } } diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/ScriptExecution.java b/gclc/src/main/java/fr/bigeon/gclc/command/ScriptExecution.java index 91129c3..155e6cd 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/ScriptExecution.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/ScriptExecution.java @@ -59,7 +59,7 @@ import fr.bigeon.gclc.exception.CommandRunExceptionType; * as a command of the application. * * @author Emmanuel Bigeon */ -public class ScriptExecution extends Command { +public final class ScriptExecution extends Command { /** The tab character */ private static final String TAB = "\t"; //$NON-NLS-1$ @@ -76,21 +76,31 @@ public class ScriptExecution extends Command { * @param application the application * @param commentPrefix the comment prefix in the script files * @param charset the charset to use for files */ - public ScriptExecution(String name, ConsoleApplication application, - String commentPrefix, Charset charset) { + public ScriptExecution(final String name, final ConsoleApplication application, + final String commentPrefix, final Charset charset) { super(name); this.application = application; this.commentPrefix = commentPrefix; this.charset = charset; } + /** @param args the arguments + * @throws CommandRunException if the arguments were not the ones + * expected */ + private void checkArgs(final String[] args) throws CommandRunException { + if (args.length == 0) { + throw new CommandRunException(CommandRunExceptionType.USAGE, + "Expecting a file", this); //$NON-NLS-1$ + } + } + /* (non-Javadoc) * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */ @Override - public void execute(String... args) throws CommandRunException { + public void execute(final String... args) throws CommandRunException { checkArgs(args); - String scriptFile = args[0]; - String[] params = Arrays.copyOfRange(args, 1, args.length); + final String scriptFile = args[0]; + final String[] params = Arrays.copyOfRange(args, 1, args.length); String cmd; int lineNo = -1; try (InputStreamReader fReader = new InputStreamReader( @@ -98,44 +108,34 @@ public class ScriptExecution extends Command { BufferedReader reader = new BufferedReader(fReader)) { while ((cmd = reader.readLine()) != null) { lineNo++; - String cmdLine = readCommandLine(cmd, params); + final String cmdLine = readCommandLine(cmd, params); if (cmdLine == null) { continue; } - List ps = GCLCConstants.splitCommand(cmdLine); - String command = ps.remove(0); + final List ps = GCLCConstants.splitCommand(cmdLine); + final String command = ps.remove(0); application.executeSub(command, ps.toArray(new String[0])); } - } catch (CommandParsingException e) { + } catch (final CommandParsingException e) { throw new CommandRunException(MessageFormat.format( "Invalid command in script ({0})", e.getLocalizedMessage()), //$NON-NLS-1$ e, this); - } catch (IOException e) { + } catch (final IOException e) { throw new CommandRunException("Unable to read script", //$NON-NLS-1$ e, this); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { throw manageRunException(e, lineNo); } } - /** @param args the arguments - * @throws CommandRunException if the arguments were not the ones - * expected */ - private void checkArgs(String[] args) throws CommandRunException { - if (args.length == 0) { - throw new CommandRunException(CommandRunExceptionType.USAGE, - "Expecting a file", this); //$NON-NLS-1$ - } - } - /** This method will create the correct exception. The exception source must * be this command. - * + * * @param e the exception * @param lineNo the line nu;ber * @return the exception to actually throw */ - private CommandRunException manageRunException(CommandRunException e, - int lineNo) { + private CommandRunException manageRunException(final CommandRunException e, + final int lineNo) { if (e.getSource() == this) { // ensure closing? return e; @@ -151,8 +151,8 @@ public class ScriptExecution extends Command { * @param params the formatting parameters * @return the command if it is indeed one, null otherwise * @throws CommandRunException if the line stqrted with a space character */ - private String readCommandLine(String cmd, - Object[] params) throws CommandRunException { + private String readCommandLine(final String cmd, + final Object[] params) throws CommandRunException { if (cmd.startsWith(SPACE) || cmd.startsWith(TAB)) { throw new CommandRunException( "Invalid command in script (line starts with space character)", //$NON-NLS-1$ @@ -164,24 +164,31 @@ public class ScriptExecution extends Command { return MessageFormat.format(cmd, params); } + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#tip() */ + @Override + public String tip() { + return "Execute a script"; //$NON-NLS-1$ + } + /* (non-Javadoc) * @see fr.bigeon.gclc.command.Command#usageDetail() */ - @SuppressWarnings("nls") @Override protected String usageDetail() { - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); builder.append( - " scriptfile: path to the file containing the script to execute."); + " scriptfile: path to the file containing the script to execute."); //$NON-NLS-1$ builder.append(System.lineSeparator()); builder.append(System.lineSeparator()); builder.append( - " The script file must contain one line commands. The lines must never"); + " The script file must contain one line commands. The lines must never"); //$NON-NLS-1$ builder.append(System.lineSeparator()); builder.append( - "start with whitespace characters. The lines starting with"); + "start with whitespace characters. The lines starting with"); //$NON-NLS-1$ builder.append(System.lineSeparator()); - builder.append("\"" + commentPrefix + - "\" will be ignored as well as empty lines."); + builder.append('"'); + builder.append(commentPrefix); + builder.append("\" will be ignored as well as empty lines."); //$NON-NLS-1$ builder.append(System.lineSeparator()); return builder.toString(); @@ -189,18 +196,9 @@ public class ScriptExecution extends Command { /* (non-Javadoc) * @see fr.bigeon.gclc.command.Command#usagePattern() */ - @SuppressWarnings("nls") @Override protected String usagePattern() { - return super.usagePattern() + " "; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#tip() */ - @SuppressWarnings("nls") - @Override - public String tip() { - return "Execute a script"; + return super.usagePattern() + " "; //$NON-NLS-1$ } } diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/SubedCommand.java b/gclc/src/main/java/fr/bigeon/gclc/command/SubedCommand.java index 569509d..28aaaf6 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/SubedCommand.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/SubedCommand.java @@ -41,33 +41,32 @@ import java.util.Arrays; import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunExceptionType; -import fr.bigeon.gclc.exception.InvalidCommandName; import fr.bigeon.gclc.manager.ConsoleManager; -/**

+/** + *

* A subed command is a command that can execute sub commands depending on the * first argument. * * @author Emmanuel BIGEON */ -public class SubedCommand implements ICommandProvider, ICommand { +public final class SubedCommand extends CommandProvider implements ICommand { /** The tab character */ private static final String TAB = "\t"; //$NON-NLS-1$ - /**

- * The command to execute when this command is called with no sub arguments. + /** The command to execute when this command is called with no sub + * arguments. + *

* This may be null, in which case the command should have arguments. */ private final ICommand noArgCommand; /** A tip on this command. */ private final String tip; - /** The provider */ - private final CommandProvider provider; /** The name of the command */ private final String name; /** @param name the name of the command */ - public SubedCommand(String name) { + public SubedCommand(final String name) { + super(); this.name = name; - provider = new CommandProvider(); noArgCommand = null; tip = null; } @@ -75,9 +74,9 @@ public class SubedCommand implements ICommandProvider, ICommand { /** @param name the name of the command * @param noArgCommand the command to execute when no extra parameter are * provided */ - public SubedCommand(String name, ICommand noArgCommand) { + public SubedCommand(final String name, final ICommand noArgCommand) { + super(); this.name = name; - provider = new CommandProvider(); this.noArgCommand = noArgCommand; tip = null; } @@ -85,32 +84,27 @@ public class SubedCommand implements ICommandProvider, ICommand { /** @param name the name of the command * @param noArgCommand the command to execute * @param tip the help tip associated */ - public SubedCommand(String name, ICommand noArgCommand, - String tip) { + public SubedCommand(final String name, final ICommand noArgCommand, + final String tip) { + super(); this.name = name; - provider = new CommandProvider(); this.noArgCommand = noArgCommand; this.tip = tip; } /** @param name the name of the command * @param tip the help tip associated */ - public SubedCommand(String name, String tip) { + public SubedCommand(final String name, final String tip) { + super(); this.name = name; - provider = new CommandProvider(); noArgCommand = null; this.tip = tip; } - @Override - public boolean add(ICommand value) throws InvalidCommandName { - return provider.add(value); - } - /* (non-Javadoc) * @see fr.bigeon.acide.Command#execute(java.lang.String[]) */ @Override - public void execute(String... args) throws CommandRunException { + public void execute(final String... args) throws CommandRunException { if (args.length == 0 || args[0].startsWith("-")) { //$NON-NLS-1$ if (noArgCommand != null) { noArgCommand.execute(args); @@ -118,10 +112,10 @@ public class SubedCommand implements ICommandProvider, ICommand { throw new CommandRunException("Unrecognized command", this); //$NON-NLS-1$ } } else { - + try { executeSub(args[0], Arrays.copyOfRange(args, 1, args.length)); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { if (e.getSource() != null) { throw e; } @@ -131,21 +125,6 @@ public class SubedCommand implements ICommandProvider, ICommand { } } - /* (non-Javadoc) - * @see - * fr.bigeon.gclc.command.ICommandProvider#executeSub(java.lang.String, - * java.lang.String[]) */ - @Override - public void executeSub(String command, - String... args) throws CommandRunException { - provider.executeSub(command, args); - } - - @Override - public ICommand get(String commandName) { - return provider.get(commandName); - } - /* (non-Javadoc) * @see fr.bigeon.gclc.command.ICommand#getCommandName() */ @Override @@ -156,8 +135,8 @@ public class SubedCommand implements ICommandProvider, ICommand { /* (non-Javadoc) * @see fr.bigeon.gclc.command.Command#help() */ @Override - public void help(ConsoleManager manager, - String... args) throws IOException { + public void help(final ConsoleManager manager, + final String... args) throws IOException { if (args.length != 0 && !args[0].startsWith("-")) { //$NON-NLS-1$ // Specific final ICommand c = get(args[0]); @@ -166,17 +145,17 @@ public class SubedCommand implements ICommandProvider, ICommand { } } else { // Generic - if (noArgCommand != null && noArgCommand.tip() != null) { - manager.println(TAB + noArgCommand.tip()); - } - for (final ICommand cmd : provider.commands) { - if (cmd.tip() == null) { - manager.println(TAB + cmd.getCommandName()); - } else { - manager.println(TAB + cmd.getCommandName() + ": " + //$NON-NLS-1$ - cmd.tip()); - } + if (noArgCommand != null && noArgCommand.tip() != null) { + manager.println(TAB + noArgCommand.tip()); + } + for (final ICommand cmd : commands) { + if (cmd.tip() == null) { + manager.println(TAB + cmd.getCommandName()); + } else { + manager.println(TAB + cmd.getCommandName() + ": " + //$NON-NLS-1$ + cmd.tip()); } + } } } @@ -191,7 +170,7 @@ public class SubedCommand implements ICommandProvider, ICommand { * @see java.lang.Object#toString() */ @Override public String toString() { - return "SubedCommand " + provider; //$NON-NLS-1$ + return "SubedCommand " + super.toString(); //$NON-NLS-1$ } } diff --git a/gclc/src/main/java/fr/bigeon/gclc/exception/CommandRunException.java b/gclc/src/main/java/fr/bigeon/gclc/exception/CommandRunException.java index c9bf497..7170adf 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/exception/CommandRunException.java +++ b/gclc/src/main/java/fr/bigeon/gclc/exception/CommandRunException.java @@ -44,7 +44,7 @@ import fr.bigeon.gclc.command.ICommand; * An exception thrown when a command failed to run correctly. * * @author Emmanuel BIGEON */ -public class CommandRunException extends Exception { +public final class CommandRunException extends Exception { /** * @@ -54,31 +54,13 @@ public class CommandRunException extends Exception { /** The type of run exception */ private final CommandRunExceptionType type; /** The command that caused the error */ - private final ICommand source; - - /** @param message a message - * @param source the source */ - public CommandRunException(String message, ICommand source) { - super(message); - type = CommandRunExceptionType.EXECUTION; - this.source = source; - } - - /** @param message a message - * @param cause the cause - * @param source the source */ - public CommandRunException(String message, Throwable cause, - ICommand source) { - super(message, cause); - type = CommandRunExceptionType.EXECUTION; - this.source = source; - } + private final transient ICommand source; /** @param type the type of exception * @param message the message * @param source the source */ - public CommandRunException(CommandRunExceptionType type, String message, - ICommand source) { + public CommandRunException(final CommandRunExceptionType type, final String message, + final ICommand source) { super(message); this.type = type; this.source = source; @@ -88,13 +70,31 @@ public class CommandRunException extends Exception { * @param message a message * @param cause the cause * @param source the source */ - public CommandRunException(CommandRunExceptionType type, String message, - Throwable cause, ICommand source) { + public CommandRunException(final CommandRunExceptionType type, final String message, + final Throwable cause, final ICommand source) { super(message, cause); this.type = type; this.source = source; } + /** @param message a message + * @param source the source */ + public CommandRunException(final String message, final ICommand source) { + super(message); + type = CommandRunExceptionType.EXECUTION; + this.source = source; + } + + /** @param message a message + * @param cause the cause + * @param source the source */ + public CommandRunException(final String message, final Throwable cause, + final ICommand source) { + super(message, cause); + type = CommandRunExceptionType.EXECUTION; + this.source = source; + } + /* (non-Javadoc) * @see java.lang.Throwable#getLocalizedMessage() */ @Override diff --git a/gclc/src/main/java/fr/bigeon/gclc/i18n/Messages.java b/gclc/src/main/java/fr/bigeon/gclc/i18n/Messages.java index 097b828..7a10253 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/i18n/Messages.java +++ b/gclc/src/main/java/fr/bigeon/gclc/i18n/Messages.java @@ -47,7 +47,7 @@ import java.util.logging.Logger; /** Internationalization class. * * @author Emmanuel Bigeon */ -public class Messages { +public final class Messages { /** The resource bundle name */ private static final String BUNDLE_NAME = "fr.bigeon.gclc.l10n.messages"; //$NON-NLS-1$ @@ -65,14 +65,14 @@ public class Messages { } /** Get formatted internationalized messages - * + * * @param key the message key * @param args the formatting arguments * @return the formatted internationalized message */ - public static String getString(String key, Object... args) { + public static String getString(final String key, final Object... args) { try { return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args); - } catch (MissingResourceException e) { + } catch (final MissingResourceException e) { LOGGER.log(Level.WARNING, "Unrecognized internationalization message key: " + key, e); //$NON-NLS-1$ return '!' + key + '!'; diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/PipedConsoleManager.java b/gclc/src/main/java/fr/bigeon/gclc/manager/PipedConsoleManager.java index c5ca922..f2349f2 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/PipedConsoleManager.java +++ b/gclc/src/main/java/fr/bigeon/gclc/manager/PipedConsoleManager.java @@ -44,7 +44,7 @@ import java.io.InputStreamReader; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; /** This console manager allows to enter commands and retrieve the output as an * input. @@ -75,18 +75,20 @@ public final class PipedConsoleManager /** The reading thread */ private final ReadingRunnable reading; - /** @throws IOException if the piping failed for streams */ + /** Create a manager that will write and read through piped stream. + * + * @throws IOException if the piping failed for streams */ public PipedConsoleManager() throws IOException { commandInput = new PipedOutputStream(); in = new PipedInputStream(commandInput); commandOutput = new PipedInputStream(); - PipedOutputStream out = new PipedOutputStream(commandOutput); + final PipedOutputStream out = new PipedOutputStream(commandOutput); commandBuffOutput = new BufferedReader( - new InputStreamReader(commandOutput, Charset.forName(UTF_8))); + new InputStreamReader(commandOutput, StandardCharsets.UTF_8)); outPrint = new PrintStream(out, true, UTF_8); innerManager = new SystemConsoleManager(outPrint, in, - Charset.forName(UTF_8)); - writing = new WritingRunnable(commandInput, Charset.forName(UTF_8)); + StandardCharsets.UTF_8); + writing = new WritingRunnable(commandInput, StandardCharsets.UTF_8); reading = new ReadingRunnable(commandBuffOutput); Thread th = new Thread(writing, "write"); //$NON-NLS-1$ th.start(); @@ -95,13 +97,50 @@ public final class PipedConsoleManager th.start(); } + /** @return the content of the next line written by the application + * @throws IOException if the reading failed */ + public boolean available() throws IOException { + return reading.hasMessage(); + } + + @Override + public void close() throws IOException { + reading.setRunning(false); + writing.setRunning(false); + in.close(); + innerManager.close(); + outPrint.close(); + commandBuffOutput.close(); + commandOutput.close(); + commandInput.close(); + } + @Override public String getPrompt() { return innerManager.getPrompt(); } + /** @param message the message + * @return the thread to join to wait for message delivery + * @see fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String) */ + public Thread getWaitForDelivery(final String message) { + return reading.getWaitForDelivery(message); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */ @Override - public void print(String object) throws IOException { + public void interruptPrompt() { + innerManager.interruptPrompt(); + } + + @Override + public boolean isClosed() { + return innerManager.isClosed(); + } + + @Override + public void print(final String object) throws IOException { innerManager.print(object); } @@ -111,7 +150,7 @@ public final class PipedConsoleManager } @Override - public void println(String object) throws IOException { + public void println(final String object) throws IOException { innerManager.println(object); } @@ -124,72 +163,35 @@ public final class PipedConsoleManager /* (non-Javadoc) * @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */ @Override - public String prompt(long timeout) throws IOException { + public String prompt(final long timeout) throws IOException { return innerManager.prompt(timeout); } @Override - public String prompt(String message) throws IOException { + public String prompt(final String message) throws IOException { return innerManager.prompt(message + System.lineSeparator()); } @Override - public String prompt(String message, long timeout) throws IOException { + public String prompt(final String message, final long timeout) throws IOException { return innerManager.prompt(message + System.lineSeparator(), timeout); } - @Override - public void setPrompt(String prompt) { - innerManager.setPrompt(prompt); - } - - @Override - public void close() throws IOException { - innerManager.close(); - reading.setRunning(false); - writing.setRunning(false); - outPrint.close(); - commandBuffOutput.close(); - commandOutput.close(); - in.close(); - commandInput.close(); - } - - @Override - public boolean isClosed() { - return innerManager.isClosed(); - } - - /** @param content the content to type to the application - * @throws IOException if the typing failed */ - public void type(String content) throws IOException { - writing.addMessage(content); - } - /** @return the content of the next line written by the application * @throws IOException if the reading failed */ public String readNextLine() throws IOException { return reading.getMessage(); } - /** @return the content of the next line written by the application - * @throws IOException if the reading failed */ - public boolean available() throws IOException { - return reading.hasMessage(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */ @Override - public void interruptPrompt() { - innerManager.interruptPrompt(); + public void setPrompt(final String prompt) { + innerManager.setPrompt(prompt); } - /** @param message the message - * @return the thread to join to wait for message delivery - * @see fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String) */ - public Thread getWaitForDelivery(String message) { - return reading.getWaitForDelivery(message); + /** @param content the content to type to the application + * @throws IOException if the typing failed */ + public void type(final String content) throws IOException { + writing.addMessage(content); } } diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/ReadingRunnable.java b/gclc/src/main/java/fr/bigeon/gclc/manager/ReadingRunnable.java index b33e15c..7c646be 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/ReadingRunnable.java +++ b/gclc/src/main/java/fr/bigeon/gclc/manager/ReadingRunnable.java @@ -51,7 +51,7 @@ import java.util.logging.Logger; /** A runnable to read the piped output. * * @author Emmanuel Bigeon */ -public class ReadingRunnable implements Runnable { +public final class ReadingRunnable implements Runnable { /** The runnable to wait for notification on an object * @@ -69,19 +69,26 @@ public class ReadingRunnable implements Runnable { /** @param obj the object to lock on * @param start the object to notify when ready to wait * @param message the message to wait for */ - public ToWaitRunnable(Object obj, Object start, String message) { + public ToWaitRunnable(final Object obj, final Object start, final String message) { this.obj = obj; this.start = start; this.message = message; } + /** @return the started */ + public boolean isStarted() { + synchronized (start) { + return started; + } + } + @SuppressWarnings("synthetic-access") @Override public void run() { synchronized (obj) { synchronized (start) { started = true; - start.notify(); + start.notifyAll(); } while (isRunning()) { try { @@ -89,20 +96,14 @@ public class ReadingRunnable implements Runnable { if (delivering.equals(message)) { return; } - } catch (InterruptedException e) { + } catch (final InterruptedException e) { LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e); + Thread.currentThread().interrupt(); } } } } - - /** @return the started */ - public boolean isStarted() { - synchronized (start) { - return started; - } - } } /** The thread intteruption logging message */ @@ -133,49 +134,16 @@ public class ReadingRunnable implements Runnable { private String delivering; /** @param reader the input to read from */ - public ReadingRunnable(BufferedReader reader) { + public ReadingRunnable(final BufferedReader reader) { super(); this.reader = reader; } - /* (non-Javadoc) - * @see java.lang.Runnable#run() */ - @Override - public void run() { - - while (running) { - try { - String line = reader.readLine(); - if (line == null) { - // Buffer end - running = false; - return; - } - LOGGER.finer("Read: " + line); //$NON-NLS-1$ - line = stripNull(line); - synchronized (lock) { - messages.add(line); - lock.notify(); - } - } catch (InterruptedIOException e) { - LOGGER.info("Reading interrupted"); //$NON-NLS-1$ - LOGGER.log(Level.FINER, - "Read interruption was caused by an exception", e); //$NON-NLS-1$ - } catch (IOException e) { - LOGGER.severe("Unable to read from stream"); //$NON-NLS-1$ - LOGGER.log(Level.FINE, "The stream reading threw an exception", //$NON-NLS-1$ - e); - running = false; - return; - } - } - } - /** Strip the string from head NULL characters. - * + * * @param line the line to strip the null character from * @return the resulting string */ - private static String stripNull(String line) { + private static String stripNull(final String line) { String res = line; while (res.length() > 0 && res.charAt(0) == 0) { LOGGER.severe( @@ -196,8 +164,9 @@ public class ReadingRunnable implements Runnable { while (messages.isEmpty()) { try { lock.wait(TIMEOUT); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e); + Thread.currentThread().interrupt(); } if (messages.isEmpty() && !running) { throw new IOException(CLOSED_PIPE); @@ -213,7 +182,7 @@ public class ReadingRunnable implements Runnable { /** @param timeout the read time out * @return The next message that was in the input * @throws IOException if the input was closed */ - public String getNextMessage(long timeout) throws IOException { + public String getNextMessage(final long timeout) throws IOException { synchronized (lock) { if (!running) { throw new IOException(CLOSED_PIPE); @@ -221,8 +190,9 @@ public class ReadingRunnable implements Runnable { waiting = true; try { lock.wait(timeout); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e); + Thread.currentThread().interrupt(); } if (messages.isEmpty() && !running) { throw new IOException(CLOSED_PIPE); @@ -235,17 +205,31 @@ public class ReadingRunnable implements Runnable { } } - /** @param running the running to set */ - public void setRunning(boolean running) { - synchronized (lock) { - this.running = running; - } - } + /** @param message the message + * @return the thread to join to wait for message delivery */ + public Thread getWaitForDelivery(final String message) { + synchronized (messageBlockerLock) { + if (!messageBlocker.containsKey(message)) { + messageBlocker.put(message, new Object()); + } + final Object obj = messageBlocker.get(message); + final Object start = new Object(); + final ToWaitRunnable waitRunn = new ToWaitRunnable(obj, start, message); + final Thread th = new Thread(waitRunn); - /** @return the running */ - public boolean isRunning() { - synchronized (lock) { - return running; + synchronized (start) { + th.start(); + while (!waitRunn.isStarted()) { + try { + start.wait(TIMEOUT); + } catch (final InterruptedException e) { + LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, + e); + Thread.currentThread().interrupt(); + } + } + } + return th; } } @@ -265,49 +249,68 @@ public class ReadingRunnable implements Runnable { synchronized (lock) { if (waiting) { messages.offer(""); //$NON-NLS-1$ - lock.notify(); + lock.notifyAll(); } } } + /** @return the running */ + public boolean isRunning() { + synchronized (lock) { + return running; + } + } + /** @param message the message */ - private void notifyMessage(String message) { + private void notifyMessage(final String message) { synchronized (messageBlockerLock) { delivering = message; if (messageBlocker.containsKey(message)) { - Object mLock = messageBlocker.get(message); + final Object mLock = messageBlocker.get(message); synchronized (mLock) { - mLock.notify(); + mLock.notifyAll(); } messageBlocker.remove(message); } } } - /** @param message the message - * @return the thread to join to wait for message delivery */ - public Thread getWaitForDelivery(final String message) { - synchronized (messageBlockerLock) { - if (!messageBlocker.containsKey(message)) { - messageBlocker.put(message, new Object()); - } - final Object obj = messageBlocker.get(message); - final Object start = new Object(); - ToWaitRunnable waitRunn = new ToWaitRunnable(obj, start, message); - Thread th = new Thread(waitRunn); - - synchronized (start) { - th.start(); - while (!waitRunn.isStarted()) { - try { - start.wait(TIMEOUT); - } catch (InterruptedException e) { - LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, - e); - } + /* (non-Javadoc) + * @see java.lang.Runnable#run() */ + @Override + public void run() { + while (running) { + try { + String line = reader.readLine(); + if (line == null) { + // Buffer end + running = false; + return; } + LOGGER.finer("Read: " + line); //$NON-NLS-1$ + line = stripNull(line); + synchronized (lock) { + messages.add(line); + lock.notifyAll(); + } + } catch (final InterruptedIOException e) { + LOGGER.info("Reading interrupted"); //$NON-NLS-1$ + LOGGER.log(Level.FINER, + "Read interruption was caused by an exception", e); //$NON-NLS-1$ + } catch (final IOException e) { + LOGGER.severe("Unable to read from stream"); //$NON-NLS-1$ + LOGGER.log(Level.FINE, "The stream reading threw an exception", //$NON-NLS-1$ + e); + running = false; + return; } - return th; + } + } + + /** @param running the running to set */ + public void setRunning(final boolean running) { + synchronized (lock) { + this.running = running; } } } diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/SystemConsoleManager.java b/gclc/src/main/java/fr/bigeon/gclc/manager/SystemConsoleManager.java index 56072a3..d5776f5 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/SystemConsoleManager.java +++ b/gclc/src/main/java/fr/bigeon/gclc/manager/SystemConsoleManager.java @@ -50,7 +50,7 @@ import java.nio.charset.Charset; * The default constructor will use the system standart input and output. * * @author Emmanuel BIGEON */ -public final class SystemConsoleManager implements ConsoleManager { // NOSONAR +public final class SystemConsoleManager implements ConsoleManager { /** The default prompt */ public static final String DEFAULT_PROMPT = "> "; //$NON-NLS-1$ @@ -81,8 +81,8 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR /** @param out the output stream * @param in the input stream * @param charset the charset for the input */ - public SystemConsoleManager(PrintStream out, InputStream in, - Charset charset) { + public SystemConsoleManager(final PrintStream out, final InputStream in, + final Charset charset) { super(); this.out = out; this.in = new BufferedReader(new InputStreamReader(in, charset)); @@ -92,27 +92,52 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR promptThread.start(); } + /** @throws IOException if the stream was closed */ + private void checkOpen() throws IOException { + if (closed) { + throw new IOException(); + } + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleManager#close() */ + @Override + public void close() throws IOException { + closed = true; + reading.setRunning(false); + promptThread.interrupt(); + in.close(); + } + /** @return the prompt */ @Override public String getPrompt() { return prompt; } + /** Beware, in this implementation this is the same as closing the manager. + * + * @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */ + @Override + public void interruptPrompt() { + reading.interrupt(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleManager#isClosed() */ + @Override + public boolean isClosed() { + return closed; + } + /* (non-Javadoc) * @see fr.bigeon.gclc.ConsoleManager#print(java.lang.Object) */ @Override - public void print(String object) throws IOException { + public void print(final String object) throws IOException { checkOpen(); out.print(object); } - /** @throws IOException if the stream was closed */ - private void checkOpen() throws IOException { - if (closed) { - throw new IOException(); - } - } - /* (non-Javadoc) * @see fr.bigeon.gclc.ConsoleManager#println() */ @Override @@ -124,7 +149,7 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR /* (non-Javadoc) * @see fr.bigeon.gclc.ConsoleManager#println(java.lang.Object) */ @Override - public void println(String object) throws IOException { + public void println(final String object) throws IOException { checkOpen(); out.println(object); } @@ -139,14 +164,14 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR /* (non-Javadoc) * @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */ @Override - public String prompt(long timeout) throws IOException { + public String prompt(final long timeout) throws IOException { return prompt(prompt, timeout); } /* (non-Javadoc) * @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */ @Override - public String prompt(String message) throws IOException { + public String prompt(final String message) throws IOException { checkOpen(); out.print(message); return reading.getMessage(); @@ -155,7 +180,7 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR /* (non-Javadoc) * @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */ @Override - public String prompt(String message, long timeout) throws IOException { + public String prompt(final String message, final long timeout) throws IOException { checkOpen(); out.print(message); return reading.getNextMessage(timeout); @@ -163,32 +188,8 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR /** @param prompt the prompt to set */ @Override - public void setPrompt(String prompt) { + public void setPrompt(final String prompt) { this.prompt = prompt; } - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleManager#close() */ - @Override - public void close() throws IOException { - closed = true; - reading.setRunning(false); - promptThread.interrupt(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleManager#isClosed() */ - @Override - public boolean isClosed() { - return closed; - } - - /** Beware, in this implementation this is the same as closing the manager. - * - * @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */ - @Override - public void interruptPrompt() { - reading.interrupt(); - } - } diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/WritingRunnable.java b/gclc/src/main/java/fr/bigeon/gclc/manager/WritingRunnable.java index f7bb87e..b554654 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/WritingRunnable.java +++ b/gclc/src/main/java/fr/bigeon/gclc/manager/WritingRunnable.java @@ -52,7 +52,7 @@ import java.util.logging.Logger; * Messages are queued to be retrieved latter on. * * @author Emmanuel Bigeon */ -public class WritingRunnable implements Runnable { +public final class WritingRunnable implements Runnable { /** Wait timeout */ private static final long TIMEOUT = 1000; @@ -73,12 +73,31 @@ public class WritingRunnable implements Runnable { /** @param outPrint the output to print to * @param charset the charset of the stream */ - public WritingRunnable(OutputStream outPrint, Charset charset) { + public WritingRunnable(final OutputStream outPrint, final Charset charset) { super(); this.outPrint = outPrint; this.charset = charset; } + /** @param message the message + * @throws IOException if the pipe is closed */ + public void addMessage(final String message) throws IOException { + synchronized (lock) { + if (!running) { + throw new IOException("Closed pipe"); //$NON-NLS-1$ + } + messages.offer(message); + lock.notifyAll(); + } + } + + /** @return the running */ + public boolean isRunning() { + synchronized (lock) { + return running; + } + } + /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override @@ -89,21 +108,22 @@ public class WritingRunnable implements Runnable { while (messages.isEmpty()) { try { lock.wait(TIMEOUT); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { LOGGER.log(Level.SEVERE, "Thread interruption exception.", e); //$NON-NLS-1$ + Thread.currentThread().interrupt(); } if (!running) { return; } } - String message = messages.poll(); - ByteBuffer buff = charset + final String message = messages.poll(); + final ByteBuffer buff = charset .encode(message + System.lineSeparator()); if (buff.hasArray()) { try { outPrint.write(buff.array()); - } catch (IOException e) { + } catch (final IOException e) { LOGGER.log(Level.SEVERE, "Unable to write to stream", //$NON-NLS-1$ e); } @@ -112,29 +132,10 @@ public class WritingRunnable implements Runnable { } } - /** @param message the message - * @throws IOException if the pipe is closed */ - public void addMessage(String message) throws IOException { - synchronized (lock) { - if (!running) { - throw new IOException("Closed pipe"); //$NON-NLS-1$ - } - messages.offer(message); - lock.notify(); - } - } - /** @param running the running to set */ - public void setRunning(boolean running) { + public void setRunning(final boolean running) { synchronized (lock) { this.running = running; } } - - /** @return the running */ - public boolean isRunning() { - synchronized (lock) { - return running; - } - } } diff --git a/gclc/src/main/java/fr/bigeon/gclc/package-info.java b/gclc/src/main/java/fr/bigeon/gclc/package-info.java new file mode 100644 index 0000000..626ada6 --- /dev/null +++ b/gclc/src/main/java/fr/bigeon/gclc/package-info.java @@ -0,0 +1,42 @@ +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.package-info.java + * Created on: Nov 5, 2017 + */ +/** A framework for commad line applications. + * + * @author Emmanuel Bigeon */ +package fr.bigeon.gclc; diff --git a/gclc/src/main/java/fr/bigeon/gclc/proc/ProcessKill.java b/gclc/src/main/java/fr/bigeon/gclc/proc/ProcessKill.java index b91f17d..eed2e17 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/proc/ProcessKill.java +++ b/gclc/src/main/java/fr/bigeon/gclc/proc/ProcessKill.java @@ -39,37 +39,41 @@ package fr.bigeon.gclc.proc; import fr.bigeon.gclc.command.Command; -import fr.bigeon.gclc.exception.CommandRunException; /** A command that will flag a task to stop * * @author Emmanuel Bigeon */ -public class ProcessKill extends Command { +public final class ProcessKill extends Command { /** The taskpool */ private final TaskPool pool; /** @param name the command name * @param pool the pool */ - public ProcessKill(String name, TaskPool pool) { + public ProcessKill(final String name, final TaskPool pool) { super(name); this.pool = pool; } /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) - */ + * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */ @Override - public void execute(String... args) throws CommandRunException { + public void execute(final String... args) { pool.get(args[0]).setRunning(false); } /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#tip() - */ + * @see fr.bigeon.gclc.command.ICommand#tip() */ @SuppressWarnings("nls") @Override public String tip() { return "Request a process to stop (softly)"; } + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#usageDetail() */ + @Override + protected String usageDetail() { + return null; + } + } diff --git a/gclc/src/main/java/fr/bigeon/gclc/proc/ProcessList.java b/gclc/src/main/java/fr/bigeon/gclc/proc/ProcessList.java index de82e53..22600ae 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/proc/ProcessList.java +++ b/gclc/src/main/java/fr/bigeon/gclc/proc/ProcessList.java @@ -51,7 +51,7 @@ import fr.bigeon.gclc.manager.ConsoleManager; /** A command to list current processes * * @author Emmanuel Bigeon */ -public class ProcessList extends Command { +public final class ProcessList extends Command { /** The process pool */ private final TaskPool pool; @@ -61,41 +61,45 @@ public class ProcessList extends Command { /** @param name the command name * @param pool the pool * @param manager the console manager */ - public ProcessList(String name, TaskPool pool, - ConsoleManager manager) { + public ProcessList(final String name, final TaskPool pool, + final ConsoleManager manager) { super(name); this.pool = pool; this.manager = manager; } /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) - */ + * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */ @Override - public void execute(String... args) throws CommandRunException { - ArrayList pids = new ArrayList<>(pool.getPIDs()); + public void execute(final String... args) throws CommandRunException { + final ArrayList pids = new ArrayList<>(pool.getPIDs()); Collections.sort(pids); - for (String string : pids) { + for (final String string : pids) { try { - manager.println( - MessageFormat.format("{0}\t{1}", string, //$NON-NLS-1$ - pool.get(string).getName())); - } catch (IOException e) { + manager.println(MessageFormat.format("{0}\t{1}", string, //$NON-NLS-1$ + pool.get(string).getName())); + } catch (final IOException e) { throw new CommandRunException( CommandRunExceptionType.INTERACTION, "Unable to communicate with user", e, this); //$NON-NLS-1$ } } - + } /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#tip() - */ + * @see fr.bigeon.gclc.command.ICommand#tip() */ @SuppressWarnings("nls") @Override public String tip() { return "List all processes"; } + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#usageDetail() */ + @Override + protected String usageDetail() { + return null; + } + } diff --git a/gclc/src/main/java/fr/bigeon/gclc/proc/Task.java b/gclc/src/main/java/fr/bigeon/gclc/proc/Task.java index 5b2e879..f961c81 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/proc/Task.java +++ b/gclc/src/main/java/fr/bigeon/gclc/proc/Task.java @@ -50,28 +50,32 @@ package fr.bigeon.gclc.proc; * * @author Emmanuel Bigeon */ public interface Task extends Runnable { - /** @return the task name */ - public String getName(); + /** Add a listener for this command end of execution + * + * @param listener the listener */ + void addInterruptionListener(InterruptionListener listener); - /** @return if the command is supposed to be running */ + /** Get the task name. + * + * @return the task name */ + String getName(); + + /** Test the running status of the task. + * + * @return if the command is supposed to be running */ boolean isRunning(); + /** Remove a listener of this command end of execution + * + * @param listener the listener */ + void rmInterruptionListener(InterruptionListener listener); + /** Set the running state. *

* This method should be only called by external objects with the false * argument. Calling this method with true has unspecified behavior and * could do nothing as well as restart the command for example. - * + * * @param running the running state */ void setRunning(boolean running); - - /** Add a listener for this command end of execution - * - * @param listener the listener */ - void addInterruptionListener(InterruptionListener listener); - - /** Remove a listener of this command end of execution - * - * @param listener the listener */ - void rmInterruptionListener(InterruptionListener listener); } diff --git a/gclc/src/main/java/fr/bigeon/gclc/proc/TaskPool.java b/gclc/src/main/java/fr/bigeon/gclc/proc/TaskPool.java index dfe2865..2ce470a 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/proc/TaskPool.java +++ b/gclc/src/main/java/fr/bigeon/gclc/proc/TaskPool.java @@ -43,24 +43,29 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; -/** A process pool +/** A process pool. * * @author Emmanuel Bigeon */ -public class TaskPool { - /** The running processes */ +public final class TaskPool { + /** The running processes. */ private final Map running = new HashMap<>(); - /** The count for process id */ + /** The count for process id. */ private int count = 0; - /** The lock for pid attribution synchronization */ + /** The lock for pid attribution synchronization. */ private final Object lock = new Object(); - /** Add a process in the pool - * + /** Default constructor. */ + public TaskPool() { + // + } + + /** Add a process in the pool. + * * @param cmd the process * @return the pid */ public String add(final Task cmd) { if (cmd == null) { - throw new NullPointerException("Task cannot be null"); //$NON-NLS-1$ + throw new IllegalArgumentException("Task cannot be null"); //$NON-NLS-1$ } final String pid = getPID(); synchronized (lock) { @@ -81,7 +86,19 @@ public class TaskPool { return pid; } - /** @return the process id */ + /** Get a process by it associated identifier. + * + * @param pid the task id + * @return the task, if any, associated to this id */ + public Task get(final String pid) { + synchronized (lock) { + return running.get(pid); + } + } + + /** Get the next process id. + * + * @return the process id */ private String getPID() { synchronized (lock) { String pid; @@ -92,17 +109,9 @@ public class TaskPool { } } - /** Get a process by it associated identifier - * - * @param pid the task id - * @return the task, if any, associated to this id */ - public Task get(String pid) { - synchronized (lock) { - return running.get(pid); - } - } - - /** @return the pids */ + /** Get the running processes' identifiers. + * + * @return the pids */ public Collection getPIDs() { return new HashSet<>(running.keySet()); } diff --git a/gclc/src/main/java/fr/bigeon/gclc/proc/TaskSpawner.java b/gclc/src/main/java/fr/bigeon/gclc/proc/TaskSpawner.java index ee1c52e..9825f80 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/proc/TaskSpawner.java +++ b/gclc/src/main/java/fr/bigeon/gclc/proc/TaskSpawner.java @@ -39,7 +39,6 @@ package fr.bigeon.gclc.proc; import fr.bigeon.gclc.command.Command; -import fr.bigeon.gclc.exception.CommandRunException; /** An abstract command to generate a task and return the control to the user * @@ -50,23 +49,23 @@ public abstract class TaskSpawner extends Command { /** @param name the command name * @param pool the pool */ - public TaskSpawner(String name, TaskPool pool) { + public TaskSpawner(final String name, final TaskPool pool) { super(name); this.pool = pool; } - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) - */ - @Override - public final void execute(String... args) throws CommandRunException { - Task task = createTask(args); - Thread th = new Thread(task); - th.start(); - pool.add(task); - } - /** @param args the arguments * @return the process to start and add to the pool */ protected abstract Task createTask(String... args); + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) + */ + @Override + public final void execute(final String... args) { + final Task task = createTask(args); + final Thread th = new Thread(task); + th.start(); + pool.add(task); + } } diff --git a/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompter.java b/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompter.java index b8b6fd5..0f9f3fd 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompter.java +++ b/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompter.java @@ -45,13 +45,18 @@ import java.util.logging.Logger; import fr.bigeon.gclc.manager.ConsoleManager; -/**

+/** + *

* The {@link CLIPrompter} class is a utility class that provides method to * prompt the user. * * @author Emmanuel BIGEON */ -public class CLIPrompter { +public final class CLIPrompter { + /** + * + */ + private static final Integer ZERO = Integer.valueOf(0); /** message key for format error in prompting a choice */ private static final String PROMPTCHOICE_FORMATERR = "promptchoice.formaterr"; //$NON-NLS-1$ /** message key for out of bound error in prompting a choice */ @@ -77,14 +82,34 @@ public class CLIPrompter { // Utility class } + /** @param val the string to parse + * @param chs the list of integers + * @param index the max index of choice + * @return if the parsing was done correctly */ + private static boolean addUserChoice(final String val, + final List chs, + final int index) { + if (val.isEmpty()) { + return true; + } + final int r; + r = Integer.parseInt(val); + if (r >= 0 && r <= index) { + chs.add(Integer.valueOf(r)); + return true; + } + return false; + } + /** @param manager the manager * @param choices the choices * @param cancel the cancel option if it exists * @return the number of choices plus one (or the number of choices if there * is a cancel) * @throws IOException if the manager was closed */ - private static int listChoices(ConsoleManager manager, List choices, - String cancel) throws IOException { + private static Integer listChoices(final ConsoleManager manager, + final List choices, + final String cancel) throws IOException { int index = 0; for (final U u : choices) { manager.println(index++ + ") " + u); //$NON-NLS-1$ @@ -92,15 +117,15 @@ public class CLIPrompter { if (cancel != null) { manager.println(index++ + ") " + cancel); //$NON-NLS-1$ } - return index - 1; + return Integer.valueOf(index - 1); } /** @param manager the manager * @param message the prompting message * @return the choice * @throws IOException if the manager was closed */ - public static boolean promptBoolean(ConsoleManager manager, - String message) throws IOException { + public static boolean promptBoolean(final ConsoleManager manager, + final String message) throws IOException { String result = manager .prompt(message + CLIPrompterMessages.getString(BOOL_CHOICES)); boolean first = true; @@ -140,9 +165,11 @@ public class CLIPrompter { * @return the choice * @throws IOException if the manager was closed */ @SuppressWarnings("boxing") - public static U promptChoice(ConsoleManager manager, List keys, - List choices, String message, - String cancel) throws IOException { + public static U promptChoice(final ConsoleManager manager, + final List keys, + final List choices, + final String message, + final String cancel) throws IOException { final Integer index = promptChoice(manager, keys, message, cancel); if (index == null) { return null; @@ -159,10 +186,12 @@ public class CLIPrompter { * @param cancel the cancel option if it exists (null otherwise) * @return the chosen object * @throws IOException if the manager was closed */ - public static T promptChoice(ConsoleManager manager, List choices, - Map choicesMap, String message, - String cancel) throws IOException { - Integer res = promptChoice(manager, choices, message, cancel); + public static T promptChoice(final ConsoleManager manager, + final List choices, + final Map choicesMap, + final String message, + final String cancel) throws IOException { + final Integer res = promptChoice(manager, choices, message, cancel); if (res == null) { return null; } @@ -176,40 +205,38 @@ public class CLIPrompter { * @param cancel the cancel option, or null * @return the index of the choice * @throws IOException if the manager was closed */ - @SuppressWarnings("boxing") - public static Integer promptChoice(ConsoleManager manager, - List choices, String message, - String cancel) throws IOException { + public static Integer promptChoice(final ConsoleManager manager, + final List choices, + final String message, + final String cancel) throws IOException { manager.println(message); - final int index = listChoices(manager, choices, cancel); - String result = ""; //$NON-NLS-1$ + final Integer index = listChoices(manager, choices, cancel); + String result; boolean keepOn = true; int r = -1; while (keepOn) { result = manager.prompt(CLIPrompterMessages.getString(PROMPT)); try { r = Integer.parseInt(result); - if (r >= 0 && r <= index) { + if (r >= 0 && r <= index.intValue()) { keepOn = false; - } else { - manager.println(CLIPrompterMessages - .getString(PROMPTCHOICE_OUTOFBOUNDS, 0, index)); - listChoices(manager, choices, cancel); + break; } - + manager.println(CLIPrompterMessages + .getString(PROMPTCHOICE_OUTOFBOUNDS, ZERO, index)); } catch (final NumberFormatException e) { LOGGER.log(Level.FINER, "Unrecognized number. Prompting user again.", e); //$NON-NLS-1$ keepOn = true; manager.println(CLIPrompterMessages - .getString(PROMPTCHOICE_FORMATERR, 0, index)); - listChoices(manager, choices, cancel); + .getString(PROMPTCHOICE_FORMATERR, ZERO, index)); } + listChoices(manager, choices, cancel); } - if (r == index && cancel != null) { + if (r == index.intValue() && cancel != null) { return null; } - return r; + return Integer.valueOf(r); } /** @param manager the manager @@ -220,9 +247,10 @@ public class CLIPrompter { * @param cancel the cancel option (or null) * @return the chosen object * @throws IOException if the manager was closed */ - public static T promptChoice(ConsoleManager manager, - Map choicesMap, String message, - String cancel) throws IOException { + public static T promptChoice(final ConsoleManager manager, + final Map choicesMap, + final String message, + final String cancel) throws IOException { return promptChoice(manager, new ArrayList<>(choicesMap.keySet()), choicesMap, message, cancel); } @@ -231,8 +259,8 @@ public class CLIPrompter { * @param message the prompt message * @return the integer * @throws IOException if the manager was closed */ - public static int promptInteger(ConsoleManager manager, - String message) throws IOException { + public static int promptInteger(final ConsoleManager manager, + final String message) throws IOException { boolean still = true; int r = 0; while (still) { @@ -259,8 +287,8 @@ public class CLIPrompter { * @param message the message * @return the list of user inputs * @throws IOException if the manager was closed */ - public static List promptList(ConsoleManager manager, - String message) throws IOException { + public static List promptList(final ConsoleManager manager, + final String message) throws IOException { return promptList(manager, message, CLIPrompterMessages.getString("promptlist.exit.defaultkey")); //$NON-NLS-1$ } @@ -272,9 +300,9 @@ public class CLIPrompter { * @param ender the ending sequence for the list * @return the list of user inputs * @throws IOException if the manager was closed */ - public static List promptList(ConsoleManager manager, - String message, - String ender) throws IOException { + public static List promptList(final ConsoleManager manager, + final String message, + final String ender) throws IOException { final List strings = new ArrayList<>(); manager.println( message + CLIPrompterMessages.getString(LIST_DISP_KEY, ender)); @@ -294,8 +322,8 @@ public class CLIPrompter { * @param message the prompting message * @return the text * @throws IOException if the manager was closed */ - public static String promptLongText(ConsoleManager manager, - String message) throws IOException { + public static String promptLongText(final ConsoleManager manager, + final String message) throws IOException { return promptLongText(manager, message, CLIPrompterMessages .getString("promptlongtext.exit.defaultkey")); //$NON-NLS-1$ } @@ -307,19 +335,21 @@ public class CLIPrompter { * @param ender the ender character * @return the text * @throws IOException if the manager was closed */ - public static String promptLongText(ConsoleManager manager, String message, - String ender) throws IOException { + public static String promptLongText(final ConsoleManager manager, + final String message, + final String ender) throws IOException { manager.println(message + CLIPrompterMessages .getString("promptlongtext.exit.dispkey", ender)); //$NON-NLS-1$ - String res = manager.prompt(CLIPrompterMessages.getString(PROMPT)); - String line = res; - while (!line.equals(ender)) { + final StringBuilder res = new StringBuilder(); + String line; + do { line = manager.prompt(CLIPrompterMessages.getString(PROMPT)); if (!line.equals(ender)) { - res += System.lineSeparator() + line; + res.append(line); + res.append(System.lineSeparator()); } - } - return res.equals(ender) ? "" : res; //$NON-NLS-1$ + } while (!line.equals(ender)); + return res.toString(); } /** @param manager the manager @@ -329,10 +359,10 @@ public class CLIPrompter { * @param the type of elements * @return the choice * @throws IOException if the manager was closed */ - public static List promptMultiChoice(ConsoleManager manager, - List keys, - List choices, - String message) throws IOException { + public static List promptMultiChoice(final ConsoleManager manager, + final List keys, + final List choices, + final String message) throws IOException { final List indices = promptMultiChoice(manager, keys, message); final List userChoices = new ArrayList<>(); for (final Integer integer : indices) { @@ -349,10 +379,10 @@ public class CLIPrompter { * @param message the prompting message * @return the chosen objects (or an empty list) * @throws IOException if the manager was closed */ - public static List promptMultiChoice(ConsoleManager manager, - List choices, - Map choicesMap, - String message) throws IOException { + public static List promptMultiChoice(final ConsoleManager manager, + final List choices, + final Map choicesMap, + final String message) throws IOException { final List chs = promptMultiChoice(manager, choices, message); final List userChoices = new ArrayList<>(); for (final Integer integer : chs) { @@ -367,13 +397,12 @@ public class CLIPrompter { * @param message the prompting message * @return the indices of the choices * @throws IOException if the manager was closed */ - @SuppressWarnings("boxing") - public static List promptMultiChoice(ConsoleManager manager, - List choices, - String message) throws IOException { + public static List promptMultiChoice(final ConsoleManager manager, + final List choices, + final String message) throws IOException { manager.println(message); - final int index = listChoices(manager, choices, null); - String result = ""; //$NON-NLS-1$ + final Integer index = listChoices(manager, choices, null); + String result; boolean keepOn = true; final List chs = new ArrayList<>(); while (keepOn) { @@ -384,19 +413,19 @@ public class CLIPrompter { for (final String val : vals) { boolean added; try { - added = addUserChoice(val, chs, index); + added = addUserChoice(val, chs, index.intValue()); } catch (final NumberFormatException e) { LOGGER.log(Level.FINER, "Unrecognized number. Prompting user again.", e); //$NON-NLS-1$ keepOn = true; manager.println(CLIPrompterMessages - .getString(PROMPTCHOICE_FORMATERR, 0, index)); + .getString(PROMPTCHOICE_FORMATERR, ZERO, index)); listChoices(manager, choices, null); break; } if (!added) { manager.println(CLIPrompterMessages - .getString(PROMPTCHOICE_OUTOFBOUNDS, 0, index)); + .getString(PROMPTCHOICE_OUTOFBOUNDS, ZERO, index)); listChoices(manager, choices, null); keepOn = true; } @@ -405,24 +434,6 @@ public class CLIPrompter { return chs; } - /** @param val the string to parse - * @param chs the list of integers - * @param index the max index of choice - * @return if the parsing was done correctly */ - private static boolean addUserChoice(String val, List chs, - int index) { - if (val.isEmpty()) { - return true; - } - final int r; - r = Integer.parseInt(val); - if (r >= 0 && r <= index) { - chs.add(Integer.valueOf(r)); - return true; - } - return false; - } - /** @param manager the manager * @param The choices labels type * @param The real choices objects @@ -430,9 +441,9 @@ public class CLIPrompter { * @param message the prompting message * @return the chosen objects * @throws IOException if the manager was closed */ - public static List promptMultiChoice(ConsoleManager manager, - Map choicesMap, - String message) throws IOException { + public static List promptMultiChoice(final ConsoleManager manager, + final Map choicesMap, + final String message) throws IOException { return promptMultiChoice(manager, new ArrayList<>(choicesMap.keySet()), choicesMap, message); } @@ -442,8 +453,9 @@ public class CLIPrompter { * @param reprompt the prompting message after empty input * @return the non empty input * @throws IOException if the manager was closed */ - public static String promptNonEmpty(ConsoleManager manager, String prompt, - String reprompt) throws IOException { + public static String promptNonEmpty(final ConsoleManager manager, + final String prompt, + final String reprompt) throws IOException { String res = manager.prompt(prompt); while (res.isEmpty()) { res = manager.prompt(reprompt); diff --git a/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompterMessages.java b/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompterMessages.java index 4d27cab..b33a59a 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompterMessages.java +++ b/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompterMessages.java @@ -48,7 +48,7 @@ import java.util.logging.Logger; * Utility class for the messages of the CLIPrompter * * @author Emmanuel BIGEON */ -public class CLIPrompterMessages { +public final class CLIPrompterMessages { /** The resource name */ private static final String BUNDLE_NAME = "fr.bigeon.gclc.messages"; //$NON-NLS-1$ @@ -70,7 +70,7 @@ public class CLIPrompterMessages { * @param key the message's key * @param args the arguments * @return the formatted message */ - public static String getString(String key, Object... args) { + public static String getString(final String key, final Object... args) { try { return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args); } catch (final MissingResourceException e) { diff --git a/gclc/src/main/java/fr/bigeon/gclc/tools/AOutputForwardRunnable.java b/gclc/src/main/java/fr/bigeon/gclc/tools/AOutputForwardRunnable.java index 2864664..1ffaf3a 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/tools/AOutputForwardRunnable.java +++ b/gclc/src/main/java/fr/bigeon/gclc/tools/AOutputForwardRunnable.java @@ -61,6 +61,15 @@ public abstract class AOutputForwardRunnable implements Runnable { /** The timeout */ private final long timeout; + /** Create a forwarding runnable. + * + * @param manager the manager */ + public AOutputForwardRunnable(final PipedConsoleManager manager) { + super(); + this.manager = manager; + timeout = DEFAULT_TIMEOUT; + } + /** Create a forward runnable with the given timeout. *

* Short timeout will be very responsive to the application actual messages, @@ -71,59 +80,50 @@ public abstract class AOutputForwardRunnable implements Runnable { *

* If you do not know what timeout length to use, please use the * {@link #AOutputForwardRunnable(PipedConsoleManager)} constructor. - * + * * @param manager the manager * @param timeout the timeout between message requests. */ - public AOutputForwardRunnable(PipedConsoleManager manager, long timeout) { + public AOutputForwardRunnable(final PipedConsoleManager manager, final long timeout) { super(); this.manager = manager; this.timeout = timeout; } - /** Create a forwarding runnable. - * - * @param manager the manager */ - public AOutputForwardRunnable(PipedConsoleManager manager) { - super(); - this.manager = manager; - timeout = DEFAULT_TIMEOUT; - } - - @Override - public void run() { - try { - while (isRunning()) { - while (isRunning() && !manager.available()) { - waitASec(); - } - if (!isRunning()) { - return; - } - String m = manager.readNextLine(); - forwardLine(m); - } - } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Unexpected problem in manager", //$NON-NLS-1$ - e); - } - } - /** @param m the line to forward */ protected abstract void forwardLine(String m); /** @return if the thread should keep running */ protected abstract boolean isRunning(); - /** a method to wait some time */ - protected void waitASec() { + @Override + public final void run() { + try { + while (isRunning()) { + while (isRunning() && !manager.available()) { + waitASec(); + } + if (!isRunning()) { + return; + } + final String m = manager.readNextLine(); + forwardLine(m); + } + } catch (final IOException e) { + LOGGER.log(Level.SEVERE, "Unexpected problem in manager", //$NON-NLS-1$ + e); + } + } + + /** a method to wait some time. */ + protected final void waitASec() { try { synchronized (this) { wait(timeout); } - } catch (InterruptedException e) { + } catch (final InterruptedException e) { LOGGER.log(Level.SEVERE, "Interrupted wait", //$NON-NLS-1$ e); - return; + Thread.currentThread().interrupt(); } } diff --git a/gclc/src/main/java/fr/bigeon/gclc/tools/PrintUtils.java b/gclc/src/main/java/fr/bigeon/gclc/tools/PrintUtils.java index 45a6b77..a7a5b29 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/tools/PrintUtils.java +++ b/gclc/src/main/java/fr/bigeon/gclc/tools/PrintUtils.java @@ -44,7 +44,7 @@ import java.util.List; /** A tool class for printing text in a console. * * @author Emmanuel BIGEON */ -public class PrintUtils { +public final class PrintUtils { /** The continuation dot string */ private static final String CONT_DOT = "..."; //$NON-NLS-1$ @@ -63,37 +63,37 @@ public class PrintUtils { * @param indicateTooLong if an indication shell be given that the text * didn't fit * @return the text to print (will be of exactly nbCharacters). */ - public static String print(String text, int nbCharacters, - boolean indicateTooLong) { - String res = text; + public static String print(final String text, final int nbCharacters, + final boolean indicateTooLong) { + StringBuilder res = new StringBuilder(text); if (res.length() > nbCharacters) { // Cut if (indicateTooLong) { // With suspension dots - res = res.substring(0, nbCharacters - CONT_DOT_LENGTH) + - CONT_DOT; + res = res.replace(nbCharacters - CONT_DOT_LENGTH, text.length(), + CONT_DOT); } else { - res = res.substring(0, nbCharacters); + res = res.replace(nbCharacters, text.length(), ""); //$NON-NLS-1$ } } while (res.length() < nbCharacters) { // Add trailing space - res = res + ' '; + res.append(' '); } - return res; + return res.toString(); } /** @param description the element to wrap in lines * @param i the length of the wrap * @return the list of resulting strings */ - public static List wrap(String description, int i) { + public static List wrap(final String description, final int i) { final String[] originalLines = description .split(System.lineSeparator()); final List result = new ArrayList<>(); for (final String string : originalLines) { String toCut = string; while (toCut.length() > i) { - int index = toCut.lastIndexOf(" ", i); //$NON-NLS-1$ + int index = toCut.lastIndexOf(' ', i); if (index == -1) { result.add(toCut.substring(0, i)); index = i - 1; diff --git a/gclc/src/test/java/fr/bigeon/gclc/ConsoleApplicationTest.java b/gclc/src/test/java/fr/bigeon/gclc/ConsoleApplicationTest.java index e9b59b9..abecd5f 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/ConsoleApplicationTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/ConsoleApplicationTest.java @@ -69,19 +69,19 @@ public class ConsoleApplicationTest { /** Test the base of a console application */ @Test - public void test() { + public void testConsoleApplication() { try (PipedConsoleManager manager = new PipedConsoleManager()) { - ConsoleApplication app = new ConsoleApplication(manager, "", ""); + final ConsoleApplication app = new ConsoleApplication(manager, "", ""); app.exit(); - } catch (IOException e) { + } catch (final IOException e) { fail("System Console Manager failed"); } } @Test - public void executionTest() { + public void testExecution() { try (CommandTestingApplication application = new CommandTestingApplication()) { // remove welcome @@ -106,17 +106,17 @@ public class ConsoleApplicationTest { assertEquals("Waita minute", application.readNextLine()); assertEquals("done!", application.readNextLine()); - CommandRequestListener crl = new CommandRequestListener() { + final CommandRequestListener crl = new CommandRequestListener() { @Override - public void commandRequest(String command) { + public void commandRequest(final String command) { // } }; - CommandRequestListener crl2 = new CommandRequestListener() { + final CommandRequestListener crl2 = new CommandRequestListener() { @Override - public void commandRequest(String command) { + public void commandRequest(final String command) { // } }; @@ -136,7 +136,7 @@ public class ConsoleApplicationTest { assertEquals(application.getApplication().footer, application.readNextLine()); assertFalse(application.getApplication().isRunning()); - } catch (IOException e1) { + } catch (final IOException e1) { assertNull(e1); } @@ -147,7 +147,7 @@ public class ConsoleApplicationTest { appli = app; app.add(new ExitCommand("exit", app)); - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @SuppressWarnings("synthetic-access") @Override @@ -174,9 +174,9 @@ public class ConsoleApplicationTest { } @Test - public void interpretCommandTest() { + public void testInterpretCommand() { try (PipedConsoleManager test = new PipedConsoleManager()) { - ConsoleApplication appl = new ConsoleApplication(test, "", ""); + final ConsoleApplication appl = new ConsoleApplication(test, "", ""); appl.interpretCommand("invalid cmd \"due to misplaced\"quote"); assertEquals("Command line cannot be parsed", test.readNextLine()); @@ -188,7 +188,7 @@ public class ConsoleApplicationTest { appl.add(new ICommand() { @Override - public void execute(String... args) throws CommandRunException { + public void execute(final String... args) throws CommandRunException { throw new CommandRunException( CommandRunExceptionType.USAGE, message, this); } @@ -199,8 +199,8 @@ public class ConsoleApplicationTest { } @Override - public void help(ConsoleManager manager, - String... args) throws IOException { + public void help(final ConsoleManager manager, + final String... args) throws IOException { manager.println(message); } @@ -210,7 +210,7 @@ public class ConsoleApplicationTest { } }); - } catch (InvalidCommandName e) { + } catch (final InvalidCommandName e) { assertNull(e); } appl.interpretCommand("fail"); @@ -220,7 +220,7 @@ public class ConsoleApplicationTest { assertEquals(message, test.readNextLine()); assertEquals(message, test.readNextLine()); - } catch (IOException e) { + } catch (final IOException e) { assertNull(e); } } diff --git a/gclc/src/test/java/fr/bigeon/gclc/ConsoleTestApplication.java b/gclc/src/test/java/fr/bigeon/gclc/ConsoleTestApplication.java index 689611b..ad49425 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/ConsoleTestApplication.java +++ b/gclc/src/test/java/fr/bigeon/gclc/ConsoleTestApplication.java @@ -43,7 +43,7 @@ import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.InvalidCommandName; /** A test-purpose application - * + * * @author Emmanuel Bigeon */ public class ConsoleTestApplication implements ApplicationAttachement { @@ -62,44 +62,41 @@ public class ConsoleTestApplication implements ApplicationAttachement { application.root)); application.add(new Command("test") { + @Override + public void execute(final String... args) throws CommandRunException { + try { + application.manager.println("Test command ran fine"); + } catch (final IOException e) { + throw new CommandRunException("manager closed", e, + this); + } + } + @Override public String tip() { return "A test command"; } @Override - public void execute(String... args) throws CommandRunException { - try { - application.manager.println("Test command ran fine"); - } catch (IOException e) { - throw new CommandRunException("manager closed", e, - this); - } + protected String usageDetail() { + return null; } }); application.add(new Command("long") { - @Override - public String tip() { - return "A long execution command"; - } - - @Override - public void execute(String... args) throws CommandRunException { + public void execute(final String... args) throws CommandRunException { try { application.manager.println("Waita minute"); Thread.sleep(TWO_SECONDS); application.manager.println("done!"); - } catch (IOException e) { + } catch (final IOException e) { throw new CommandRunException("manager closed", e, this); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { throw new CommandRunException("wait interrupted", e, this); } } - }); - application.add(new Command("failingCmd") { @Override public String tip() { @@ -107,9 +104,25 @@ public class ConsoleTestApplication implements ApplicationAttachement { } @Override - public void execute(String... args) throws CommandRunException { + protected String usageDetail() { + return null; + } + }); + application.add(new Command("failingCmd") { + @Override + public void execute(final String... args) throws CommandRunException { throw new CommandRunException("Failing command", this); } + + @Override + public String tip() { + return "A long execution command"; + } + + @Override + protected String usageDetail() { + return null; + } }); } catch (final InvalidCommandName e) { e.printStackTrace(); diff --git a/gclc/src/test/java/fr/bigeon/gclc/GCLCConstantsTest.java b/gclc/src/test/java/fr/bigeon/gclc/GCLCConstantsTest.java index e39a72b..4649983 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/GCLCConstantsTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/GCLCConstantsTest.java @@ -61,7 +61,7 @@ public class GCLCConstantsTest { List res; try { res = GCLCConstants.splitCommand("aCommand"); - } catch (CommandParsingException e) { + } catch (final CommandParsingException e) { fail("Unable to parse simple command " + e.getLocalizedMessage()); //$NON-NLS-1$ return; } @@ -70,7 +70,7 @@ public class GCLCConstantsTest { try { res = GCLCConstants.splitCommand("aCommand with some arguments"); - } catch (CommandParsingException e) { + } catch (final CommandParsingException e) { fail("Unable to parse command with arguments " + //$NON-NLS-1$ e.getLocalizedMessage()); return; @@ -82,7 +82,7 @@ public class GCLCConstantsTest { assertTrue(res.get(3).equals("arguments")); try { res = GCLCConstants.splitCommand("aCommand with some arguments"); - } catch (CommandParsingException e) { + } catch (final CommandParsingException e) { fail("Unable to parse command with arguments and double whitspaces " + //$NON-NLS-1$ e.getLocalizedMessage()); return; @@ -95,7 +95,7 @@ public class GCLCConstantsTest { try { res = GCLCConstants .splitCommand("aCommand \"with some\" arguments"); - } catch (CommandParsingException e) { + } catch (final CommandParsingException e) { fail("Unable to parse command with string argument " + //$NON-NLS-1$ e.getLocalizedMessage()); return; @@ -106,7 +106,7 @@ public class GCLCConstantsTest { assertTrue(res.get(2).equals("arguments")); try { res = GCLCConstants.splitCommand("aCommand with\\ some arguments"); - } catch (CommandParsingException e) { + } catch (final CommandParsingException e) { fail("Unable to parse command with arguments with escaped whitspaces " + //$NON-NLS-1$ e.getLocalizedMessage()); return; @@ -118,7 +118,7 @@ public class GCLCConstantsTest { try { res = GCLCConstants .splitCommand("aCommand wi\\\"th some arguments"); - } catch (CommandParsingException e) { + } catch (final CommandParsingException e) { fail("Unable to parse command with string argument " + //$NON-NLS-1$ e.getLocalizedMessage()); return; @@ -132,7 +132,7 @@ public class GCLCConstantsTest { try { res = GCLCConstants .splitCommand("aCommand with \"some arguments\""); - } catch (CommandParsingException e) { + } catch (final CommandParsingException e) { fail("Unable to parse command ending with string argument " + //$NON-NLS-1$ e.getLocalizedMessage()); return; @@ -147,9 +147,8 @@ public class GCLCConstantsTest { res = GCLCConstants .splitCommand("aCommand with \"some ar\"guments"); fail("Parsing argument with string cut"); - } catch (CommandParsingException e) { + } catch (final CommandParsingException e) { // OK - assertTrue(e.getLocalizedMessage(), true); } } diff --git a/gclc/src/test/java/fr/bigeon/gclc/command/CommandTest.java b/gclc/src/test/java/fr/bigeon/gclc/command/CommandTest.java index 3b969b0..1262b03 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/command/CommandTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/command/CommandTest.java @@ -54,44 +54,49 @@ import fr.bigeon.gclc.manager.PipedConsoleManager; public class CommandTest { @Test - public final void test() { + public final void testCommand() { try (PipedConsoleManager test = new PipedConsoleManager()) { Command cmd; cmd = new Command("name") { + @Override + public void execute(final String... args) throws CommandRunException { + // + } + @Override public String tip() { return null; } @Override - public void execute(String... args) throws CommandRunException { - // + protected String usageDetail() { + return null; } }; cmd.help(test); cmd = new Command("name") { + @Override + public void execute(final String... args) throws CommandRunException { + // + } + @Override public String tip() { return ""; } @Override - public void execute(String... args) throws CommandRunException { - // + protected String usageDetail() { + return null; } }; cmd.help(test); cmd = new Command("name") { - @Override - public String tip() { - return "tip"; - } - /* (non-Javadoc) * @see fr.bigeon.gclc.command.Command#brief() */ @Override @@ -100,19 +105,24 @@ public class CommandTest { } @Override - public void execute(String... args) throws CommandRunException { + public void execute(final String... args) throws CommandRunException { // } - }; - cmd.help(test); - - cmd = new Command("name") { @Override public String tip() { return "tip"; } + @Override + protected String usageDetail() { + return null; + } + }; + cmd.help(test); + + cmd = new Command("name") { + /* (non-Javadoc) * @see fr.bigeon.gclc.command.Command#brief() */ @Override @@ -121,14 +131,29 @@ public class CommandTest { } @Override - public void execute(String... args) throws CommandRunException { + public void execute(final String... args) throws CommandRunException { // } + + @Override + public String tip() { + return "tip"; + } + + @Override + protected String usageDetail() { + return null; + } }; cmd.help(test); cmd = new Command("name") { + @Override + public void execute(final String... args) throws CommandRunException { + // + } + @Override public String tip() { return "tip"; @@ -140,16 +165,16 @@ public class CommandTest { protected String usageDetail() { return null; } - - @Override - public void execute(String... args) throws CommandRunException { - // - } }; cmd.help(test); cmd = new Command("name") { + @Override + public void execute(final String... args) throws CommandRunException { + // + } + @Override public String tip() { return "tip"; @@ -161,15 +186,15 @@ public class CommandTest { protected String usageDetail() { return "details"; } - - @Override - public void execute(String... args) throws CommandRunException { - // - } }; cmd.help(test); cmd = new Command("name") { + @Override + public void execute(final String... args) throws CommandRunException { + // + } + @Override public String tip() { return "tip"; @@ -181,16 +206,16 @@ public class CommandTest { protected String usageDetail() { return "details" + System.lineSeparator(); } - - @Override - public void execute(String... args) throws CommandRunException { - // - } }; cmd.help(test); cmd = new Command("name") { + @Override + public void execute(final String... args) throws CommandRunException { + // + } + @Override public String tip() { return "tip"; @@ -202,15 +227,10 @@ public class CommandTest { protected String usageDetail() { return "\n"; } - - @Override - public void execute(String... args) throws CommandRunException { - // - } }; cmd.help(test); - } catch (IOException e) { + } catch (final IOException e) { assertNull(e); } } diff --git a/gclc/src/test/java/fr/bigeon/gclc/command/HelpExecutorTest.java b/gclc/src/test/java/fr/bigeon/gclc/command/HelpExecutorTest.java index 4492cac..85faf4d 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/command/HelpExecutorTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/command/HelpExecutorTest.java @@ -42,6 +42,8 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; +import java.io.IOException; + import org.junit.Test; import fr.bigeon.gclc.exception.CommandRunException; @@ -56,37 +58,18 @@ import fr.bigeon.gclc.manager.PipedConsoleManager; */ public class HelpExecutorTest { - /** - * Test method for {@link fr.bigeon.gclc.command.HelpExecutor#HelpExecutor(java.lang.String, fr.bigeon.gclc.manager.ConsoleManager, fr.bigeon.gclc.command.ICommand)}. - */ - @Test - public final void testHelpExecutor(){ - HelpExecutor help; - try { - help = new HelpExecutor("?", null, new MockCommand("mock")); - fail("help is an interactive command, should need console manager"); - } catch (Exception e) { - assertNotNull(e); - } - try (PipedConsoleManager test = new PipedConsoleManager()) { - help = new HelpExecutor("?", test, new MockCommand("mock")); - } catch (Exception e) { - assertNull(e); - } - } - /** * Test method for {@link fr.bigeon.gclc.command.HelpExecutor#execute(java.lang.String[])}. */ @Test public final void testExecute(){ try { - PipedConsoleManager test = new PipedConsoleManager(); - HelpExecutor help = new HelpExecutor("?", test, + final PipedConsoleManager test = new PipedConsoleManager(); + final HelpExecutor help = new HelpExecutor("?", test, new Command("mock") { @Override - public void execute(String... args) throws CommandRunException { + public void execute(final String... args) throws CommandRunException { // } @@ -94,6 +77,10 @@ public class HelpExecutorTest { public String tip() { return ""; } + @Override + protected String usageDetail() { + return null; + } }); @@ -103,33 +90,45 @@ public class HelpExecutorTest { try { help.execute(); fail("manager closed shall provoke failure of help command execution"); - } catch (Exception e) { + } catch (final Exception e) { assertNotNull(e); } - } catch (Exception e) { + } catch (final Exception e) { assertNull(e); } } + /** Test method for + * {@link fr.bigeon.gclc.command.HelpExecutor#HelpExecutor(java.lang.String, fr.bigeon.gclc.manager.ConsoleManager, fr.bigeon.gclc.command.ICommand)}. + * + * @throws IOException if an IO occurs */ + @Test + public final void testHelpExecutor() throws IOException { + HelpExecutor help; + try (PipedConsoleManager test = new PipedConsoleManager()) { + help = new HelpExecutor("?", test, new MockCommand("mock")); + } + } + /** * Test method for {@link fr.bigeon.gclc.command.HelpExecutor#tip()}. */ @Test public final void testTip(){ try (PipedConsoleManager test = new PipedConsoleManager()) { - HelpExecutor help = new HelpExecutor("?", test, + final HelpExecutor help = new HelpExecutor("?", test, new MockCommand("mock")); help.tip(); help.help(test); - } catch (Exception e) { + } catch (final Exception e) { assertNull(e); } try (PipedConsoleManager test = new PipedConsoleManager()) { - HelpExecutor help = new HelpExecutor("?", test, + final HelpExecutor help = new HelpExecutor("?", test, new SubedCommand("sub", new MockCommand("mock"))); help.tip(); help.help(test); - } catch (Exception e) { + } catch (final Exception e) { assertNull(e); } } diff --git a/gclc/src/test/java/fr/bigeon/gclc/command/ParametrizedCommandTest.java b/gclc/src/test/java/fr/bigeon/gclc/command/ParametrizedCommandTest.java index ce62a79..4abfe54 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/command/ParametrizedCommandTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/command/ParametrizedCommandTest.java @@ -59,144 +59,47 @@ import fr.bigeon.gclc.manager.PipedConsoleManager; * @author Emmanuel Bigeon */ public class ParametrizedCommandTest { - /** Test method for - * {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */ - @Test - public final void testParametrizedCommandConsoleManagerString() { - try (PipedConsoleManager test = new PipedConsoleManager()) { - ParametrizedCommand cmd = new ParametrizedCommand(test, "name") { - - @Override - public String tip() { - return null; - } - - @Override - protected void doExecute(CommandParameters parameters) { - // - } - }; - assertTrue(cmd.isStrict()); - assertTrue(cmd.isInteractive()); - } catch (IOException e) { - fail("Unexpected exception in creation"); - assertNull(e); - } - ParametrizedCommand cmd = new ParametrizedCommand(null, "name") { - - @Override - public String tip() { - return null; - } - - @Override - protected void doExecute(CommandParameters parameters) { - // - } - }; - assertTrue(cmd.isStrict()); - assertFalse(cmd.isInteractive()); - cmd = new ParametrizedCommand("name") { - - @Override - public String tip() { - return null; - } - - @Override - protected void doExecute(CommandParameters parameters) { - // - } - }; - assertTrue(cmd.isStrict()); - assertFalse(cmd.isInteractive()); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String, boolean)}. */ - @Test - public final void testParametrizedCommandConsoleManagerStringBoolean() { - try (PipedConsoleManager test = new PipedConsoleManager()) { - ParametrizedCommand cmd = new ParametrizedCommand(test, "name", - false) { - - @Override - public String tip() { - return null; - } - - @Override - protected void doExecute(CommandParameters parameters) { - // - } - }; - assertFalse(cmd.isStrict()); - assertTrue(cmd.isInteractive()); - } catch (IOException e) { - fail("Unexpected exception in creation"); - assertNull(e); - } - ParametrizedCommand cmd = new ParametrizedCommand(null, "name", false) { - - @Override - public String tip() { - return null; - } - - @Override - protected void doExecute(CommandParameters parameters) { - // - } - }; - assertFalse(cmd.isStrict()); - assertFalse(cmd.isInteractive()); - cmd = new ParametrizedCommand("name", false) { - - @Override - public String tip() { - return null; - } - - @Override - protected void doExecute(CommandParameters parameters) { - // - } - }; - assertFalse(cmd.isStrict()); - assertFalse(cmd.isInteractive()); - } - /** Test method for * {@link fr.bigeon.gclc.command.ParametrizedCommand#addParameter(java.lang.String, boolean, boolean)}. */ @Test public final void testAddParameter() { ParametrizedCommand cmd = new ParametrizedCommand(null, "name") { + @Override + protected void doExecute(final CommandParameters parameters) { + // + } + @Override public String tip() { return null; } @Override - protected void doExecute(CommandParameters parameters) { - // + protected String usageDetail() { + return null; } }; cmd = new ParametrizedCommand(null, "name", true) { + @Override + protected void doExecute(final CommandParameters parameters) { + // + } + @Override public String tip() { return null; } @Override - protected void doExecute(CommandParameters parameters) { - // + protected String usageDetail() { + return null; } }; // XXX Boolean flag should not be specified mandatory! They are by // nature qualified - String str = "str"; + final String str = "str"; try { assertTrue(cmd.getBooleanParameters().isEmpty()); assertTrue(cmd.getStringParameters().isEmpty()); @@ -218,7 +121,7 @@ public class ParametrizedCommandTest { assertEquals(1, cmd.getBooleanParameters().size()); assertEquals(1, cmd.getStringParameters().size()); assertTrue(cmd.isNeeded(str)); - } catch (InvalidParameterException e) { + } catch (final InvalidParameterException e) { fail("Unexpected error in addition of legitimate parameter"); assertNotNull(e); } @@ -239,12 +142,7 @@ public class ParametrizedCommandTest { private boolean evenCall = true; @Override - public String tip() { - return ""; - } - - @Override - protected void doExecute(CommandParameters parameters) { + protected void doExecute(final CommandParameters parameters) { assertTrue(parameters.getBooleanArgumentKeys().isEmpty()); assertTrue(parameters.getStringArgumentKeys().isEmpty()); if (evenCall) { @@ -256,13 +154,23 @@ public class ParametrizedCommandTest { evenCall = true; } } + + @Override + public String tip() { + return ""; + } + + @Override + protected String usageDetail() { + return null; + } }; try { cmd.execute(); cmd.execute("-" + addParam); cmd.execute(addParam); cmd.execute("-" + addParam, addParam); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNull(e); fail("unepected error"); } @@ -275,19 +183,14 @@ public class ParametrizedCommandTest { addStringParameter(str2, false); addBooleanParameter(bool1); addBooleanParameter(bool2); - } catch (InvalidParameterException e) { + } catch (final InvalidParameterException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override - public String tip() { - return ""; - } - - @Override - protected void doExecute(CommandParameters parameters) { + protected void doExecute(final CommandParameters parameters) { assertEquals(2, parameters.getBooleanArgumentKeys().size()); assertEquals(2, parameters.getStringArgumentKeys().size()); switch (call) { @@ -319,6 +222,16 @@ public class ParametrizedCommandTest { break; } } + + @Override + public String tip() { + return ""; + } + + @Override + protected String usageDetail() { + return null; + } }; try { cmd.execute(); @@ -327,7 +240,7 @@ public class ParametrizedCommandTest { cmd.execute("-" + addParam, addParam); cmd.execute("-" + str1, str2); cmd.execute("-" + str1, str2, "-" + bool1); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNull(e); fail("unepected error"); } @@ -340,19 +253,13 @@ public class ParametrizedCommandTest { addStringParameter(str2, false); addBooleanParameter(bool1); addBooleanParameter(bool2); - } catch (InvalidParameterException e) { + } catch (final InvalidParameterException e) { // TODO Auto-generated catch block e.printStackTrace(); } } - @Override - public String tip() { - return ""; - } - - @Override - protected void doExecute(CommandParameters parameters) { + protected void doExecute(final CommandParameters parameters) { assertEquals(2, parameters.getBooleanArgumentKeys().size()); assertEquals(2, parameters.getStringArgumentKeys().size()); switch (call) { @@ -381,25 +288,35 @@ public class ParametrizedCommandTest { break; } } + + @Override + public String tip() { + return ""; + } + + @Override + protected String usageDetail() { + return null; + } }; try { cmd.execute(); cmd.execute("-" + str1, str2); cmd.execute("-" + str1, str2, "-" + bool1); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNull(e); fail("unexpected error"); } try { cmd.execute(addParam); fail("Strict should fail with unexpected argument"); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNotNull(e); } try { cmd.execute("-" + addParam); fail("Strict should fail with unexpected argument"); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNotNull(e); } // Test on command with missing needed elements @@ -412,11 +329,15 @@ public class ParametrizedCommandTest { addStringParameter(str2, false); addBooleanParameter(bool1); addBooleanParameter(bool2); - } catch (InvalidParameterException e) { + } catch (final InvalidParameterException e) { // TODO Auto-generated catch block e.printStackTrace(); } } + @Override + protected void doExecute(final CommandParameters parameters) { + assertEquals(str2, parameters.get(str1)); + } @Override public String tip() { @@ -424,8 +345,8 @@ public class ParametrizedCommandTest { } @Override - protected void doExecute(CommandParameters parameters) { - assertEquals(str2, parameters.get(str1)); + protected String usageDetail() { + return null; } }; try { @@ -434,14 +355,14 @@ public class ParametrizedCommandTest { cmd.execute("-" + str1, str2, "-" + addParam); cmd.execute("-" + str1, str2, addParam); cmd.execute("-" + str1, str2, "-" + addParam, addParam); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNull(e); fail("unepected error"); } try { cmd.execute(); fail("needed " + str1 + " not provided shall fail"); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNotNull(e); } cmd = new ParametrizedCommand("name", true) { @@ -453,52 +374,57 @@ public class ParametrizedCommandTest { addStringParameter(str2, false); addBooleanParameter(bool1); addBooleanParameter(bool2); - } catch (InvalidParameterException e) { + } catch (final InvalidParameterException e) { // TODO Auto-generated catch block e.printStackTrace(); } } + @Override + protected void doExecute(final CommandParameters parameters) { + // + assertEquals(str2, parameters.get(str1)); + } + @Override public String tip() { return ""; } @Override - protected void doExecute(CommandParameters parameters) { - // - assertEquals(str2, parameters.get(str1)); + protected String usageDetail() { + return null; } }; try { cmd.execute("-" + str1, str2); cmd.execute("-" + str1, str2, "-" + bool1); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNull(e); fail("unepected error"); } try { cmd.execute("-" + str1, str2, addParam); fail("Additional parameter should cause failure"); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNotNull(e); } try { cmd.execute(); fail("needed " + str1 + " not provided shall fail"); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNotNull(e); } try { cmd.execute("-" + str1, str2, "-" + addParam); fail("unepected error"); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNotNull(e); } try { cmd.execute("-" + str1, str2, "-" + addParam, addParam); fail("unepected error"); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNotNull(e); } // TODO Test of interactive not providing and providing all needed @@ -510,11 +436,15 @@ public class ParametrizedCommandTest { addStringParameter(str2, false); addBooleanParameter(bool1); addBooleanParameter(bool2); - } catch (InvalidParameterException e) { + } catch (final InvalidParameterException e) { // TODO Auto-generated catch block e.printStackTrace(); } } + @Override + protected void doExecute(final CommandParameters parameters) { + assertEquals(str2, parameters.get(str1)); + } @Override public String tip() { @@ -522,8 +452,8 @@ public class ParametrizedCommandTest { } @Override - protected void doExecute(CommandParameters parameters) { - assertEquals(str2, parameters.get(str1)); + protected String usageDetail() { + return null; } }; try { @@ -532,7 +462,7 @@ public class ParametrizedCommandTest { cmd.execute("-" + str1, str2, addParam); cmd.execute("-" + str1, str2, "-" + addParam); cmd.execute("-" + str1, str2, "-" + addParam, addParam); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNull(e); fail("unepected error"); } @@ -554,7 +484,7 @@ public class ParametrizedCommandTest { "value of " + str1 + "? (cannot be empty) ", test.readNextLine()); test.type(str2); - } catch (IOException e) { + } catch (final IOException e) { assertNull(e); } } @@ -573,7 +503,7 @@ public class ParametrizedCommandTest { assertEquals("value of " + str1 + "? ", test.readNextLine()); test.type(str2); - } catch (IOException e) { + } catch (final IOException e) { assertNull(e); } } @@ -587,12 +517,12 @@ public class ParametrizedCommandTest { assertNull(e); fail("unepected error"); } - } catch (IOException e) { + } catch (final IOException e) { assertNull(e); fail("unepected error"); } try { - PipedConsoleManager test = new PipedConsoleManager(); + final PipedConsoleManager test = new PipedConsoleManager(); cmd = new ParametrizedCommand(test, "name") { { try { @@ -600,32 +530,168 @@ public class ParametrizedCommandTest { addStringParameter(str2, false); addBooleanParameter(bool1); addBooleanParameter(bool2); - } catch (InvalidParameterException e) { + } catch (final InvalidParameterException e) { // TODO Auto-generated catch block e.printStackTrace(); } } + @Override + protected void doExecute(final CommandParameters parameters) { + assertEquals(str2, parameters.get(str1)); + } + @Override public String tip() { return ""; } @Override - protected void doExecute(CommandParameters parameters) { - assertEquals(str2, parameters.get(str1)); + protected String usageDetail() { + return null; } }; test.close(); cmd.execute("-" + str1, str2); cmd.execute("-" + addParam); fail("Closed manager shall cause error"); - } catch (IOException e) { + } catch (final IOException e) { assertNull(e); - } catch (CommandRunException e) { + } catch (final CommandRunException e) { assertNotNull(e); } } + /** Test method for + * {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */ + @Test + public final void testParametrizedCommandConsoleManagerString() { + try (PipedConsoleManager test = new PipedConsoleManager()) { + final ParametrizedCommand cmd = new ParametrizedCommand(test, "name") { + + @Override + protected void doExecute(final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + @Override + protected String usageDetail() { + return null; + } + }; + assertTrue(cmd.isStrict()); + assertTrue(cmd.isInteractive()); + } catch (final IOException e) { + fail("Unexpected exception in creation"); + assertNull(e); + } + ParametrizedCommand cmd = new ParametrizedCommand(null, "name") { + @Override + protected void doExecute(final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + assertTrue(cmd.isStrict()); + assertFalse(cmd.isInteractive()); + cmd = new ParametrizedCommand("name") { + @Override + protected void doExecute(final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + assertTrue(cmd.isStrict()); + assertFalse(cmd.isInteractive()); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String, boolean)}. */ + @Test + public final void testParametrizedCommandConsoleManagerStringBoolean() { + try (PipedConsoleManager test = new PipedConsoleManager()) { + final ParametrizedCommand cmd = new ParametrizedCommand(test, "name", + false) { + @Override + protected void doExecute(final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + assertFalse(cmd.isStrict()); + assertTrue(cmd.isInteractive()); + } catch (final IOException e) { + fail("Unexpected exception in creation"); + assertNull(e); + } + ParametrizedCommand cmd = new ParametrizedCommand(null, "name", false) { + @Override + protected void doExecute(final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + assertFalse(cmd.isStrict()); + assertFalse(cmd.isInteractive()); + cmd = new ParametrizedCommand("name", false) { + @Override + protected void doExecute(final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + assertFalse(cmd.isStrict()); + assertFalse(cmd.isInteractive()); + } + } diff --git a/gclc/src/test/java/fr/bigeon/gclc/command/ScriptExecutionTest.java b/gclc/src/test/java/fr/bigeon/gclc/command/ScriptExecutionTest.java index 371e1f8..1179b26 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/command/ScriptExecutionTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/command/ScriptExecutionTest.java @@ -68,20 +68,20 @@ public class ScriptExecutionTest { PipedConsoleManager test; try { test = new PipedConsoleManager(); - } catch (IOException e2) { + } catch (final IOException e2) { fail("creation of console manager failed"); //$NON-NLS-1$ assertNotNull(e2); return; } - ConsoleApplication app = new ConsoleApplication( + final ConsoleApplication app = new ConsoleApplication( test, "", ""); new ConsoleTestApplication().attach(app); - ScriptExecution exec = new ScriptExecution("script", app, "#", //$NON-NLS-1$ //$NON-NLS-2$ + final ScriptExecution exec = new ScriptExecution("script", app, "#", //$NON-NLS-1$ //$NON-NLS-2$ Charset.forName("UTF-8")); try { exec.execute(); fail("execution of script command with no file should fail"); //$NON-NLS-1$ - } catch (CommandRunException e1) { + } catch (final CommandRunException e1) { // ok assertEquals(exec, e1.getSource()); assertEquals(CommandRunExceptionType.USAGE, e1.getType()); @@ -90,7 +90,7 @@ public class ScriptExecutionTest { try { exec.execute("src/test/resources/scripts/withprependSpace.txt"); //$NON-NLS-1$ fail("execution of script with lines begining with space should fail"); //$NON-NLS-1$ - } catch (CommandRunException e1) { + } catch (final CommandRunException e1) { // ok assertEquals(exec, e1.getSource()); assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); @@ -99,7 +99,7 @@ public class ScriptExecutionTest { try { exec.execute("src/test/resources/scripts/invalidCmdParse.txt"); //$NON-NLS-1$ fail("execution of script with invalid command line should fail"); //$NON-NLS-1$ - } catch (CommandRunException e1) { + } catch (final CommandRunException e1) { // ok assertEquals(exec, e1.getSource()); assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); @@ -108,7 +108,7 @@ public class ScriptExecutionTest { try { exec.execute("src/test/resources/scripts/invalidCmd.txt"); //$NON-NLS-1$ fail("execution of script with invalid command should fail"); //$NON-NLS-1$ - } catch (CommandRunException e1) { + } catch (final CommandRunException e1) { // ok assertEquals(exec, e1.getSource()); assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); @@ -117,7 +117,7 @@ public class ScriptExecutionTest { try { exec.execute("src/test/resources/scripts/failingCmdInvoc.txt"); //$NON-NLS-1$ fail("execution of script with failing command should fail"); //$NON-NLS-1$ - } catch (CommandRunException e1) { + } catch (final CommandRunException e1) { // ok assertEquals(exec, e1.getSource()); assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); @@ -126,7 +126,7 @@ public class ScriptExecutionTest { try { exec.execute("src/test/resources/scripts/someNonExisting.file"); //$NON-NLS-1$ fail("execution of script with unexisting file should fail"); //$NON-NLS-1$ - } catch (CommandRunException e1) { + } catch (final CommandRunException e1) { // ok assertEquals(exec, e1.getSource()); assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); @@ -138,38 +138,38 @@ public class ScriptExecutionTest { exec.execute("src/test/resources/script3.txt"); //$NON-NLS-1$ exec.execute("src/test/resources/script4.txt"); //$NON-NLS-1$ exec.execute("src/test/resources/script5.txt", "test"); //$NON-NLS-1$ //$NON-NLS-2$ - } catch (CommandRunException e) { + } catch (final CommandRunException e) { e.printStackTrace(); fail("execution of wellformed script should not fail"); //$NON-NLS-1$ } try { test.close(); - } catch (IOException e) { + } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } - /** Test method for {@link fr.bigeon.gclc.command.ScriptExecution#tip()}. */ - @Test - public void testTip() { - ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$ - Charset.forName("UTF-8")); - exec.tip(); - } - /** Test method for * {@link fr.bigeon.gclc.command.ScriptExecution#help(fr.bigeon.gclc.manager.ConsoleManager, String...)}. */ @Test public void testHelp() { - ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$ + final ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$ Charset.forName("UTF-8")); try (PipedConsoleManager test = new PipedConsoleManager()) { exec.help(test); exec.help(test, "ignored element"); - } catch (IOException e) { + } catch (final IOException e) { e.printStackTrace(); fail("unexpected error in help invocation"); //$NON-NLS-1$ } } + + /** Test method for {@link fr.bigeon.gclc.command.ScriptExecution#tip()}. */ + @Test + public void testTip() { + final ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$ + Charset.forName("UTF-8")); + assertNotNull("Tip should not be null", exec.tip()); + } } diff --git a/gclc/src/test/java/fr/bigeon/gclc/command/SubedCommandTest.java b/gclc/src/test/java/fr/bigeon/gclc/command/SubedCommandTest.java index bba4620..edc837a 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/command/SubedCommandTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/command/SubedCommandTest.java @@ -59,6 +59,296 @@ import fr.bigeon.gclc.manager.PipedConsoleManager; @SuppressWarnings("all") public class SubedCommandTest { + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#add(fr.bigeon.gclc.command.ICommand)}. */ + @Test + public final void testAdd() { + final SubedCommand cmd = new SubedCommand("name"); + + try { + cmd.add(new MockCommand("id")); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + try { + cmd.add(new MockCommand("id")); + fail("addition of command with already used id succeeded"); + } catch (final InvalidCommandName e) { + // + assertNotNull(e); + } + try { + cmd.add(new MockCommand("")); + fail("addition of command with invalid id succeeded"); + } catch (final InvalidCommandName e) { + // + assertNotNull(e); + } + + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#execute(java.lang.String[])}. */ + @Test + public final void testExecute() { + SubedCommand cmd = new SubedCommand("name"); + + final MockCommand mock = new MockCommand("id"); + try { + cmd.add(mock); + cmd.add(new Command("fail") { + + @Override + public void execute(final String... args) throws CommandRunException { + throw new CommandRunException("Failing command", null); + } + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + + try { + cmd.execute("id"); + } catch (final CommandRunException e) { + fail("Unexpected exception when running mock command"); + assertNotNull(e); + } + try { + cmd.execute("fail"); + fail("Fail command error should be re thrown"); + } catch (final CommandRunException e) { + assertNotNull(e); + assertEquals(cmd, e.getSource()); + } + try { + cmd.execute(); + fail("Request for inexistent default command should fail"); + } catch (final CommandRunException e) { + assertNotNull(e); + assertEquals(cmd, e.getSource()); + } + cmd = new SubedCommand("name", mock); + + try { + cmd.add(mock); + cmd.add(new Command("fail") { + + @Override + public void execute(final String... args) throws CommandRunException { + throw new CommandRunException("Failing command", this); + } + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + + try { + cmd.execute("id"); + } catch (final CommandRunException e) { + fail("Unexpected exception when running mock command"); + assertNotNull(e); + } + try { + cmd.execute("fail"); + fail("Fail command error should be re thrown"); + } catch (final CommandRunException e) { + assertNotNull(e); + assertEquals(cmd.get("fail"), e.getSource()); + } + try { + cmd.execute(); + } catch (final CommandRunException e) { + fail("Request for default command should execute default command"); + assertNotNull(e); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#executeSub(java.lang.String, java.lang.String[])}. */ + @Test + public final void testExecuteSub() { + final SubedCommand cmd = new SubedCommand("name"); + + final MockCommand mock = new MockCommand("id"); + try { + cmd.add(mock); + cmd.add(new Command("fail") { + + @Override + public void execute(final String... args) throws CommandRunException { + throw new CommandRunException("Failing command", this); + } + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + + try { + cmd.executeSub("id"); + } catch (final CommandRunException e) { + fail("Unexpected exception when running mock command"); + assertNotNull(e); + } + try { + cmd.executeSub("fail"); + fail("Fail command error should be re thrown"); + } catch (final CommandRunException e) { + assertNotNull(e); + assertEquals(cmd.get("fail"), e.getSource()); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#get(java.lang.String)}. */ + @Test + public final void testGet() { + final SubedCommand cmd = new SubedCommand("name"); + + assertNull(cmd.get("id")); + + final MockCommand mock = new MockCommand("id"); + try { + cmd.add(mock); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + assertEquals(mock, cmd.get("id")); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#getCommandName()}. */ + @Test + public final void testGetCommandName() { + SubedCommand cmd = new SubedCommand("name"); + assertEquals("name", cmd.getCommandName()); + cmd = new SubedCommand("name with spaces"); + assertEquals("name with spaces", cmd.getCommandName()); + cmd = new SubedCommand("name", "some tip"); + assertEquals("name", cmd.getCommandName()); + cmd = new SubedCommand("name", new MockCommand("")); + assertEquals("name", cmd.getCommandName()); + cmd = new SubedCommand("name", new MockCommand(""), "some tip"); + assertEquals("name", cmd.getCommandName()); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#help(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String[])}. */ + @Test + public final void testHelp() { + SubedCommand cmd = new SubedCommand("name"); + + ICommand mock = new MockCommand("id"); + try { + cmd.add(mock); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + + try (PipedConsoleManager manager = new PipedConsoleManager(); + PipedConsoleManager manager2 = new PipedConsoleManager()) { + cmd.help(manager); + assertEquals("\tid", manager.readNextLine()); + cmd.help(manager, "id"); + cmd.help(manager, "inexistent"); + } catch (final IOException e) { + fail("Unexpected exception when running help"); + assertNotNull(e); + } + + cmd = new SubedCommand("name", mock); + + try { + cmd.add(mock); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + + try (PipedConsoleManager manager = new PipedConsoleManager(); + PipedConsoleManager manager2 = new PipedConsoleManager()) { + cmd.help(manager); + assertEquals("\tid", manager.readNextLine()); + } catch (final IOException e) { + fail("Unexpected exception when running help"); + assertNotNull(e); + } + + mock = new ICommand() { + + @Override + public void execute(final String... args) throws CommandRunException { + // + } + + @Override + public String getCommandName() { + return "id"; + } + + @Override + public void help(final ConsoleManager manager, + final String... args) throws IOException { + // + } + + @Override + public String tip() { + return "tip"; + } + }; + cmd = new SubedCommand("name", mock); + + try { + cmd.add(mock); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + + try (PipedConsoleManager manager = new PipedConsoleManager(); + PipedConsoleManager manager2 = new PipedConsoleManager()) { + cmd.help(manager); + assertEquals("\ttip", manager.readNextLine()); + assertEquals("\tid: tip", manager.readNextLine()); + } catch (final IOException e) { + fail("Unexpected exception when running help"); + assertNotNull(e); + } + } + /** Test method for * {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String)}. */ @Test @@ -101,284 +391,6 @@ public class SubedCommandTest { assertEquals("name with spaces", cmd.getCommandName()); } - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#add(fr.bigeon.gclc.command.ICommand)}. */ - @Test - public final void testAdd() { - SubedCommand cmd = new SubedCommand("name"); - - try { - cmd.add(new MockCommand("id")); - } catch (InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - try { - cmd.add(new MockCommand("id")); - fail("addition of command with already used id succeeded"); - } catch (InvalidCommandName e) { - // - assertNotNull(e); - } - try { - cmd.add(new MockCommand("")); - fail("addition of command with invalid id succeeded"); - } catch (InvalidCommandName e) { - // - assertNotNull(e); - } - - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#execute(java.lang.String[])}. */ - @Test - public final void testExecute() { - SubedCommand cmd = new SubedCommand("name"); - - MockCommand mock = new MockCommand("id"); - try { - cmd.add(mock); - cmd.add(new Command("fail") { - - @Override - public String tip() { - return null; - } - - @Override - public void execute(String... args) throws CommandRunException { - throw new CommandRunException("Failing command", null); - } - }); - } catch (InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - - try { - cmd.execute("id"); - } catch (CommandRunException e) { - fail("Unexpected exception when running mock command"); - assertNotNull(e); - } - try { - cmd.execute("fail"); - fail("Fail command error should be re thrown"); - } catch (CommandRunException e) { - assertNotNull(e); - assertEquals(cmd, e.getSource()); - } - try { - cmd.execute(); - fail("Request for inexistent default command should fail"); - } catch (CommandRunException e) { - assertNotNull(e); - assertEquals(cmd, e.getSource()); - } - cmd = new SubedCommand("name", mock); - - try { - cmd.add(mock); - cmd.add(new Command("fail") { - - @Override - public String tip() { - return null; - } - - @Override - public void execute(String... args) throws CommandRunException { - throw new CommandRunException("Failing command", this); - } - }); - } catch (InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - - try { - cmd.execute("id"); - } catch (CommandRunException e) { - fail("Unexpected exception when running mock command"); - assertNotNull(e); - } - try { - cmd.execute("fail"); - fail("Fail command error should be re thrown"); - } catch (CommandRunException e) { - assertNotNull(e); - assertEquals(cmd.get("fail"), e.getSource()); - } - try { - cmd.execute(); - } catch (CommandRunException e) { - fail("Request for default command should execute default command"); - assertNotNull(e); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#executeSub(java.lang.String, java.lang.String[])}. */ - @Test - public final void testExecuteSub() { - SubedCommand cmd = new SubedCommand("name"); - - MockCommand mock = new MockCommand("id"); - try { - cmd.add(mock); - cmd.add(new Command("fail") { - - @Override - public String tip() { - return null; - } - - @Override - public void execute(String... args) throws CommandRunException { - throw new CommandRunException("Failing command", this); - } - }); - } catch (InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - - try { - cmd.executeSub("id"); - } catch (CommandRunException e) { - fail("Unexpected exception when running mock command"); - assertNotNull(e); - } - try { - cmd.executeSub("fail"); - fail("Fail command error should be re thrown"); - } catch (CommandRunException e) { - assertNotNull(e); - assertEquals(cmd.get("fail"), e.getSource()); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#get(java.lang.String)}. */ - @Test - public final void testGet() { - SubedCommand cmd = new SubedCommand("name"); - - assertNull(cmd.get("id")); - - MockCommand mock = new MockCommand("id"); - try { - cmd.add(mock); - } catch (InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - assertEquals(mock, cmd.get("id")); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#getCommandName()}. */ - @Test - public final void testGetCommandName() { - SubedCommand cmd = new SubedCommand("name"); - assertEquals("name", cmd.getCommandName()); - cmd = new SubedCommand("name with spaces"); - assertEquals("name with spaces", cmd.getCommandName()); - cmd = new SubedCommand("name", "some tip"); - assertEquals("name", cmd.getCommandName()); - cmd = new SubedCommand("name", new MockCommand("")); - assertEquals("name", cmd.getCommandName()); - cmd = new SubedCommand("name", new MockCommand(""), "some tip"); - assertEquals("name", cmd.getCommandName()); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#help(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String[])}. */ - @Test - public final void testHelp() { - SubedCommand cmd = new SubedCommand("name"); - - ICommand mock = new MockCommand("id"); - try { - cmd.add(mock); - } catch (InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - - try (PipedConsoleManager manager = new PipedConsoleManager(); - PipedConsoleManager manager2 = new PipedConsoleManager()) { - cmd.help(manager); - assertEquals("\tid", manager.readNextLine()); - cmd.help(manager, "id"); - cmd.help(manager, "inexistent"); - } catch (IOException e) { - fail("Unexpected exception when running help"); - assertNotNull(e); - } - - cmd = new SubedCommand("name", mock); - - try { - cmd.add(mock); - } catch (InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - - try (PipedConsoleManager manager = new PipedConsoleManager(); - PipedConsoleManager manager2 = new PipedConsoleManager()) { - cmd.help(manager); - assertEquals("\tid", manager.readNextLine()); - } catch (IOException e) { - fail("Unexpected exception when running help"); - assertNotNull(e); - } - - mock = new ICommand() { - - @Override - public String tip() { - return "tip"; - } - - @Override - public void help(ConsoleManager manager, - String... args) throws IOException { - // - } - - @Override - public String getCommandName() { - return "id"; - } - - @Override - public void execute(String... args) throws CommandRunException { - // - } - }; - cmd = new SubedCommand("name", mock); - - try { - cmd.add(mock); - } catch (InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - - try (PipedConsoleManager manager = new PipedConsoleManager(); - PipedConsoleManager manager2 = new PipedConsoleManager()) { - cmd.help(manager); - assertEquals("\ttip", manager.readNextLine()); - assertEquals("\tid: tip", manager.readNextLine()); - } catch (IOException e) { - fail("Unexpected exception when running help"); - assertNotNull(e); - } - } - /** Test method for {@link fr.bigeon.gclc.command.SubedCommand#tip()}. */ @Test public final void testTip() { diff --git a/gclc/src/test/java/fr/bigeon/gclc/proc/ProcessListTest.java b/gclc/src/test/java/fr/bigeon/gclc/proc/ProcessListTest.java index 8ce5b8d..f0fdff4 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/proc/ProcessListTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/proc/ProcessListTest.java @@ -38,6 +38,9 @@ */ package fr.bigeon.gclc.proc; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import java.io.IOException; import org.junit.Test; @@ -49,68 +52,65 @@ import fr.bigeon.gclc.manager.PipedConsoleManager; *

* TODO * - * @author Emmanuel Bigeon - * - */ + * @author Emmanuel Bigeon */ public class ProcessListTest { /** Test method for * {@link fr.bigeon.gclc.proc.ProcessList#execute(java.lang.String[])}. - * + * * @throws CommandRunException if an error occured in the execution * @throws IOException if the manager could not be created */ @Test public final void testExecute() throws CommandRunException, IOException { - TaskPool pool = new TaskPool(); - ProcessList pl = new ProcessList("list", pool, - new PipedConsoleManager()); + final TaskPool pool = new TaskPool(); + try (PipedConsoleManager pcm = new PipedConsoleManager()) { + final ProcessList pl = new ProcessList("list", pool, pcm); pl.execute(); - pool.add(new Task() { + pool.add(new Task() { - @Override - public void run() { - // TODO Auto-generated method stub - // - throw new RuntimeException("Not implemented yet"); - } + @Override + public void addInterruptionListener(final InterruptionListener listener) { + // + } - @Override - public void setRunning(boolean running) { - // - } + @Override + public String getName() { + return "name"; + } - @Override - public void rmInterruptionListener(InterruptionListener listener) { - // - } + @Override + public boolean isRunning() { + return false; + } - @Override - public boolean isRunning() { - return false; - } + @Override + public void rmInterruptionListener(final InterruptionListener listener) { + // + } - @Override - public String getName() { - return "name"; - } + @Override + public void run() { + // TODO Auto-generated method stub + // + throw new RuntimeException("Not implemented yet"); + } - @Override - public void addInterruptionListener(InterruptionListener listener) { - // - } - }); - pl.execute(); + @Override + public void setRunning(final boolean running) { + // + } + }); + pl.execute(); + assertTrue("List should give the process", + pcm.readNextLine().endsWith("name")); + } } @Test - public void testTip() { - try { - new ProcessList("list", new TaskPool(), new PipedConsoleManager()) - .tip(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + public void testTip() throws IOException { + try (PipedConsoleManager pcm = new PipedConsoleManager()) { + assertNotNull("Tip should not be null", new ProcessList("list", + new TaskPool(), pcm).tip()); } - } } diff --git a/gclc/src/test/java/fr/bigeon/gclc/proc/TaskPoolTest.java b/gclc/src/test/java/fr/bigeon/gclc/proc/TaskPoolTest.java index 638db45..069b541 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/proc/TaskPoolTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/proc/TaskPoolTest.java @@ -39,7 +39,6 @@ package fr.bigeon.gclc.proc; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import org.junit.Test; @@ -55,26 +54,46 @@ public class TaskPoolTest { * {@link fr.bigeon.gclc.proc.TaskPool#add(fr.bigeon.gclc.proc.Task)}. */ @Test public final void testAdd() { - TaskPool pool = new TaskPool(); + final TaskPool pool = new TaskPool(); Task task = null; try { pool.add(task); fail("Expected a null pointer exception"); - } catch (NullPointerException e) { - assertNotNull(e); + } catch (final IllegalArgumentException e) { + // ok } task = new Task() { private final Object lock = new Object(); private boolean running; private InterruptionListener listener; + @Override + public void addInterruptionListener(final InterruptionListener listener) { + this.listener = listener; + } + + @Override + public String getName() { + return "Test"; + } + + @Override + public boolean isRunning() { + return running; + } + + @Override + public void rmInterruptionListener(final InterruptionListener listener) { + // + } + @Override public void run() { synchronized (lock) { while (running) { try { lock.wait(100); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -84,45 +103,25 @@ public class TaskPoolTest { } @Override - public void setRunning(boolean running) { + public void setRunning(final boolean running) { synchronized (lock) { this.running = running; } // } - - @Override - public void rmInterruptionListener(InterruptionListener listener) { - // - } - - @Override - public boolean isRunning() { - return running; - } - - @Override - public String getName() { - return "Test"; - } - - @Override - public void addInterruptionListener(InterruptionListener listener) { - this.listener = listener; - } }; pool.add(task); assertEquals(1, pool.getPIDs().size()); - for (String pid : pool.getPIDs()) { + for (final String pid : pool.getPIDs()) { assertEquals(task, pool.get(pid)); } - Thread th = new Thread(task); + final Thread th = new Thread(task); th.start(); task.setRunning(false); try { th.join(1000); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } diff --git a/gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterTest.java b/gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterTest.java index 3370151..2e647b8 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterTest.java @@ -55,7 +55,8 @@ import org.junit.Test; import fr.bigeon.gclc.manager.PipedConsoleManager; -/**

+/** + *

* TODO * * @author Emmanuel Bigeon */ @@ -78,7 +79,7 @@ public class CLIPrompterTest { @Test public final void testPromptBoolean() { try (final PipedConsoleManager test = new PipedConsoleManager()) { - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { @@ -91,7 +92,7 @@ public class CLIPrompterTest { CLIPrompter.promptBoolean(test, "My message")); //$NON-NLS-1$ assertFalse( CLIPrompter.promptBoolean(test, "My message")); //$NON-NLS-1$ - } catch (IOException e) { + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -131,7 +132,7 @@ public class CLIPrompterTest { final String cancel = "Cancel"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$ - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { @@ -142,7 +143,7 @@ public class CLIPrompterTest { test, keys, choices, message, null)); assertEquals(null, CLIPrompter.promptChoice(test, keys, choices, message, cancel)); - } catch (IOException e) { + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -157,9 +158,10 @@ public class CLIPrompterTest { test.readNextLine()); test.type("yoyo"); //$NON-NLS-1$ // fail, reprompt - String msg = CLIPrompterMessages.getString("promptchoice.formaterr", //$NON-NLS-1$ + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ 0, keys.size()); - for (String line : msg.split(System.lineSeparator())) { + for (final String line : msg.split(System.lineSeparator())) { assertEquals(line, test.readNextLine()); } assertTrue(test.readNextLine().contains(keys.get(0))); @@ -176,9 +178,9 @@ public class CLIPrompterTest { test.readNextLine()); test.type("2"); //$NON-NLS-1$ // fail, reprompt - assertEquals(CLIPrompterMessages - .getString("promptchoice.outofbounds", 0, keys.size() - 1), //$NON-NLS-1$ - test.readNextLine()); + assertEquals( + CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ + keys.size() - 1), test.readNextLine()); assertTrue(test.readNextLine().contains(keys.get(0))); assertTrue(test.readNextLine().contains(keys.get(1))); assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ @@ -199,94 +201,6 @@ public class CLIPrompterTest { } } - @Test - public final void testPromptChoiceConsoleManagerListOfUStringString() { - try (final PipedConsoleManager test = new PipedConsoleManager()) { - final List keys = new ArrayList<>(); - keys.add("A choice"); //$NON-NLS-1$ - keys.add("An other"); //$NON-NLS-1$ - final String cancel = "Cancel"; //$NON-NLS-1$ - final String message = "My message"; //$NON-NLS-1$ - - Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals(Integer.valueOf(0), - CLIPrompter.promptChoice(test, - keys, message, cancel)); - assertEquals(Integer.valueOf(0), CLIPrompter - .promptChoice(test, - keys, message, null)); - assertEquals(Integer.valueOf(1), CLIPrompter - .promptChoice(test, keys, message, null)); - assertEquals(null, CLIPrompter.promptChoice(test, keys, - message, cancel)); - } catch (IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - assertTrue(test.readNextLine().startsWith(message)); - assertTrue(test.readNextLine().contains(keys.get(0).toString())); - assertTrue(test.readNextLine().contains(keys.get(1).toString())); - assertTrue(test.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - test.readNextLine()); - test.type("yoyo"); //$NON-NLS-1$ - // fail, reprompt - String msg = CLIPrompterMessages.getString("promptchoice.formaterr", //$NON-NLS-1$ - 0, keys.size()); - for (String line : msg.split(System.lineSeparator())) { - assertEquals(line, test.readNextLine()); - } - assertTrue(test.readNextLine().contains(keys.get(0).toString())); - assertTrue(test.readNextLine().contains(keys.get(1).toString())); - assertTrue(test.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - test.readNextLine()); - test.type("0"); //$NON-NLS-1$ - // Sucess, reprompt without cancel - assertTrue(test.readNextLine().startsWith(message)); - assertTrue(test.readNextLine().contains(keys.get(0).toString())); - assertTrue(test.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - test.readNextLine()); - test.type("2"); //$NON-NLS-1$ - // fail, reprompt - assertEquals(CLIPrompterMessages - .getString("promptchoice.outofbounds", 0, keys.size() - 1), //$NON-NLS-1$ - test.readNextLine()); - assertTrue(test.readNextLine().contains(keys.get(0).toString())); - assertTrue(test.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - test.readNextLine()); - test.type("0"); //$NON-NLS-1$ - // Success do it again - assertTrue(test.readNextLine().startsWith(message)); - assertTrue(test.readNextLine().contains(keys.get(0).toString())); - assertTrue(test.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - test.readNextLine()); - test.type("1"); //$NON-NLS-1$ - // Sucess, prompt with cancel - assertTrue(test.readNextLine().startsWith(message)); - assertTrue(test.readNextLine().contains(keys.get(0).toString())); - assertTrue(test.readNextLine().contains(keys.get(1).toString())); - assertTrue(test.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - test.readNextLine()); - test.type("2"); //$NON-NLS-1$ - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - @Test public final void testPromptChoiceConsoleManagerListOfUMapOfUTStringString() { try (final PipedConsoleManager test = new PipedConsoleManager()) { @@ -299,20 +213,20 @@ public class CLIPrompterTest { final String cancel = "Cancel"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$ - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { try { assertEquals(choices.get(keys.get(0)), - CLIPrompter.promptChoice( - test, keys, choices, message, cancel)); + CLIPrompter.promptChoice(test, keys, choices, + message, cancel)); assertEquals(choices.get(keys.get(0)), - CLIPrompter.promptChoice( - test, keys, choices, message, null)); + CLIPrompter.promptChoice(test, keys, choices, + message, null)); assertEquals(null, CLIPrompter.promptChoice(test, keys, choices, message, cancel)); - } catch (IOException e) { + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -327,9 +241,10 @@ public class CLIPrompterTest { test.readNextLine()); test.type("yoyo"); //$NON-NLS-1$ // fail, reprompt - String msg = CLIPrompterMessages.getString("promptchoice.formaterr", //$NON-NLS-1$ + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ 0, keys.size()); - for (String line : msg.split(System.lineSeparator())) { + for (final String line : msg.split(System.lineSeparator())) { assertEquals(line, test.readNextLine()); } assertTrue(test.readNextLine().contains(keys.get(0).toString())); @@ -346,9 +261,9 @@ public class CLIPrompterTest { test.readNextLine()); test.type("2"); //$NON-NLS-1$ // fail, reprompt - assertEquals(CLIPrompterMessages - .getString("promptchoice.outofbounds", 0, keys.size() - 1), //$NON-NLS-1$ - test.readNextLine()); + assertEquals( + CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ + keys.size() - 1), test.readNextLine()); assertTrue(test.readNextLine().contains(keys.get(0).toString())); assertTrue(test.readNextLine().contains(keys.get(1).toString())); assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ @@ -369,6 +284,93 @@ public class CLIPrompterTest { } } + @Test + public final void testPromptChoiceConsoleManagerListOfUStringString() { + try (final PipedConsoleManager test = new PipedConsoleManager()) { + final List keys = new ArrayList<>(); + keys.add("A choice"); //$NON-NLS-1$ + keys.add("An other"); //$NON-NLS-1$ + final String cancel = "Cancel"; //$NON-NLS-1$ + final String message = "My message"; //$NON-NLS-1$ + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals(Integer.valueOf(0), CLIPrompter + .promptChoice(test, keys, message, cancel)); + assertEquals(Integer.valueOf(0), CLIPrompter + .promptChoice(test, keys, message, null)); + assertEquals(Integer.valueOf(1), CLIPrompter + .promptChoice(test, keys, message, null)); + assertEquals(null, CLIPrompter.promptChoice(test, keys, + message, cancel)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + assertTrue(test.readNextLine().startsWith(message)); + assertTrue(test.readNextLine().contains(keys.get(0).toString())); + assertTrue(test.readNextLine().contains(keys.get(1).toString())); + assertTrue(test.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + test.readNextLine()); + test.type("yoyo"); //$NON-NLS-1$ + // fail, reprompt + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ + 0, keys.size()); + for (final String line : msg.split(System.lineSeparator())) { + assertEquals(line, test.readNextLine()); + } + assertTrue(test.readNextLine().contains(keys.get(0).toString())); + assertTrue(test.readNextLine().contains(keys.get(1).toString())); + assertTrue(test.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + test.readNextLine()); + test.type("0"); //$NON-NLS-1$ + // Sucess, reprompt without cancel + assertTrue(test.readNextLine().startsWith(message)); + assertTrue(test.readNextLine().contains(keys.get(0).toString())); + assertTrue(test.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + test.readNextLine()); + test.type("2"); //$NON-NLS-1$ + // fail, reprompt + assertEquals( + CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ + keys.size() - 1), test.readNextLine()); + assertTrue(test.readNextLine().contains(keys.get(0).toString())); + assertTrue(test.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + test.readNextLine()); + test.type("0"); //$NON-NLS-1$ + // Success do it again + assertTrue(test.readNextLine().startsWith(message)); + assertTrue(test.readNextLine().contains(keys.get(0).toString())); + assertTrue(test.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + test.readNextLine()); + test.type("1"); //$NON-NLS-1$ + // Sucess, prompt with cancel + assertTrue(test.readNextLine().startsWith(message)); + assertTrue(test.readNextLine().contains(keys.get(0).toString())); + assertTrue(test.readNextLine().contains(keys.get(1).toString())); + assertTrue(test.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + test.readNextLine()); + test.type("2"); //$NON-NLS-1$ + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + /** Test method for * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptChoice(fr.bigeon.gclc.manager.ConsoleManager, java.util.Map, java.lang.String, java.lang.String)}. */ @Test @@ -383,18 +385,20 @@ public class CLIPrompterTest { final String cancel = "Cancel"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$ - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { try { - assertEquals(choices.get(keys.get(0)), CLIPrompter - .promptChoice(test, choices, message, cancel)); - assertEquals(choices.get(keys.get(0)), CLIPrompter - .promptChoice(test, choices, message, null)); - assertEquals(null, CLIPrompter.promptChoice(test, + assertEquals(choices.get(keys.get(0)), + CLIPrompter.promptChoice(test, keys, choices, + message, cancel)); + assertEquals(choices.get(keys.get(0)), + CLIPrompter.promptChoice(test, keys, choices, + message, null)); + assertEquals(null, CLIPrompter.promptChoice(test, keys, choices, message, cancel)); - } catch (IOException e) { + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -402,16 +406,19 @@ public class CLIPrompterTest { }); th.start(); assertTrue(test.readNextLine().startsWith(message)); - assertTrue(test.readNextLine().contains(keys.get(0).toString())); + final String readNextLine = test.readNextLine(); + assertTrue(readNextLine + " expected to contain " + keys.get(0), + readNextLine.contains(keys.get(0).toString())); assertTrue(test.readNextLine().contains(keys.get(1).toString())); assertTrue(test.readNextLine().contains(cancel)); assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ test.readNextLine()); test.type("yoyo"); //$NON-NLS-1$ // fail, reprompt - String msg = CLIPrompterMessages.getString("promptchoice.formaterr", //$NON-NLS-1$ + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ 0, keys.size()); - for (String line : msg.split(System.lineSeparator())) { + for (final String line : msg.split(System.lineSeparator())) { assertEquals(line, test.readNextLine()); } assertTrue(test.readNextLine().contains(keys.get(0).toString())); @@ -428,9 +435,9 @@ public class CLIPrompterTest { test.readNextLine()); test.type("2"); //$NON-NLS-1$ // fail, reprompt - assertEquals(CLIPrompterMessages - .getString("promptchoice.outofbounds", 0, keys.size() - 1), //$NON-NLS-1$ - test.readNextLine()); + assertEquals( + CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ + keys.size() - 1), test.readNextLine()); assertTrue(test.readNextLine().contains(keys.get(0).toString())); assertTrue(test.readNextLine().contains(keys.get(1).toString())); assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ @@ -456,7 +463,7 @@ public class CLIPrompterTest { @Test public final void testPromptInteger() { try (final PipedConsoleManager test = new PipedConsoleManager()) { - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { @@ -465,7 +472,7 @@ public class CLIPrompterTest { CLIPrompter.promptInteger(test, "My message")); //$NON-NLS-1$ assertEquals(-15, CLIPrompter.promptInteger(test, "My message")); //$NON-NLS-1$ - } catch (IOException e) { + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -498,7 +505,7 @@ public class CLIPrompterTest { keys.add("An other"); //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$ - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { @@ -507,7 +514,7 @@ public class CLIPrompterTest { CLIPrompter.promptList(test, message)); assertEquals(keys, CLIPrompter.promptList(test, message)); - } catch (IOException e) { + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -556,7 +563,7 @@ public class CLIPrompterTest { final String ender = "*"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$ - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { @@ -565,7 +572,7 @@ public class CLIPrompterTest { CLIPrompter.promptList(test, message, ender)); assertEquals(keys, CLIPrompter.promptList(test, message, ender)); - } catch (IOException e) { + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -606,19 +613,21 @@ public class CLIPrompterTest { try (final PipedConsoleManager test = new PipedConsoleManager()) { final String message = "My message"; final String longText = "Some text with" + System.lineSeparator() + - "line feeds and other" + System.lineSeparator() + - System.lineSeparator() + " \tspecial characters"; + "line feeds and other" + + System.lineSeparator() + + System.lineSeparator() + + " \tspecial characters"; - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { try { assertEquals("", CLIPrompter.promptLongText(test, message)); - assertEquals(longText, + assertEquals(longText + System.lineSeparator(), CLIPrompter.promptLongText(test, message)); - } catch (IOException e) { + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -627,10 +636,9 @@ public class CLIPrompterTest { th.start(); String nLine = test.readNextLine(); assertTrue(nLine.startsWith(message)); - assertTrue(nLine.endsWith(CLIPrompterMessages - .getString("promptlongtext.exit.dispkey", - CLIPrompterMessages.getString( - "promptlongtext.exit.defaultkey")))); + assertTrue(nLine.endsWith(CLIPrompterMessages.getString( + "promptlongtext.exit.dispkey", CLIPrompterMessages + .getString("promptlongtext.exit.defaultkey")))); assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), test.readNextLine()); test.type(CLIPrompterMessages @@ -638,14 +646,13 @@ public class CLIPrompterTest { // enter long text nLine = test.readNextLine(); assertTrue(nLine.startsWith(message)); - assertTrue(nLine.endsWith(CLIPrompterMessages - .getString("promptlongtext.exit.dispkey", - CLIPrompterMessages.getString( - "promptlongtext.exit.defaultkey")))); + assertTrue(nLine.endsWith(CLIPrompterMessages.getString( + "promptlongtext.exit.dispkey", CLIPrompterMessages + .getString("promptlongtext.exit.defaultkey")))); assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), test.readNextLine()); - String[] text = longText.split(System.lineSeparator()); - for (String element : text) { + final String[] text = longText.split(System.lineSeparator()); + for (final String element : text) { test.type(element); assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), test.readNextLine()); @@ -666,21 +673,23 @@ public class CLIPrompterTest { try (final PipedConsoleManager test = new PipedConsoleManager()) { final String message = "My message"; final String ender = "\\quit"; - final String[] text = new String[]{"Some text with" , - "feeds and other" , " \tspecial characters"}; + final String[] text = new String[] {"Some text with", + "feeds and other", " \tspecial characters"}; final String longText = text[0] + System.lineSeparator() + text[1] + - System.lineSeparator() + text[2]; + System.lineSeparator() + text[2]; - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { try { assertEquals("", //$NON-NLS-1$ - CLIPrompter.promptLongText(test, message, ender)); - assertEquals(longText, - CLIPrompter.promptLongText(test, message, ender)); - } catch (IOException e) { + CLIPrompter.promptLongText(test, message, + ender)); + assertEquals(longText + System.lineSeparator(), + CLIPrompter.promptLongText(test, message, + ender)); + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -690,8 +699,7 @@ public class CLIPrompterTest { String nLine = test.readNextLine(); assertTrue(nLine.startsWith(message)); assertTrue(nLine.endsWith(CLIPrompterMessages - .getString("promptlongtext.exit.dispkey", - ender))); + .getString("promptlongtext.exit.dispkey", ender))); assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), test.readNextLine()); test.type(ender); @@ -699,11 +707,10 @@ public class CLIPrompterTest { nLine = test.readNextLine(); assertTrue(nLine.startsWith(message)); assertTrue(nLine.endsWith(CLIPrompterMessages - .getString("promptlongtext.exit.dispkey", - ender))); + .getString("promptlongtext.exit.dispkey", ender))); assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), test.readNextLine()); - for (String element : text) { + for (final String element : text) { test.type(element); assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), test.readNextLine()); @@ -729,7 +736,7 @@ public class CLIPrompterTest { choices.add("The actual other"); //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$ - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { @@ -737,14 +744,14 @@ public class CLIPrompterTest { assertTrue(CLIPrompter .promptMultiChoice(test, keys, choices, message) .isEmpty()); - ArrayList l = new ArrayList<>(); + final ArrayList l = new ArrayList<>(); l.add(choices.get(0)); assertEquals(l, CLIPrompter.promptMultiChoice(test, keys, choices, message)); l.add(choices.get(1)); assertEquals(l, CLIPrompter.promptMultiChoice(test, keys, choices, message)); - } catch (IOException e) { + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -758,9 +765,10 @@ public class CLIPrompterTest { test.readNextLine()); test.type("yoyo"); //$NON-NLS-1$ // fail, reprompt - String msg = CLIPrompterMessages.getString("promptchoice.formaterr", //$NON-NLS-1$ + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ 0, keys.size() - 1); - for (String line : msg.split(System.lineSeparator())) { + for (final String line : msg.split(System.lineSeparator())) { assertEquals(line, test.readNextLine()); } assertTrue(test.readNextLine().contains(keys.get(0))); @@ -812,7 +820,7 @@ public class CLIPrompterTest { choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$ - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { @@ -820,14 +828,14 @@ public class CLIPrompterTest { assertTrue(CLIPrompter .promptMultiChoice(test, keys, choices, message) .isEmpty()); - ArrayList l = new ArrayList<>(); + final ArrayList l = new ArrayList<>(); l.add(choices.get(keys.get(0))); assertEquals(l, CLIPrompter.promptMultiChoice(test, keys, choices, message)); l.add(choices.get(keys.get(1))); assertEquals(l, CLIPrompter.promptMultiChoice(test, keys, choices, message)); - } catch (IOException e) { + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -841,9 +849,10 @@ public class CLIPrompterTest { test.readNextLine()); test.type("yoyo"); //$NON-NLS-1$ // fail, reprompt - String msg = CLIPrompterMessages.getString("promptchoice.formaterr", //$NON-NLS-1$ + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ 0, keys.size() - 1); - for (String line : msg.split(System.lineSeparator())) { + for (final String line : msg.split(System.lineSeparator())) { assertEquals(line, test.readNextLine()); } assertTrue(test.readNextLine().contains(keys.get(0).toString())); @@ -892,7 +901,7 @@ public class CLIPrompterTest { keys.add("An other"); //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$ - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { @@ -900,14 +909,14 @@ public class CLIPrompterTest { assertTrue(CLIPrompter .promptMultiChoice(test, keys, message) .isEmpty()); - ArrayList l = new ArrayList<>(); + final ArrayList l = new ArrayList<>(); l.add(0); assertEquals(l, CLIPrompter.promptMultiChoice(test, keys, message)); l.add(1); assertEquals(l, CLIPrompter.promptMultiChoice(test, keys, message)); - } catch (IOException e) { + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -921,9 +930,10 @@ public class CLIPrompterTest { test.readNextLine()); test.type("yoyo"); //$NON-NLS-1$ // fail, reprompt - String msg = CLIPrompterMessages.getString("promptchoice.formaterr", //$NON-NLS-1$ + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ 0, keys.size() - 1); - for (String line : msg.split(System.lineSeparator())) { + for (final String line : msg.split(System.lineSeparator())) { assertEquals(line, test.readNextLine()); } assertTrue(test.readNextLine().contains(keys.get(0).toString())); @@ -975,22 +985,22 @@ public class CLIPrompterTest { choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$ - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { try { assertTrue(CLIPrompter - .promptMultiChoice(test, choices, message) + .promptMultiChoice(test, keys, choices, message) .isEmpty()); - ArrayList l = new ArrayList<>(); + final ArrayList l = new ArrayList<>(); l.add(choices.get(keys.get(0))); assertEquals(l, CLIPrompter.promptMultiChoice(test, - choices, message)); + keys, choices, message)); l.add(choices.get(keys.get(1))); assertEquals(l, CLIPrompter.promptMultiChoice(test, - choices, message)); - } catch (IOException e) { + keys, choices, message)); + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); } @@ -998,15 +1008,18 @@ public class CLIPrompterTest { }); th.start(); assertTrue(test.readNextLine().startsWith(message)); - assertTrue(test.readNextLine().contains(keys.get(0).toString())); + final String readNextLine = test.readNextLine(); + assertTrue(readNextLine + " expected to contain " + keys.get(0), + readNextLine.contains(keys.get(0).toString())); assertTrue(test.readNextLine().contains(keys.get(1).toString())); assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ test.readNextLine()); test.type("yoyo"); //$NON-NLS-1$ // fail, reprompt - String msg = CLIPrompterMessages.getString("promptchoice.formaterr", //$NON-NLS-1$ + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ 0, keys.size() - 1); - for (String line : msg.split(System.lineSeparator())) { + for (final String line : msg.split(System.lineSeparator())) { assertEquals(line, test.readNextLine()); } assertTrue(test.readNextLine().contains(keys.get(0).toString())); @@ -1051,14 +1064,14 @@ public class CLIPrompterTest { public final void testPromptNonEmpty() { try (final PipedConsoleManager test = new PipedConsoleManager()) { final String res = "some content"; //$NON-NLS-1$ - Thread th = new Thread(new Runnable() { + final Thread th = new Thread(new Runnable() { @Override public void run() { try { assertEquals(res, CLIPrompter.promptNonEmpty(test, "My message", "my reprompt")); //$NON-NLS-1$ //$NON-NLS-2$ - } catch (IOException e) { + } catch (final IOException e) { fail("Unexpected io excpetion"); //$NON-NLS-1$ e.printStackTrace(); }