Adding javadoc and code compliance

Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
This commit is contained in:
Emmanuel Bigeon 2017-11-13 22:01:33 -05:00
parent fce2b01914
commit 83c02f82ec
46 changed files with 1051 additions and 1002 deletions

View File

@ -56,15 +56,14 @@ import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput; import fr.bigeon.gclc.manager.ConsoleOutput;
/** /**
* <p>
* A {@link ConsoleApplication} is an application that require the user to input * A {@link ConsoleApplication} is an application that require the user to input
* commands. * commands.
* <p> * <p>
* A typical use case is the following: * A typical use case is the following:
* *
* <pre> * <pre>
* {@link ConsoleOutput} out = new {@link fr.bigeon.gclc.manager.SystemConsoleOutput SystemConsoleOutput}(); * {@link ConsoleOutput} out = new {@link fr.bigeon.gclc.manager.StreamConsoleOutput StreamConsoleOutput}();
* {@link ConsoleInput} in = new {@link fr.bigeon.gclc.manager.SystemConsoleInput SystemConsoleInput}(); * {@link ConsoleInput} in = new {@link fr.bigeon.gclc.manager.StreamConsoleInput StreamConsoleInput}();
* {@link ConsoleApplication} app = new {@link ConsoleApplication}(out, in, "welcome", "see you latter")}; * {@link ConsoleApplication} app = new {@link ConsoleApplication}(out, in, "welcome", "see you latter")};
* app.{@link ConsoleApplication#add(ICommand) add}("my_command", new {@link ICommand MyCommand()}); * app.{@link ConsoleApplication#add(ICommand) add}("my_command", new {@link ICommand MyCommand()});
* app.{@link ConsoleApplication#start() start()}; * app.{@link ConsoleApplication#start() start()};
@ -117,7 +116,9 @@ public final class ConsoleApplication implements ICommandProvider {
return root.add(cmd); return root.add(cmd);
} }
/** @param listener the command listener */ /** Add a listener for command requests.
*
* @param listener the command listener */
public void addListener(final CommandRequestListener listener) { public void addListener(final CommandRequestListener listener) {
listeners.add(listener); listeners.add(listener);
} }
@ -132,17 +133,7 @@ public final class ConsoleApplication implements ICommandProvider {
root.executeSub(output, input, command, args); root.executeSub(output, input, command, args);
} }
/* (non-Javadoc) /** Signify to the application that no command should be inputed anymore. */
* @see fr.bigeon.gclc.command.ICommandProvider#executeSub(java.lang.String, java.lang.String[])
*/
@Deprecated
@Override
public void executeSub(final String command,
final String... args) throws CommandRunException {
executeSub(out, in, command, args);
}
/** Signify to the application that no command should be inputed anymore */
public void exit() { public void exit() {
LOGGER.fine("Request exiting application..."); //$NON-NLS-1$ LOGGER.fine("Request exiting application..."); //$NON-NLS-1$
running = false; running = false;
@ -156,7 +147,12 @@ public final class ConsoleApplication implements ICommandProvider {
return root.get(command); return root.get(command);
} }
/** @param cmd the command /** Interpret a command line.
* <p>
* This method will split the command in its part and execute the command
* with {@link #executeSub(ConsoleOutput, ConsoleInput, String, String...)}.
*
* @param cmd the command
* @throws IOException if the command could not be parsed */ * @throws IOException if the command could not be parsed */
public void interpretCommand(final String cmd) throws IOException { public void interpretCommand(final String cmd) throws IOException {
List<String> args; List<String> args;
@ -183,12 +179,16 @@ public final class ConsoleApplication implements ICommandProvider {
} }
} }
/** @return the running status */ /** Test if the application is running.
*
* @return the running status */
public boolean isRunning() { public boolean isRunning() {
return running; return running;
} }
/** @param listener the command listener to remove */ /** Remove a listener from this application.
*
* @param listener the command listener to remove */
public void removeListener(final CommandRequestListener listener) { public void removeListener(final CommandRequestListener listener) {
listeners.remove(listener); listeners.remove(listener);
} }
@ -223,7 +223,7 @@ public final class ConsoleApplication implements ICommandProvider {
} }
} }
/** Start the application */ /** Start the application. */
public void start() { public void start() {
try { try {
running = true; running = true;

View File

@ -51,15 +51,17 @@ import fr.bigeon.gclc.exception.CommandParsingException;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class GCLCConstants { public final class GCLCConstants {
/** The escaping character */ /** The escaping character. */
private static final char ESCAPING_CHAR = getSystemEscapingChar(); private static final char ESCAPING_CHAR = getSystemEscapingChar();
/** Hide utility class constructor */ /** Hide utility class constructor. */
private GCLCConstants() { private GCLCConstants() {
// utility class // utility class
} }
/** @param cmd the command to parse /** Get the end of a string argument.
*
* @param cmd the command to parse
* @param startIndex the starting point of the parsing * @param startIndex the starting point of the parsing
* @param index the index of the current position * @param index the index of the current position
* @return the argument * @return the argument
@ -73,12 +75,16 @@ public final class GCLCConstants {
return cmd.substring(startIndex + 1, index - 1); return cmd.substring(startIndex + 1, index - 1);
} }
/** @return the escaping character */ /** Get the excaping character.
*
* @return the escaping character */
private static char getSystemEscapingChar() { private static char getSystemEscapingChar() {
return '\\'; return '\\';
} }
/** @param arg the string to remove excaping character from /** Remove escaping characters from the string.
*
* @param arg the string to remove excaping character from
* @return the string without escape character */ * @return the string without escape character */
private static String removeEscaped(final String arg) { private static String removeEscaped(final String arg) {
final StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
@ -93,7 +99,7 @@ public final class GCLCConstants {
return builder.toString(); return builder.toString();
} }
/** Splits a command in the diferrent arguments /** Splits a command in the diferrent arguments.
* *
* @param cmd the command to split in its parts * @param cmd the command to split in its parts
* @return the list of argument preceded by the command name * @return the list of argument preceded by the command name

View File

@ -42,10 +42,10 @@ import java.io.IOException;
import fr.bigeon.gclc.manager.ConsoleOutput; import fr.bigeon.gclc.manager.ConsoleOutput;
/** /** A command to execute.
* <p> * <p>
* A command to execute. It is mandatory that it has a name and that name cannot * It is mandatory that it has a name and that name cannot start with minus
* start with minus character or contain spaces. * character or contain spaces.
* <p> * <p>
* A command can be executed, with parameters that will be provided as an array * A command can be executed, with parameters that will be provided as an array
* of strings. * of strings.
@ -68,16 +68,24 @@ public abstract class Command implements ICommand {
/** The linux end of line character. */ /** The linux end of line character. */
private static final String EOL_LINUX = "\n"; //$NON-NLS-1$ private static final String EOL_LINUX = "\n"; //$NON-NLS-1$
/** The name of the command */ /** The name of the command. */
protected final String name; protected final String name;
/** @param name the command name */ /** Create the command.
*
* @param name the command name */
public Command(final String name) { public Command(final String name) {
super(); super();
this.name = name; this.name = name;
} }
/** @return a brief description of the command */ /** Get the brief part of the command help.
* <p>
* This method may be overriden by implementations to improve the help
* content. The default behavior is to print the tip.
*
* @return a brief description of the command
* @see Command#help(ConsoleOutput, String...) */
protected String brief() { protected String brief() {
return " " + tip(); //$NON-NLS-1$ return " " + tip(); //$NON-NLS-1$
} }
@ -89,9 +97,21 @@ public abstract class Command implements ICommand {
return name; return name;
} }
/* (non-Javadoc) /** Prints a help content for this command to the console output.
* @see fr.bigeon.gclc.command.ICommand#help(fr.bigeon.gclc.ConsoleManager, * <p>
* java.lang.String) */ * This help is following the given format:
*
* <pre>
* [Command name]
* [brief message]
*
* Usage:
* [Usage pattern]
*
* [Usage details]
* </pre>
*
* @see fr.bigeon.gclc.command.ICommand#help(ConsoleOutput, String...) */
@Override @Override
public final void help(final ConsoleOutput manager, public final void help(final ConsoleOutput manager,
final String... args) throws IOException { final String... args) throws IOException {
@ -111,18 +131,16 @@ public abstract class Command implements ICommand {
} }
} }
/** /** This method return the detail of the help.
* <p> * <p>
* This method return the detail of the help. It immediatly follows the * It immediatly follows the {@link #usagePattern() usage pattern}.
* {@link #usagePattern() usage pattern}.
* *
* @return the detailed help (should end with end of line or be empty) */ * @return the detailed help (should end with end of line or be empty) */
protected abstract String usageDetail(); protected abstract String usageDetail();
/** /** This prints the usage pattern for the command.
* <p> * <p>
* This prints the usage pattern for the command. It follows the brief * It follows the brief introduction on the command ({@link #brief()})
* introduction on the command ({@link #brief()})
* *
* @return the usage pattern */ * @return the usage pattern */
protected String usagePattern() { protected String usagePattern() {

View File

@ -44,29 +44,27 @@ import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.i18n.Messages; import fr.bigeon.gclc.i18n.Messages;
import fr.bigeon.gclc.manager.ConsoleInput; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput; import fr.bigeon.gclc.manager.ConsoleOutput;
import fr.bigeon.gclc.manager.EmptyInput;
import fr.bigeon.gclc.manager.SinkOutput;
/** /** A command provider is a map of key word to command to execute.
* <p>
* A command provider is a map of key word to command to execute
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public class CommandProvider implements ICommandProvider { public class CommandProvider implements ICommandProvider {
/** The minus character */ /** The minus character. */
private static final String MINUS = "-"; //$NON-NLS-1$ private static final String MINUS = "-"; //$NON-NLS-1$
/** The space character */ /** The space character. */
private static final String SPACE = " "; //$NON-NLS-1$ private static final String SPACE = " "; //$NON-NLS-1$
/** The commands map */ /** The commands map. */
protected final List<ICommand> commands; protected final List<ICommand> commands;
/** Create a command provider */ /** Create a command provider. */
public CommandProvider() { public CommandProvider() {
super(); super();
commands = new ArrayList<>(); commands = new ArrayList<>();
} }
/** @param name the command name /** Test the command name validity.
*
* @param name the command name
* @throws InvalidCommandName if the name is invalid */ * @throws InvalidCommandName if the name is invalid */
private static void testCommandName(final String name) throws InvalidCommandName { private static void testCommandName(final String name) throws InvalidCommandName {
if (name == null || name.isEmpty() || name.startsWith(MINUS) || if (name == null || name.isEmpty() || name.startsWith(MINUS) ||
@ -94,6 +92,11 @@ public class CommandProvider implements ICommandProvider {
return commands.add(value); return commands.add(value);
} }
/* (non-Javadoc)
* @see
* fr.bigeon.gclc.command.ICommandProvider#executeSub(fr.bigeon.gclc.manager
* .ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, java.lang.String,
* java.lang.String[]) */
@Override @Override
public final void executeSub(final ConsoleOutput out, final ConsoleInput in, public final void executeSub(final ConsoleOutput out, final ConsoleInput in,
final String cmd, final String cmd,
@ -108,20 +111,6 @@ public class CommandProvider implements ICommandProvider {
Messages.getString("CommandProvider.unrecognized", cmd), null); //$NON-NLS-1$ Messages.getString("CommandProvider.unrecognized", cmd), null); //$NON-NLS-1$
} }
@Deprecated
@Override
public final void executeSub(final String cmd,
final String... args) throws CommandRunException {
for (final ICommand command : commands) {
if (command.getCommandName().equals(cmd)) {
command.execute(SinkOutput.INSTANCE, EmptyInput.INSTANCE, args);
return;
}
}
throw new CommandRunException(
Messages.getString("CommandProvider.unrecognized", cmd), null); //$NON-NLS-1$
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommandProvider#get(java.lang.String) */ * @see fr.bigeon.gclc.command.ICommandProvider#get(java.lang.String) */
@Override @Override

View File

@ -45,29 +45,32 @@ import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput; import fr.bigeon.gclc.manager.ConsoleOutput;
import fr.bigeon.gclc.prompt.CLIPrompterMessages; import fr.bigeon.gclc.prompt.CLIPrompterMessages;
/** <p> /** A command to exit a {@link ConsoleApplication}.
* A command to exit a {@link ConsoleApplication}.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public final class ExitCommand implements ICommand { public class ExitCommand implements ICommand {
/** The exit command manual message key */ /** The exit command manual message key. */
private static final String EXIT_MAN = "exit.man"; //$NON-NLS-1$ private static final String EXIT_MAN = "exit.man"; //$NON-NLS-1$
/** The tip of the exit command */ /** The tip of the exit command. */
private static final String EXIT = "exit.tip"; //$NON-NLS-1$ private static final String EXIT = "exit.tip"; //$NON-NLS-1$
/** The application that will be exited when this command runs */ /** The application that will be exited when this command runs. */
private final ConsoleApplication app; private final ConsoleApplication app;
/** The exit command name */ /** The exit command name. */
private final String name; private final String name;
/** @param name the name of the command /** Create the exiting command.
*
* @param name the name of the command
* @param app the application to exit */ * @param app the application to exit */
public ExitCommand(final String name, final ConsoleApplication app) { public ExitCommand(final String name, final ConsoleApplication app) {
this.name = name; this.name = name;
this.app = app; this.app = app;
} }
/** The actions to take before exiting */ /** The actions to take before exiting.
public void beforeExit() { * <p>
* This method is intended to be overriden by sub classes. */
protected void beforeExit() {
// Do nothing by default // Do nothing by default
} }

View File

@ -53,10 +53,12 @@ import fr.bigeon.gclc.prompt.CLIPrompterMessages;
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public final class HelpExecutor extends Command { public final class HelpExecutor extends Command {
/** The command to execute the help of */ /** The command to execute the help of. */
private final ICommand cmd; private final ICommand cmd;
/** @param cmdName the command name /** Create the help command.
*
* @param cmdName the command name
* @param cmd the command to execute the help of */ * @param cmd the command to execute the help of */
public HelpExecutor(final String cmdName, public HelpExecutor(final String cmdName,
final ICommand cmd) { final ICommand cmd) {
@ -75,8 +77,8 @@ public final class HelpExecutor extends Command {
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, java.lang.String[]) * @see fr.bigeon.gclc.command.ICommand#execute(ConsoleOutput, ConsoleInput,
*/ * String[]) */
@Override @Override
public void execute(final ConsoleOutput out, final ConsoleInput in, public void execute(final ConsoleOutput out, final ConsoleInput in,
final String... args) throws CommandRunException { final String... args) throws CommandRunException {

View File

@ -44,7 +44,7 @@ import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.manager.ConsoleInput; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput; import fr.bigeon.gclc.manager.ConsoleOutput;
/** The contract of commands /** The contract of commands.
* <p> * <p>
* This interface describe the contract of commands * This interface describe the contract of commands
* *
@ -64,25 +64,15 @@ public interface ICommand {
String getCommandName(); String getCommandName();
/** This prints the help associated to this command. /** This prints the help associated to this command.
* <p>
* The default behavior is to print:
*
* <pre>
* [Command name]
* [brief message]
*
* Usage:
* [Usage pattern]
*
* [Usage details]
* </pre>
* *
* @param output the output to print the data * @param output the output to print the data
* @param args the arguments called with the help * @param args the arguments called with the help
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
void help(ConsoleOutput output, String... args) throws IOException; void help(ConsoleOutput output, String... args) throws IOException;
/** @return a tip on the command */ /** Get a tip (brief helping message) for the command.
*
* @return a tip on the command */
String tip(); String tip();
} }

View File

@ -41,60 +41,41 @@ import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.ConsoleInput; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput; import fr.bigeon.gclc.manager.ConsoleOutput;
/** <p> /** An ICommadProvider is a provider of commands that can register commands
* An ICommadProvider is a provider of commands that can register commands under * under some keywords.
* some keywords.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public interface ICommandProvider { public interface ICommandProvider {
/** <p> /** Adds a command to this provider, if no command was associated with the
* Adds a command to this provider, if no command was associated with the * given key.
* given key
* *
* @param value the command to execute * @param value the command to execute
* @return if the command was added * @return if the command was added
* @throws InvalidCommandName if the command name is invalid */ * @throws InvalidCommandName if the command name is invalid */
boolean add(ICommand value) throws InvalidCommandName; boolean add(ICommand value) throws InvalidCommandName;
/** /** Execute the command with the given name.
* <p> * <p>
* This method executes the command with the given name found. If no command * If no command with this name is found, an error command is usually
* with this name is found, an error command is usually executed. If there * executed. If there are several commands with the same name, the behavior
* are several commands with the same name, the behavior is unspecified. * is unspecified. Depending on the implementation, it may run an error
* Depending on the implementation, it may run an error command or prompt * command or prompt the user for a choice.
* the user for a choice.
* *
* @param out the output * @param out the output
* @param in the input * @param in the input
* @param command the name of the command the user wishes to execute * @param command the name of the command the user wishes to execute
* @param args the arguments for the command * @param args the arguments for the command
* @throws CommandRunException if the command failed to run */ * @throws CommandRunException if the command failed to run */
void executeSub(ConsoleOutput out, ConsoleInput in, void executeSub(ConsoleOutput out, ConsoleInput in, String command,
String command,
String... args) throws CommandRunException; String... args) throws CommandRunException;
/** <p> /** Get the command with the given name.
* This method executes the command with the given name found. If no command
* with this name is found, an error command is usually executed. If there
* are several commands with the same name, the behavior is unspecified.
* Depending on the implementation, it may run an error command or prompt
* the user for a choice.
*
* @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 */
@Deprecated
void executeSub(String command,
String... args) throws CommandRunException;
/**
* <p> * <p>
* This method provide the command with the given name found. If no command * If no command with this name is found, an error command is usually
* with this name is found, an error command is usually returned. If there * returned. If there are several commands with the same name, the behavior
* are several commands with the same name, the behavior is unspecified. * is unspecified. Depending on the implementation, it may return an error
* Depending on the implementation, it may return an error command or the * command or the first command with this name found.
* first command with this name found.
* *
* @param command the name of the command the user wishes to execute * @param command the name of the command the user wishes to execute
* @return the command to execute */ * @return the command to execute */

View File

@ -38,7 +38,6 @@
*/ */
package fr.bigeon.gclc.command; package fr.bigeon.gclc.command;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.manager.ConsoleInput; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput; import fr.bigeon.gclc.manager.ConsoleOutput;
@ -49,20 +48,22 @@ import fr.bigeon.gclc.manager.ConsoleOutput;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class MockCommand implements ICommand { public final class MockCommand implements ICommand {
/** The command name */ /** The command name. */
private final String name; private final String name;
/** @param name the command name */ /** Create the command.
*
* @param name the command name */
public MockCommand(final String name) { public MockCommand(final String name) {
this.name = name; this.name = name;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, java.lang.String[]) * @see fr.bigeon.gclc.command.ICommand#execute(ConsoleOutput, ConsoleInput,
*/ * String[]) */
@Override @Override
public void execute(final ConsoleOutput out, final ConsoleInput in, public void execute(final ConsoleOutput out, final ConsoleInput in,
final String... args) throws CommandRunException { final String... args) {
// //
} }

View File

@ -55,7 +55,7 @@ import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.manager.ConsoleInput; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput; import fr.bigeon.gclc.manager.ConsoleOutput;
/** A command that will laucnh a series of command from a file /** A command that will launch a series of command from a file.
* <p> * <p>
* This command will read a file and execute each non empty non commented line * This command will read a file and execute each non empty non commented line
* as a command of the application. * as a command of the application.
@ -63,18 +63,20 @@ import fr.bigeon.gclc.manager.ConsoleOutput;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class ScriptExecution extends Command { public final class ScriptExecution extends Command {
/** The tab character */ /** The tab character. */
private static final String TAB = "\t"; //$NON-NLS-1$ private static final String TAB = "\t"; //$NON-NLS-1$
/** the space character */ /** the space character. */
private static final String SPACE = " "; //$NON-NLS-1$ private static final String SPACE = " "; //$NON-NLS-1$
/** The application */ /** The application. */
private final ConsoleApplication application; private final ConsoleApplication application;
/** The commenting prefix */ /** The commenting prefix. */
private final String commentPrefix; private final String commentPrefix;
/** The charset for files */ /** The charset for files. */
private final Charset charset; private final Charset charset;
/** @param name the name of the command /** Create the script command.
*
* @param name the name of the command
* @param application the application * @param application the application
* @param commentPrefix the comment prefix in the script files * @param commentPrefix the comment prefix in the script files
* @param charset the charset to use for files */ * @param charset the charset to use for files */
@ -86,7 +88,9 @@ public final class ScriptExecution extends Command {
this.charset = charset; this.charset = charset;
} }
/** @param args the arguments /** Check the arguments.
*
* @param args the arguments
* @throws CommandRunException if the arguments were not the ones * @throws CommandRunException if the arguments were not the ones
* expected */ * expected */
private void checkArgs(final String[] args) throws CommandRunException { private void checkArgs(final String[] args) throws CommandRunException {
@ -153,7 +157,9 @@ public final class ScriptExecution extends Command {
e, this); e, this);
} }
/** @param cmd the line /** Read a line of the script.
*
* @param cmd the line
* @param params the formatting parameters * @param params the formatting parameters
* @return the command if it is indeed one, null otherwise * @return the command if it is indeed one, null otherwise
* @throws CommandRunException if the line stqrted with a space character */ * @throws CommandRunException if the line stqrted with a space character */
@ -161,10 +167,11 @@ public final class ScriptExecution extends Command {
final Object[] params) throws CommandRunException { final Object[] params) throws CommandRunException {
if (cmd.startsWith(SPACE) || cmd.startsWith(TAB)) { if (cmd.startsWith(SPACE) || cmd.startsWith(TAB)) {
throw new CommandRunException( throw new CommandRunException(
"Invalid command in script (line starts with space character)", //$NON-NLS-1$ "Invalid line in script (line starts with space character)", //$NON-NLS-1$
this); this);
} }
if (cmd.isEmpty() || cmd.startsWith(commentPrefix)) { if (cmd.isEmpty() || cmd.startsWith(commentPrefix)) {
// Comment line
return null; return null;
} }
return MessageFormat.format(cmd, params); return MessageFormat.format(cmd, params);

View File

@ -52,7 +52,7 @@ import fr.bigeon.gclc.manager.ConsoleOutput;
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public final class SubedCommand extends CommandProvider implements ICommand { public final class SubedCommand extends CommandProvider implements ICommand {
/** The tab character */ /** The tab character. */
private static final String TAB = "\t"; //$NON-NLS-1$ private static final String TAB = "\t"; //$NON-NLS-1$
/** The command to execute when this command is called with no sub /** The command to execute when this command is called with no sub
* arguments. * arguments.
@ -64,7 +64,9 @@ public final class SubedCommand extends CommandProvider implements ICommand {
/** The name of the command */ /** The name of the command */
private final String name; private final String name;
/** @param name the name of the command */ /** Create the command that defines sub commands.
*
* @param name the name of the command */
public SubedCommand(final String name) { public SubedCommand(final String name) {
super(); super();
this.name = name; this.name = name;
@ -72,7 +74,9 @@ public final class SubedCommand extends CommandProvider implements ICommand {
tip = null; tip = null;
} }
/** @param name the name of the command /** Create the command that defines sub commands.
*
* @param name the name of the command
* @param noArgCommand the command to execute when no extra parameter are * @param noArgCommand the command to execute when no extra parameter are
* provided */ * provided */
public SubedCommand(final String name, final ICommand noArgCommand) { public SubedCommand(final String name, final ICommand noArgCommand) {
@ -82,7 +86,9 @@ public final class SubedCommand extends CommandProvider implements ICommand {
tip = null; tip = null;
} }
/** @param name the name of the command /** Create the command that defines sub commands.
*
* @param name the name of the command
* @param noArgCommand the command to execute * @param noArgCommand the command to execute
* @param tip the help tip associated */ * @param tip the help tip associated */
public SubedCommand(final String name, final ICommand noArgCommand, public SubedCommand(final String name, final ICommand noArgCommand,
@ -93,7 +99,9 @@ public final class SubedCommand extends CommandProvider implements ICommand {
this.tip = tip; this.tip = tip;
} }
/** @param name the name of the command /** Create the command that defines sub commands.
*
* @param name the name of the command
* @param tip the help tip associated */ * @param tip the help tip associated */
public SubedCommand(final String name, final String tip) { public SubedCommand(final String name, final String tip) {
super(); super();

View File

@ -38,27 +38,33 @@
*/ */
package fr.bigeon.gclc.exception; package fr.bigeon.gclc.exception;
/** An exception raised during command parsing /** An exception raised during command parsing.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class CommandParsingException extends Exception { public class CommandParsingException extends Exception {
/** svuid */ /** svuid. */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** @param message an explaination /** Create the exception with a message.
* @param cause the cause */ *
public CommandParsingException(String message, Throwable cause) { * @param message the message */
super(message, cause); public CommandParsingException(final String message) {
}
/** @param message an explaination */
public CommandParsingException(String message) {
super(message); super(message);
} }
/** @param cause the cause */ /** Create the exception with a message and a cause.
public CommandParsingException(Throwable cause) { *
* @param message the message
* @param cause the cause */
public CommandParsingException(final String message, final Throwable cause) {
super(message, cause);
}
/** Create the exception with a message.
*
* @param cause the cause */
public CommandParsingException(final Throwable cause) {
super(cause); super(cause);
} }

View File

@ -40,44 +40,49 @@ package fr.bigeon.gclc.exception;
import fr.bigeon.gclc.command.ICommand; import fr.bigeon.gclc.command.ICommand;
/** <p> /** An exception thrown when a command failed to run correctly.
* An exception thrown when a command failed to run correctly.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public final class CommandRunException extends Exception { public final class CommandRunException extends Exception {
/** /** the SVUID. */
*
*/
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** The type of run exception */ /** The type of run exception. */
private final CommandRunExceptionType type; private final CommandRunExceptionType type;
/** The command that caused the error */ /** The command that caused the error. */
private final transient ICommand source; private final ICommand source;
/** @param type the type of exception /** Create the exception.
*
* @param type the type of exception
* @param message the message * @param message the message
* @param source the source */ * @param source the source */
public CommandRunException(final CommandRunExceptionType type, final String message, public CommandRunException(final CommandRunExceptionType type,
final ICommand source) { final String message, final ICommand source) {
super(message); super(message);
this.type = type; this.type = type;
this.source = source; this.source = source;
} }
/** @param type the type of exception /** Create the exception with a cause.
*
* @param type the type of exception
* @param message a message * @param message a message
* @param cause the cause * @param cause the cause
* @param source the source */ * @param source the source */
public CommandRunException(final CommandRunExceptionType type, final String message, public CommandRunException(final CommandRunExceptionType type,
final Throwable cause, final ICommand source) { final String message, final Throwable cause,
final ICommand source) {
super(message, cause); super(message, cause);
this.type = type; this.type = type;
this.source = source; this.source = source;
} }
/** @param message a message /** Create the exception with type
* {@link CommandRunExceptionType#EXECUTION}.
*
* @param message a message
* @param source the source */ * @param source the source */
public CommandRunException(final String message, final ICommand source) { public CommandRunException(final String message, final ICommand source) {
super(message); super(message);
@ -85,7 +90,10 @@ public final class CommandRunException extends Exception {
this.source = source; this.source = source;
} }
/** @param message a message /** Create the exception with type {@link CommandRunExceptionType#EXECUTION}
* and a cause.
*
* @param message a message
* @param cause the cause * @param cause the cause
* @param source the source */ * @param source the source */
public CommandRunException(final String message, final Throwable cause, public CommandRunException(final String message, final Throwable cause,
@ -106,12 +114,16 @@ public final class CommandRunException extends Exception {
return super.getLocalizedMessage(); return super.getLocalizedMessage();
} }
/** @return the source */ /** Get the exception raising command.
*
* @return the source */
public ICommand getSource() { public ICommand getSource() {
return source; return source;
} }
/** @return the type */ /** Get the exception type.
*
* @return the type */
public CommandRunExceptionType getType() { public CommandRunExceptionType getType() {
return type; return type;
} }

View File

@ -38,14 +38,14 @@
*/ */
package fr.bigeon.gclc.exception; package fr.bigeon.gclc.exception;
/** The command run exception possible types /** The command run exception possible types.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public enum CommandRunExceptionType { public enum CommandRunExceptionType {
/** Type of exception due to a wrong usage */ /** Type of exception due to a wrong usage. */
USAGE, USAGE,
/** Type of exception due to a problem in execution */ /** Type of exception due to a problem in execution. */
EXECUTION, EXECUTION,
/** Type of exception due to the impossibility to interact with user */ /** Type of exception due to the impossibility to interact with user. */
INTERACTION; INTERACTION;
} }

View File

@ -38,36 +38,39 @@
*/ */
package fr.bigeon.gclc.exception; package fr.bigeon.gclc.exception;
/** <p> /** Exception sent from the application when a command is added but the name of
* Exception sent from the application when a command is added but the name of * the command is already used.
* the command is already used
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public class InvalidCommandName extends Exception { public class InvalidCommandName extends Exception {
/** /** the SVUID. */
*
*/
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** Default constructor */ /** Default constructor. */
public InvalidCommandName() { public InvalidCommandName() {
super(); super();
} }
/** @param message the message /** Create the exception with a message.
* @param cause the cause */ *
public InvalidCommandName(String message, Throwable cause) { * @param message the message */
super(message, cause); public InvalidCommandName(final String message) {
}
/** @param message the message */
public InvalidCommandName(String message) {
super(message); super(message);
} }
/** @param cause the cause */ /** Create the exception with a message and a cause.
public InvalidCommandName(Throwable cause) { *
* @param message the message
* @param cause the cause */
public InvalidCommandName(final String message, final Throwable cause) {
super(message, cause);
}
/** Create the exception with a cause.
*
* @param cause the cause */
public InvalidCommandName(final Throwable cause) {
super(cause); super(cause);
} }

View File

@ -47,24 +47,28 @@ package fr.bigeon.gclc.exception;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class InvalidParameterException extends Exception { public class InvalidParameterException extends Exception {
/** /** the SVUID. */
*
*/
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** @param message the message /** Create the exception with a message.
* @param cause the cause */ *
public InvalidParameterException(String message, Throwable cause) { * @param message the message */
super(message, cause); public InvalidParameterException(final String message) {
}
/** @param message the message */
public InvalidParameterException(String message) {
super(message); super(message);
} }
/** @param cause the cause */ /** Create the exception with a message and a cause.
public InvalidParameterException(Throwable cause) { *
* @param message the message
* @param cause the cause */
public InvalidParameterException(final String message, final Throwable cause) {
super(message, cause);
}
/** Create the exception with a cause.
*
* @param cause the cause */
public InvalidParameterException(final Throwable cause) {
super(cause); super(cause);
} }

View File

@ -0,0 +1,8 @@
/**
* gclc:fr.bigeon.gclc.exception.package-info.java
* Created on: Nov 13, 2017
*/
/** Exceptions package.
*
* @author Emmanuel Bigeon */
package fr.bigeon.gclc.exception;

View File

@ -48,23 +48,23 @@ import java.util.logging.Logger;
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class Messages { public final class Messages {
/** The resource bundle name */ /** The resource bundle name. */
private static final String BUNDLE_NAME = "fr.bigeon.gclc.l10n.messages"; //$NON-NLS-1$ private static final String BUNDLE_NAME = "fr.bigeon.gclc.l10n.messages"; //$NON-NLS-1$
/** The resource bundle */ /** The resource bundle. */
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
.getBundle(BUNDLE_NAME); .getBundle(BUNDLE_NAME);
/** The class logger */ /** The class logger. */
private static final Logger LOGGER = Logger private static final Logger LOGGER = Logger
.getLogger(Messages.class.getName()); .getLogger(Messages.class.getName());
/** Utility class */ /** Utility class. */
private Messages() { private Messages() {
// Utility class // Utility class
} }
/** Get formatted internationalized messages /** Get formatted internationalized messages.
* *
* @param key the message key * @param key the message key
* @param args the formatting arguments * @param args the formatting arguments

View File

@ -0,0 +1,8 @@
/**
* gclc:fr.bigeon.gclc.i18n.package-info.java
* Created on: Nov 13, 2017
*/
/** Internationalization package.
*
* @author Emmanuel Bigeon */
package fr.bigeon.gclc.i18n;

View File

@ -46,7 +46,7 @@ import java.io.InterruptedIOException;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public interface ConsoleInput extends AutoCloseable { public interface ConsoleInput extends AutoCloseable {
/** Closes the manager. /** Closes the input.
* *
* @throws IOException if the close raised an exception */ * @throws IOException if the close raised an exception */
@Override @Override
@ -57,7 +57,7 @@ public interface ConsoleInput extends AutoCloseable {
* @return the prompt prefix */ * @return the prompt prefix */
String getPrompt(); String getPrompt();
/** Indicate to the manager that is should interrompt the prompting, if /** Indicate to the input that is should interrompt the prompting, if
* possible. * possible.
* <p> * <p>
* The pending {@link #prompt()} or {@link #prompt(String)} operations * The pending {@link #prompt()} or {@link #prompt(String)} operations

View File

@ -40,38 +40,37 @@ package fr.bigeon.gclc.manager;
import java.io.IOException; import java.io.IOException;
/** /** A console output definition.
* <p>
* TODO
* *
* @author Emmanuel Bigeon * @author Emmanuel Bigeon */
*
*/
public interface ConsoleOutput extends AutoCloseable { public interface ConsoleOutput extends AutoCloseable {
/* (non-Javadoc)
* @see java.lang.AutoCloseable#close() */ /** Test if the output is closed.
@Override *
void close() throws IOException; * @return if the manager is closed. */
boolean isClosed();
/** Print a string. /** Print a string.
*
* @param text the message to print (without line break at the end). * @param text the message to print (without line break at the end).
* @throws IOException if the manager is closed or could not read the * @throws IOException if the manager is closed or could not read the
* prompt */ * prompt */
void print(String text) throws IOException; void print(String text) throws IOException;
/** Prints an end of line /** Prints an end of line.
* *
* @throws IOException if the manager is closed or could not read the * @throws IOException if the manager is closed or could not read the
* prompt */ * prompt */
void println() throws IOException; void println() throws IOException;
/** @param message the message to print /** Print a string followed by an end of line.
* <p>
* This is the same as calling successively {@link #print(String)} and
* {@link #println()}.
*
* @param message the message to print
* @throws IOException if the manager is closed or could not read the * @throws IOException if the manager is closed or could not read the
* prompt */ * prompt */
void println(String message) throws IOException; void println(String message) throws IOException;
/** @return if the manager is closed. */
boolean isClosed();
} }

View File

@ -38,8 +38,6 @@
*/ */
package fr.bigeon.gclc.manager; package fr.bigeon.gclc.manager;
import java.io.IOException;
/** A console input that return empty to all prompting. /** A console input that return empty to all prompting.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
@ -54,7 +52,7 @@ public final class EmptyInput implements ConsoleInput {
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#close() */ * @see fr.bigeon.gclc.manager.ConsoleInput#close() */
@Override @Override
public void close() throws IOException { public void close() {
// //
} }
@ -82,21 +80,21 @@ public final class EmptyInput implements ConsoleInput {
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#prompt() */ * @see fr.bigeon.gclc.manager.ConsoleInput#prompt() */
@Override @Override
public String prompt() throws IOException { public String prompt() {
return ""; //$NON-NLS-1$ return ""; //$NON-NLS-1$
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#prompt(long) */ * @see fr.bigeon.gclc.manager.ConsoleInput#prompt(long) */
@Override @Override
public String prompt(final long timeout) throws IOException { public String prompt(final long timeout) {
return ""; //$NON-NLS-1$ return ""; //$NON-NLS-1$
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String) */ * @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String) */
@Override @Override
public String prompt(final String message) throws IOException { public String prompt(final String message) {
return ""; //$NON-NLS-1$ return ""; //$NON-NLS-1$
} }
@ -105,7 +103,7 @@ public final class EmptyInput implements ConsoleInput {
* long) */ * long) */
@Override @Override
public String prompt(final String message, public String prompt(final String message,
final long timeout) throws IOException { final long timeout) {
return ""; //$NON-NLS-1$ return ""; //$NON-NLS-1$
} }

View File

@ -46,33 +46,33 @@ import java.io.PipedOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
/** This console manager allows to enter commands and retrieve the output as an /** This console input allows to enter commands and retrieve the output as an
* input. * input.
* <p> * <p>
* This console manager is used to internally pilot an application. This can be * This console input is used to internally pilot an application. This can be
* used to test application behavior. * used to test application behavior.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class PipedConsoleInput public final class PipedConsoleInput
implements ConsoleInput { implements ConsoleInput {
/** The encoding between streams */ /** The encoding between streams. */
private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$ private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
/** THe inner manager */ /** THe inner manager. */
private final SystemConsoleInput innerManager; private final StreamConsoleInput innerManager;
/** The stream to pipe commands into */ /** The stream to pipe commands into. */
private final PipedOutputStream commandInput; private final PipedOutputStream commandInput;
/** The reader to get application return from */ /** The reader to get application return from. */
private final BufferedReader commandBuffOutput; private final BufferedReader commandBuffOutput;
/** The stream to get application return from */ /** The stream to get application return from. */
private final PipedInputStream commandOutput; private final PipedInputStream commandOutput;
/** The print writer for application to write return to */ /** The print writer for application to write return to. */
private final PrintStream outPrint; private final PrintStream outPrint;
/** The stream for the application to read commands from */ /** The stream for the application to read commands from. */
private final PipedInputStream in; private final PipedInputStream in;
/** The writing thread */ /** The writing thread. */
private final WritingRunnable writing; private final WritingRunnable writing;
/** The reading thread */ /** The reading thread. */
private final ReadingRunnable reading; private final ReadingRunnable reading;
/** Create a manager that will write and read through piped stream. /** Create a manager that will write and read through piped stream.
@ -86,7 +86,7 @@ public final class PipedConsoleInput
commandBuffOutput = new BufferedReader( commandBuffOutput = new BufferedReader(
new InputStreamReader(commandOutput, StandardCharsets.UTF_8)); new InputStreamReader(commandOutput, StandardCharsets.UTF_8));
outPrint = new PrintStream(out, true, UTF_8); outPrint = new PrintStream(out, true, UTF_8);
innerManager = new SystemConsoleInput(outPrint, in, innerManager = new StreamConsoleInput(outPrint, in,
StandardCharsets.UTF_8); StandardCharsets.UTF_8);
writing = new WritingRunnable(commandInput, StandardCharsets.UTF_8); writing = new WritingRunnable(commandInput, StandardCharsets.UTF_8);
reading = new ReadingRunnable(commandBuffOutput); reading = new ReadingRunnable(commandBuffOutput);
@ -97,7 +97,12 @@ public final class PipedConsoleInput
th.start(); th.start();
} }
/** @return the content of the next line written by the application /** Test if a content is available on the reading head.
* <p>
* If this method returns true, the next {@link #prompt()} operation should
* return immediatly.
*
* @return the content of the next line written by the application
* @throws IOException if the reading failed */ * @throws IOException if the reading failed */
public boolean available() throws IOException { public boolean available() throws IOException {
return reading.hasMessage(); return reading.hasMessage();
@ -120,7 +125,12 @@ public final class PipedConsoleInput
return innerManager.getPrompt(); return innerManager.getPrompt();
} }
/** @param message the message /** Wait for a specific message to arrive.
* <p>
* When this method returns, the message was appended to the data, it
* <em>may or may not</em> be the next line of data.
*
* @param message the message
* @return the thread to join to wait for message delivery * @return the thread to join to wait for message delivery
* @see fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String) */ * @see fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String) */
public Thread getWaitForDelivery(final String message) { public Thread getWaitForDelivery(final String message) {
@ -134,11 +144,15 @@ public final class PipedConsoleInput
innerManager.interruptPrompt(); innerManager.interruptPrompt();
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#isClosed() */
@Override @Override
public boolean isClosed() { public boolean isClosed() {
return innerManager.isClosed(); return innerManager.isClosed();
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#prompt() */
@Override @Override
public String prompt() throws IOException { public String prompt() throws IOException {
return innerManager return innerManager
@ -152,28 +166,41 @@ public final class PipedConsoleInput
return innerManager.prompt(timeout); return innerManager.prompt(timeout);
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String) */
@Override @Override
public String prompt(final String message) throws IOException { public String prompt(final String message) throws IOException {
return innerManager.prompt(message + System.lineSeparator()); return innerManager.prompt(message + System.lineSeparator());
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String,
* long) */
@Override @Override
public String prompt(final String message, final long timeout) throws IOException { public String prompt(final String message, final long timeout) throws IOException {
return innerManager.prompt(message + System.lineSeparator(), timeout); return innerManager.prompt(message + System.lineSeparator(), timeout);
} }
/** @return the content of the next line written by the application /** Read the next line in the input printed content.
* <p>
* This corresponds to the {@link #prompt(String)} messages.
*
* @return the content of the next line written by the application
* @throws IOException if the reading failed */ * @throws IOException if the reading failed */
public String readNextLine() throws IOException { public String readNextLine() throws IOException {
return reading.getMessage(); return reading.getMessage();
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String) */
@Override @Override
public void setPrompt(final String prompt) { public void setPrompt(final String prompt) {
innerManager.setPrompt(prompt); innerManager.setPrompt(prompt);
} }
/** @param content the content to type to the application /** Type a message in the input.
*
* @param content the content to type to the application
* @throws IOException if the typing failed */ * @throws IOException if the typing failed */
public void type(final String content) throws IOException { public void type(final String content) throws IOException {
writing.addMessage(content); writing.addMessage(content);

View File

@ -46,27 +46,26 @@ import java.io.PipedOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
/** This console manager allows to enter commands and retrieve the output as an /** This console output allows to retrieve the output as an input.
* input.
* <p> * <p>
* This console manager is used to internally pilot an application. This can be * This console output is used to internally pilot an application. This can be
* used to test application behavior. * used to test application behavior.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class PipedConsoleOutput public final class PipedConsoleOutput
implements ConsoleOutput { implements ConsoleOutput {
/** The encoding between streams */ /** The encoding between streams. */
private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$ private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
/** THe inner manager */ /** THe inner manager. */
private final SystemConsoleOutput innerManager; private final StreamConsoleOutput innerManager;
/** The reader to get application return from */ /** The reader to get application return from. */
private final BufferedReader commandBuffOutput; private final BufferedReader commandBuffOutput;
/** The stream to get application return from */ /** The stream to get application return from. */
private final PipedInputStream commandOutput; private final PipedInputStream commandOutput;
/** The print writer for application to write return to */ /** The print writer for application to write return to. */
private final PrintStream outPrint; private final PrintStream outPrint;
/** The reading thread */ /** The reading thread. */
private final ReadingRunnable reading; private final ReadingRunnable reading;
/** Create a manager that will write and read through piped stream. /** Create a manager that will write and read through piped stream.
@ -78,19 +77,23 @@ public final class PipedConsoleOutput
commandBuffOutput = new BufferedReader( commandBuffOutput = new BufferedReader(
new InputStreamReader(commandOutput, StandardCharsets.UTF_8)); new InputStreamReader(commandOutput, StandardCharsets.UTF_8));
outPrint = new PrintStream(out, true, UTF_8); outPrint = new PrintStream(out, true, UTF_8);
innerManager = new SystemConsoleOutput(outPrint); innerManager = new StreamConsoleOutput(outPrint);
reading = new ReadingRunnable(commandBuffOutput); reading = new ReadingRunnable(commandBuffOutput);
final Thread th = new Thread(reading, "read"); //$NON-NLS-1$ final Thread th = new Thread(reading, "read"); //$NON-NLS-1$
th.setDaemon(true); th.setDaemon(true);
th.start(); th.start();
} }
/** @return the content of the next line written by the application /** Test if there is available data.
*
* @return the content of the next line written by the application
* @throws IOException if the reading failed */ * @throws IOException if the reading failed */
public boolean available() throws IOException { public boolean available() throws IOException {
return reading.hasMessage(); return reading.hasMessage();
} }
/* (non-Javadoc)
* @see java.lang.AutoCloseable#close() */
@Override @Override
public void close() throws IOException { public void close() throws IOException {
reading.setRunning(false); reading.setRunning(false);
@ -100,34 +103,49 @@ public final class PipedConsoleOutput
commandOutput.close(); commandOutput.close();
} }
/** @param message the message /** Wait for a specific message to arrive.
* <p>
* When this method returns, the message was appended to the data, it
* <em>may or may not</em> be the next line of data.
*
* @param message the message
* @return the thread to join to wait for message delivery * @return the thread to join to wait for message delivery
* @see fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String) */ * @see fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String) */
public Thread getWaitForDelivery(final String message) { public Thread getWaitForDelivery(final String message) {
return reading.getWaitForDelivery(message); return reading.getWaitForDelivery(message);
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleOutput#isClosed() */
@Override @Override
public boolean isClosed() { public boolean isClosed() {
return innerManager.isClosed(); return innerManager.isClosed();
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleOutput#print(java.lang.String) */
@Override @Override
public void print(final String object) throws IOException { public void print(final String object) throws IOException {
innerManager.print(object); innerManager.print(object);
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleOutput#println() */
@Override @Override
public void println() throws IOException { public void println() throws IOException {
innerManager.println(); innerManager.println();
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleOutput#println(java.lang.String) */
@Override @Override
public void println(final String object) throws IOException { public void println(final String object) throws IOException {
innerManager.println(object); innerManager.println(object);
} }
/** @return the content of the next line written by the application /** Read the next line of data.
*
* @return the content of the next line written by the application
* @throws IOException if the reading failed */ * @throws IOException if the reading failed */
public String readNextLine() throws IOException { public String readNextLine() throws IOException {
return reading.getMessage(); return reading.getMessage();

View File

@ -53,20 +53,22 @@ import java.util.logging.Logger;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class ReadingRunnable implements Runnable { public final class ReadingRunnable implements Runnable {
/** The runnable to wait for notification on an object /** The runnable to wait for arrival of a message in the queue.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
private final class ToWaitRunnable implements Runnable { private final class ToWaitRunnable implements Runnable {
/** The Object */ /** The Object. */
private final Object obj; private final Object obj;
/** The locking object */ /** The locking object. */
private final Object start; private final Object start;
/** The message */ /** The message. */
private final String message; private final String message;
/** The started status */ /** The started status. */
private boolean started = false; private boolean started = false;
/** @param obj the object to lock on /** Create the waiting runnable.
*
* @param obj the object to lock on
* @param start the object to notify when ready to wait * @param start the object to notify when ready to wait
* @param message the message to wait for */ * @param message the message to wait for */
public ToWaitRunnable(final Object obj, final Object start, public ToWaitRunnable(final Object obj, final Object start,
@ -76,13 +78,17 @@ public final class ReadingRunnable implements Runnable {
this.message = message; this.message = message;
} }
/** @return the started */ /** Test if the waiting runnable is started.
*
* @return the started */
public boolean isStarted() { public boolean isStarted() {
synchronized (start) { synchronized (start) {
return started; return started;
} }
} }
/* (non-Javadoc)
* @see java.lang.Runnable#run() */
@SuppressWarnings("synthetic-access") @SuppressWarnings("synthetic-access")
@Override @Override
public void run() { public void run() {
@ -107,34 +113,36 @@ public final class ReadingRunnable implements Runnable {
} }
} }
/** The thread intteruption logging message */ /** The thread intteruption logging message. */
private static final String THREAD_INTERRUPTION_EXCEPTION = "Thread interruption exception."; //$NON-NLS-1$ private static final String THREAD_INTERRUPTION_EXCEPTION = "Thread interruption exception."; //$NON-NLS-1$
/** The closed pipe message */ /** The closed pipe message. */
private static final String CLOSED_PIPE = "Closed pipe"; //$NON-NLS-1$ private static final String CLOSED_PIPE = "Closed pipe"; //$NON-NLS-1$
/** Wait timeout */ /** Wait timeout. */
private static final long TIMEOUT = 1000; private static final long TIMEOUT = 1000;
/** Class logger */ /** Class logger. */
private static final Logger LOGGER = Logger private static final Logger LOGGER = Logger
.getLogger(ReadingRunnable.class.getName()); .getLogger(ReadingRunnable.class.getName());
/** Read messages */ /** Read messages. */
private final Deque<String> messages = new ArrayDeque<>(); private final Deque<String> messages = new ArrayDeque<>();
/** the reader */ /** the reader. */
private final BufferedReader reader; private final BufferedReader reader;
/** the state of this runnable */ /** the state of this runnable. */
private boolean running = true; private boolean running = true;
/** Synchro object */ /** Synchro object. */
private final Object lock = new Object(); private final Object lock = new Object();
/** The waiting status for a message */ /** The waiting status for a message. */
private boolean waiting; private boolean waiting;
/** The blocker for a given message */ /** The blocker for a given message. */
private final Map<String, Object> messageBlocker = new HashMap<>(); private final Map<String, Object> messageBlocker = new HashMap<>();
/** The lock */ /** The lock */
private final Object messageBlockerLock = new Object(); private final Object messageBlockerLock = new Object();
/** The message being delivered */ /** The message being delivered. */
private String delivering; private String delivering;
/** @param reader the input to read from */ /** Create a reading runnable.
*
* @param reader the input to read from */
public ReadingRunnable(final BufferedReader reader) { public ReadingRunnable(final BufferedReader reader) {
super(); super();
this.reader = reader; this.reader = reader;
@ -154,7 +162,9 @@ public final class ReadingRunnable implements Runnable {
return res; return res;
} }
/** @return the next read message /** Get the next message.
*
* @return the next read message
* @throws IOException if the pipe is closed */ * @throws IOException if the pipe is closed */
public String getMessage() throws IOException { public String getMessage() throws IOException {
synchronized (lock) { synchronized (lock) {
@ -180,7 +190,9 @@ public final class ReadingRunnable implements Runnable {
} }
} }
/** @param timeout the read time out /** Get the next message, but wait only a given time for it.
*
* @param timeout the read time out
* @return The next message that was in the input * @return The next message that was in the input
* @throws IOException if the input was closed */ * @throws IOException if the input was closed */
public String getNextMessage(final long timeout) throws IOException { public String getNextMessage(final long timeout) throws IOException {
@ -206,7 +218,9 @@ public final class ReadingRunnable implements Runnable {
} }
} }
/** @param message the message /** Get a waiting thread for a specific message delivery.
*
* @param message the message
* @return the thread to join to wait for message delivery */ * @return the thread to join to wait for message delivery */
public Thread getWaitForDelivery(final String message) { public Thread getWaitForDelivery(final String message) {
synchronized (messageBlockerLock) { synchronized (messageBlockerLock) {
@ -235,7 +249,9 @@ public final class ReadingRunnable implements Runnable {
} }
} }
/** @return if a message is waiting /** Test if some data is available.
*
* @return if a message is waiting
* @throws IOException if the pipe is closed */ * @throws IOException if the pipe is closed */
public boolean hasMessage() throws IOException { public boolean hasMessage() throws IOException {
synchronized (lock) { synchronized (lock) {
@ -246,7 +262,8 @@ public final class ReadingRunnable implements Runnable {
} }
} }
/** Interrupts the wait on the next message by providing an empty message */ /** Interrupts the wait on the next message by providing an empty
* message. */
public void interrupt() { public void interrupt() {
synchronized (lock) { synchronized (lock) {
if (waiting) { if (waiting) {
@ -256,14 +273,18 @@ public final class ReadingRunnable implements Runnable {
} }
} }
/** @return the running */ /** Test if this element is still running.
*
* @return the running */
public boolean isRunning() { public boolean isRunning() {
synchronized (lock) { synchronized (lock) {
return running; return running;
} }
} }
/** @param message the message */ /** Notify the arrival of a given message.
*
* @param message the message */
private void notifyMessage(final String message) { private void notifyMessage(final String message) {
synchronized (messageBlockerLock) { synchronized (messageBlockerLock) {
delivering = message; delivering = message;
@ -313,7 +334,9 @@ public final class ReadingRunnable implements Runnable {
} }
} }
/** @param running the running to set */ /** Set the running status for this reading runnable.
*
* @param running the running to set */
public void setRunning(final boolean running) { public void setRunning(final boolean running) {
synchronized (lock) { synchronized (lock) {
this.running = running; this.running = running;

View File

@ -43,7 +43,7 @@ import java.io.IOException;
/** A console output that absorbs every message. /** A console output that absorbs every message.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class SinkOutput implements ConsoleOutput { public final class SinkOutput implements ConsoleOutput {
/** The sink output. */ /** The sink output. */
public static final ConsoleOutput INSTANCE = new SinkOutput(); public static final ConsoleOutput INSTANCE = new SinkOutput();

View File

@ -50,38 +50,40 @@ import java.nio.charset.Charset;
* The default constructor will use the system standart input and output. * The default constructor will use the system standart input and output.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public final class SystemConsoleInput implements ConsoleInput { public final class StreamConsoleInput implements ConsoleInput {
/** The default prompt */ /** The default prompt. */
public static final String DEFAULT_PROMPT = "> "; //$NON-NLS-1$ public static final String DEFAULT_PROMPT = "> "; //$NON-NLS-1$
/** The command prompt. It can be changed. */ /** The command prompt. It can be changed. */
private String prompt = DEFAULT_PROMPT; private String prompt = DEFAULT_PROMPT;
/** The print stream */ /** The print stream. */
private final PrintStream out; private final PrintStream out;
/** The input stream */ /** The input stream. */
private final BufferedReader in; private final BufferedReader in;
/** If the manager is closed */ /** If the manager is closed. */
private boolean closed = false; private boolean closed = false;
/** The prompting thread */ /** The prompting thread. */
private final Thread promptThread; private final Thread promptThread;
/** The reading runnable */ /** The reading runnable. */
private final ReadingRunnable reading; private final ReadingRunnable reading;
/** This default constructor relies on the system defined standart output /** This default constructor relies on the system defined standart output
* and input stream. */ * and input stream. */
public SystemConsoleInput() { public StreamConsoleInput() {
this(System.out, System.in, Charset.defaultCharset()); this(System.out, System.in, Charset.defaultCharset());
} }
/** @param out the output stream /** Create the stream base console input.
*
* @param out the output stream
* @param in the input stream * @param in the input stream
* @param charset the charset for the input */ * @param charset the charset for the input */
public SystemConsoleInput(final PrintStream out, final InputStream in, public StreamConsoleInput(final PrintStream out, final InputStream in,
final Charset charset) { final Charset charset) {
super(); super();
this.out = out; this.out = out;
@ -92,7 +94,9 @@ public final class SystemConsoleInput implements ConsoleInput {
promptThread.start(); promptThread.start();
} }
/** @throws IOException if the stream was closed */ /** Check that the console input is not closed.
*
* @throws IOException if the stream was closed */
private void checkOpen() throws IOException { private void checkOpen() throws IOException {
if (closed) { if (closed) {
throw new IOException(); throw new IOException();
@ -109,7 +113,8 @@ public final class SystemConsoleInput implements ConsoleInput {
in.close(); in.close();
} }
/** @return the prompt */ /* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#getPrompt() */
@Override @Override
public String getPrompt() { public String getPrompt() {
return prompt; return prompt;
@ -156,13 +161,15 @@ public final class SystemConsoleInput implements ConsoleInput {
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */ * @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */
@Override @Override
public String prompt(final String message, final long timeout) throws IOException { public String prompt(final String message,
final long timeout) throws IOException {
checkOpen(); checkOpen();
out.print(message); out.print(message);
return reading.getNextMessage(timeout); return reading.getNextMessage(timeout);
} }
/** @param prompt the prompt to set */ /* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String) */
@Override @Override
public void setPrompt(final String prompt) { public void setPrompt(final String prompt) {
this.prompt = prompt; this.prompt = prompt;

View File

@ -46,30 +46,29 @@ import java.io.PrintStream;
* The default constructor will use the system standart input and output. * The default constructor will use the system standart input and output.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public final class SystemConsoleOutput implements ConsoleOutput { public final class StreamConsoleOutput implements ConsoleOutput {
/** The print stream. */
/** The default prompt */
public static final String DEFAULT_PROMPT = "> "; //$NON-NLS-1$
/** The print stream */
private final PrintStream out; private final PrintStream out;
/** If the manager is closed. */
/** If the manager is closed */
private boolean closed = false; private boolean closed = false;
/** This default constructor relies on the system defined standart output /** This default constructor relies on the system defined standart output
* and input stream. */ * and input stream. */
public SystemConsoleOutput() { public StreamConsoleOutput() {
this(System.out); this(System.out);
} }
/** @param out the output stream */ /** Create a print stream based console output.
public SystemConsoleOutput(final PrintStream out) { *
* @param out the output stream */
public StreamConsoleOutput(final PrintStream out) {
super(); super();
this.out = out; this.out = out;
} }
/** @throws IOException if the stream was closed */ /** Check the open status.
*
* @throws IOException if the stream was closed */
private void checkOpen() throws IOException { private void checkOpen() throws IOException {
if (closed) { if (closed) {
throw new IOException(); throw new IOException();
@ -79,7 +78,7 @@ public final class SystemConsoleOutput implements ConsoleOutput {
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#close() */ * @see fr.bigeon.gclc.manager.ConsoleManager#close() */
@Override @Override
public void close() throws IOException { public void close() {
closed = true; closed = true;
} }

View File

@ -54,24 +54,26 @@ import java.util.logging.Logger;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class WritingRunnable implements Runnable { public final class WritingRunnable implements Runnable {
/** Wait timeout */ /** Wait timeout. */
private static final long TIMEOUT = 1000; private static final long TIMEOUT = 1000;
/** Class logger */ /** Class logger. */
private static final Logger LOGGER = Logger private static final Logger LOGGER = Logger
.getLogger(WritingRunnable.class.getName()); .getLogger(WritingRunnable.class.getName());
/** Messages to write */ /** Messages to write. */
private final Deque<String> messages = new ArrayDeque<>(); private final Deque<String> messages = new ArrayDeque<>();
/** Stream to write to */ /** Stream to write to. */
private final OutputStream outPrint; private final OutputStream outPrint;
/** The charset */ /** The charset. */
private final Charset charset; private final Charset charset;
/** Runnable state */ /** Runnable state. */
private boolean running = true; private boolean running = true;
/** Synchro object */ /** Synchro object. */
private final Object lock = new Object(); private final Object lock = new Object();
/** @param outPrint the output to print to /** Create the writing runnable.
*
* @param outPrint the output to print to
* @param charset the charset of the stream */ * @param charset the charset of the stream */
public WritingRunnable(final OutputStream outPrint, final Charset charset) { public WritingRunnable(final OutputStream outPrint, final Charset charset) {
super(); super();
@ -79,9 +81,11 @@ public final class WritingRunnable implements Runnable {
this.charset = charset; this.charset = charset;
} }
/** @param message the message /** Add a message in the queue.
*
* @param message the message
* @throws IOException if the pipe is closed */ * @throws IOException if the pipe is closed */
public void addMessage(final String message) throws IOException { public synchronized void addMessage(final String message) throws IOException {
synchronized (lock) { synchronized (lock) {
if (!running) { if (!running) {
throw new IOException("Closed pipe"); //$NON-NLS-1$ throw new IOException("Closed pipe"); //$NON-NLS-1$
@ -91,7 +95,9 @@ public final class WritingRunnable implements Runnable {
} }
} }
/** @return the running */ /** Test if the message is running.
*
* @return the running */
public boolean isRunning() { public boolean isRunning() {
synchronized (lock) { synchronized (lock) {
return running; return running;
@ -102,21 +108,43 @@ public final class WritingRunnable implements Runnable {
* @see java.lang.Runnable#run() */ * @see java.lang.Runnable#run() */
@Override @Override
public void run() { public void run() {
while (running) { while (running) {
synchronized (lock) { synchronized (lock) {
while (messages.isEmpty()) { while (messages.isEmpty()) {
try { waitNextMessage();
lock.wait(TIMEOUT);
} catch (final InterruptedException e) {
LOGGER.log(Level.SEVERE,
"Thread interruption exception.", e); //$NON-NLS-1$
Thread.currentThread().interrupt();
}
if (!running) { if (!running) {
return; return;
} }
} }
writeMessage();
}
}
}
/** Set the running status.
*
* @param running the running to set */
public synchronized void setRunning(final boolean running) {
synchronized (lock) {
this.running = running;
}
}
/** Wait for next message. */
private void waitNextMessage() {
try {
lock.wait(TIMEOUT);
} catch (final InterruptedException e) {
if (running) {
LOGGER.log(Level.SEVERE,
"Thread interruption exception.", e); //$NON-NLS-1$
}
Thread.currentThread().interrupt();
}
}
/** Write next message to output. */
private void writeMessage() {
final String message = messages.poll(); final String message = messages.poll();
final ByteBuffer buff = charset final ByteBuffer buff = charset
.encode(message + System.lineSeparator()); .encode(message + System.lineSeparator());
@ -130,12 +158,3 @@ public final class WritingRunnable implements Runnable {
} }
} }
} }
}
/** @param running the running to set */
public void setRunning(final boolean running) {
synchronized (lock) {
this.running = running;
}
}
}

View File

@ -0,0 +1,8 @@
/**
* gclc:fr.bigeon.gclc.manager.package-info.java
* Created on: Nov 13, 2017
*/
/** The console input and output definitions.
*
* @author Emmanuel Bigeon */
package fr.bigeon.gclc.manager;

View File

@ -46,44 +46,42 @@ import java.util.logging.Logger;
import fr.bigeon.gclc.manager.ConsoleInput; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput; import fr.bigeon.gclc.manager.ConsoleOutput;
/** /** The {@link CLIPrompter} class is a utility class that provides method to
* <p>
* The {@link CLIPrompter} class is a utility class that provides method to
* prompt the user. * prompt the user.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public final class CLIPrompter { public final class CLIPrompter {
/** /** The zero integer. */
*
*/
private static final Integer ZERO = Integer.valueOf(0); private static final Integer ZERO = Integer.valueOf(0);
/** message key for format error in prompting a choice */ /** message key for format error in prompting a choice. */
private static final String PROMPTCHOICE_FORMATERR = "promptchoice.formaterr"; //$NON-NLS-1$ private static final String PROMPTCHOICE_FORMATERR = "promptchoice.formaterr"; //$NON-NLS-1$
/** message key for out of bound error in prompting a choice */ /** message key for out of bound error in prompting a choice. */
private static final String PROMPTCHOICE_OUTOFBOUNDS = "promptchoice.outofbounds"; //$NON-NLS-1$ private static final String PROMPTCHOICE_OUTOFBOUNDS = "promptchoice.outofbounds"; //$NON-NLS-1$
/** message key for first form of no in prompting a choice */ /** message key for first form of no in prompting a choice. */
private static final String PROMPTBOOL_CHOICES_NO1 = "promptbool.choices.no1"; //$NON-NLS-1$ private static final String PROMPTBOOL_CHOICES_NO1 = "promptbool.choices.no1"; //$NON-NLS-1$
/** message key for first form of yes in prompting a choice */ /** message key for first form of yes in prompting a choice. */
private static final String PROMPTBOOL_CHOICES_YES1 = "promptbool.choices.yes1"; //$NON-NLS-1$ private static final String PROMPTBOOL_CHOICES_YES1 = "promptbool.choices.yes1"; //$NON-NLS-1$
@SuppressWarnings("javadoc") /** Message key for boolean choosing. */
private static final String BOOL_CHOICES = "promptbool.choices"; //$NON-NLS-1$ private static final String BOOL_CHOICES = "promptbool.choices"; //$NON-NLS-1$
@SuppressWarnings("javadoc") /** Message key for the list end of prompt symbol. */
private static final String LIST_DISP_KEY = "promptlist.exit.dispkey"; //$NON-NLS-1$ private static final String LIST_DISP_KEY = "promptlist.exit.dispkey"; //$NON-NLS-1$
@SuppressWarnings("javadoc") /** Message key for the line prompt. */
private static final String PROMPT = "prompt.lineprompt"; //$NON-NLS-1$ private static final String PROMPT = "prompt.lineprompt"; //$NON-NLS-1$
@SuppressWarnings("javadoc") /** Message key for the separation of choices selection. */
private static final String LIST_CHOICE_SEP = "promptlist.multi.sepkey"; //$NON-NLS-1$ private static final String LIST_CHOICE_SEP = "promptlist.multi.sepkey"; //$NON-NLS-1$
/** The class logger */ /** The class logger. */
private static final Logger LOGGER = Logger private static final Logger LOGGER = Logger
.getLogger(CLIPrompter.class.getName()); .getLogger(CLIPrompter.class.getName());
/** Utility class */ /** Utility class. */
private CLIPrompter() { private CLIPrompter() {
// Utility class // Utility class
} }
/** @param val the string to parse /** Add a user choice to the list.
*
* @param val the string to parse
* @param chs the list of integers * @param chs the list of integers
* @param index the max index of choice * @param index the max index of choice
* @return if the parsing was done correctly */ * @return if the parsing was done correctly */
@ -102,7 +100,9 @@ public final class CLIPrompter {
return false; return false;
} }
/** @param output the manager /** List the choices on the output.
*
* @param output the manager
* @param choices the choices * @param choices the choices
* @param cancel the cancel option if it exists * @param cancel the cancel option if it exists
* @return the number of choices plus one (or the number of choices if there * @return the number of choices plus one (or the number of choices if there
@ -121,7 +121,9 @@ public final class CLIPrompter {
return Integer.valueOf(index - 1); return Integer.valueOf(index - 1);
} }
/** @param manager the manager /** Prompt for a boolean value.
*
* @param manager the manager
* @param input the input * @param input the input
* @param message the prompting message * @param message the prompting message
* @return the choice * @return the choice
@ -159,7 +161,9 @@ public final class CLIPrompter {
.getString("promptbool.choices.yes2")); //$NON-NLS-1$ .getString("promptbool.choices.yes2")); //$NON-NLS-1$
} }
/** @param manager the manager /** Prompt for a choice.
*
* @param manager the manager
* @param input the input * @param input the input
* @param keys the keys to be printed * @param keys the keys to be printed
* @param choices the real choices * @param choices the real choices
@ -168,21 +172,23 @@ public final class CLIPrompter {
* @param <U> the type of elements * @param <U> the type of elements
* @return the choice * @return the choice
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
@SuppressWarnings("boxing")
public static <U> U promptChoice(final ConsoleOutput manager, public static <U> U promptChoice(final ConsoleOutput manager,
final ConsoleInput input, final ConsoleInput input,
final List<String> keys, final List<String> keys,
final List<U> choices, final List<U> choices,
final String message, final String message,
final String cancel) throws IOException { final String cancel) throws IOException {
final Integer index = promptChoice(manager, input, keys, message, cancel); final Integer index = promptChoice(manager, input, keys, message,
cancel);
if (index == null) { if (index == null) {
return null; return null;
} }
return choices.get(index); return choices.get(index.intValue());
} }
/** @param manager the manager /** Prompt for a choice.
*
* @param manager the manager
* @param input the input * @param input the input
* @param <U> The choices labels type * @param <U> The choices labels type
* @param <T> The real choices objects * @param <T> The real choices objects
@ -206,7 +212,9 @@ public final class CLIPrompter {
return choicesMap.get(choices.get(res.intValue())); return choicesMap.get(choices.get(res.intValue()));
} }
/** @param manager the manager /** Prompt for a choice.
*
* @param manager the manager
* @param input the input * @param input the input
* @param <U> the type of choices * @param <U> the type of choices
* @param choices the list of choices * @param choices the list of choices
@ -222,14 +230,12 @@ public final class CLIPrompter {
manager.println(message); manager.println(message);
final Integer index = listChoices(manager, choices, cancel); final Integer index = listChoices(manager, choices, cancel);
String result; String result;
boolean keepOn = true;
int r = -1; int r = -1;
while (keepOn) { while (true) {
result = input.prompt(CLIPrompterMessages.getString(PROMPT)); result = input.prompt(CLIPrompterMessages.getString(PROMPT));
try { try {
r = Integer.parseInt(result); r = Integer.parseInt(result);
if (r >= 0 && r <= index.intValue()) { if (r >= 0 && r <= index.intValue()) {
keepOn = false;
break; break;
} }
manager.println(CLIPrompterMessages manager.println(CLIPrompterMessages
@ -237,7 +243,6 @@ public final class CLIPrompter {
} catch (final NumberFormatException e) { } catch (final NumberFormatException e) {
LOGGER.log(Level.FINER, LOGGER.log(Level.FINER,
"Unrecognized number. Prompting user again.", e); //$NON-NLS-1$ "Unrecognized number. Prompting user again.", e); //$NON-NLS-1$
keepOn = true;
manager.println(CLIPrompterMessages manager.println(CLIPrompterMessages
.getString(PROMPTCHOICE_FORMATERR, ZERO, index)); .getString(PROMPTCHOICE_FORMATERR, ZERO, index));
} }
@ -249,7 +254,9 @@ public final class CLIPrompter {
return Integer.valueOf(r); return Integer.valueOf(r);
} }
/** @param manager the manager /** Prompt for a choice.
*
* @param manager the manager
* @param input the input * @param input the input
* @param <U> The choices labels type * @param <U> The choices labels type
* @param <T> The real choices objects * @param <T> The real choices objects
@ -264,11 +271,13 @@ public final class CLIPrompter {
final String message, final String message,
final String cancel) throws IOException { final String cancel) throws IOException {
return promptChoice(manager, input, return promptChoice(manager, input,
new ArrayList<>(choicesMap.keySet()), new ArrayList<>(choicesMap.keySet()), choicesMap, message,
choicesMap, message, cancel); cancel);
} }
/** @param manager the manager /** Prompt for an integer.
*
* @param manager the manager
* @param message the prompt message * @param message the prompt message
* @return the integer * @return the integer
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
@ -294,7 +303,7 @@ public final class CLIPrompter {
return r; return r;
} }
/** This methods prompt the user for a list of elements /** This methods prompt the user for a list of elements.
* *
* @param manager the manager * @param manager the manager
* @param input the input * @param input the input
@ -308,7 +317,7 @@ public final class CLIPrompter {
CLIPrompterMessages.getString("promptlist.exit.defaultkey")); //$NON-NLS-1$ CLIPrompterMessages.getString("promptlist.exit.defaultkey")); //$NON-NLS-1$
} }
/** This methods prompt the user for a list of elements /** This methods prompt the user for a list of elements.
* *
* @param manager the manager * @param manager the manager
* @param input the input * @param input the input
@ -373,7 +382,9 @@ public final class CLIPrompter {
return res.toString(); return res.toString();
} }
/** @param manager the manager /** Prompt the user to select zero or more elements from a list.
*
* @param manager the manager
* @param input the input * @param input the input
* @param keys the keys to be printed * @param keys the keys to be printed
* @param choices the real choices * @param choices the real choices
@ -386,7 +397,8 @@ public final class CLIPrompter {
final List<String> keys, final List<String> keys,
final List<U> choices, final List<U> choices,
final String message) throws IOException { final String message) throws IOException {
final List<Integer> indices = promptMultiChoice(manager, input, keys, message); final List<Integer> indices = promptMultiChoice(manager, input, keys,
message);
final List<U> userChoices = new ArrayList<>(); final List<U> userChoices = new ArrayList<>();
for (final Integer integer : indices) { for (final Integer integer : indices) {
userChoices.add(choices.get(integer.intValue())); userChoices.add(choices.get(integer.intValue()));
@ -394,7 +406,9 @@ public final class CLIPrompter {
return userChoices; return userChoices;
} }
/** @param manager the manager /** Prompt the user to select zero or more elements from a list.
*
* @param manager the manager
* @param input the input * @param input the input
* @param <U> The choices labels type * @param <U> The choices labels type
* @param <T> The real choices objects * @param <T> The real choices objects
@ -417,7 +431,9 @@ public final class CLIPrompter {
return userChoices; return userChoices;
} }
/** @param manager the manager /** Prompt the user to select zero or more elements from a list.
*
* @param manager the manager
* @param input the input * @param input the input
* @param <U> the type of choices * @param <U> the type of choices
* @param choices the list of choices * @param choices the list of choices
@ -462,7 +478,9 @@ public final class CLIPrompter {
return chs; return chs;
} }
/** @param manager the manager /** Prompt the user to select zero or more elements from a list.
*
* @param manager the manager
* @param input the input * @param input the input
* @param <U> The choices labels type * @param <U> The choices labels type
* @param <T> The real choices objects * @param <T> The real choices objects
@ -475,11 +493,12 @@ public final class CLIPrompter {
final Map<U, T> choicesMap, final Map<U, T> choicesMap,
final String message) throws IOException { final String message) throws IOException {
return promptMultiChoice(manager, input, return promptMultiChoice(manager, input,
new ArrayList<>(choicesMap.keySet()), new ArrayList<>(choicesMap.keySet()), choicesMap, message);
choicesMap, message);
} }
/** @param manager the manager /** Prompt the user for a non empty text.
*
* @param manager the manager
* @param prompt the prompting message * @param prompt the prompting message
* @param reprompt the prompting message after empty input * @param reprompt the prompting message after empty input
* @return the non empty input * @return the non empty input

View File

@ -44,28 +44,25 @@ import java.util.ResourceBundle;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
/** <p> /** Utility class for the messages of the CLIPrompter.
* Utility class for the messages of the CLIPrompter
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public final class CLIPrompterMessages { public final class CLIPrompterMessages {
/** The resource name */ /** The resource name. */
private static final String BUNDLE_NAME = "fr.bigeon.gclc.messages"; //$NON-NLS-1$ private static final String BUNDLE_NAME = "fr.bigeon.gclc.messages"; //$NON-NLS-1$
/** The resource. */
/** The resource */
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
.getBundle(BUNDLE_NAME); .getBundle(BUNDLE_NAME);
/** The logger. */
/** The logger */
private static final Logger LOGGER = Logger private static final Logger LOGGER = Logger
.getLogger(CLIPrompterMessages.class.getName()); .getLogger(CLIPrompterMessages.class.getName());
/** Utility class */ /** Utility class. */
private CLIPrompterMessages() { private CLIPrompterMessages() {
// Utility constructor // Utility constructor
} }
/** Return the formatted message corresponding to the given key /** Return the formatted message corresponding to the given key.
* *
* @param key the message's key * @param key the message's key
* @param args the arguments * @param args the arguments

View File

@ -51,14 +51,14 @@ import fr.bigeon.gclc.manager.PipedConsoleOutput;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public abstract class AOutputForwardRunnable implements Runnable { public abstract class AOutputForwardRunnable implements Runnable {
/** The class logger */ /** The class logger. */
private static final Logger LOGGER = Logger private static final Logger LOGGER = Logger
.getLogger(AOutputForwardRunnable.class.getName()); .getLogger(AOutputForwardRunnable.class.getName());
/** The default timeout (one tenth of second). */ /** The default timeout (one tenth of second). */
private static final long DEFAULT_TIMEOUT = 100; private static final long DEFAULT_TIMEOUT = 100;
/** The manager. */ /** The manager. */
private final PipedConsoleOutput manager; private final PipedConsoleOutput manager;
/** The timeout */ /** The timeout. */
private final long timeout; private final long timeout;
/** Create a forwarding runnable. /** Create a forwarding runnable.
@ -90,12 +90,18 @@ public abstract class AOutputForwardRunnable implements Runnable {
this.timeout = timeout; this.timeout = timeout;
} }
/** @param m the line to forward */ /** Do forward the line.
*
* @param m the line to forward */
protected abstract void forwardLine(String m); protected abstract void forwardLine(String m);
/** @return if the thread should keep running */ /** Test if the runable is still running.
*
* @return if the thread should keep running */
protected abstract boolean isRunning(); protected abstract boolean isRunning();
/* (non-Javadoc)
* @see java.lang.Runnable#run() */
@Override @Override
public final void run() { public final void run() {
try { try {

View File

@ -46,19 +46,22 @@ import java.util.List;
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public final class PrintUtils { public final class PrintUtils {
/** The continuation dot string */ /** The continuation dot string. */
private static final String CONT_DOT = "..."; //$NON-NLS-1$ private static final String CONT_DOT = "..."; //$NON-NLS-1$
/** The continuation dot string length */ /** The continuation dot string length. */
private static final int CONT_DOT_LENGTH = CONT_DOT.length(); private static final int CONT_DOT_LENGTH = CONT_DOT.length();
/** The empty string constant */ /** The empty string constant. */
private static final String EMPTY = ""; //$NON-NLS-1$ private static final String EMPTY = ""; //$NON-NLS-1$
/** Utility class */ /** Utility class. */
private PrintUtils() { private PrintUtils() {
// Utility class // Utility class
} }
/** @param text the text to print /** Print the text possibly cutting it if it goes over the authorized length
* and adding a mark of continuation.
*
* @param text the text to print
* @param nbCharacters the number of characters of the resulting text * @param nbCharacters the number of characters of the resulting text
* @param indicateTooLong if an indication shell be given that the text * @param indicateTooLong if an indication shell be given that the text
* didn't fit * didn't fit
@ -83,7 +86,9 @@ public final class PrintUtils {
return res.toString(); return res.toString();
} }
/** @param description the element to wrap in lines /** Wrap the text, cutting at spaces.
*
* @param description the element to wrap in lines
* @param i the length of the wrap * @param i the length of the wrap
* @return the list of resulting strings */ * @return the list of resulting strings */
public static List<String> wrap(final String description, final int i) { public static List<String> wrap(final String description, final int i) {

View File

@ -0,0 +1,8 @@
/**
* gclc:fr.bigeon.gclc.tools.package-info.java
* Created on: Nov 13, 2017
*/
/** Tool classes.
*
* @author Emmanuel Bigeon */
package fr.bigeon.gclc.tools;

View File

@ -41,7 +41,6 @@ package fr.bigeon.gclc;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -74,8 +73,8 @@ public class ConsoleApplicationTest {
public void testConsoleApplication() { public void testConsoleApplication() {
try (PipedConsoleInput manager = new PipedConsoleInput()) { try (PipedConsoleInput manager = new PipedConsoleInput()) {
final ConsoleApplication app = new ConsoleApplication(null, final ConsoleApplication app = new ConsoleApplication(null, manager,
manager, "", ""); "", "");
app.exit(); app.exit();
} catch (final IOException e) { } catch (final IOException e) {
fail("System Console Manager failed"); fail("System Console Manager failed");
@ -84,26 +83,32 @@ public class ConsoleApplicationTest {
} }
@Test @Test
public void testExecution() { public void testExecution() throws IOException, InterruptedException,
InvalidCommandName {
try (CommandTestingApplication application = new CommandTestingApplication()) { try (CommandTestingApplication application = new CommandTestingApplication()) {
// remove welcome // remove welcome
assertEquals(application.getApplication().header, assertEquals("Header should be preserved",
application.getApplication().header,
application.readNextLine()); application.readNextLine());
// Remove first prompt // Remove first prompt
application.sendCommand(""); application.sendCommand("");
application.sendCommand("test"); application.sendCommand("test");
assertEquals("Test command ran fine", application.readNextLine()); assertEquals("Test should run", "Test command ran fine",
application.readNextLine());
application.sendCommand("toto"); application.sendCommand("toto");
assertEquals( assertEquals("Command fail should dispaly appropriate message",
Messages.getString("ConsoleApplication.cmd.failed", "toto"), Messages.getString("ConsoleApplication.cmd.failed", "toto"),
application.readNextLine()); application.readNextLine());
assertEquals( assertEquals(
"Unrecognized comment should result in a specific message.",
Messages.getString("CommandProvider.unrecognized", "toto"), Messages.getString("CommandProvider.unrecognized", "toto"),
application.readNextLine()); application.readNextLine());
application.sendCommand("long"); application.sendCommand("long");
assertEquals("Waita minute", application.readNextLine()); assertEquals("Before wait should receive message", "Waita minute",
assertEquals("done!", application.readNextLine()); application.readNextLine());
assertEquals("Unexpected message", "done!",
application.readNextLine());
final CommandRequestListener crl = new CommandRequestListener() { final CommandRequestListener crl = new CommandRequestListener() {
@ -122,27 +127,28 @@ public class ConsoleApplicationTest {
application.getApplication().addListener(crl); application.getApplication().addListener(crl);
application.getApplication().addListener(crl2); application.getApplication().addListener(crl2);
application.sendCommand("test"); application.sendCommand("test");
assertEquals("Test command ran fine", application.readNextLine()); assertEquals("Unexpected message", "Test command ran fine",
application.readNextLine());
application.getApplication().removeListener(crl2); application.getApplication().removeListener(crl2);
application.getApplication().removeListener(crl); application.getApplication().removeListener(crl);
application.getApplication().removeListener(crl); application.getApplication().removeListener(crl);
assertTrue(application.getApplication().isRunning()); assertTrue("Unclosed application should be running",
application.getApplication().isRunning());
application.sendCommand("exit"); application.sendCommand("exit");
assertEquals(application.getApplication().footer, assertEquals("Footer should be preserved",
application.getApplication().footer,
application.readNextLine()); application.readNextLine());
assertFalse(application.getApplication().isRunning()); assertFalse("Stopped application should not be running",
} catch (final IOException e1) { application.getApplication().isRunning());
assertNull(e1);
} }
ConsoleApplication appli = null; ConsoleApplication appli = null;
try (PipedConsoleOutput manager = new PipedConsoleOutput(); try (PipedConsoleOutput manager = new PipedConsoleOutput();
PipedConsoleInput in = new PipedConsoleInput()) { PipedConsoleInput in = new PipedConsoleInput()) {
final ConsoleApplication app = new ConsoleApplication(manager, final ConsoleApplication app = new ConsoleApplication(manager, in,
in, null, null, null);
null);
appli = app; appli = app;
app.add(new ExitCommand("exit", app)); app.add(new ExitCommand("exit", app));
@ -154,52 +160,46 @@ public class ConsoleApplicationTest {
app.start(); app.start();
} }
}); });
th.start(); th.start();
in.type("exit"); in.type("exit");
th.join(); th.join();
} catch (IOException | InvalidCommandName |
InterruptedException e) {
assertNull(e);
} }
assertNotNull(appli); assertNotNull(
"Application should still exist even if the console input and output are closed.",
appli);
appli.start(); appli.start();
assertFalse(appli.isRunning()); assertFalse(
"Application should not start on closed console input and output",
appli.isRunning());
} }
@Test @Test
public void testInterpretCommand() { public void testInterpretCommand() throws InvalidCommandName, IOException {
try (PipedConsoleInput test = new PipedConsoleInput(); try (PipedConsoleInput test = new PipedConsoleInput();
PipedConsoleOutput out = new PipedConsoleOutput()) { PipedConsoleOutput out = new PipedConsoleOutput()) {
final ConsoleApplication appl = new ConsoleApplication(out, test, final ConsoleApplication appl = new ConsoleApplication(out, test,
"", ""); "", "");
appl.interpretCommand("invalid cmd \"due to misplaced\"quote"); appl.interpretCommand("invalid cmd \"due to misplaced\"quote");
assertEquals("Command line cannot be parsed", out.readNextLine()); assertEquals("Specific error message expected",
"Command line cannot be parsed", out.readNextLine());
appl.interpretCommand(""); appl.interpretCommand("");
final String message = "message"; final String message = "message";
try {
appl.add(new ICommand() { appl.add(new ICommand() {
/* (non-Javadoc) /* (non-Javadoc)
* @see * @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc.
* fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc. * manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput,
* manager.ConsoleOutput,
* fr.bigeon.gclc.manager.ConsoleInput,
* java.lang.String[]) */ * java.lang.String[]) */
@Override @Override
public void execute(final ConsoleOutput out, public void execute(final ConsoleOutput out,
final ConsoleInput in, final ConsoleInput in,
final String... args) throws CommandRunException { final String... args) throws CommandRunException {
throw new CommandRunException( throw new CommandRunException(CommandRunExceptionType.USAGE,
CommandRunExceptionType.USAGE, message, this); message, this);
} }
@Override @Override
@ -219,18 +219,13 @@ public class ConsoleApplicationTest {
} }
}); });
} catch (final InvalidCommandName e) {
assertNull(e);
}
appl.interpretCommand("fail"); appl.interpretCommand("fail");
assertEquals( assertEquals("Unexpected message",
Messages.getString("ConsoleApplication.cmd.failed", "fail"), Messages.getString("ConsoleApplication.cmd.failed", "fail"),
out.readNextLine()); out.readNextLine());
assertEquals(message, out.readNextLine()); assertEquals("Unexpected message", message, out.readNextLine());
assertEquals(message, out.readNextLine()); assertEquals("Unexpected message", message, out.readNextLine());
} catch (final IOException e) {
assertNull(e);
} }
} }
} }

View File

@ -38,6 +38,7 @@
*/ */
package fr.bigeon.gclc; package fr.bigeon.gclc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -53,102 +54,74 @@ import fr.bigeon.gclc.exception.CommandParsingException;
@SuppressWarnings({"nls", "static-method"}) @SuppressWarnings({"nls", "static-method"})
public class GCLCConstantsTest { public class GCLCConstantsTest {
/** /** Test method for
* Test method for {@link fr.bigeon.gclc.GCLCConstants#splitCommand(java.lang.String)}. * {@link fr.bigeon.gclc.GCLCConstants#splitCommand(java.lang.String)}.
*/ *
* @throws CommandParsingException if an error occured */
@Test @Test
public void testSplitCommand() { public void testSplitCommand() throws CommandParsingException {
List<String> res; List<String> res;
try {
res = GCLCConstants.splitCommand("aCommand"); res = GCLCConstants.splitCommand("aCommand");
} catch (final CommandParsingException e) { assertTrue("single word command should have one element",
fail("Unable to parse simple command " + e.getLocalizedMessage()); //$NON-NLS-1$ res.size() == 1);
return; assertTrue("Command should be preserved",
} res.get(0).equals("aCommand"));
assertTrue(res.size() == 1);
assertTrue(res.get(0).equals("aCommand"));
try {
res = GCLCConstants.splitCommand("aCommand with some arguments"); res = GCLCConstants.splitCommand("aCommand with some arguments");
} catch (final CommandParsingException e) { assertEquals("Command size", 4, res.size());
fail("Unable to parse command with arguments " + //$NON-NLS-1$ assertEquals("Elements should be preserved", "aCommand", res.get(0));
e.getLocalizedMessage()); assertTrue("Elements should be preserved", res.get(1).equals("with"));
return; assertTrue("Elements should be preserved", res.get(2).equals("some"));
} assertTrue("Elements should be preserved",
assertTrue(res.size() == 4); res.get(3).equals("arguments"));
assertTrue(res.get(0).equals("aCommand"));
assertTrue(res.get(1).equals("with"));
assertTrue(res.get(2).equals("some"));
assertTrue(res.get(3).equals("arguments"));
try {
res = GCLCConstants.splitCommand("aCommand with some arguments"); res = GCLCConstants.splitCommand("aCommand with some arguments");
} catch (final CommandParsingException e) { assertEquals("Command size", 4, res.size());
fail("Unable to parse command with arguments and double whitspaces " + //$NON-NLS-1$ assertTrue("Elements should be preserved",
e.getLocalizedMessage()); res.get(0).equals("aCommand"));
return; assertTrue("Elements should be preserved", res.get(1).equals("with"));
} assertTrue("Elements should be preserved", res.get(2).equals("some"));
assertTrue(res.size() == 4); assertTrue("Elements should be preserved",
assertTrue(res.get(0).equals("aCommand")); res.get(3).equals("arguments"));
assertTrue(res.get(1).equals("with")); res = GCLCConstants.splitCommand("aCommand \"with some\" arguments");
assertTrue(res.get(2).equals("some")); assertEquals("Command size", 3, res.size());
assertTrue(res.get(3).equals("arguments")); assertTrue("Elements should be preserved",
try { res.get(0).equals("aCommand"));
res = GCLCConstants assertTrue("Elements should be preserved",
.splitCommand("aCommand \"with some\" arguments"); res.get(1).equals("with some"));
} catch (final CommandParsingException e) { assertTrue("Elements should be preserved",
fail("Unable to parse command with string argument " + //$NON-NLS-1$ res.get(2).equals("arguments"));
e.getLocalizedMessage());
return;
}
assertTrue(res.size() == 3);
assertTrue(res.get(0).equals("aCommand"));
assertTrue(res.get(1).equals("with some"));
assertTrue(res.get(2).equals("arguments"));
try {
res = GCLCConstants.splitCommand("aCommand with\\ some arguments"); res = GCLCConstants.splitCommand("aCommand with\\ some arguments");
} catch (final CommandParsingException e) { assertEquals("Command size", 3, res.size());
fail("Unable to parse command with arguments with escaped whitspaces " + //$NON-NLS-1$ assertTrue("Elements should be preserved",
e.getLocalizedMessage()); res.get(0).equals("aCommand"));
return; assertTrue("Elements should be preserved",
} res.get(1).equals("with some"));
assertTrue(res.size() == 3); assertTrue("Elements should be preserved",
assertTrue(res.get(0).equals("aCommand")); res.get(2).equals("arguments"));
assertTrue(res.get(1).equals("with some")); res = GCLCConstants.splitCommand("aCommand wi\\\"th some arguments");
assertTrue(res.get(2).equals("arguments")); assertEquals("Command size", 4, res.size());
try { assertTrue("Elements should be preserved",
res = GCLCConstants res.get(0).equals("aCommand"));
.splitCommand("aCommand wi\\\"th some arguments"); assertTrue("Elements should be preserved", res.get(1).equals("wi\"th"));
} catch (final CommandParsingException e) { assertTrue("Elements should be preserved", res.get(2).equals("some"));
fail("Unable to parse command with string argument " + //$NON-NLS-1$ assertTrue("Elements should be preserved",
e.getLocalizedMessage()); res.get(3).equals("arguments"));
return;
} res = GCLCConstants.splitCommand("aCommand with \"some arguments\"");
assertTrue(res.size() == 4); assertEquals("Command size", 3, res.size());
assertTrue(res.get(0).equals("aCommand")); assertTrue("Elements should be preserved",
assertTrue(res.get(1).equals("wi\"th")); res.get(0).equals("aCommand"));
assertTrue(res.get(2).equals("some")); assertTrue("Elements should be preserved", res.get(1).equals("with"));
assertTrue(res.get(3).equals("arguments")); assertTrue("Elements should be preserved",
res.get(2).equals("some arguments"));
try { try {
res = GCLCConstants
.splitCommand("aCommand with \"some arguments\"");
} catch (final CommandParsingException e) {
fail("Unable to parse command ending with string argument " + //$NON-NLS-1$
e.getLocalizedMessage());
return;
}
assertTrue(res.size() == 3);
assertTrue(res.get(0).equals("aCommand"));
assertTrue(res.get(1).equals("with"));
assertTrue(res.get(2).equals("some arguments"));
// Wrong lines? // Wrong lines?
try {
res = GCLCConstants res = GCLCConstants
.splitCommand("aCommand with \"some ar\"guments"); .splitCommand("aCommand with \"some ar\"guments");
fail("Parsing argument with string cut"); fail("Misplaced quotes should fail");
} catch (final CommandParsingException e) { } catch (final CommandParsingException e) {
// OK // ok
} }
} }

View File

@ -40,7 +40,6 @@ package fr.bigeon.gclc.command;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -52,7 +51,8 @@ import org.junit.Test;
import fr.bigeon.gclc.exception.CommandParsingException; import fr.bigeon.gclc.exception.CommandParsingException;
/** <p> /**
* <p>
* TODO * TODO
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
@ -60,66 +60,63 @@ import fr.bigeon.gclc.exception.CommandParsingException;
public class CommandParametersTest { public class CommandParametersTest {
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.CommandParameters#CommandParameters(java.util.Set, java.util.Set, boolean)}. */ * {@link fr.bigeon.gclc.command.CommandParameters#CommandParameters(java.util.Set, java.util.Set, boolean)}.
*
* @throws CommandParsingException if an unexpected exception is thrown */
@Test @Test
public final void testCommandParameters() { public final void testCommandParameters() throws CommandParsingException {
Set<String> strings = new HashSet<>(); final Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); final Set<String> bools = new HashSet<>();
CommandParameters parameters = new CommandParameters(bools, strings, CommandParameters parameters = new CommandParameters(bools, strings,
true); true);
try { try {
parameters.parseArgs("-ungivenFlag"); parameters.parseArgs("-ungivenFlag");
fail("parse of unknown in strict should fail"); fail("parse of unknown in strict should fail");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
assertNotNull(e); // ok
} }
parameters = new CommandParameters(bools, strings, false); parameters = new CommandParameters(bools, strings, false);
try {
parameters.parseArgs("-ungivenFlag"); parameters.parseArgs("-ungivenFlag");
} catch (CommandParsingException e) {
fail("parse of unknown in non strict should suceed");
assertNull(e);
}
} }
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.CommandParameters#get(java.lang.String)}. */ * {@link fr.bigeon.gclc.command.CommandParameters#get(java.lang.String)}.
*
* @throws CommandParsingException if an exception occired */
@Test @Test
public final void testGet() { public final void testGet() throws CommandParsingException {
Set<String> strings = new HashSet<>(); final Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); final Set<String> bools = new HashSet<>();
bools.add("boolFlag"); bools.add("boolFlag");
strings.add("str"); strings.add("str");
CommandParameters parameters = new CommandParameters(bools, strings, final CommandParameters parameters = new CommandParameters(bools,
true); strings, true);
assertNull(parameters.get("ungiven")); assertNull(parameters.get("ungiven"));
assertNull(parameters.get("str")); assertNull(parameters.get("str"));
try { try {
parameters.parseArgs("-ungiven", "val"); parameters.parseArgs("-ungiven", "val");
} catch (CommandParsingException e) { fail("Missing parameter should fail for strict element");
assertNotNull(e); } catch (final CommandParsingException e) {
// ok
} }
assertNull(parameters.get("ungiven")); assertNull(parameters.get("ungiven"));
assertNull(parameters.get("str")); assertNull(parameters.get("str"));
try {
parameters.parseArgs("-str", "val"); parameters.parseArgs("-str", "val");
} catch (CommandParsingException e) {
assertNull(e);
}
assertNull(parameters.get("ungiven")); assertNull(parameters.get("ungiven"));
assertEquals("val", parameters.get("str")); assertEquals("val", parameters.get("str"));
try { try {
parameters.parseArgs("-ungiven"); parameters.parseArgs("-ungiven");
} catch (CommandParsingException e) { fail("Invalid argument type parsing should fail");
assertNotNull(e); } catch (final CommandParsingException e) {
// ok
} }
assertNull(parameters.get("ungiven")); assertNull(parameters.get("ungiven"));
assertEquals("val", parameters.get("str")); assertEquals("val", parameters.get("str"));
@ -128,9 +125,9 @@ public class CommandParametersTest {
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.CommandParameters#getAdditionals()}. */ * {@link fr.bigeon.gclc.command.CommandParameters#getAdditionals()}. */
@Test @Test
public final void testGetAdditionals() { public final void testGetAdditionals() throws CommandParsingException {
Set<String> strings = new HashSet<>(); final Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); final Set<String> bools = new HashSet<>();
bools.add("boolFlag"); bools.add("boolFlag");
strings.add("str"); strings.add("str");
@ -138,44 +135,35 @@ public class CommandParametersTest {
CommandParameters parameters = new CommandParameters(bools, strings, CommandParameters parameters = new CommandParameters(bools, strings,
true); true);
try {
parameters.parseArgs("-boolFlag"); parameters.parseArgs("-boolFlag");
} catch (CommandParsingException e) {
assertNull(e);
}
assertTrue(parameters.getAdditionals().isEmpty()); assertTrue(parameters.getAdditionals().isEmpty());
try { try {
parameters.parseArgs("-ungiven"); parameters.parseArgs("-ungiven");
} catch (CommandParsingException e) { fail("Should fail");
assertNotNull(e); } catch (final CommandParsingException e) {
// ok
} }
assertTrue(parameters.getAdditionals().isEmpty()); assertTrue(parameters.getAdditionals().isEmpty());
parameters = new CommandParameters(bools, strings, false); parameters = new CommandParameters(bools, strings, false);
try {
parameters.parseArgs("-boolFlag"); parameters.parseArgs("-boolFlag");
} catch (CommandParsingException e) {
assertNull(e);
}
assertTrue(parameters.getAdditionals().isEmpty()); assertTrue(parameters.getAdditionals().isEmpty());
try {
parameters.parseArgs("-ungiven"); parameters.parseArgs("-ungiven");
} catch (CommandParsingException e) {
assertNotNull(e);
}
assertTrue(parameters.getAdditionals().contains("ungiven")); assertTrue(parameters.getAdditionals().contains("ungiven"));
assertEquals(1, parameters.getAdditionals().size()); assertEquals(1, parameters.getAdditionals().size());
} }
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.CommandParameters#getBool(java.lang.String)}. */ * {@link fr.bigeon.gclc.command.CommandParameters#getBool(java.lang.String)}.
*
* @throws CommandParsingException */
@Test @Test
public final void testGetBool() { public final void testGetBool() throws CommandParsingException {
Set<String> strings = new HashSet<>(); final Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); final Set<String> bools = new HashSet<>();
bools.add("boolFlag"); bools.add("boolFlag");
strings.add("str"); strings.add("str");
@ -186,19 +174,15 @@ public class CommandParametersTest {
assertFalse(parameters.getBool("ungiven")); assertFalse(parameters.getBool("ungiven"));
assertFalse(parameters.getBool("boolFlag")); assertFalse(parameters.getBool("boolFlag"));
try {
parameters.parseArgs("-boolFlag"); parameters.parseArgs("-boolFlag");
} catch (CommandParsingException e) {
assertNull(e);
}
assertTrue(parameters.getBool("boolFlag")); assertTrue(parameters.getBool("boolFlag"));
assertFalse(parameters.getBool("ungiven")); assertFalse(parameters.getBool("ungiven"));
try { try {
parameters.parseArgs("-ungiven"); parameters.parseArgs("-ungiven");
fail("unknown parameter should fail"); fail("unknown parameter should fail");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
assertNotNull(e); // ok
} }
assertFalse(parameters.getBool("ungiven")); assertFalse(parameters.getBool("ungiven"));
assertTrue(parameters.getBool("boolFlag")); assertTrue(parameters.getBool("boolFlag"));
@ -210,70 +194,59 @@ public class CommandParametersTest {
try { try {
parameters.parseArgs("-boolFlag"); parameters.parseArgs("-boolFlag");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
assertNull(e); // ok
} }
assertTrue(parameters.getBool("boolFlag")); assertTrue(parameters.getBool("boolFlag"));
assertFalse(parameters.getBool("ungiven")); assertFalse(parameters.getBool("ungiven"));
try { try {
parameters.parseArgs("-ungiven"); parameters.parseArgs("-ungiven");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
assertNull(e); // ok
} }
assertFalse(parameters.getBool("ungiven")); assertFalse(parameters.getBool("ungiven"));
assertTrue(parameters.getBool("boolFlag")); assertTrue(parameters.getBool("boolFlag"));
} }
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.CommandParameters#parseArgs(java.lang.String[])}. */ * {@link fr.bigeon.gclc.command.CommandParameters#parseArgs(java.lang.String[])}.
*
* @throws CommandParsingException */
@Test @Test
public final void testParseArgs() { public final void testParseArgs() throws CommandParsingException {
Set<String> strings = new HashSet<>(); final Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); final Set<String> bools = new HashSet<>();
bools.add("boolFlag"); bools.add("boolFlag");
strings.add("str"); strings.add("str");
CommandParameters parameters = new CommandParameters(bools, strings, final CommandParameters parameters = new CommandParameters(bools,
true); strings, true);
try { try {
parameters.parseArgs("-ungivenFlag"); parameters.parseArgs("-ungivenFlag");
fail("unknown argument should fail in strict"); fail("Strict should fail with flag");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
assertNotNull(e); // ok
} }
try { try {
parameters.parseArgs("-str"); parameters.parseArgs("-str");
fail("missing string argument value should fail"); fail("String argument without second element should fail");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
assertNotNull(e); // ok
} }
try {
parameters.parseArgs("-boolFlag"); parameters.parseArgs("-boolFlag");
} catch (CommandParsingException e) {
assertNull(e);
}
try {
parameters.parseArgs("-str", "-boolFlag"); parameters.parseArgs("-str", "-boolFlag");
} catch (CommandParsingException e) {
assertNull(e);
}
try {
parameters.parseArgs("-boolFlag", "-str", "val"); parameters.parseArgs("-boolFlag", "-str", "val");
} catch (CommandParsingException e) {
assertNull(e);
}
} }
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, boolean)}. */ * {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, boolean)}. */
@Test @Test
public final void testSetStringBoolean() { public final void testSetStringBoolean() {
Set<String> strings = new HashSet<>(); final Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); final Set<String> bools = new HashSet<>();
bools.add("boolFlag"); bools.add("boolFlag");
strings.add("str"); strings.add("str");
@ -310,8 +283,8 @@ public class CommandParametersTest {
* {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, java.lang.String)}. */ * {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, java.lang.String)}. */
@Test @Test
public final void testSetStringString() { public final void testSetStringString() {
Set<String> strings = new HashSet<>(); final Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); final Set<String> bools = new HashSet<>();
bools.add("boolFlag"); bools.add("boolFlag");
strings.add("str"); strings.add("str");

View File

@ -38,68 +38,61 @@
*/ */
package fr.bigeon.gclc.command; package fr.bigeon.gclc.command;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import org.junit.Test; import org.junit.Test;
import fr.bigeon.gclc.exception.InvalidCommandName; import fr.bigeon.gclc.exception.InvalidCommandName;
/** <p> /**
* <p>
* TODO * TODO
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class CommandProviderTest { public class CommandProviderTest {
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.CommandProvider#add(fr.bigeon.gclc.command.ICommand)}. */ * {@link fr.bigeon.gclc.command.CommandProvider#add(fr.bigeon.gclc.command.ICommand)}.
*
* @throws InvalidCommandName */
@Test @Test
public final void testAdd() { public final void testAdd() throws InvalidCommandName {
CommandProvider provider = new CommandProvider(); final CommandProvider provider = new CommandProvider();
try { try {
provider.add(new MockCommand(null)); provider.add(new MockCommand(null));
fail("null name for command should be rejected"); fail("null name for command should be rejected");
} catch (InvalidCommandName e) { } catch (final InvalidCommandName e) {
assertNotNull(e); // ok
} }
try { try {
provider.add(new MockCommand("")); provider.add(new MockCommand(""));
fail("null name for command should be rejected"); fail("null name for command should be rejected");
} catch (InvalidCommandName e) { } catch (final InvalidCommandName e) {
assertNotNull(e); // ok
} }
try { try {
provider.add(new MockCommand("-name")); provider.add(new MockCommand("-name"));
fail("name with minus as starting character for command should be rejected"); fail("name with minus as starting character for command should be rejected");
} catch (InvalidCommandName e) { } catch (final InvalidCommandName e) {
assertNotNull(e); // ok
} }
try { try {
provider.add(new MockCommand("name command")); provider.add(new MockCommand("name command"));
fail("name with space for command should be rejected"); fail("name with space for command should be rejected");
} catch (InvalidCommandName e) { } catch (final InvalidCommandName e) {
assertNotNull(e); // ok
} }
ICommand mock = new MockCommand("name"); final ICommand mock = new MockCommand("name");
try {
provider.add(mock); provider.add(mock);
} catch (InvalidCommandName e) {
assertNull(e);
}
try { try {
provider.add(new MockCommand(mock.getCommandName())); provider.add(new MockCommand(mock.getCommandName()));
fail("already existing command name should be rejected"); fail("already existing command name should be rejected");
} catch (InvalidCommandName e) { } catch (final InvalidCommandName e) {
assertNotNull(e); // ok
} }
try {
provider.add(mock); provider.add(mock);
} catch (InvalidCommandName e) {
assertNotNull(e);
}
} }
} }

View File

@ -38,8 +38,6 @@
*/ */
package fr.bigeon.gclc.command; package fr.bigeon.gclc.command;
import static org.junit.Assert.assertNull;
import java.io.IOException; import java.io.IOException;
import org.junit.Test; import org.junit.Test;
@ -56,7 +54,7 @@ import fr.bigeon.gclc.manager.PipedConsoleOutput;
public class CommandTest { public class CommandTest {
@Test @Test
public final void testCommand() { public final void testCommand() throws IOException {
try (PipedConsoleOutput test = new PipedConsoleOutput()) { try (PipedConsoleOutput test = new PipedConsoleOutput()) {
Command cmd; Command cmd;
cmd = new Command("name") { cmd = new Command("name") {
@ -248,8 +246,6 @@ public class CommandTest {
}; };
cmd.help(test); cmd.help(test);
} catch (final IOException e) {
assertNull(e);
} }
} }
} }

View File

@ -38,8 +38,6 @@
*/ */
package fr.bigeon.gclc.command; package fr.bigeon.gclc.command;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.IOException; import java.io.IOException;
@ -59,17 +57,17 @@ import fr.bigeon.gclc.manager.PipedConsoleOutput;
public class HelpExecutorTest { public class HelpExecutorTest {
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.HelpExecutor#execute(java.lang.String[])}. */ * {@link fr.bigeon.gclc.command.HelpExecutor#execute(java.lang.String[])}.
*
* @throws CommandRunException
* @throws IOException */
@Test @Test
public final void testExecute() { public final void testExecute() throws CommandRunException, IOException {
try {
final PipedConsoleOutput test = new PipedConsoleOutput(); final PipedConsoleOutput test = new PipedConsoleOutput();
final HelpExecutor help = new HelpExecutor("?", final HelpExecutor help = new HelpExecutor("?", new Command("mock") {
new Command("mock") {
@Override @Override
public void execute(final ConsoleOutput out, public void execute(final ConsoleOutput out, final ConsoleInput in,
final ConsoleInput in,
final String... args) throws CommandRunException { final String... args) throws CommandRunException {
// //
} }
@ -93,10 +91,7 @@ public class HelpExecutorTest {
help.execute(test, null); help.execute(test, null);
fail("manager closed shall provoke failure of help command execution"); fail("manager closed shall provoke failure of help command execution");
} catch (final Exception e) { } catch (final Exception e) {
assertNotNull(e); // ok
}
} catch (final Exception e) {
assertNull(e);
} }
} }
@ -110,24 +105,22 @@ public class HelpExecutorTest {
help = new HelpExecutor("?", new MockCommand("mock")); help = new HelpExecutor("?", new MockCommand("mock"));
} }
/** Test method for {@link fr.bigeon.gclc.command.HelpExecutor#tip()}. */ /** Test method for {@link fr.bigeon.gclc.command.HelpExecutor#tip()}.
*
* @throws IOException */
@Test @Test
public final void testTip() { public final void testTip() throws IOException {
try (PipedConsoleOutput test = new PipedConsoleOutput()) { try (PipedConsoleOutput test = new PipedConsoleOutput()) {
final HelpExecutor help = new HelpExecutor("?", final HelpExecutor help = new HelpExecutor("?",
new MockCommand("mock")); new MockCommand("mock"));
help.tip(); help.tip();
help.help(test); help.help(test);
} catch (final Exception e) {
assertNull(e);
} }
try (PipedConsoleOutput test = new PipedConsoleOutput()) { try (PipedConsoleOutput test = new PipedConsoleOutput()) {
final HelpExecutor help = new HelpExecutor("?", final HelpExecutor help = new HelpExecutor("?",
new SubedCommand("sub", new MockCommand("mock"))); new SubedCommand("sub", new MockCommand("mock")));
help.tip(); help.tip();
help.help(test); help.help(test);
} catch (final Exception e) {
assertNull(e);
} }
} }

View File

@ -40,7 +40,6 @@ package fr.bigeon.gclc.command;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -64,9 +63,11 @@ import fr.bigeon.gclc.manager.PipedConsoleOutput;
public class ParametrizedCommandTest { public class ParametrizedCommandTest {
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.ParametrizedCommand#addParameter(java.lang.String, boolean, boolean)}. */ * {@link fr.bigeon.gclc.command.ParametrizedCommand#addParameter(java.lang.String, boolean, boolean)}.
*
* @throws InvalidParameterException */
@Test @Test
public final void testAddParameter() { public final void testAddParameter() throws InvalidParameterException {
ParametrizedCommand cmd = new ParametrizedCommand("name") { ParametrizedCommand cmd = new ParametrizedCommand("name") {
@Override @Override
@ -108,7 +109,6 @@ public class ParametrizedCommandTest {
// XXX Boolean flag should not be specified mandatory! They are by // XXX Boolean flag should not be specified mandatory! They are by
// nature qualified // nature qualified
final String str = "str"; final String str = "str";
try {
assertTrue(cmd.getBooleanParameters().isEmpty()); assertTrue(cmd.getBooleanParameters().isEmpty());
assertTrue(cmd.getStringParameters().isEmpty()); assertTrue(cmd.getStringParameters().isEmpty());
cmd.addBooleanParameter("boolFlag"); cmd.addBooleanParameter("boolFlag");
@ -129,16 +129,17 @@ public class ParametrizedCommandTest {
assertEquals(1, cmd.getBooleanParameters().size()); assertEquals(1, cmd.getBooleanParameters().size());
assertEquals(1, cmd.getStringParameters().size()); assertEquals(1, cmd.getStringParameters().size());
assertTrue(cmd.isNeeded(str)); assertTrue(cmd.isNeeded(str));
} catch (final InvalidParameterException e) {
fail("Unexpected error in addition of legitimate parameter");
assertNotNull(e);
}
} }
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.ParametrizedCommand#execute(java.lang.String[])}. */ * {@link fr.bigeon.gclc.command.ParametrizedCommand#execute(java.lang.String[])}.
*
* @throws CommandRunException
* @throws InterruptedException
* @throws IOException */
@Test @Test
public final void testExecute() { public final void testExecute() throws CommandRunException,
InterruptedException, IOException {
final String addParam = "additional"; final String addParam = "additional";
final String str1 = "str1"; final String str1 = "str1";
final String str2 = "str2"; final String str2 = "str2";
@ -175,15 +176,10 @@ public class ParametrizedCommandTest {
return null; return null;
} }
}; };
try {
cmd.execute(null, null); cmd.execute(null, null);
cmd.execute(null, null, "-" + addParam); cmd.execute(null, null, "-" + addParam);
cmd.execute(null, null, addParam); cmd.execute(null, null, addParam);
cmd.execute(null, null, "-" + addParam, addParam); cmd.execute(null, null, "-" + addParam, addParam);
} catch (final CommandRunException e) {
assertNull(e);
fail("unepected error");
}
cmd = new ParametrizedCommand("name", false) { cmd = new ParametrizedCommand("name", false) {
private int call = 0; private int call = 0;
{ {
@ -245,17 +241,12 @@ public class ParametrizedCommandTest {
return null; return null;
} }
}; };
try {
cmd.execute(null, null); cmd.execute(null, null);
cmd.execute(null, null, "-" + addParam); cmd.execute(null, null, "-" + addParam);
cmd.execute(null, null, addParam); cmd.execute(null, null, addParam);
cmd.execute(null, null, "-" + addParam, addParam); cmd.execute(null, null, "-" + addParam, addParam);
cmd.execute(null, null, "-" + str1, str2); cmd.execute(null, null, "-" + str1, str2);
cmd.execute(null, null, "-" + str1, str2, "-" + bool1); cmd.execute(null, null, "-" + str1, str2, "-" + bool1);
} catch (final CommandRunException e) {
assertNull(e);
fail("unepected error");
}
cmd = new ParametrizedCommand("name", true) { cmd = new ParametrizedCommand("name", true) {
private int call = 0; private int call = 0;
{ {
@ -314,25 +305,20 @@ public class ParametrizedCommandTest {
return null; return null;
} }
}; };
try {
cmd.execute(null, null); cmd.execute(null, null);
cmd.execute(null, null, "-" + str1, str2); cmd.execute(null, null, "-" + str1, str2);
cmd.execute(null, null, "-" + str1, str2, "-" + bool1); cmd.execute(null, null, "-" + str1, str2, "-" + bool1);
} catch (final CommandRunException e) {
assertNull(e);
fail("unexpected error");
}
try { try {
cmd.execute(null, null, addParam); cmd.execute(null, null, addParam);
fail("Strict should fail with unexpected argument"); fail("Strict should fail with unexpected argument");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); // ok
} }
try { try {
cmd.execute(null, null, "-" + addParam); cmd.execute(null, null, "-" + addParam);
fail("Strict should fail with unexpected argument"); fail("Strict should fail with unexpected argument");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); // ok
} }
// Test on command with missing needed elements // Test on command with missing needed elements
cmd = new ParametrizedCommand("name", false) { cmd = new ParametrizedCommand("name", false) {
@ -367,21 +353,16 @@ public class ParametrizedCommandTest {
return null; return null;
} }
}; };
try {
cmd.execute(null, null, "-" + str1, str2); cmd.execute(null, null, "-" + str1, str2);
cmd.execute(null, null, "-" + str1, str2, "-" + bool1); cmd.execute(null, null, "-" + str1, str2, "-" + bool1);
cmd.execute(null, null, "-" + str1, str2, "-" + addParam); cmd.execute(null, null, "-" + str1, str2, "-" + addParam);
cmd.execute(null, null, "-" + str1, str2, addParam); cmd.execute(null, null, "-" + str1, str2, addParam);
cmd.execute(null, null, "-" + str1, str2, "-" + addParam, addParam); cmd.execute(null, null, "-" + str1, str2, "-" + addParam, addParam);
} catch (final CommandRunException e) {
assertNull(e);
fail("unepected error");
}
try { try {
cmd.execute(null, null); cmd.execute(null, null);
fail("needed " + str1 + " not provided shall fail"); fail("needed " + str1 + " not provided shall fail");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); // ok
} }
cmd = new ParametrizedCommand("name", true) { cmd = new ParametrizedCommand("name", true) {
private final int call = 0; private final int call = 0;
@ -416,36 +397,31 @@ public class ParametrizedCommandTest {
return null; return null;
} }
}; };
try {
cmd.execute(null, null, "-" + str1, str2); cmd.execute(null, null, "-" + str1, str2);
cmd.execute(null, null, "-" + str1, str2, "-" + bool1); cmd.execute(null, null, "-" + str1, str2, "-" + bool1);
} catch (final CommandRunException e) {
assertNull(e);
fail("unepected error");
}
try { try {
cmd.execute(null, null, "-" + str1, str2, addParam); cmd.execute(null, null, "-" + str1, str2, addParam);
fail("Additional parameter should cause failure"); fail("Additional parameter should cause failure");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); // ok
} }
try { try {
cmd.execute(null, null); cmd.execute(null, null);
fail("needed " + str1 + " not provided shall fail"); fail("needed " + str1 + " not provided shall fail");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); // ok
} }
try { try {
cmd.execute(null, null, "-" + str1, str2, "-" + addParam); cmd.execute(null, null, "-" + str1, str2, "-" + addParam);
fail("unepected error"); fail("unepected error");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); // ok
} }
try { try {
cmd.execute(null, null, "-" + str1, str2, "-" + addParam, addParam); cmd.execute(null, null, "-" + str1, str2, "-" + addParam, addParam);
fail("unepected error"); fail("unepected error");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); // ok
} }
// TODO Test of interactive not providing and providing all needed // TODO Test of interactive not providing and providing all needed
try (PipedConsoleOutput out = new PipedConsoleOutput(); try (PipedConsoleOutput out = new PipedConsoleOutput();
@ -480,18 +456,11 @@ public class ParametrizedCommandTest {
return null; return null;
} }
}; };
try {
cmd.execute(out, in, "-" + str1, str2); cmd.execute(out, in, "-" + str1, str2);
cmd.execute(out, in, "-" + str1, str2, "-" + bool1); cmd.execute(out, in, "-" + str1, str2, "-" + bool1);
cmd.execute(out, in, "-" + str1, str2, addParam); cmd.execute(out, in, "-" + str1, str2, addParam);
cmd.execute(out, in, "-" + str1, str2, "-" + addParam); cmd.execute(out, in, "-" + str1, str2, "-" + addParam);
cmd.execute(out, in, "-" + str1, str2, "-" + addParam, cmd.execute(out, in, "-" + str1, str2, "-" + addParam, addParam);
addParam);
} catch (final CommandRunException e) {
assertNull(e);
fail("unepected error");
}
try {
Thread th = new Thread(new Runnable() { Thread th = new Thread(new Runnable() {
@ -538,13 +507,6 @@ public class ParametrizedCommandTest {
cmd.execute(out, in, "-" + addParam); cmd.execute(out, in, "-" + addParam);
th.join(); th.join();
} catch (CommandRunException | InterruptedException e) {
assertNull(e);
fail("unepected error");
}
} catch (final IOException e) {
assertNull(e);
fail("unepected error");
} }
try { try {
final PipedConsoleOutput out = new PipedConsoleOutput(); final PipedConsoleOutput out = new PipedConsoleOutput();
@ -584,10 +546,8 @@ public class ParametrizedCommandTest {
cmd.execute(out, test, "-" + str1, str2); cmd.execute(out, test, "-" + str1, str2);
cmd.execute(out, test, "-" + addParam); cmd.execute(out, test, "-" + addParam);
fail("Closed manager shall cause error"); fail("Closed manager shall cause error");
} catch (final IOException e) {
assertNull(e);
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); // ok
} }
} }

View File

@ -73,7 +73,6 @@ public class ScriptExecutionTest {
test = new PipedConsoleOutput(); test = new PipedConsoleOutput();
} catch (final IOException e2) { } catch (final IOException e2) {
fail("creation of console manager failed"); //$NON-NLS-1$ fail("creation of console manager failed"); //$NON-NLS-1$
assertNotNull(e2);
return; return;
} }
final ConsoleApplication app = new ConsoleApplication( final ConsoleApplication app = new ConsoleApplication(

View File

@ -71,21 +71,18 @@ public class SubedCommandTest {
cmd.add(new MockCommand("id")); cmd.add(new MockCommand("id"));
} catch (final InvalidCommandName e) { } catch (final InvalidCommandName e) {
fail("addition of command with valid id failed"); fail("addition of command with valid id failed");
assertNotNull(e);
} }
try { try {
cmd.add(new MockCommand("id")); cmd.add(new MockCommand("id"));
fail("addition of command with already used id succeeded"); fail("addition of command with already used id succeeded");
} catch (final InvalidCommandName e) { } catch (final InvalidCommandName e) {
// //
assertNotNull(e);
} }
try { try {
cmd.add(new MockCommand("")); cmd.add(new MockCommand(""));
fail("addition of command with invalid id succeeded"); fail("addition of command with invalid id succeeded");
} catch (final InvalidCommandName e) { } catch (final InvalidCommandName e) {
// //
assertNotNull(e);
} }
} }
@ -226,13 +223,13 @@ public class SubedCommandTest {
} }
try { try {
cmd.executeSub("id"); cmd.executeSub(null, null,"id");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
fail("Unexpected exception when running mock command"); fail("Unexpected exception when running mock command");
assertNotNull(e); assertNotNull(e);
} }
try { try {
cmd.executeSub("fail"); cmd.executeSub(null, null, "fail");
fail("Fail command error should be re thrown"); fail("Fail command error should be re thrown");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);

View File

@ -38,8 +38,6 @@
*/ */
package fr.bigeon.gclc.manager; package fr.bigeon.gclc.manager;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -68,76 +66,71 @@ public class ReadingRunnableTest {
* {@link fr.bigeon.gclc.manager.ReadingRunnable#getMessage()}. */ * {@link fr.bigeon.gclc.manager.ReadingRunnable#getMessage()}. */
@Test @Test
public final void testGetMessage() { public final void testGetMessage() {
BufferedReader reader = null; final BufferedReader reader = null;
ReadingRunnable runnable = new ReadingRunnable(reader); final ReadingRunnable runnable = new ReadingRunnable(reader);
runnable.setRunning(false); runnable.setRunning(false);
try { try {
runnable.getMessage(); runnable.getMessage();
fail("reading from closed runnable"); fail("reading from closed runnable");
} catch (IOException e) { } catch (final IOException e) {
assertNotNull(e); // ok
} }
} }
/** Test method for
* {@link fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String)}.
*
* @throws InterruptedException
* @throws IOException */
@Test
public final void testGetWaitForDelivery() throws InterruptedException, IOException {
try (PipedOutputStream out = new PipedOutputStream();
InputStream piped = new PipedInputStream(out);
BufferedReader reader = new BufferedReader(
new InputStreamReader(piped, "UTF-8"))) {
final ReadingRunnable runnable = new ReadingRunnable(reader);
final Thread th0 = new Thread(runnable, "read");
th0.start();
final Thread th = runnable.getWaitForDelivery("msg");
out.write(Charset.forName("UTF-8")
.encode("msg" + System.lineSeparator()).array());
final Thread th2 = new Thread(new Runnable() {
@Override
public void run() {
try {
runnable.getMessage();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, "get");
th2.start();
th.join();
runnable.setRunning(false);
out.close();
}
}
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.manager.ReadingRunnable#hasMessage()}. */ * {@link fr.bigeon.gclc.manager.ReadingRunnable#hasMessage()}. */
@Test @Test
public final void testHasMessage() { public final void testHasMessage() {
BufferedReader reader = null; final BufferedReader reader = null;
ReadingRunnable runnable = new ReadingRunnable(reader); final ReadingRunnable runnable = new ReadingRunnable(reader);
runnable.setRunning(false); runnable.setRunning(false);
try { try {
runnable.getMessage(); runnable.getMessage();
fail("reading from closed runnable"); fail("reading from closed runnable");
} catch (IOException e) { } catch (final IOException e) {
assertNotNull(e); // ok
}
}
/** Test method for
* {@link fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String)}.
*
* @throws InterruptedException */
@Test
public final void testGetWaitForDelivery() throws InterruptedException {
try (PipedOutputStream out = new PipedOutputStream();
InputStream piped = new PipedInputStream(out);
BufferedReader reader = new BufferedReader(
new InputStreamReader(piped, "UTF-8"))) {
final ReadingRunnable runnable = new ReadingRunnable(reader);
Thread th0 = new Thread(runnable, "read");
th0.start();
Thread th = runnable.getWaitForDelivery("msg");
out.write(Charset.forName("UTF-8")
.encode("msg" + System.lineSeparator()).array());
Thread th2 = new Thread(new Runnable() {
@Override
public void run() {
try {
runnable.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, "get");
th2.start();
try {
th.join();
} catch (InterruptedException e) {
assertNull(e);
}
runnable.setRunning(false);
out.close();
} catch (IOException e1) {
assertNull(e1);
} }
} }

View File

@ -40,8 +40,6 @@ package fr.bigeon.gclc.manager;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -54,23 +52,25 @@ import java.nio.charset.Charset;
import org.junit.Test; import org.junit.Test;
/** <p> /**
* <p>
* TODO * TODO
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class SystemConsoleManagerTest { public class SystemConsoleManagerTest {
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.manager.SystemConsoleManager#isClosed()}. */ * {@link fr.bigeon.gclc.manager.SystemConsoleManager#isClosed()}.
*
* @throws IOException
* @throws InterruptedException */
@Test @Test
public final void testIsClosed() { public final void testIsClosed() throws IOException, InterruptedException {
try {
final PipedOutputStream outStream = new PipedOutputStream(); final PipedOutputStream outStream = new PipedOutputStream();
final InputStream in = new PipedInputStream(outStream); final InputStream in = new PipedInputStream(outStream);
final PrintStream out = new PrintStream(outStream); final PrintStream out = new PrintStream(outStream);
final String test = "test"; final String test = "test";
final SystemConsoleInput manager = new SystemConsoleInput( final StreamConsoleInput manager = new StreamConsoleInput(System.out,
System.out,
in, Charset.forName("UTF-8")); in, Charset.forName("UTF-8"));
final Thread th = new Thread(new Runnable() { final Thread th = new Thread(new Runnable() {
@ -91,25 +91,25 @@ public class SystemConsoleManagerTest {
manager.prompt(); manager.prompt();
fail("prompt on closed manager"); fail("prompt on closed manager");
} catch (final IOException e) { } catch (final IOException e) {
assertNotNull(e); // ok
} }
th.join(); th.join();
} catch (IOException | InterruptedException e) {
assertNull(e);
}
} }
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.manager.SystemConsoleManager#prompt()}. */ * {@link fr.bigeon.gclc.manager.SystemConsoleManager#prompt()}.
*
* @throws IOException
* @throws InterruptedException */
@Test @Test
public final void testPrompt() { public final void testPrompt() throws IOException, InterruptedException {
final String test = "test"; final String test = "test";
try (PipedOutputStream outStream = new PipedOutputStream(); try (PipedOutputStream outStream = new PipedOutputStream();
InputStream in = new PipedInputStream(outStream); InputStream in = new PipedInputStream(outStream);
final PrintStream out = new PrintStream(outStream); final PrintStream out = new PrintStream(outStream);
SystemConsoleInput manager = new SystemConsoleInput(System.out, StreamConsoleInput manager = new StreamConsoleInput(System.out, in,
in, Charset.forName("UTF-8"))) { Charset.forName("UTF-8"))) {
final Thread th = new Thread(new Runnable() { final Thread th = new Thread(new Runnable() {
@ -124,26 +124,24 @@ public class SystemConsoleManagerTest {
assertEquals(test, manager.prompt()); assertEquals(test, manager.prompt());
th.join(); th.join();
} catch (IOException | InterruptedException e) {
assertNull(e);
} }
} }
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.manager.SystemConsoleManager#setPrompt(java.lang.String)}. */ * {@link fr.bigeon.gclc.manager.SystemConsoleManager#setPrompt(java.lang.String)}.
*
* @throws IOException */
@Test @Test
public final void testSetPrompt() { public final void testSetPrompt() throws IOException {
try (PipedOutputStream outStream = new PipedOutputStream(); try (PipedOutputStream outStream = new PipedOutputStream();
InputStream in = new PipedInputStream(outStream); InputStream in = new PipedInputStream(outStream);
final PrintStream out = new PrintStream(outStream); final PrintStream out = new PrintStream(outStream);
SystemConsoleInput manager = new SystemConsoleInput(System.out, StreamConsoleInput manager = new StreamConsoleInput(System.out, in,
in, Charset.forName("UTF-8"))) { Charset.forName("UTF-8"))) {
final String prt = "++"; final String prt = "++";
manager.setPrompt(prt); manager.setPrompt(prt);
assertEquals(prt, manager.getPrompt()); assertEquals(prt, manager.getPrompt());
} catch (final IOException e) {
assertNull(e);
} }
} }