Add Code compliance

Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
This commit is contained in:
Emmanuel Bigeon 2017-11-05 16:19:50 -05:00
parent 6f8c536f55
commit 9747cf21b2
41 changed files with 1919 additions and 1679 deletions

View File

@ -52,7 +52,8 @@ public class ConsoleTestApplication {
/** Exit command */ /** Exit command */
public static final String EXIT = "exit"; //$NON-NLS-1$ public static final String EXIT = "exit"; //$NON-NLS-1$
/** @param manager the manager */ /** @param manager the manager
* @return create the application */
@SuppressWarnings("nls") @SuppressWarnings("nls")
public static ConsoleApplication create(final ConsoleManager manager) { public static ConsoleApplication create(final ConsoleManager manager) {
try { try {

View File

@ -38,13 +38,12 @@
*/ */
package fr.bigeon.gclc; package fr.bigeon.gclc;
/** <p> /** Command Request Listeners are listeners that are notified before a command
* Command Request Listeners are listeners that are notified before a command is * is executed by the ConsoleApplication.
* executed by the ConsoleApplication,
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public interface CommandRequestListener { public interface CommandRequestListener {
/** Indicates that the given command was requested to the application /** Indicates that the given command was requested to the application.
* *
* @param command the command */ * @param command the command */
void commandRequest(String command); void commandRequest(String command);

View File

@ -54,17 +54,18 @@ import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.i18n.Messages; import fr.bigeon.gclc.i18n.Messages;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
/** <p> /**
* <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 ConsoleManager} manager = new {@link fr.bigeon.gclc.manager.SystemConsoleManager#SystemConsoleManager()} * {@link ConsoleManager} manager = new {@link fr.bigeon.gclc.manager.SystemConsoleManager SystemConsoleManager}();
* {@link ConsoleApplication} app = new {@link ConsoleApplication#ConsoleApplication(ConsoleManager, String, String) ConsoleApplication(manager, "welcome", "see you latter")}; * {@link ConsoleApplication} app = new {@link ConsoleApplication}(manager, "welcome", "see you latter")};
* app.{@link ConsoleApplication#add(ICommand) add}("my_command", new {@link ICommand MyCommand()}); * app.{@link ConsoleApplication#add(ICommand) add}("my_command", new {@link ICommand MyCommand()});
* app.{@link ConsoleApplication#start start}(); * app.{@link ConsoleApplication#start() start()};
* </pre> * </pre>
* <p> * <p>
* That will launch in the console application that will display "welcome", * That will launch in the console application that will display "welcome",
@ -75,40 +76,42 @@ import fr.bigeon.gclc.manager.ConsoleManager;
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public final class ConsoleApplication implements ICommandProvider { public final class ConsoleApplication implements ICommandProvider {
/** The class logger */ /** The class logger. */
private static final Logger LOGGER = Logger private static final Logger LOGGER = Logger
.getLogger(ConsoleApplication.class.getName()); .getLogger(ConsoleApplication.class.getName());
/** The welcome message */ /** The welcome message. */
public final String header; public final String header;
/** The good bye message */ /** The good bye message. */
public final String footer; public final String footer;
/** The console manager */ /** The console manager. */
public final ConsoleManager manager; public final ConsoleManager manager;
/** The container of commands */ /** The container of commands. */
public final SubedCommand root; public final SubedCommand root;
/** The state of this application */ /** The state of this application. */
private boolean running; private boolean running;
/** The listeners */ /** The listeners. */
private final List<CommandRequestListener> listeners = new ArrayList<>(); private final List<CommandRequestListener> listeners = new ArrayList<>();
/** @param manager the manager /** Create a console application.
*
* @param manager the manager
* @param welcome the welcoming message * @param welcome the welcoming message
* @param goodbye the goodbye message */ * @param goodbye the goodbye message */
public ConsoleApplication(ConsoleManager manager, String welcome, public ConsoleApplication(final ConsoleManager manager, final String welcome,
String goodbye) { final String goodbye) {
this.header = welcome; header = welcome;
this.footer = goodbye; footer = goodbye;
this.manager = manager; this.manager = manager;
root = new SubedCommand(""); //$NON-NLS-1$ root = new SubedCommand(""); //$NON-NLS-1$
} }
@Override @Override
public final boolean add(ICommand cmd) throws InvalidCommandName { public boolean add(final ICommand cmd) throws InvalidCommandName {
return root.add(cmd); return root.add(cmd);
} }
/** @param listener the command listener */ /** @param listener the command listener */
public final void addListener(CommandRequestListener listener) { public void addListener(final CommandRequestListener listener) {
listeners.add(listener); listeners.add(listener);
} }
@ -116,13 +119,13 @@ public final class ConsoleApplication implements ICommandProvider {
* @see fr.bigeon.gclc.command.ICommandProvider#executeSub(java.lang.String, * @see fr.bigeon.gclc.command.ICommandProvider#executeSub(java.lang.String,
* java.lang.String[]) */ * java.lang.String[]) */
@Override @Override
public final void executeSub(String command, public void executeSub(final String command,
String... args) throws CommandRunException { final String... args) throws CommandRunException {
root.executeSub(command, args); root.executeSub(command, args);
} }
/** Signify to the application that no command should be inputed anymore */ /** Signify to the application that no command should be inputed anymore */
public final void exit() { public void exit() {
LOGGER.fine("Request exiting application..."); //$NON-NLS-1$ LOGGER.fine("Request exiting application..."); //$NON-NLS-1$
running = false; running = false;
manager.interruptPrompt(); manager.interruptPrompt();
@ -131,17 +134,17 @@ public final class ConsoleApplication implements ICommandProvider {
/* (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
public final ICommand get(String command) { public ICommand get(final String command) {
return root.get(command); return root.get(command);
} }
/** @param cmd the command /** @param cmd the command
* @throws IOException if the command could not be parsed */ * @throws IOException if the command could not be parsed */
public final void interpretCommand(String cmd) throws IOException { public void interpretCommand(final String cmd) throws IOException {
List<String> args; List<String> args;
try { try {
args = GCLCConstants.splitCommand(cmd); args = GCLCConstants.splitCommand(cmd);
} catch (CommandParsingException e1) { } catch (final CommandParsingException e1) {
manager.println("Command line cannot be parsed"); //$NON-NLS-1$ manager.println("Command line cannot be parsed"); //$NON-NLS-1$
LOGGER.log(Level.FINE, "Invalid user command " + cmd, e1); //$NON-NLS-1$ LOGGER.log(Level.FINE, "Invalid user command " + cmd, e1); //$NON-NLS-1$
return; return;
@ -162,50 +165,14 @@ public final class ConsoleApplication implements ICommandProvider {
} }
} }
/** @param listener the command listener to remove */ /** @return the running status */
public final void removeListener(CommandRequestListener listener) { public boolean isRunning() {
for (int i = 0; i < listeners.size(); i++) { return running;
if (listeners.get(i) == listener) {
listeners.remove(i);
return;
}
}
} }
/** Start the application */ /** @param listener the command listener to remove */
public final void start() { public void removeListener(final CommandRequestListener listener) {
try { listeners.remove(listener);
running = true;
if (header != null) {
manager.println(header);
}
} catch (IOException e) {
// The manager was closed
running = false;
LOGGER.warning(
"The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$
LOGGER.log(Level.FINE,
"An exception caused the closing of the application", //$NON-NLS-1$
e);
return;
}
do {
runLoop();
} while (running);
if (footer != null) {
try {
manager.println(footer);
} catch (IOException e) {
// The manager was closed
running = false;
LOGGER.warning("The console manager was closed."); //$NON-NLS-1$
LOGGER.log(Level.FINE,
"An exception occured when trying to print the good by e message... The application will still close.", //$NON-NLS-1$
e);
}
}
running = false;
LOGGER.fine("Exiting application."); //$NON-NLS-1$
} }
/** The running loop content. /** The running loop content.
@ -222,12 +189,12 @@ public final class ConsoleApplication implements ICommandProvider {
listener.commandRequest(cmd); listener.commandRequest(cmd);
} }
interpretCommand(cmd); interpretCommand(cmd);
} catch (InterruptedIOException e) { } catch (final InterruptedIOException e) {
LOGGER.info( LOGGER.info(
"Prompt interrupted. It is likely the application is closing."); //$NON-NLS-1$ "Prompt interrupted. It is likely the application is closing."); //$NON-NLS-1$
LOGGER.log(Level.FINER, "Interruption of the prompt.", //$NON-NLS-1$ LOGGER.log(Level.FINER, "Interruption of the prompt.", //$NON-NLS-1$
e); e);
} catch (IOException e) { } catch (final IOException e) {
// The manager was closed // The manager was closed
running = false; running = false;
LOGGER.warning( LOGGER.warning(
@ -238,8 +205,39 @@ public final class ConsoleApplication implements ICommandProvider {
} }
} }
/** @return the running status */ /** Start the application */
public boolean isRunning() { public void start() {
return running; try {
running = true;
if (header != null) {
manager.println(header);
}
} catch (final IOException e) {
// The manager was closed
running = false;
LOGGER.warning(
"The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$
LOGGER.log(Level.FINE,
"An exception caused the closing of the application", //$NON-NLS-1$
e);
return;
}
do {
runLoop();
} while (running);
if (footer != null) {
try {
manager.println(footer);
} catch (final IOException e) {
// The manager was closed
running = false;
LOGGER.warning("Console manager alreaady closed."); //$NON-NLS-1$
LOGGER.log(Level.FINE,
"Exception raised by goodbye message printing... Application will still close.", //$NON-NLS-1$
e);
}
}
running = false;
LOGGER.fine("Exiting application."); //$NON-NLS-1$
} }
} }

View File

@ -49,7 +49,7 @@ import fr.bigeon.gclc.exception.CommandParsingException;
* arguments. * arguments.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public 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();
@ -59,17 +59,46 @@ public class GCLCConstants {
// utility class // utility class
} }
/** @param cmd the command to parse
* @param startIndex the starting point of the parsing
* @param index the index of the current position
* @return the argument
* @throws CommandParsingException if the end of string does not mark end of
* command and is not followed by a space */
private static String endOfString(final String cmd, final int startIndex,
final int index) throws CommandParsingException {
if (index < cmd.length() && cmd.charAt(index) != ' ') {
throw new CommandParsingException("Misplaced quote"); //$NON-NLS-1$
}
return cmd.substring(startIndex + 1, index - 1);
}
/** @return the escaping character */ /** @return the escaping character */
private static char getSystemEscapingChar() { private static char getSystemEscapingChar() {
return '\\'; return '\\';
} }
/** @param arg the string to remove excaping character from
* @return the string without escape character */
private static String removeEscaped(final String arg) {
final StringBuilder builder = new StringBuilder();
int index = 0;
int endIndex = arg.indexOf(ESCAPING_CHAR);
while (endIndex != -1) {
builder.append(arg.subSequence(index, endIndex));
index = endIndex + 1;
endIndex = arg.indexOf(ESCAPING_CHAR, index + 1);
}
builder.append(arg.substring(index));
return builder.toString();
}
/** Splits a command in the diferrent arguments /** 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
* @throws CommandParsingException if the parsing of the command failed */ * @throws CommandParsingException if the parsing of the command failed */
public static List<String> splitCommand(String cmd) throws CommandParsingException { public static List<String> splitCommand(final String cmd) throws CommandParsingException {
final List<String> args = new ArrayList<>(); final List<String> args = new ArrayList<>();
// parse the string to separate arguments // parse the string to separate arguments
int index = 0; int index = 0;
@ -77,7 +106,7 @@ public class GCLCConstants {
boolean escaped = false; boolean escaped = false;
boolean inString = false; boolean inString = false;
while (index < cmd.length()) { while (index < cmd.length()) {
char c = cmd.charAt(index); final char c = cmd.charAt(index);
index++; index++;
if (escaped || c == ESCAPING_CHAR) { if (escaped || c == ESCAPING_CHAR) {
escaped = !escaped; escaped = !escaped;
@ -105,33 +134,4 @@ public class GCLCConstants {
return args; return args;
} }
/** @param arg the string to remove excaping character from
* @return the string without escape character */
private static String removeEscaped(String arg) {
StringBuilder builder = new StringBuilder();
int index = 0;
int endIndex = arg.indexOf(ESCAPING_CHAR);
while (endIndex != -1) {
builder.append(arg.subSequence(index, endIndex));
index = endIndex + 1;
endIndex = arg.indexOf(ESCAPING_CHAR, index + 1);
}
builder.append(arg.substring(index));
return builder.toString();
}
/** @param cmd the command to parse
* @param startIndex the starting point of the parsing
* @param index the index of the current position
* @return the argument
* @throws CommandParsingException if the end of string does not mark end of
* command and is not followed by a space */
private static String endOfString(String cmd, int startIndex,
int index) throws CommandParsingException {
if (index < cmd.length() && cmd.charAt(index) != ' ') {
throw new CommandParsingException("Misplaced quote"); //$NON-NLS-1$
}
return cmd.substring(startIndex + 1, index - 1);
}
} }

View File

@ -42,7 +42,8 @@ import java.io.IOException;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
/** <p> /**
* <p>
* A command to execute. It is mandatory that it has a name and that name cannot * A command to execute. It is mandatory that it has a name and that name cannot
* start with minus character or contain spaces. * start with minus character or contain spaces.
* <p> * <p>
@ -65,17 +66,13 @@ import fr.bigeon.gclc.manager.ConsoleManager;
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public abstract class Command implements ICommand { public abstract class Command implements ICommand {
/** /** 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 empty string constant */
private static final String EMPTY = ""; //$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 */ /** @param name the command name */
public Command(String name) { public Command(final String name) {
super(); super();
this.name = name; this.name = name;
} }
@ -96,8 +93,8 @@ public abstract class Command implements ICommand {
* @see fr.bigeon.gclc.command.ICommand#help(fr.bigeon.gclc.ConsoleManager, * @see fr.bigeon.gclc.command.ICommand#help(fr.bigeon.gclc.ConsoleManager,
* java.lang.String) */ * java.lang.String) */
@Override @Override
public final void help(ConsoleManager manager, public final void help(final ConsoleManager manager,
String... args) throws IOException { final String... args) throws IOException {
manager.println(getCommandName()); manager.println(getCommandName());
manager.println(brief()); manager.println(brief());
manager.println(); manager.println();
@ -114,17 +111,16 @@ public abstract class Command implements ICommand {
} }
} }
/** <p> /**
* <p>
* This method return the detail of the help. It immediatly follows the * This method return the detail of the help. 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) */
@SuppressWarnings("static-method") protected abstract String usageDetail();
protected String usageDetail() {
return EMPTY;
}
/** <p> /**
* <p>
* This prints the usage pattern for the command. It follows the brief * This prints the usage pattern for the command. It follows the brief
* introduction on the command ({@link #brief()}) * introduction on the command ({@link #brief()})
* *

View File

@ -47,33 +47,32 @@ import java.util.Set;
import fr.bigeon.gclc.exception.CommandParsingException; import fr.bigeon.gclc.exception.CommandParsingException;
/** <p> /** An object representing a collection of parameters.
* An object representing a collection of parameters. It is used for defaulting * <p>
* values. * It is used for defaulting values.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public class CommandParameters { public final class CommandParameters {
/** /** Number of element for a string argument. */
*
*/
private static final int STRINGARG_NUMBER_OF_ELEMENTS = 2; private static final int STRINGARG_NUMBER_OF_ELEMENTS = 2;
/** Boolean arguments */ /** Boolean arguments. */
private final Map<String, Boolean> booleanArguments = new HashMap<>(); private final Map<String, Boolean> booleanArguments = new HashMap<>();
/** String arguments */ /** String arguments. */
private final Map<String, String> stringArguments = new HashMap<>(); private final Map<String, String> stringArguments = new HashMap<>();
/** Arguments restriction on the named ones */ /** Arguments restriction on the named ones. */
private final boolean strict; private final boolean strict;
/** additional (unnamed) parameters */ /** additional (unnamed) parameters. */
private final List<String> additional = new ArrayList<>(); private final List<String> additional = new ArrayList<>();
/** @param bools the boolean parameters /** Create a command parameter object.
*
* @param bools the boolean parameters
* @param strings the string parameters * @param strings the string parameters
* @param strict if the argument are restricted to the declared ones */ * @param strict if the argument are restricted to the declared ones */
@SuppressWarnings("boxing") public CommandParameters(final Set<String> bools, final Set<String> strings,
public CommandParameters(Set<String> bools, Set<String> strings, final boolean strict) {
boolean strict) {
for (final String string : bools) { for (final String string : bools) {
booleanArguments.put(string, false); booleanArguments.put(string, Boolean.FALSE);
} }
for (final String string : strings) { for (final String string : strings) {
stringArguments.put(string, null); stringArguments.put(string, null);
@ -81,41 +80,51 @@ public class CommandParameters {
this.strict = strict; this.strict = strict;
} }
/** @param key the key /** Get the value of a string argument.
*
* @param key the key
* @return the associated value, null if it was not specified */ * @return the associated value, null if it was not specified */
public String get(String key) { public String get(final String key) {
return stringArguments.get(key); return stringArguments.get(key);
} }
/** @return additional non parsed parameters */ /** Get the additional (unrecognized) arguments.
*
* @return additional non parsed parameters */
public List<String> getAdditionals() { public List<String> getAdditionals() {
return Collections.unmodifiableList(additional); return Collections.unmodifiableList(additional);
} }
/** @param key the key /** Get the value of a boolean argument.
*
* @param key the key
* @return if the key was specified */ * @return if the key was specified */
public boolean getBool(String key) { public boolean getBool(final String key) {
return booleanArguments.containsKey(key) && return booleanArguments.containsKey(key) &&
booleanArguments.get(key).booleanValue(); booleanArguments.get(key).booleanValue();
} }
/** @param args the arguments to parse /** Get the boolean arguments.
* @throws CommandParsingException if the arguments parsing failed */ *
public void parseArgs(String... args) throws CommandParsingException { * @return the boolean arguments */
int i = 0; public Set<String> getBooleanArgumentKeys() {
while (i < args.length) { return booleanArguments.keySet();
String next = null; }
if (i < args.length - 1) {
next = args[i + 1];
}
int p = parseArg(args[i], next);
if (p == 0) {
throw new CommandParsingException(
"Invalid parameter " + args[i]); //$NON-NLS-1$
}
i += p;
}
/** Get the string arguments.
*
* @return the boolean arguments */
public Set<String> getStringArgumentKeys() {
return stringArguments.keySet();
}
/** Test if an argument exists in this object.
*
* @param key the key
* @return if the key is present in string arguments or boolean ones. */
public boolean hasArgument(final String key) {
return stringArguments.containsKey(key) ||
booleanArguments.containsKey(key);
} }
/** Attempt to parse an argument. /** Attempt to parse an argument.
@ -126,11 +135,11 @@ public class CommandParameters {
* @param arg the argument * @param arg the argument
* @param next the next element * @param next the next element
* @return the number of element read */ * @return the number of element read */
private int parseArg(String arg, String next) { private int parseArg(final String arg, final String next) {
if (!arg.startsWith("-")) { //$NON-NLS-1$ if (!arg.startsWith("-")) { //$NON-NLS-1$
return strict ? 0 : 1; return strict ? 0 : 1;
} }
String name = arg.substring(1); final String name = arg.substring(1);
if (booleanArguments.containsKey(name)) { if (booleanArguments.containsKey(name)) {
booleanArguments.put(name, Boolean.TRUE); booleanArguments.put(name, Boolean.TRUE);
return 1; return 1;
@ -145,12 +154,33 @@ public class CommandParameters {
return 1; return 1;
} }
/** Add a string arg value /** Parse arguments.
*
* @param args the arguments to parse
* @throws CommandParsingException if the arguments parsing failed */
public void parseArgs(final String... args) throws CommandParsingException {
int i = 0;
while (i < args.length) {
String next = null;
if (i < args.length - 1) {
next = args[i + 1];
}
final int p = parseArg(args[i], next);
if (p == 0) {
throw new CommandParsingException(
"Invalid parameter " + args[i]); //$NON-NLS-1$
}
i += p;
}
}
/** Add a string arg value.
* *
* @param name the string arg name * @param name the string arg name
* @param next the string arg value * @param next the string arg value
* @return 2 or 0 if next is invalid */ * @return 2 or 0 if next is invalid */
private int parseStringArg(String name, String next) { private int parseStringArg(final String name, final String next) {
if (next == null) { if (next == null) {
return 0; return 0;
} }
@ -158,37 +188,23 @@ public class CommandParameters {
return STRINGARG_NUMBER_OF_ELEMENTS; return STRINGARG_NUMBER_OF_ELEMENTS;
} }
/** @param string the key /** Set a boolean parameter value.
*
* @param string the key
* @param value the value */ * @param value the value */
@SuppressWarnings("boxing") public void set(final String string, final boolean value) {
public void set(String string, boolean value) {
if (booleanArguments.containsKey(string)) { if (booleanArguments.containsKey(string)) {
booleanArguments.put(string, value); booleanArguments.put(string, Boolean.valueOf(value));
} }
} }
/** @param string the key /** Set a string parameter value.
*
* @param string the key
* @param value the value */ * @param value the value */
public void set(String string, String value) { public void set(final String string, final String value) {
if (stringArguments.containsKey(string)) { if (stringArguments.containsKey(string)) {
stringArguments.put(string, value); stringArguments.put(string, value);
} }
} }
/** @return the boolean arguments */
public Set<String> getBooleanArgumentKeys() {
return booleanArguments.keySet();
}
/** @return the boolean arguments */
public Set<String> getStringArgumentKeys() {
return stringArguments.keySet();
}
/** @param key the key
* @return if the key is present in string arguments or boolean ones. */
public boolean hasArgument(String key) {
return stringArguments.containsKey(key) ||
booleanArguments.containsKey(key);
}
} }

View File

@ -61,17 +61,26 @@ public class CommandProvider implements ICommandProvider {
commands = new ArrayList<>(); commands = new ArrayList<>();
} }
/** @param name the command name
* @throws InvalidCommandName if the name is invalid */
private static void testCommandName(final String name) throws InvalidCommandName {
if (name == null || name.isEmpty() || name.startsWith(MINUS) ||
name.contains(SPACE)) {
throw new InvalidCommandName();
}
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommandProvider#add(java.lang.String, * @see fr.bigeon.gclc.command.ICommandProvider#add(java.lang.String,
* fr.bigeon.gclc.command.Command) */ * fr.bigeon.gclc.command.Command) */
@Override @Override
public boolean add(ICommand value) throws InvalidCommandName { public final boolean add(final ICommand value) throws InvalidCommandName {
final String name = value.getCommandName(); final String name = value.getCommandName();
testCommandName(name); testCommandName(name);
if (commands.contains(value)) { if (commands.contains(value)) {
return true; return true;
} }
for (ICommand iCommand : commands) { for (final ICommand iCommand : commands) {
if (iCommand.getCommandName().equals(value.getCommandName())) { if (iCommand.getCommandName().equals(value.getCommandName())) {
throw new InvalidCommandName( throw new InvalidCommandName(
"Name already used: " + value.getCommandName()); //$NON-NLS-1$ "Name already used: " + value.getCommandName()); //$NON-NLS-1$
@ -80,18 +89,9 @@ public class CommandProvider implements ICommandProvider {
return commands.add(value); return commands.add(value);
} }
/** @param name the command name
* @throws InvalidCommandName if the name is invalid */
private static void testCommandName(String name) throws InvalidCommandName {
if (name == null || name.isEmpty() || name.startsWith(MINUS) ||
name.contains(SPACE)) {
throw new InvalidCommandName();
}
}
@Override @Override
public void executeSub(String cmd, public final void executeSub(final String cmd,
String... args) throws CommandRunException { final String... args) throws CommandRunException {
for (final ICommand command : commands) { for (final ICommand command : commands) {
if (command.getCommandName().equals(cmd)) { if (command.getCommandName().equals(cmd)) {
command.execute(args); command.execute(args);
@ -105,7 +105,7 @@ public class CommandProvider implements ICommandProvider {
/* (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
public ICommand get(String commandName) { public final ICommand get(final String commandName) {
for (final ICommand command : commands) { for (final ICommand command : commands) {
if (command.getCommandName().equals(commandName)) { if (command.getCommandName().equals(commandName)) {
return command; return command;

View File

@ -48,7 +48,7 @@ import fr.bigeon.gclc.prompt.CLIPrompterMessages;
* A command to exit a {@link ConsoleApplication}. * A command to exit a {@link ConsoleApplication}.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public class ExitCommand implements ICommand { public final 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 */
@ -60,7 +60,7 @@ public class ExitCommand implements ICommand {
/** @param name the name of the command /** @param name the name of the command
* @param app the application to exit */ * @param app the application to exit */
public ExitCommand(String name, ConsoleApplication app) { public ExitCommand(final String name, final ConsoleApplication app) {
this.name = name; this.name = name;
this.app = app; this.app = app;
} }
@ -71,7 +71,7 @@ public class ExitCommand implements ICommand {
} }
@Override @Override
public final void execute(String... args) { public void execute(final String... args) {
beforeExit(); beforeExit();
app.exit(); app.exit();
} }
@ -79,13 +79,13 @@ public class ExitCommand implements ICommand {
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#getCommandName() */ * @see fr.bigeon.gclc.command.ICommand#getCommandName() */
@Override @Override
public final String getCommandName() { public String getCommandName() {
return name; return name;
} }
@Override @Override
public void help(ConsoleManager manager, public void help(final ConsoleManager manager,
String... args) throws IOException { final String... args) throws IOException {
manager.println( manager.println(
CLIPrompterMessages.getString(EXIT_MAN, (Object[]) args)); CLIPrompterMessages.getString(EXIT_MAN, (Object[]) args));
} }

View File

@ -50,7 +50,7 @@ import fr.bigeon.gclc.prompt.CLIPrompterMessages;
* This command will display the help of an other command * This command will display the help of an other command
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public 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;
@ -60,29 +60,13 @@ public class HelpExecutor extends Command {
/** @param cmdName the command name /** @param cmdName the command name
* @param consoleManager the manager for the console * @param consoleManager the manager for the console
* @param cmd the command to execute the help of */ * @param cmd the command to execute the help of */
public HelpExecutor(String cmdName, ConsoleManager consoleManager, public HelpExecutor(final String cmdName, final ConsoleManager consoleManager,
ICommand cmd) { final ICommand cmd) {
super(cmdName); super(cmdName);
this.cmd = cmd; this.cmd = cmd;
if (consoleManager == null) {
throw new NullPointerException(
"Argument cannot be null: ConsoleManager"); //$NON-NLS-1$
}
this.consoleManager = consoleManager; this.consoleManager = consoleManager;
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#execute(java.lang.String[]) */
@Override
public void execute(String... args) throws CommandRunException {
try {
cmd.help(consoleManager, args);
} catch (IOException e) {
throw new CommandRunException(CommandRunExceptionType.INTERACTION,
"Console manager closed", e, this); //$NON-NLS-1$
}
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#brief() */ * @see fr.bigeon.gclc.command.Command#brief() */
@Override @Override
@ -94,13 +78,15 @@ public class HelpExecutor extends Command {
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usagePattern() */ * @see fr.bigeon.gclc.command.Command#execute(java.lang.String[]) */
@Override @Override
protected String usagePattern() { public void execute(final String... args) throws CommandRunException {
if (cmd instanceof SubedCommand) { try {
return getCommandName() + " <otherCommand>"; //$NON-NLS-1$ cmd.help(consoleManager, args);
} catch (final IOException e) {
throw new CommandRunException(CommandRunExceptionType.INTERACTION,
"Console manager closed", e, this); //$NON-NLS-1$
} }
return getCommandName();
} }
/* (non-Javadoc) /* (non-Javadoc)
@ -109,4 +95,22 @@ public class HelpExecutor extends Command {
public String tip() { public String tip() {
return CLIPrompterMessages.getString("help.cmd.tip"); //$NON-NLS-1$ return CLIPrompterMessages.getString("help.cmd.tip"); //$NON-NLS-1$
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail()
*/
@Override
protected String usageDetail() {
return null;
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usagePattern() */
@Override
protected String usagePattern() {
if (cmd instanceof SubedCommand) {
return getCommandName() + " <otherCommand>"; //$NON-NLS-1$
}
return getCommandName();
}
} }

View File

@ -53,7 +53,7 @@ public interface ICommandProvider {
* @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 */
public boolean add(ICommand value) throws InvalidCommandName; boolean add(ICommand value) throws InvalidCommandName;
/** <p> /** <p>
* This method executes the command with the given name found. If no command * This method executes the command with the given name found. If no command
@ -65,7 +65,7 @@ public interface ICommandProvider {
* @param command the name of the command the user wishes to execute * @param 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 */
public void executeSub(String command, void executeSub(String command,
String... args) throws CommandRunException; String... args) throws CommandRunException;
/** <p> /** <p>
@ -77,6 +77,6 @@ public interface ICommandProvider {
* *
* @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 */
public ICommand get(String command); ICommand get(String command);
} }

View File

@ -38,9 +38,6 @@
*/ */
package fr.bigeon.gclc.command; package fr.bigeon.gclc.command;
import java.io.IOException;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
/** This implement a command that does nothing. /** This implement a command that does nothing.
@ -54,24 +51,17 @@ public final class MockCommand implements ICommand {
private final String name; private final String name;
/** @param name the command name */ /** @param name the command name */
public MockCommand(String name) { public MockCommand(final String name) {
this.name = name; this.name = name;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */ * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */
@Override @Override
public void execute(String... args) throws CommandRunException { public void execute(final String... args) {
// //
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#tip() */
@Override
public String tip() {
return null;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#getCommandName() */ * @see fr.bigeon.gclc.command.ICommand#getCommandName() */
@Override @Override
@ -83,9 +73,16 @@ public final class MockCommand implements ICommand {
* @see fr.bigeon.gclc.command.ICommand#help(fr.bigeon.gclc.manager. * @see fr.bigeon.gclc.command.ICommand#help(fr.bigeon.gclc.manager.
* ConsoleManager, java.lang.String[]) */ * ConsoleManager, java.lang.String[]) */
@Override @Override
public void help(ConsoleManager manager, public void help(final ConsoleManager manager,
String... args) throws IOException { final String... args) {
// //
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#tip() */
@Override
public String tip() {
return null;
}
} }

View File

@ -55,52 +55,81 @@ import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.exception.InvalidParameterException; import fr.bigeon.gclc.exception.InvalidParameterException;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
/** <p> /** A command relying on the {@link CommandParameters} to store parameters
* A command relying on the {@link CommandParameters} to store parameters values * values.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public abstract class ParametrizedCommand extends Command { public abstract class ParametrizedCommand extends Command {
/** If the command may use interactive prompting for required parameters /** If the command may use interactive prompting for required parameters
* that were not provided on execution */ * that were not provided on execution. */
private boolean interactive = true; private boolean interactive = true;
/** The manager */ /** The manager. */
protected final ConsoleManager manager; protected final ConsoleManager manager;
/** The boolean parameters mandatory status */ /** The boolean parameters mandatory status. */
private final Set<String> boolParams = new HashSet<>(); private final Set<String> boolParams = new HashSet<>();
/** The string parameters mandatory status */ /** The string parameters mandatory status. */
private final Map<String, Boolean> stringParams = new HashMap<>(); private final Map<String, Boolean> stringParams = new HashMap<>();
/** The parameters mandatory status */ /** The parameters mandatory status. */
private final Map<String, Boolean> params = new HashMap<>(); private final Map<String, Boolean> params = new HashMap<>();
/** The restriction of provided parameters on execution to declared /** The restriction of provided parameters on execution to declared
* paramters in the status maps. */ * paramters in the status maps. */
private final boolean strict; private final boolean strict;
/** @param manager the manager /** Create a parametrized command.
* <p>
* Implementation are supposed to call the
* {@link #addBooleanParameter(String)} and
* {@link #addStringParameter(String, boolean)} method to set the
* parameters.
*
* @param manager the manager
* @param name the name */ * @param name the name */
public ParametrizedCommand(ConsoleManager manager, String name) { public ParametrizedCommand(final ConsoleManager manager,
final String name) {
this(manager, name, true); this(manager, name, true);
} }
/** @param name the name */ /** Create a parametrized command.
public ParametrizedCommand(String name) { * <p>
this(null, name, true); * Implementation are supposed to call the
} * {@link #addBooleanParameter(String)} and
* {@link #addStringParameter(String, boolean)} method to set the
/** @param manager the manager * parameters.
*
* @param manager the manager
* @param name the name * @param name the name
* @param strict if the arguments are restricted to the declared ones */ * @param strict if the arguments are restricted to the declared ones */
public ParametrizedCommand(ConsoleManager manager, String name, public ParametrizedCommand(final ConsoleManager manager, final String name,
boolean strict) { final boolean strict) {
super(name); super(name);
this.manager = manager; this.manager = manager;
interactive = manager != null; interactive = manager != null;
this.strict = strict; this.strict = strict;
} }
/** @param name the name /** Create a parametrized command.
* <p>
* Implementation are supposed to call the
* {@link #addBooleanParameter(String)} and
* {@link #addStringParameter(String, boolean)} method to set the
* parameters.
*
* @param name the name */
public ParametrizedCommand(final String name) {
this(null, name, true);
}
/** Create a parametrized command.
* <p>
* Implementation are supposed to call the
* {@link #addBooleanParameter(String)} and
* {@link #addStringParameter(String, boolean)} method to set the
* parameters.
*
* @param name the name
* @param strict if the arguments are restricted to the declared ones */ * @param strict if the arguments are restricted to the declared ones */
public ParametrizedCommand(String name, boolean strict) { public ParametrizedCommand(final String name, final boolean strict) {
this(null, name, strict); this(null, name, strict);
} }
@ -109,13 +138,13 @@ public abstract class ParametrizedCommand extends Command {
* @param flag the boolean flag * @param flag the boolean flag
* @throws InvalidParameterException if the parameter is already defined as * @throws InvalidParameterException if the parameter is already defined as
* a string parameter */ * a string parameter */
protected void addBooleanParameter(String flag) throws InvalidParameterException { protected final void addBooleanParameter(final String flag) throws InvalidParameterException {
if (params.containsKey(flag) && stringParams.containsKey(flag)) { if (params.containsKey(flag) && stringParams.containsKey(flag)) {
throw new InvalidParameterException( throw new InvalidParameterException(
"Parameter is already defined as string"); //$NON-NLS-1$ "Parameter is already defined as string"); //$NON-NLS-1$
} }
boolParams.add(flag); boolParams.add(flag);
params.put(flag, Boolean.valueOf(false)); params.put(flag, Boolean.FALSE);
} }
/** Add a string parameter to defined parmaters. /** Add a string parameter to defined parmaters.
@ -124,8 +153,8 @@ public abstract class ParametrizedCommand extends Command {
* @param needed if the parameter's absence should cause an exception * @param needed if the parameter's absence should cause an exception
* @throws InvalidParameterException if the parameter is already defined as * @throws InvalidParameterException if the parameter is already defined as
* a boolean parameter */ * a boolean parameter */
protected void addStringParameter(String flag, protected final void addStringParameter(final String flag,
boolean needed) throws InvalidParameterException { final boolean needed) throws InvalidParameterException {
if (params.containsKey(flag)) { if (params.containsKey(flag)) {
checkParam(flag, needed); checkParam(flag, needed);
return; return;
@ -134,13 +163,15 @@ public abstract class ParametrizedCommand extends Command {
params.put(flag, Boolean.valueOf(needed)); params.put(flag, Boolean.valueOf(needed));
} }
/** @param param the string parameter /** Check a parameter.
*
* @param param the string parameter
* @param needed if the parameter is needed * @param needed if the parameter is needed
* @throws InvalidParameterException if the new definition is invalid */ * @throws InvalidParameterException if the new definition is invalid */
private void checkParam(String param, private void checkParam(final String param,
boolean needed) throws InvalidParameterException { final boolean needed) throws InvalidParameterException {
if (stringParams.containsKey(param)) { if (stringParams.containsKey(param)) {
Boolean need = Boolean final Boolean need = Boolean
.valueOf(needed || stringParams.get(param).booleanValue()); .valueOf(needed || stringParams.get(param).booleanValue());
stringParams.put(param, need); stringParams.put(param, need);
params.put(param, need); params.put(param, need);
@ -150,26 +181,28 @@ public abstract class ParametrizedCommand extends Command {
"Parameter is already defined as boolean"); //$NON-NLS-1$ "Parameter is already defined as boolean"); //$NON-NLS-1$
} }
/** @param parameters the command parameters /** Actually performs the execution after parsing the parameters.
*
* @param parameters the command parameters
* @throws CommandRunException if the command failed */ * @throws CommandRunException if the command failed */
protected abstract void doExecute(CommandParameters parameters) throws CommandRunException; protected abstract void doExecute(CommandParameters parameters) throws CommandRunException;
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#execute(java.lang.String[]) */ * @see fr.bigeon.gclc.command.Command#execute(java.lang.String[]) */
@SuppressWarnings("boxing")
@Override @Override
public final void execute(String... args) throws CommandRunException { public final void execute(final String... args) throws CommandRunException {
final CommandParameters parameters = new CommandParameters(boolParams, final CommandParameters parameters = new CommandParameters(boolParams,
stringParams.keySet(), strict); stringParams.keySet(), strict);
try { try {
parameters.parseArgs(args); parameters.parseArgs(args);
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
throw new CommandRunException(CommandRunExceptionType.USAGE, throw new CommandRunException(CommandRunExceptionType.USAGE,
"Unable to read arguments", e, this); //$NON-NLS-1$ "Unable to read arguments", e, this); //$NON-NLS-1$
} }
final List<String> toProvide = new ArrayList<>(); final List<String> toProvide = new ArrayList<>();
for (final Entry<String, Boolean> string : params.entrySet()) { for (final Entry<String, Boolean> string : params.entrySet()) {
if (string.getValue() && parameters.get(string.getKey()) == null) { if (string.getValue().booleanValue() &&
parameters.get(string.getKey()) == null) {
if (!interactive) { if (!interactive) {
throw new CommandRunException( throw new CommandRunException(
CommandRunExceptionType.INTERACTION, CommandRunExceptionType.INTERACTION,
@ -184,23 +217,26 @@ public abstract class ParametrizedCommand extends Command {
doExecute(parameters); doExecute(parameters);
} }
/** @param parameters the parameter list to complete /** Fill the undefined parameters.
* <p>
* This method prompts the user to fill the needed parameters.
*
* @param parameters the parameter list to complete
* @param toProvide the parameters to ask for * @param toProvide the parameters to ask for
* @throws CommandRunException if the manager was closed */ * @throws CommandRunException if the manager was closed */
private void fillParameters(List<String> toProvide, private final void fillParameters(final List<String> toProvide,
CommandParameters parameters) throws CommandRunException { final CommandParameters parameters) throws CommandRunException {
for (final String string : toProvide) { for (final String string : toProvide) {
String value; String value;
try { try {
value = manager value = manager
.prompt(MessageFormat.format("value of {0}? ", string)); //$NON-NLS-1$ .prompt(MessageFormat.format("value of {0}? ", string)); //$NON-NLS-1$
while (value.isEmpty()) { while (value.isEmpty()) {
value = manager.prompt( value = manager.prompt(MessageFormat.format(
MessageFormat.format( "value of {0}? (cannot be empty) ", //$NON-NLS-1$
"value of {0}? (cannot be empty) ", //$NON-NLS-1$ string));
string));
} }
} catch (IOException e) { } catch (final IOException e) {
throw new CommandRunException( throw new CommandRunException(
CommandRunExceptionType.INTERACTION, CommandRunExceptionType.INTERACTION,
"Interactive command but manager closed...", e, this); //$NON-NLS-1$ "Interactive command but manager closed...", e, this); //$NON-NLS-1$
@ -209,34 +245,48 @@ public abstract class ParametrizedCommand extends Command {
} }
} }
/** @return the set of boolean parameters */ /** Retrieve the boolean parameters (aka flags).
public Set<String> getBooleanParameters() { *
* @return the set of boolean parameters */
public final Set<String> getBooleanParameters() {
return Collections.unmodifiableSet(boolParams); return Collections.unmodifiableSet(boolParams);
} }
/** @return the stringParams */ /** Retrieve the parameter names.
public Set<String> getStringParameters() { *
return stringParams.keySet(); * @return the stringParams */
} public final Set<String> getParameters() {
/** @return the stringParams */
public Set<String> getParameters() {
return params.keySet(); return params.keySet();
} }
/** @param param the parameter name /** Get the string parameters names.
*
* @return the stringParams */
public final Set<String> getStringParameters() {
return stringParams.keySet();
}
/** If the command is interactive.
* <p>
* An interactive command will prompt the user for missing parameters.
*
* @return the interactive */
public final boolean isInteractive() {
return interactive;
}
/** Test if a parameter is needed.
*
* @param param the parameter name
* @return if the parameter is needed */ * @return if the parameter is needed */
public boolean isNeeded(String param) { public final boolean isNeeded(final String param) {
return params.containsKey(param) && params.get(param).booleanValue(); return params.containsKey(param) && params.get(param).booleanValue();
} }
/** @return the strict */ /** If the command refuse unrecognized parameters.
public boolean isStrict() { *
* @return the strict */
public final boolean isStrict() {
return strict; return strict;
} }
/** @return the interactive */
public boolean isInteractive() {
return interactive;
}
} }

View File

@ -59,7 +59,7 @@ import fr.bigeon.gclc.exception.CommandRunExceptionType;
* as a command of the application. * as a command of the application.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public 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$
@ -76,21 +76,31 @@ public class ScriptExecution extends 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 */
public ScriptExecution(String name, ConsoleApplication application, public ScriptExecution(final String name, final ConsoleApplication application,
String commentPrefix, Charset charset) { final String commentPrefix, final Charset charset) {
super(name); super(name);
this.application = application; this.application = application;
this.commentPrefix = commentPrefix; this.commentPrefix = commentPrefix;
this.charset = charset; this.charset = charset;
} }
/** @param args the arguments
* @throws CommandRunException if the arguments were not the ones
* expected */
private void checkArgs(final String[] args) throws CommandRunException {
if (args.length == 0) {
throw new CommandRunException(CommandRunExceptionType.USAGE,
"Expecting a file", this); //$NON-NLS-1$
}
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */ * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */
@Override @Override
public void execute(String... args) throws CommandRunException { public void execute(final String... args) throws CommandRunException {
checkArgs(args); checkArgs(args);
String scriptFile = args[0]; final String scriptFile = args[0];
String[] params = Arrays.copyOfRange(args, 1, args.length); final String[] params = Arrays.copyOfRange(args, 1, args.length);
String cmd; String cmd;
int lineNo = -1; int lineNo = -1;
try (InputStreamReader fReader = new InputStreamReader( try (InputStreamReader fReader = new InputStreamReader(
@ -98,44 +108,34 @@ public class ScriptExecution extends Command {
BufferedReader reader = new BufferedReader(fReader)) { BufferedReader reader = new BufferedReader(fReader)) {
while ((cmd = reader.readLine()) != null) { while ((cmd = reader.readLine()) != null) {
lineNo++; lineNo++;
String cmdLine = readCommandLine(cmd, params); final String cmdLine = readCommandLine(cmd, params);
if (cmdLine == null) { if (cmdLine == null) {
continue; continue;
} }
List<String> ps = GCLCConstants.splitCommand(cmdLine); final List<String> ps = GCLCConstants.splitCommand(cmdLine);
String command = ps.remove(0); final String command = ps.remove(0);
application.executeSub(command, ps.toArray(new String[0])); application.executeSub(command, ps.toArray(new String[0]));
} }
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
throw new CommandRunException(MessageFormat.format( throw new CommandRunException(MessageFormat.format(
"Invalid command in script ({0})", e.getLocalizedMessage()), //$NON-NLS-1$ "Invalid command in script ({0})", e.getLocalizedMessage()), //$NON-NLS-1$
e, this); e, this);
} catch (IOException e) { } catch (final IOException e) {
throw new CommandRunException("Unable to read script", //$NON-NLS-1$ throw new CommandRunException("Unable to read script", //$NON-NLS-1$
e, this); e, this);
} catch (CommandRunException e) { } catch (final CommandRunException e) {
throw manageRunException(e, lineNo); throw manageRunException(e, lineNo);
} }
} }
/** @param args the arguments
* @throws CommandRunException if the arguments were not the ones
* expected */
private void checkArgs(String[] args) throws CommandRunException {
if (args.length == 0) {
throw new CommandRunException(CommandRunExceptionType.USAGE,
"Expecting a file", this); //$NON-NLS-1$
}
}
/** This method will create the correct exception. The exception source must /** This method will create the correct exception. The exception source must
* be this command. * be this command.
* *
* @param e the exception * @param e the exception
* @param lineNo the line nu;ber * @param lineNo the line nu;ber
* @return the exception to actually throw */ * @return the exception to actually throw */
private CommandRunException manageRunException(CommandRunException e, private CommandRunException manageRunException(final CommandRunException e,
int lineNo) { final int lineNo) {
if (e.getSource() == this) { if (e.getSource() == this) {
// ensure closing? // ensure closing?
return e; return e;
@ -151,8 +151,8 @@ public class ScriptExecution extends Command {
* @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 */
private String readCommandLine(String cmd, private String readCommandLine(final String cmd,
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 command in script (line starts with space character)", //$NON-NLS-1$
@ -164,24 +164,31 @@ public class ScriptExecution extends Command {
return MessageFormat.format(cmd, params); return MessageFormat.format(cmd, params);
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#tip() */
@Override
public String tip() {
return "Execute a script"; //$NON-NLS-1$
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail() */ * @see fr.bigeon.gclc.command.Command#usageDetail() */
@SuppressWarnings("nls")
@Override @Override
protected String usageDetail() { protected String usageDetail() {
StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
builder.append( builder.append(
" scriptfile: path to the file containing the script to execute."); " scriptfile: path to the file containing the script to execute."); //$NON-NLS-1$
builder.append(System.lineSeparator()); builder.append(System.lineSeparator());
builder.append(System.lineSeparator()); builder.append(System.lineSeparator());
builder.append( builder.append(
" The script file must contain one line commands. The lines must never"); " The script file must contain one line commands. The lines must never"); //$NON-NLS-1$
builder.append(System.lineSeparator()); builder.append(System.lineSeparator());
builder.append( builder.append(
"start with whitespace characters. The lines starting with"); "start with whitespace characters. The lines starting with"); //$NON-NLS-1$
builder.append(System.lineSeparator()); builder.append(System.lineSeparator());
builder.append("\"" + commentPrefix + builder.append('"');
"\" will be ignored as well as empty lines."); builder.append(commentPrefix);
builder.append("\" will be ignored as well as empty lines."); //$NON-NLS-1$
builder.append(System.lineSeparator()); builder.append(System.lineSeparator());
return builder.toString(); return builder.toString();
@ -189,18 +196,9 @@ public class ScriptExecution extends Command {
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usagePattern() */ * @see fr.bigeon.gclc.command.Command#usagePattern() */
@SuppressWarnings("nls")
@Override @Override
protected String usagePattern() { protected String usagePattern() {
return super.usagePattern() + " <scriptfile>"; return super.usagePattern() + " <scriptfile>"; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#tip() */
@SuppressWarnings("nls")
@Override
public String tip() {
return "Execute a script";
} }
} }

View File

@ -41,33 +41,32 @@ import java.util.Arrays;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType; import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
/** <p> /**
* <p>
* A subed command is a command that can execute sub commands depending on the * A subed command is a command that can execute sub commands depending on the
* first argument. * first argument.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public class SubedCommand implements ICommandProvider, 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$
/** <p> /** 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.
* <p>
* This may be null, in which case the command should have arguments. */ * This may be null, in which case the command should have arguments. */
private final ICommand noArgCommand; private final ICommand noArgCommand;
/** A tip on this command. */ /** A tip on this command. */
private final String tip; private final String tip;
/** The provider */
private final CommandProvider provider;
/** 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 */ /** @param name the name of the command */
public SubedCommand(String name) { public SubedCommand(final String name) {
super();
this.name = name; this.name = name;
provider = new CommandProvider();
noArgCommand = null; noArgCommand = null;
tip = null; tip = null;
} }
@ -75,9 +74,9 @@ public class SubedCommand implements ICommandProvider, ICommand {
/** @param name the name of the command /** @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(String name, ICommand noArgCommand) { public SubedCommand(final String name, final ICommand noArgCommand) {
super();
this.name = name; this.name = name;
provider = new CommandProvider();
this.noArgCommand = noArgCommand; this.noArgCommand = noArgCommand;
tip = null; tip = null;
} }
@ -85,32 +84,27 @@ public class SubedCommand implements ICommandProvider, ICommand {
/** @param name the name of the command /** @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(String name, ICommand noArgCommand, public SubedCommand(final String name, final ICommand noArgCommand,
String tip) { final String tip) {
super();
this.name = name; this.name = name;
provider = new CommandProvider();
this.noArgCommand = noArgCommand; this.noArgCommand = noArgCommand;
this.tip = tip; this.tip = tip;
} }
/** @param name the name of the command /** @param name the name of the command
* @param tip the help tip associated */ * @param tip the help tip associated */
public SubedCommand(String name, String tip) { public SubedCommand(final String name, final String tip) {
super();
this.name = name; this.name = name;
provider = new CommandProvider();
noArgCommand = null; noArgCommand = null;
this.tip = tip; this.tip = tip;
} }
@Override
public boolean add(ICommand value) throws InvalidCommandName {
return provider.add(value);
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.acide.Command#execute(java.lang.String[]) */ * @see fr.bigeon.acide.Command#execute(java.lang.String[]) */
@Override @Override
public void execute(String... args) throws CommandRunException { public void execute(final String... args) throws CommandRunException {
if (args.length == 0 || args[0].startsWith("-")) { //$NON-NLS-1$ if (args.length == 0 || args[0].startsWith("-")) { //$NON-NLS-1$
if (noArgCommand != null) { if (noArgCommand != null) {
noArgCommand.execute(args); noArgCommand.execute(args);
@ -121,7 +115,7 @@ public class SubedCommand implements ICommandProvider, ICommand {
try { try {
executeSub(args[0], Arrays.copyOfRange(args, 1, args.length)); executeSub(args[0], Arrays.copyOfRange(args, 1, args.length));
} catch (CommandRunException e) { } catch (final CommandRunException e) {
if (e.getSource() != null) { if (e.getSource() != null) {
throw e; throw e;
} }
@ -131,21 +125,6 @@ public class SubedCommand implements ICommandProvider, ICommand {
} }
} }
/* (non-Javadoc)
* @see
* fr.bigeon.gclc.command.ICommandProvider#executeSub(java.lang.String,
* java.lang.String[]) */
@Override
public void executeSub(String command,
String... args) throws CommandRunException {
provider.executeSub(command, args);
}
@Override
public ICommand get(String commandName) {
return provider.get(commandName);
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#getCommandName() */ * @see fr.bigeon.gclc.command.ICommand#getCommandName() */
@Override @Override
@ -156,8 +135,8 @@ public class SubedCommand implements ICommandProvider, ICommand {
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#help() */ * @see fr.bigeon.gclc.command.Command#help() */
@Override @Override
public void help(ConsoleManager manager, public void help(final ConsoleManager manager,
String... args) throws IOException { final String... args) throws IOException {
if (args.length != 0 && !args[0].startsWith("-")) { //$NON-NLS-1$ if (args.length != 0 && !args[0].startsWith("-")) { //$NON-NLS-1$
// Specific // Specific
final ICommand c = get(args[0]); final ICommand c = get(args[0]);
@ -166,17 +145,17 @@ public class SubedCommand implements ICommandProvider, ICommand {
} }
} else { } else {
// Generic // Generic
if (noArgCommand != null && noArgCommand.tip() != null) { if (noArgCommand != null && noArgCommand.tip() != null) {
manager.println(TAB + noArgCommand.tip()); manager.println(TAB + noArgCommand.tip());
} }
for (final ICommand cmd : provider.commands) { for (final ICommand cmd : commands) {
if (cmd.tip() == null) { if (cmd.tip() == null) {
manager.println(TAB + cmd.getCommandName()); manager.println(TAB + cmd.getCommandName());
} else { } else {
manager.println(TAB + cmd.getCommandName() + ": " + //$NON-NLS-1$ manager.println(TAB + cmd.getCommandName() + ": " + //$NON-NLS-1$
cmd.tip()); cmd.tip());
}
} }
}
} }
} }
@ -191,7 +170,7 @@ public class SubedCommand implements ICommandProvider, ICommand {
* @see java.lang.Object#toString() */ * @see java.lang.Object#toString() */
@Override @Override
public String toString() { public String toString() {
return "SubedCommand " + provider; //$NON-NLS-1$ return "SubedCommand " + super.toString(); //$NON-NLS-1$
} }
} }

View File

@ -44,7 +44,7 @@ import fr.bigeon.gclc.command.ICommand;
* 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 class CommandRunException extends Exception { public final class CommandRunException extends Exception {
/** /**
* *
@ -54,31 +54,13 @@ public class CommandRunException extends Exception {
/** 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 ICommand source; private final transient ICommand source;
/** @param message a message
* @param source the source */
public CommandRunException(String message, ICommand source) {
super(message);
type = CommandRunExceptionType.EXECUTION;
this.source = source;
}
/** @param message a message
* @param cause the cause
* @param source the source */
public CommandRunException(String message, Throwable cause,
ICommand source) {
super(message, cause);
type = CommandRunExceptionType.EXECUTION;
this.source = source;
}
/** @param type the type of 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(CommandRunExceptionType type, String message, public CommandRunException(final CommandRunExceptionType type, final String message,
ICommand source) { final ICommand source) {
super(message); super(message);
this.type = type; this.type = type;
this.source = source; this.source = source;
@ -88,13 +70,31 @@ public class CommandRunException extends 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(CommandRunExceptionType type, String message, public CommandRunException(final CommandRunExceptionType type, final String message,
Throwable cause, ICommand source) { 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
* @param source the source */
public CommandRunException(final String message, final ICommand source) {
super(message);
type = CommandRunExceptionType.EXECUTION;
this.source = source;
}
/** @param message a message
* @param cause the cause
* @param source the source */
public CommandRunException(final String message, final Throwable cause,
final ICommand source) {
super(message, cause);
type = CommandRunExceptionType.EXECUTION;
this.source = source;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see java.lang.Throwable#getLocalizedMessage() */ * @see java.lang.Throwable#getLocalizedMessage() */
@Override @Override

View File

@ -47,7 +47,7 @@ import java.util.logging.Logger;
/** Internationalization class. /** Internationalization class.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public 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$
@ -69,10 +69,10 @@ public class Messages {
* @param key the message key * @param key the message key
* @param args the formatting arguments * @param args the formatting arguments
* @return the formatted internationalized message */ * @return the formatted internationalized message */
public static String getString(String key, Object... args) { public static String getString(final String key, final Object... args) {
try { try {
return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args); return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args);
} catch (MissingResourceException e) { } catch (final MissingResourceException e) {
LOGGER.log(Level.WARNING, LOGGER.log(Level.WARNING,
"Unrecognized internationalization message key: " + key, e); //$NON-NLS-1$ "Unrecognized internationalization message key: " + key, e); //$NON-NLS-1$
return '!' + key + '!'; return '!' + key + '!';

View File

@ -44,7 +44,7 @@ import java.io.InputStreamReader;
import java.io.PipedInputStream; import java.io.PipedInputStream;
import java.io.PipedOutputStream; import java.io.PipedOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
/** This console manager allows to enter commands and retrieve the output as an /** This console manager allows to enter commands and retrieve the output as an
* input. * input.
@ -75,18 +75,20 @@ public final class PipedConsoleManager
/** The reading thread */ /** The reading thread */
private final ReadingRunnable reading; private final ReadingRunnable reading;
/** @throws IOException if the piping failed for streams */ /** Create a manager that will write and read through piped stream.
*
* @throws IOException if the piping failed for streams */
public PipedConsoleManager() throws IOException { public PipedConsoleManager() throws IOException {
commandInput = new PipedOutputStream(); commandInput = new PipedOutputStream();
in = new PipedInputStream(commandInput); in = new PipedInputStream(commandInput);
commandOutput = new PipedInputStream(); commandOutput = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(commandOutput); final PipedOutputStream out = new PipedOutputStream(commandOutput);
commandBuffOutput = new BufferedReader( commandBuffOutput = new BufferedReader(
new InputStreamReader(commandOutput, Charset.forName(UTF_8))); new InputStreamReader(commandOutput, StandardCharsets.UTF_8));
outPrint = new PrintStream(out, true, UTF_8); outPrint = new PrintStream(out, true, UTF_8);
innerManager = new SystemConsoleManager(outPrint, in, innerManager = new SystemConsoleManager(outPrint, in,
Charset.forName(UTF_8)); StandardCharsets.UTF_8);
writing = new WritingRunnable(commandInput, Charset.forName(UTF_8)); writing = new WritingRunnable(commandInput, StandardCharsets.UTF_8);
reading = new ReadingRunnable(commandBuffOutput); reading = new ReadingRunnable(commandBuffOutput);
Thread th = new Thread(writing, "write"); //$NON-NLS-1$ Thread th = new Thread(writing, "write"); //$NON-NLS-1$
th.start(); th.start();
@ -95,13 +97,50 @@ public final class PipedConsoleManager
th.start(); th.start();
} }
/** @return the content of the next line written by the application
* @throws IOException if the reading failed */
public boolean available() throws IOException {
return reading.hasMessage();
}
@Override
public void close() throws IOException {
reading.setRunning(false);
writing.setRunning(false);
in.close();
innerManager.close();
outPrint.close();
commandBuffOutput.close();
commandOutput.close();
commandInput.close();
}
@Override @Override
public String getPrompt() { public String getPrompt() {
return innerManager.getPrompt(); return innerManager.getPrompt();
} }
/** @param message the message
* @return the thread to join to wait for message delivery
* @see fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String) */
public Thread getWaitForDelivery(final String message) {
return reading.getWaitForDelivery(message);
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */
@Override @Override
public void print(String object) throws IOException { public void interruptPrompt() {
innerManager.interruptPrompt();
}
@Override
public boolean isClosed() {
return innerManager.isClosed();
}
@Override
public void print(final String object) throws IOException {
innerManager.print(object); innerManager.print(object);
} }
@ -111,7 +150,7 @@ public final class PipedConsoleManager
} }
@Override @Override
public void println(String object) throws IOException { public void println(final String object) throws IOException {
innerManager.println(object); innerManager.println(object);
} }
@ -124,72 +163,35 @@ public final class PipedConsoleManager
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */ * @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */
@Override @Override
public String prompt(long timeout) throws IOException { public String prompt(final long timeout) throws IOException {
return innerManager.prompt(timeout); return innerManager.prompt(timeout);
} }
@Override @Override
public String prompt(String message) throws IOException { public String prompt(final String message) throws IOException {
return innerManager.prompt(message + System.lineSeparator()); return innerManager.prompt(message + System.lineSeparator());
} }
@Override @Override
public String prompt(String message, long timeout) throws IOException { public String prompt(final String message, final long timeout) throws IOException {
return innerManager.prompt(message + System.lineSeparator(), timeout); return innerManager.prompt(message + System.lineSeparator(), timeout);
} }
@Override
public void setPrompt(String prompt) {
innerManager.setPrompt(prompt);
}
@Override
public void close() throws IOException {
innerManager.close();
reading.setRunning(false);
writing.setRunning(false);
outPrint.close();
commandBuffOutput.close();
commandOutput.close();
in.close();
commandInput.close();
}
@Override
public boolean isClosed() {
return innerManager.isClosed();
}
/** @param content the content to type to the application
* @throws IOException if the typing failed */
public void type(String content) throws IOException {
writing.addMessage(content);
}
/** @return the content of the next line written by the application /** @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();
} }
/** @return the content of the next line written by the application
* @throws IOException if the reading failed */
public boolean available() throws IOException {
return reading.hasMessage();
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */
@Override @Override
public void interruptPrompt() { public void setPrompt(final String prompt) {
innerManager.interruptPrompt(); innerManager.setPrompt(prompt);
} }
/** @param message the message /** @param content the content to type to the application
* @return the thread to join to wait for message delivery * @throws IOException if the typing failed */
* @see fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String) */ public void type(final String content) throws IOException {
public Thread getWaitForDelivery(String message) { writing.addMessage(content);
return reading.getWaitForDelivery(message);
} }
} }

View File

@ -51,7 +51,7 @@ import java.util.logging.Logger;
/** A runnable to read the piped output. /** A runnable to read the piped output.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class ReadingRunnable implements Runnable { public final class ReadingRunnable implements Runnable {
/** The runnable to wait for notification on an object /** The runnable to wait for notification on an object
* *
@ -69,19 +69,26 @@ public class ReadingRunnable implements Runnable {
/** @param obj the object to lock on /** @param 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(Object obj, Object start, String message) { public ToWaitRunnable(final Object obj, final Object start, final String message) {
this.obj = obj; this.obj = obj;
this.start = start; this.start = start;
this.message = message; this.message = message;
} }
/** @return the started */
public boolean isStarted() {
synchronized (start) {
return started;
}
}
@SuppressWarnings("synthetic-access") @SuppressWarnings("synthetic-access")
@Override @Override
public void run() { public void run() {
synchronized (obj) { synchronized (obj) {
synchronized (start) { synchronized (start) {
started = true; started = true;
start.notify(); start.notifyAll();
} }
while (isRunning()) { while (isRunning()) {
try { try {
@ -89,20 +96,14 @@ public class ReadingRunnable implements Runnable {
if (delivering.equals(message)) { if (delivering.equals(message)) {
return; return;
} }
} catch (InterruptedException e) { } catch (final InterruptedException e) {
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION,
e); e);
Thread.currentThread().interrupt();
} }
} }
} }
} }
/** @return the started */
public boolean isStarted() {
synchronized (start) {
return started;
}
}
} }
/** The thread intteruption logging message */ /** The thread intteruption logging message */
@ -133,49 +134,16 @@ public class ReadingRunnable implements Runnable {
private String delivering; private String delivering;
/** @param reader the input to read from */ /** @param reader the input to read from */
public ReadingRunnable(BufferedReader reader) { public ReadingRunnable(final BufferedReader reader) {
super(); super();
this.reader = reader; this.reader = reader;
} }
/* (non-Javadoc)
* @see java.lang.Runnable#run() */
@Override
public void run() {
while (running) {
try {
String line = reader.readLine();
if (line == null) {
// Buffer end
running = false;
return;
}
LOGGER.finer("Read: " + line); //$NON-NLS-1$
line = stripNull(line);
synchronized (lock) {
messages.add(line);
lock.notify();
}
} catch (InterruptedIOException e) {
LOGGER.info("Reading interrupted"); //$NON-NLS-1$
LOGGER.log(Level.FINER,
"Read interruption was caused by an exception", e); //$NON-NLS-1$
} catch (IOException e) {
LOGGER.severe("Unable to read from stream"); //$NON-NLS-1$
LOGGER.log(Level.FINE, "The stream reading threw an exception", //$NON-NLS-1$
e);
running = false;
return;
}
}
}
/** Strip the string from head NULL characters. /** Strip the string from head NULL characters.
* *
* @param line the line to strip the null character from * @param line the line to strip the null character from
* @return the resulting string */ * @return the resulting string */
private static String stripNull(String line) { private static String stripNull(final String line) {
String res = line; String res = line;
while (res.length() > 0 && res.charAt(0) == 0) { while (res.length() > 0 && res.charAt(0) == 0) {
LOGGER.severe( LOGGER.severe(
@ -196,8 +164,9 @@ public class ReadingRunnable implements Runnable {
while (messages.isEmpty()) { while (messages.isEmpty()) {
try { try {
lock.wait(TIMEOUT); lock.wait(TIMEOUT);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e); LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e);
Thread.currentThread().interrupt();
} }
if (messages.isEmpty() && !running) { if (messages.isEmpty() && !running) {
throw new IOException(CLOSED_PIPE); throw new IOException(CLOSED_PIPE);
@ -213,7 +182,7 @@ public class ReadingRunnable implements Runnable {
/** @param timeout the read time out /** @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(long timeout) throws IOException { public String getNextMessage(final long timeout) throws IOException {
synchronized (lock) { synchronized (lock) {
if (!running) { if (!running) {
throw new IOException(CLOSED_PIPE); throw new IOException(CLOSED_PIPE);
@ -221,8 +190,9 @@ public class ReadingRunnable implements Runnable {
waiting = true; waiting = true;
try { try {
lock.wait(timeout); lock.wait(timeout);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e); LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e);
Thread.currentThread().interrupt();
} }
if (messages.isEmpty() && !running) { if (messages.isEmpty() && !running) {
throw new IOException(CLOSED_PIPE); throw new IOException(CLOSED_PIPE);
@ -235,17 +205,31 @@ public class ReadingRunnable implements Runnable {
} }
} }
/** @param running the running to set */ /** @param message the message
public void setRunning(boolean running) { * @return the thread to join to wait for message delivery */
synchronized (lock) { public Thread getWaitForDelivery(final String message) {
this.running = running; synchronized (messageBlockerLock) {
} if (!messageBlocker.containsKey(message)) {
} messageBlocker.put(message, new Object());
}
final Object obj = messageBlocker.get(message);
final Object start = new Object();
final ToWaitRunnable waitRunn = new ToWaitRunnable(obj, start, message);
final Thread th = new Thread(waitRunn);
/** @return the running */ synchronized (start) {
public boolean isRunning() { th.start();
synchronized (lock) { while (!waitRunn.isStarted()) {
return running; try {
start.wait(TIMEOUT);
} catch (final InterruptedException e) {
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION,
e);
Thread.currentThread().interrupt();
}
}
}
return th;
} }
} }
@ -265,49 +249,68 @@ public class ReadingRunnable implements Runnable {
synchronized (lock) { synchronized (lock) {
if (waiting) { if (waiting) {
messages.offer(""); //$NON-NLS-1$ messages.offer(""); //$NON-NLS-1$
lock.notify(); lock.notifyAll();
} }
} }
} }
/** @return the running */
public boolean isRunning() {
synchronized (lock) {
return running;
}
}
/** @param message the message */ /** @param message the message */
private void notifyMessage(String message) { private void notifyMessage(final String message) {
synchronized (messageBlockerLock) { synchronized (messageBlockerLock) {
delivering = message; delivering = message;
if (messageBlocker.containsKey(message)) { if (messageBlocker.containsKey(message)) {
Object mLock = messageBlocker.get(message); final Object mLock = messageBlocker.get(message);
synchronized (mLock) { synchronized (mLock) {
mLock.notify(); mLock.notifyAll();
} }
messageBlocker.remove(message); messageBlocker.remove(message);
} }
} }
} }
/** @param message the message /* (non-Javadoc)
* @return the thread to join to wait for message delivery */ * @see java.lang.Runnable#run() */
public Thread getWaitForDelivery(final String message) { @Override
synchronized (messageBlockerLock) { public void run() {
if (!messageBlocker.containsKey(message)) { while (running) {
messageBlocker.put(message, new Object()); try {
} String line = reader.readLine();
final Object obj = messageBlocker.get(message); if (line == null) {
final Object start = new Object(); // Buffer end
ToWaitRunnable waitRunn = new ToWaitRunnable(obj, start, message); running = false;
Thread th = new Thread(waitRunn); return;
synchronized (start) {
th.start();
while (!waitRunn.isStarted()) {
try {
start.wait(TIMEOUT);
} catch (InterruptedException e) {
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION,
e);
}
} }
LOGGER.finer("Read: " + line); //$NON-NLS-1$
line = stripNull(line);
synchronized (lock) {
messages.add(line);
lock.notifyAll();
}
} catch (final InterruptedIOException e) {
LOGGER.info("Reading interrupted"); //$NON-NLS-1$
LOGGER.log(Level.FINER,
"Read interruption was caused by an exception", e); //$NON-NLS-1$
} catch (final IOException e) {
LOGGER.severe("Unable to read from stream"); //$NON-NLS-1$
LOGGER.log(Level.FINE, "The stream reading threw an exception", //$NON-NLS-1$
e);
running = false;
return;
} }
return th; }
}
/** @param running the running to set */
public void setRunning(final boolean running) {
synchronized (lock) {
this.running = running;
} }
} }
} }

View File

@ -50,7 +50,7 @@ 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 SystemConsoleManager implements ConsoleManager { // NOSONAR public final class SystemConsoleManager implements ConsoleManager {
/** The default prompt */ /** The default prompt */
public static final String DEFAULT_PROMPT = "> "; //$NON-NLS-1$ public static final String DEFAULT_PROMPT = "> "; //$NON-NLS-1$
@ -81,8 +81,8 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR
/** @param out the output stream /** @param 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 SystemConsoleManager(PrintStream out, InputStream in, public SystemConsoleManager(final PrintStream out, final InputStream in,
Charset charset) { final Charset charset) {
super(); super();
this.out = out; this.out = out;
this.in = new BufferedReader(new InputStreamReader(in, charset)); this.in = new BufferedReader(new InputStreamReader(in, charset));
@ -92,27 +92,52 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR
promptThread.start(); promptThread.start();
} }
/** @throws IOException if the stream was closed */
private void checkOpen() throws IOException {
if (closed) {
throw new IOException();
}
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#close() */
@Override
public void close() throws IOException {
closed = true;
reading.setRunning(false);
promptThread.interrupt();
in.close();
}
/** @return the prompt */ /** @return the prompt */
@Override @Override
public String getPrompt() { public String getPrompt() {
return prompt; return prompt;
} }
/** Beware, in this implementation this is the same as closing the manager.
*
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */
@Override
public void interruptPrompt() {
reading.interrupt();
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#isClosed() */
@Override
public boolean isClosed() {
return closed;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#print(java.lang.Object) */ * @see fr.bigeon.gclc.ConsoleManager#print(java.lang.Object) */
@Override @Override
public void print(String object) throws IOException { public void print(final String object) throws IOException {
checkOpen(); checkOpen();
out.print(object); out.print(object);
} }
/** @throws IOException if the stream was closed */
private void checkOpen() throws IOException {
if (closed) {
throw new IOException();
}
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#println() */ * @see fr.bigeon.gclc.ConsoleManager#println() */
@Override @Override
@ -124,7 +149,7 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#println(java.lang.Object) */ * @see fr.bigeon.gclc.ConsoleManager#println(java.lang.Object) */
@Override @Override
public void println(String object) throws IOException { public void println(final String object) throws IOException {
checkOpen(); checkOpen();
out.println(object); out.println(object);
} }
@ -139,14 +164,14 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */ * @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */
@Override @Override
public String prompt(long timeout) throws IOException { public String prompt(final long timeout) throws IOException {
return prompt(prompt, timeout); return prompt(prompt, timeout);
} }
/* (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(String message) throws IOException { public String prompt(final String message) throws IOException {
checkOpen(); checkOpen();
out.print(message); out.print(message);
return reading.getMessage(); return reading.getMessage();
@ -155,7 +180,7 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR
/* (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(String message, 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);
@ -163,32 +188,8 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR
/** @param prompt the prompt to set */ /** @param prompt the prompt to set */
@Override @Override
public void setPrompt(String prompt) { public void setPrompt(final String prompt) {
this.prompt = prompt; this.prompt = prompt;
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#close() */
@Override
public void close() throws IOException {
closed = true;
reading.setRunning(false);
promptThread.interrupt();
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#isClosed() */
@Override
public boolean isClosed() {
return closed;
}
/** Beware, in this implementation this is the same as closing the manager.
*
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */
@Override
public void interruptPrompt() {
reading.interrupt();
}
} }

View File

@ -52,7 +52,7 @@ import java.util.logging.Logger;
* Messages are queued to be retrieved latter on. * Messages are queued to be retrieved latter on.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public 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;
@ -73,12 +73,31 @@ public class WritingRunnable implements Runnable {
/** @param outPrint the output to print to /** @param outPrint the output to print to
* @param charset the charset of the stream */ * @param charset the charset of the stream */
public WritingRunnable(OutputStream outPrint, Charset charset) { public WritingRunnable(final OutputStream outPrint, final Charset charset) {
super(); super();
this.outPrint = outPrint; this.outPrint = outPrint;
this.charset = charset; this.charset = charset;
} }
/** @param message the message
* @throws IOException if the pipe is closed */
public void addMessage(final String message) throws IOException {
synchronized (lock) {
if (!running) {
throw new IOException("Closed pipe"); //$NON-NLS-1$
}
messages.offer(message);
lock.notifyAll();
}
}
/** @return the running */
public boolean isRunning() {
synchronized (lock) {
return running;
}
}
/* (non-Javadoc) /* (non-Javadoc)
* @see java.lang.Runnable#run() */ * @see java.lang.Runnable#run() */
@Override @Override
@ -89,21 +108,22 @@ public class WritingRunnable implements Runnable {
while (messages.isEmpty()) { while (messages.isEmpty()) {
try { try {
lock.wait(TIMEOUT); lock.wait(TIMEOUT);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
LOGGER.log(Level.SEVERE, LOGGER.log(Level.SEVERE,
"Thread interruption exception.", e); //$NON-NLS-1$ "Thread interruption exception.", e); //$NON-NLS-1$
Thread.currentThread().interrupt();
} }
if (!running) { if (!running) {
return; return;
} }
} }
String message = messages.poll(); final String message = messages.poll();
ByteBuffer buff = charset final ByteBuffer buff = charset
.encode(message + System.lineSeparator()); .encode(message + System.lineSeparator());
if (buff.hasArray()) { if (buff.hasArray()) {
try { try {
outPrint.write(buff.array()); outPrint.write(buff.array());
} catch (IOException e) { } catch (final IOException e) {
LOGGER.log(Level.SEVERE, "Unable to write to stream", //$NON-NLS-1$ LOGGER.log(Level.SEVERE, "Unable to write to stream", //$NON-NLS-1$
e); e);
} }
@ -112,29 +132,10 @@ public class WritingRunnable implements Runnable {
} }
} }
/** @param message the message
* @throws IOException if the pipe is closed */
public void addMessage(String message) throws IOException {
synchronized (lock) {
if (!running) {
throw new IOException("Closed pipe"); //$NON-NLS-1$
}
messages.offer(message);
lock.notify();
}
}
/** @param running the running to set */ /** @param running the running to set */
public void setRunning(boolean running) { public void setRunning(final boolean running) {
synchronized (lock) { synchronized (lock) {
this.running = running; this.running = running;
} }
} }
/** @return the running */
public boolean isRunning() {
synchronized (lock) {
return running;
}
}
} }

View File

@ -0,0 +1,42 @@
/*
* Copyright Bigeon Emmanuel (2014)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a generic framework for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
/**
* gclc:fr.bigeon.gclc.package-info.java
* Created on: Nov 5, 2017
*/
/** A framework for commad line applications.
*
* @author Emmanuel Bigeon */
package fr.bigeon.gclc;

View File

@ -39,37 +39,41 @@
package fr.bigeon.gclc.proc; package fr.bigeon.gclc.proc;
import fr.bigeon.gclc.command.Command; import fr.bigeon.gclc.command.Command;
import fr.bigeon.gclc.exception.CommandRunException;
/** A command that will flag a task to stop /** A command that will flag a task to stop
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class ProcessKill extends Command { public final class ProcessKill extends Command {
/** The taskpool */ /** The taskpool */
private final TaskPool pool; private final TaskPool pool;
/** @param name the command name /** @param name the command name
* @param pool the pool */ * @param pool the pool */
public ProcessKill(String name, TaskPool pool) { public ProcessKill(final String name, final TaskPool pool) {
super(name); super(name);
this.pool = pool; this.pool = pool;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */
*/
@Override @Override
public void execute(String... args) throws CommandRunException { public void execute(final String... args) {
pool.get(args[0]).setRunning(false); pool.get(args[0]).setRunning(false);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#tip() * @see fr.bigeon.gclc.command.ICommand#tip() */
*/
@SuppressWarnings("nls") @SuppressWarnings("nls")
@Override @Override
public String tip() { public String tip() {
return "Request a process to stop (softly)"; return "Request a process to stop (softly)";
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail() */
@Override
protected String usageDetail() {
return null;
}
} }

View File

@ -51,7 +51,7 @@ import fr.bigeon.gclc.manager.ConsoleManager;
/** A command to list current processes /** A command to list current processes
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class ProcessList extends Command { public final class ProcessList extends Command {
/** The process pool */ /** The process pool */
private final TaskPool pool; private final TaskPool pool;
@ -61,26 +61,24 @@ public class ProcessList extends Command {
/** @param name the command name /** @param name the command name
* @param pool the pool * @param pool the pool
* @param manager the console manager */ * @param manager the console manager */
public ProcessList(String name, TaskPool pool, public ProcessList(final String name, final TaskPool pool,
ConsoleManager manager) { final ConsoleManager manager) {
super(name); super(name);
this.pool = pool; this.pool = pool;
this.manager = manager; this.manager = manager;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */
*/
@Override @Override
public void execute(String... args) throws CommandRunException { public void execute(final String... args) throws CommandRunException {
ArrayList<String> pids = new ArrayList<>(pool.getPIDs()); final ArrayList<String> pids = new ArrayList<>(pool.getPIDs());
Collections.sort(pids); Collections.sort(pids);
for (String string : pids) { for (final String string : pids) {
try { try {
manager.println( manager.println(MessageFormat.format("{0}\t{1}", string, //$NON-NLS-1$
MessageFormat.format("{0}\t{1}", string, //$NON-NLS-1$ pool.get(string).getName()));
pool.get(string).getName())); } catch (final IOException e) {
} catch (IOException e) {
throw new CommandRunException( throw new CommandRunException(
CommandRunExceptionType.INTERACTION, CommandRunExceptionType.INTERACTION,
"Unable to communicate with user", e, this); //$NON-NLS-1$ "Unable to communicate with user", e, this); //$NON-NLS-1$
@ -90,12 +88,18 @@ public class ProcessList extends Command {
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#tip() * @see fr.bigeon.gclc.command.ICommand#tip() */
*/
@SuppressWarnings("nls") @SuppressWarnings("nls")
@Override @Override
public String tip() { public String tip() {
return "List all processes"; return "List all processes";
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail() */
@Override
protected String usageDetail() {
return null;
}
} }

View File

@ -50,12 +50,26 @@ package fr.bigeon.gclc.proc;
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public interface Task extends Runnable { public interface Task extends Runnable {
/** @return the task name */ /** Add a listener for this command end of execution
public String getName(); *
* @param listener the listener */
void addInterruptionListener(InterruptionListener listener);
/** @return if the command is supposed to be running */ /** Get the task name.
*
* @return the task name */
String getName();
/** Test the running status of the task.
*
* @return if the command is supposed to be running */
boolean isRunning(); boolean isRunning();
/** Remove a listener of this command end of execution
*
* @param listener the listener */
void rmInterruptionListener(InterruptionListener listener);
/** Set the running state. /** Set the running state.
* <p> * <p>
* This method should be only called by external objects with the false * This method should be only called by external objects with the false
@ -64,14 +78,4 @@ public interface Task extends Runnable {
* *
* @param running the running state */ * @param running the running state */
void setRunning(boolean running); void setRunning(boolean running);
/** Add a listener for this command end of execution
*
* @param listener the listener */
void addInterruptionListener(InterruptionListener listener);
/** Remove a listener of this command end of execution
*
* @param listener the listener */
void rmInterruptionListener(InterruptionListener listener);
} }

View File

@ -43,24 +43,29 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
/** A process pool /** A process pool.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class TaskPool { public final class TaskPool {
/** The running processes */ /** The running processes. */
private final Map<String, Task> running = new HashMap<>(); private final Map<String, Task> running = new HashMap<>();
/** The count for process id */ /** The count for process id. */
private int count = 0; private int count = 0;
/** The lock for pid attribution synchronization */ /** The lock for pid attribution synchronization. */
private final Object lock = new Object(); private final Object lock = new Object();
/** Add a process in the pool /** Default constructor. */
public TaskPool() {
//
}
/** Add a process in the pool.
* *
* @param cmd the process * @param cmd the process
* @return the pid */ * @return the pid */
public String add(final Task cmd) { public String add(final Task cmd) {
if (cmd == null) { if (cmd == null) {
throw new NullPointerException("Task cannot be null"); //$NON-NLS-1$ throw new IllegalArgumentException("Task cannot be null"); //$NON-NLS-1$
} }
final String pid = getPID(); final String pid = getPID();
synchronized (lock) { synchronized (lock) {
@ -81,7 +86,19 @@ public class TaskPool {
return pid; return pid;
} }
/** @return the process id */ /** Get a process by it associated identifier.
*
* @param pid the task id
* @return the task, if any, associated to this id */
public Task get(final String pid) {
synchronized (lock) {
return running.get(pid);
}
}
/** Get the next process id.
*
* @return the process id */
private String getPID() { private String getPID() {
synchronized (lock) { synchronized (lock) {
String pid; String pid;
@ -92,17 +109,9 @@ public class TaskPool {
} }
} }
/** Get a process by it associated identifier /** Get the running processes' identifiers.
* *
* @param pid the task id * @return the pids */
* @return the task, if any, associated to this id */
public Task get(String pid) {
synchronized (lock) {
return running.get(pid);
}
}
/** @return the pids */
public Collection<String> getPIDs() { public Collection<String> getPIDs() {
return new HashSet<>(running.keySet()); return new HashSet<>(running.keySet());
} }

View File

@ -39,7 +39,6 @@
package fr.bigeon.gclc.proc; package fr.bigeon.gclc.proc;
import fr.bigeon.gclc.command.Command; import fr.bigeon.gclc.command.Command;
import fr.bigeon.gclc.exception.CommandRunException;
/** An abstract command to generate a task and return the control to the user /** An abstract command to generate a task and return the control to the user
* *
@ -50,23 +49,23 @@ public abstract class TaskSpawner extends Command {
/** @param name the command name /** @param name the command name
* @param pool the pool */ * @param pool the pool */
public TaskSpawner(String name, TaskPool pool) { public TaskSpawner(final String name, final TaskPool pool) {
super(name); super(name);
this.pool = pool; this.pool = pool;
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[])
*/
@Override
public final void execute(String... args) throws CommandRunException {
Task task = createTask(args);
Thread th = new Thread(task);
th.start();
pool.add(task);
}
/** @param args the arguments /** @param args the arguments
* @return the process to start and add to the pool */ * @return the process to start and add to the pool */
protected abstract Task createTask(String... args); protected abstract Task createTask(String... args);
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[])
*/
@Override
public final void execute(final String... args) {
final Task task = createTask(args);
final Thread th = new Thread(task);
th.start();
pool.add(task);
}
} }

View File

@ -45,13 +45,18 @@ import java.util.logging.Logger;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
/** <p> /**
* <p>
* The {@link CLIPrompter} class is a utility class that provides method to * 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 class CLIPrompter { public final class CLIPrompter {
/**
*
*/
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 */
@ -77,14 +82,34 @@ public class CLIPrompter {
// Utility class // Utility class
} }
/** @param val the string to parse
* @param chs the list of integers
* @param index the max index of choice
* @return if the parsing was done correctly */
private static boolean addUserChoice(final String val,
final List<Integer> chs,
final int index) {
if (val.isEmpty()) {
return true;
}
final int r;
r = Integer.parseInt(val);
if (r >= 0 && r <= index) {
chs.add(Integer.valueOf(r));
return true;
}
return false;
}
/** @param manager the manager /** @param manager 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
* is a cancel) * is a cancel)
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
private static <U> int listChoices(ConsoleManager manager, List<U> choices, private static <U> Integer listChoices(final ConsoleManager manager,
String cancel) throws IOException { final List<U> choices,
final String cancel) throws IOException {
int index = 0; int index = 0;
for (final U u : choices) { for (final U u : choices) {
manager.println(index++ + ") " + u); //$NON-NLS-1$ manager.println(index++ + ") " + u); //$NON-NLS-1$
@ -92,15 +117,15 @@ public class CLIPrompter {
if (cancel != null) { if (cancel != null) {
manager.println(index++ + ") " + cancel); //$NON-NLS-1$ manager.println(index++ + ") " + cancel); //$NON-NLS-1$
} }
return index - 1; return Integer.valueOf(index - 1);
} }
/** @param manager the manager /** @param manager the manager
* @param message the prompting message * @param message the prompting message
* @return the choice * @return the choice
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
public static boolean promptBoolean(ConsoleManager manager, public static boolean promptBoolean(final ConsoleManager manager,
String message) throws IOException { final String message) throws IOException {
String result = manager String result = manager
.prompt(message + CLIPrompterMessages.getString(BOOL_CHOICES)); .prompt(message + CLIPrompterMessages.getString(BOOL_CHOICES));
boolean first = true; boolean first = true;
@ -140,9 +165,11 @@ public class CLIPrompter {
* @return the choice * @return the choice
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
@SuppressWarnings("boxing") @SuppressWarnings("boxing")
public static <U> U promptChoice(ConsoleManager manager, List<String> keys, public static <U> U promptChoice(final ConsoleManager manager,
List<U> choices, String message, final List<String> keys,
String cancel) throws IOException { final List<U> choices,
final String message,
final String cancel) throws IOException {
final Integer index = promptChoice(manager, keys, message, cancel); final Integer index = promptChoice(manager, keys, message, cancel);
if (index == null) { if (index == null) {
return null; return null;
@ -159,10 +186,12 @@ public class CLIPrompter {
* @param cancel the cancel option if it exists (null otherwise) * @param cancel the cancel option if it exists (null otherwise)
* @return the chosen object * @return the chosen object
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
public static <U, T> T promptChoice(ConsoleManager manager, List<U> choices, public static <U, T> T promptChoice(final ConsoleManager manager,
Map<U, T> choicesMap, String message, final List<U> choices,
String cancel) throws IOException { final Map<U, T> choicesMap,
Integer res = promptChoice(manager, choices, message, cancel); final String message,
final String cancel) throws IOException {
final Integer res = promptChoice(manager, choices, message, cancel);
if (res == null) { if (res == null) {
return null; return null;
} }
@ -176,40 +205,38 @@ public class CLIPrompter {
* @param cancel the cancel option, or null * @param cancel the cancel option, or null
* @return the index of the choice * @return the index of the choice
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
@SuppressWarnings("boxing") public static <U> Integer promptChoice(final ConsoleManager manager,
public static <U> Integer promptChoice(ConsoleManager manager, final List<U> choices,
List<U> choices, String message, final String message,
String cancel) throws IOException { final String cancel) throws IOException {
manager.println(message); manager.println(message);
final int index = listChoices(manager, choices, cancel); final Integer index = listChoices(manager, choices, cancel);
String result = ""; //$NON-NLS-1$ String result;
boolean keepOn = true; boolean keepOn = true;
int r = -1; int r = -1;
while (keepOn) { while (keepOn) {
result = manager.prompt(CLIPrompterMessages.getString(PROMPT)); result = manager.prompt(CLIPrompterMessages.getString(PROMPT));
try { try {
r = Integer.parseInt(result); r = Integer.parseInt(result);
if (r >= 0 && r <= index) { if (r >= 0 && r <= index.intValue()) {
keepOn = false; keepOn = false;
} else { break;
manager.println(CLIPrompterMessages
.getString(PROMPTCHOICE_OUTOFBOUNDS, 0, index));
listChoices(manager, choices, cancel);
} }
manager.println(CLIPrompterMessages
.getString(PROMPTCHOICE_OUTOFBOUNDS, ZERO, index));
} 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; keepOn = true;
manager.println(CLIPrompterMessages manager.println(CLIPrompterMessages
.getString(PROMPTCHOICE_FORMATERR, 0, index)); .getString(PROMPTCHOICE_FORMATERR, ZERO, index));
listChoices(manager, choices, cancel);
} }
listChoices(manager, choices, cancel);
} }
if (r == index && cancel != null) { if (r == index.intValue() && cancel != null) {
return null; return null;
} }
return r; return Integer.valueOf(r);
} }
/** @param manager the manager /** @param manager the manager
@ -220,9 +247,10 @@ public class CLIPrompter {
* @param cancel the cancel option (or null) * @param cancel the cancel option (or null)
* @return the chosen object * @return the chosen object
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
public static <U, T> T promptChoice(ConsoleManager manager, public static <U, T> T promptChoice(final ConsoleManager manager,
Map<U, T> choicesMap, String message, final Map<U, T> choicesMap,
String cancel) throws IOException { final String message,
final String cancel) throws IOException {
return promptChoice(manager, new ArrayList<>(choicesMap.keySet()), return promptChoice(manager, new ArrayList<>(choicesMap.keySet()),
choicesMap, message, cancel); choicesMap, message, cancel);
} }
@ -231,8 +259,8 @@ public class CLIPrompter {
* @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 */
public static int promptInteger(ConsoleManager manager, public static int promptInteger(final ConsoleManager manager,
String message) throws IOException { final String message) throws IOException {
boolean still = true; boolean still = true;
int r = 0; int r = 0;
while (still) { while (still) {
@ -259,8 +287,8 @@ public class CLIPrompter {
* @param message the message * @param message the message
* @return the list of user inputs * @return the list of user inputs
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
public static List<String> promptList(ConsoleManager manager, public static List<String> promptList(final ConsoleManager manager,
String message) throws IOException { final String message) throws IOException {
return promptList(manager, message, return promptList(manager, message,
CLIPrompterMessages.getString("promptlist.exit.defaultkey")); //$NON-NLS-1$ CLIPrompterMessages.getString("promptlist.exit.defaultkey")); //$NON-NLS-1$
} }
@ -272,9 +300,9 @@ public class CLIPrompter {
* @param ender the ending sequence for the list * @param ender the ending sequence for the list
* @return the list of user inputs * @return the list of user inputs
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
public static List<String> promptList(ConsoleManager manager, public static List<String> promptList(final ConsoleManager manager,
String message, final String message,
String ender) throws IOException { final String ender) throws IOException {
final List<String> strings = new ArrayList<>(); final List<String> strings = new ArrayList<>();
manager.println( manager.println(
message + CLIPrompterMessages.getString(LIST_DISP_KEY, ender)); message + CLIPrompterMessages.getString(LIST_DISP_KEY, ender));
@ -294,8 +322,8 @@ public class CLIPrompter {
* @param message the prompting message * @param message the prompting message
* @return the text * @return the text
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
public static String promptLongText(ConsoleManager manager, public static String promptLongText(final ConsoleManager manager,
String message) throws IOException { final String message) throws IOException {
return promptLongText(manager, message, CLIPrompterMessages return promptLongText(manager, message, CLIPrompterMessages
.getString("promptlongtext.exit.defaultkey")); //$NON-NLS-1$ .getString("promptlongtext.exit.defaultkey")); //$NON-NLS-1$
} }
@ -307,19 +335,21 @@ public class CLIPrompter {
* @param ender the ender character * @param ender the ender character
* @return the text * @return the text
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
public static String promptLongText(ConsoleManager manager, String message, public static String promptLongText(final ConsoleManager manager,
String ender) throws IOException { final String message,
final String ender) throws IOException {
manager.println(message + CLIPrompterMessages manager.println(message + CLIPrompterMessages
.getString("promptlongtext.exit.dispkey", ender)); //$NON-NLS-1$ .getString("promptlongtext.exit.dispkey", ender)); //$NON-NLS-1$
String res = manager.prompt(CLIPrompterMessages.getString(PROMPT)); final StringBuilder res = new StringBuilder();
String line = res; String line;
while (!line.equals(ender)) { do {
line = manager.prompt(CLIPrompterMessages.getString(PROMPT)); line = manager.prompt(CLIPrompterMessages.getString(PROMPT));
if (!line.equals(ender)) { if (!line.equals(ender)) {
res += System.lineSeparator() + line; res.append(line);
res.append(System.lineSeparator());
} }
} } while (!line.equals(ender));
return res.equals(ender) ? "" : res; //$NON-NLS-1$ return res.toString();
} }
/** @param manager the manager /** @param manager the manager
@ -329,10 +359,10 @@ public 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 */
public static <U> List<U> promptMultiChoice(ConsoleManager manager, public static <U> List<U> promptMultiChoice(final ConsoleManager manager,
List<String> keys, final List<String> keys,
List<U> choices, final List<U> choices,
String message) throws IOException { final String message) throws IOException {
final List<Integer> indices = promptMultiChoice(manager, keys, message); final List<Integer> indices = promptMultiChoice(manager, keys, message);
final List<U> userChoices = new ArrayList<>(); final List<U> userChoices = new ArrayList<>();
for (final Integer integer : indices) { for (final Integer integer : indices) {
@ -349,10 +379,10 @@ public class CLIPrompter {
* @param message the prompting message * @param message the prompting message
* @return the chosen objects (or an empty list) * @return the chosen objects (or an empty list)
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
public static <U, T> List<T> promptMultiChoice(ConsoleManager manager, public static <U, T> List<T> promptMultiChoice(final ConsoleManager manager,
List<U> choices, final List<U> choices,
Map<U, T> choicesMap, final Map<U, T> choicesMap,
String message) throws IOException { final String message) throws IOException {
final List<Integer> chs = promptMultiChoice(manager, choices, message); final List<Integer> chs = promptMultiChoice(manager, choices, message);
final List<T> userChoices = new ArrayList<>(); final List<T> userChoices = new ArrayList<>();
for (final Integer integer : chs) { for (final Integer integer : chs) {
@ -367,13 +397,12 @@ public class CLIPrompter {
* @param message the prompting message * @param message the prompting message
* @return the indices of the choices * @return the indices of the choices
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
@SuppressWarnings("boxing") public static <U> List<Integer> promptMultiChoice(final ConsoleManager manager,
public static <U> List<Integer> promptMultiChoice(ConsoleManager manager, final List<U> choices,
List<U> choices, final String message) throws IOException {
String message) throws IOException {
manager.println(message); manager.println(message);
final int index = listChoices(manager, choices, null); final Integer index = listChoices(manager, choices, null);
String result = ""; //$NON-NLS-1$ String result;
boolean keepOn = true; boolean keepOn = true;
final List<Integer> chs = new ArrayList<>(); final List<Integer> chs = new ArrayList<>();
while (keepOn) { while (keepOn) {
@ -384,19 +413,19 @@ public class CLIPrompter {
for (final String val : vals) { for (final String val : vals) {
boolean added; boolean added;
try { try {
added = addUserChoice(val, chs, index); added = addUserChoice(val, chs, index.intValue());
} 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; keepOn = true;
manager.println(CLIPrompterMessages manager.println(CLIPrompterMessages
.getString(PROMPTCHOICE_FORMATERR, 0, index)); .getString(PROMPTCHOICE_FORMATERR, ZERO, index));
listChoices(manager, choices, null); listChoices(manager, choices, null);
break; break;
} }
if (!added) { if (!added) {
manager.println(CLIPrompterMessages manager.println(CLIPrompterMessages
.getString(PROMPTCHOICE_OUTOFBOUNDS, 0, index)); .getString(PROMPTCHOICE_OUTOFBOUNDS, ZERO, index));
listChoices(manager, choices, null); listChoices(manager, choices, null);
keepOn = true; keepOn = true;
} }
@ -405,24 +434,6 @@ public class CLIPrompter {
return chs; return chs;
} }
/** @param val the string to parse
* @param chs the list of integers
* @param index the max index of choice
* @return if the parsing was done correctly */
private static boolean addUserChoice(String val, List<Integer> chs,
int index) {
if (val.isEmpty()) {
return true;
}
final int r;
r = Integer.parseInt(val);
if (r >= 0 && r <= index) {
chs.add(Integer.valueOf(r));
return true;
}
return false;
}
/** @param manager the manager /** @param manager the manager
* @param <U> The choices labels type * @param <U> The choices labels type
* @param <T> The real choices objects * @param <T> The real choices objects
@ -430,9 +441,9 @@ public class CLIPrompter {
* @param message the prompting message * @param message the prompting message
* @return the chosen objects * @return the chosen objects
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
public static <U, T> List<T> promptMultiChoice(ConsoleManager manager, public static <U, T> List<T> promptMultiChoice(final ConsoleManager manager,
Map<U, T> choicesMap, final Map<U, T> choicesMap,
String message) throws IOException { final String message) throws IOException {
return promptMultiChoice(manager, new ArrayList<>(choicesMap.keySet()), return promptMultiChoice(manager, new ArrayList<>(choicesMap.keySet()),
choicesMap, message); choicesMap, message);
} }
@ -442,8 +453,9 @@ public class CLIPrompter {
* @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
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
public static String promptNonEmpty(ConsoleManager manager, String prompt, public static String promptNonEmpty(final ConsoleManager manager,
String reprompt) throws IOException { final String prompt,
final String reprompt) throws IOException {
String res = manager.prompt(prompt); String res = manager.prompt(prompt);
while (res.isEmpty()) { while (res.isEmpty()) {
res = manager.prompt(reprompt); res = manager.prompt(reprompt);

View File

@ -48,7 +48,7 @@ import java.util.logging.Logger;
* Utility class for the messages of the CLIPrompter * Utility class for the messages of the CLIPrompter
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public 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$
@ -70,7 +70,7 @@ public class CLIPrompterMessages {
* @param key the message's key * @param key the message's key
* @param args the arguments * @param args the arguments
* @return the formatted message */ * @return the formatted message */
public static String getString(String key, Object... args) { public static String getString(final String key, final Object... args) {
try { try {
return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args); return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args);
} catch (final MissingResourceException e) { } catch (final MissingResourceException e) {

View File

@ -61,6 +61,15 @@ public abstract class AOutputForwardRunnable implements Runnable {
/** The timeout */ /** The timeout */
private final long timeout; private final long timeout;
/** Create a forwarding runnable.
*
* @param manager the manager */
public AOutputForwardRunnable(final PipedConsoleManager manager) {
super();
this.manager = manager;
timeout = DEFAULT_TIMEOUT;
}
/** Create a forward runnable with the given timeout. /** Create a forward runnable with the given timeout.
* <p> * <p>
* Short timeout will be very responsive to the application actual messages, * Short timeout will be very responsive to the application actual messages,
@ -74,56 +83,47 @@ public abstract class AOutputForwardRunnable implements Runnable {
* *
* @param manager the manager * @param manager the manager
* @param timeout the timeout between message requests. */ * @param timeout the timeout between message requests. */
public AOutputForwardRunnable(PipedConsoleManager manager, long timeout) { public AOutputForwardRunnable(final PipedConsoleManager manager, final long timeout) {
super(); super();
this.manager = manager; this.manager = manager;
this.timeout = timeout; this.timeout = timeout;
} }
/** Create a forwarding runnable.
*
* @param manager the manager */
public AOutputForwardRunnable(PipedConsoleManager manager) {
super();
this.manager = manager;
timeout = DEFAULT_TIMEOUT;
}
@Override
public void run() {
try {
while (isRunning()) {
while (isRunning() && !manager.available()) {
waitASec();
}
if (!isRunning()) {
return;
}
String m = manager.readNextLine();
forwardLine(m);
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Unexpected problem in manager", //$NON-NLS-1$
e);
}
}
/** @param m the line to forward */ /** @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 */ /** @return if the thread should keep running */
protected abstract boolean isRunning(); protected abstract boolean isRunning();
/** a method to wait some time */ @Override
protected void waitASec() { public final void run() {
try {
while (isRunning()) {
while (isRunning() && !manager.available()) {
waitASec();
}
if (!isRunning()) {
return;
}
final String m = manager.readNextLine();
forwardLine(m);
}
} catch (final IOException e) {
LOGGER.log(Level.SEVERE, "Unexpected problem in manager", //$NON-NLS-1$
e);
}
}
/** a method to wait some time. */
protected final void waitASec() {
try { try {
synchronized (this) { synchronized (this) {
wait(timeout); wait(timeout);
} }
} catch (InterruptedException e) { } catch (final InterruptedException e) {
LOGGER.log(Level.SEVERE, "Interrupted wait", //$NON-NLS-1$ LOGGER.log(Level.SEVERE, "Interrupted wait", //$NON-NLS-1$
e); e);
return; Thread.currentThread().interrupt();
} }
} }

View File

@ -44,7 +44,7 @@ import java.util.List;
/** A tool class for printing text in a console. /** A tool class for printing text in a console.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public 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$
@ -63,37 +63,37 @@ public class PrintUtils {
* @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
* @return the text to print (will be of exactly nbCharacters). */ * @return the text to print (will be of exactly nbCharacters). */
public static String print(String text, int nbCharacters, public static String print(final String text, final int nbCharacters,
boolean indicateTooLong) { final boolean indicateTooLong) {
String res = text; StringBuilder res = new StringBuilder(text);
if (res.length() > nbCharacters) { if (res.length() > nbCharacters) {
// Cut // Cut
if (indicateTooLong) { if (indicateTooLong) {
// With suspension dots // With suspension dots
res = res.substring(0, nbCharacters - CONT_DOT_LENGTH) + res = res.replace(nbCharacters - CONT_DOT_LENGTH, text.length(),
CONT_DOT; CONT_DOT);
} else { } else {
res = res.substring(0, nbCharacters); res = res.replace(nbCharacters, text.length(), ""); //$NON-NLS-1$
} }
} }
while (res.length() < nbCharacters) { while (res.length() < nbCharacters) {
// Add trailing space // Add trailing space
res = res + ' '; res.append(' ');
} }
return res; return res.toString();
} }
/** @param description the element to wrap in lines /** @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(String description, int i) { public static List<String> wrap(final String description, final int i) {
final String[] originalLines = description final String[] originalLines = description
.split(System.lineSeparator()); .split(System.lineSeparator());
final List<String> result = new ArrayList<>(); final List<String> result = new ArrayList<>();
for (final String string : originalLines) { for (final String string : originalLines) {
String toCut = string; String toCut = string;
while (toCut.length() > i) { while (toCut.length() > i) {
int index = toCut.lastIndexOf(" ", i); //$NON-NLS-1$ int index = toCut.lastIndexOf(' ', i);
if (index == -1) { if (index == -1) {
result.add(toCut.substring(0, i)); result.add(toCut.substring(0, i));
index = i - 1; index = i - 1;

View File

@ -69,19 +69,19 @@ public class ConsoleApplicationTest {
/** Test the base of a console application */ /** Test the base of a console application */
@Test @Test
public void test() { public void testConsoleApplication() {
try (PipedConsoleManager manager = new PipedConsoleManager()) { try (PipedConsoleManager manager = new PipedConsoleManager()) {
ConsoleApplication app = new ConsoleApplication(manager, "", ""); final ConsoleApplication app = new ConsoleApplication(manager, "", "");
app.exit(); app.exit();
} catch (IOException e) { } catch (final IOException e) {
fail("System Console Manager failed"); fail("System Console Manager failed");
} }
} }
@Test @Test
public void executionTest() { public void testExecution() {
try (CommandTestingApplication application = new CommandTestingApplication()) { try (CommandTestingApplication application = new CommandTestingApplication()) {
// remove welcome // remove welcome
@ -106,17 +106,17 @@ public class ConsoleApplicationTest {
assertEquals("Waita minute", application.readNextLine()); assertEquals("Waita minute", application.readNextLine());
assertEquals("done!", application.readNextLine()); assertEquals("done!", application.readNextLine());
CommandRequestListener crl = new CommandRequestListener() { final CommandRequestListener crl = new CommandRequestListener() {
@Override @Override
public void commandRequest(String command) { public void commandRequest(final String command) {
// //
} }
}; };
CommandRequestListener crl2 = new CommandRequestListener() { final CommandRequestListener crl2 = new CommandRequestListener() {
@Override @Override
public void commandRequest(String command) { public void commandRequest(final String command) {
// //
} }
}; };
@ -136,7 +136,7 @@ public class ConsoleApplicationTest {
assertEquals(application.getApplication().footer, assertEquals(application.getApplication().footer,
application.readNextLine()); application.readNextLine());
assertFalse(application.getApplication().isRunning()); assertFalse(application.getApplication().isRunning());
} catch (IOException e1) { } catch (final IOException e1) {
assertNull(e1); assertNull(e1);
} }
@ -147,7 +147,7 @@ public class ConsoleApplicationTest {
appli = app; appli = app;
app.add(new ExitCommand("exit", app)); app.add(new ExitCommand("exit", app));
Thread th = new Thread(new Runnable() { final Thread th = new Thread(new Runnable() {
@SuppressWarnings("synthetic-access") @SuppressWarnings("synthetic-access")
@Override @Override
@ -174,9 +174,9 @@ public class ConsoleApplicationTest {
} }
@Test @Test
public void interpretCommandTest() { public void testInterpretCommand() {
try (PipedConsoleManager test = new PipedConsoleManager()) { try (PipedConsoleManager test = new PipedConsoleManager()) {
ConsoleApplication appl = new ConsoleApplication(test, "", ""); final ConsoleApplication appl = new ConsoleApplication(test, "", "");
appl.interpretCommand("invalid cmd \"due to misplaced\"quote"); appl.interpretCommand("invalid cmd \"due to misplaced\"quote");
assertEquals("Command line cannot be parsed", test.readNextLine()); assertEquals("Command line cannot be parsed", test.readNextLine());
@ -188,7 +188,7 @@ public class ConsoleApplicationTest {
appl.add(new ICommand() { appl.add(new ICommand() {
@Override @Override
public void execute(String... args) throws CommandRunException { public void execute(final String... args) throws CommandRunException {
throw new CommandRunException( throw new CommandRunException(
CommandRunExceptionType.USAGE, message, this); CommandRunExceptionType.USAGE, message, this);
} }
@ -199,8 +199,8 @@ public class ConsoleApplicationTest {
} }
@Override @Override
public void help(ConsoleManager manager, public void help(final ConsoleManager manager,
String... args) throws IOException { final String... args) throws IOException {
manager.println(message); manager.println(message);
} }
@ -210,7 +210,7 @@ public class ConsoleApplicationTest {
} }
}); });
} catch (InvalidCommandName e) { } catch (final InvalidCommandName e) {
assertNull(e); assertNull(e);
} }
appl.interpretCommand("fail"); appl.interpretCommand("fail");
@ -220,7 +220,7 @@ public class ConsoleApplicationTest {
assertEquals(message, test.readNextLine()); assertEquals(message, test.readNextLine());
assertEquals(message, test.readNextLine()); assertEquals(message, test.readNextLine());
} catch (IOException e) { } catch (final IOException e) {
assertNull(e); assertNull(e);
} }
} }

View File

@ -62,44 +62,41 @@ public class ConsoleTestApplication implements ApplicationAttachement {
application.root)); application.root));
application.add(new Command("test") { application.add(new Command("test") {
@Override
public void execute(final String... args) throws CommandRunException {
try {
application.manager.println("Test command ran fine");
} catch (final IOException e) {
throw new CommandRunException("manager closed", e,
this);
}
}
@Override @Override
public String tip() { public String tip() {
return "A test command"; return "A test command";
} }
@Override @Override
public void execute(String... args) throws CommandRunException { protected String usageDetail() {
try { return null;
application.manager.println("Test command ran fine");
} catch (IOException e) {
throw new CommandRunException("manager closed", e,
this);
}
} }
}); });
application.add(new Command("long") { application.add(new Command("long") {
@Override @Override
public String tip() { public void execute(final String... args) throws CommandRunException {
return "A long execution command";
}
@Override
public void execute(String... args) throws CommandRunException {
try { try {
application.manager.println("Waita minute"); application.manager.println("Waita minute");
Thread.sleep(TWO_SECONDS); Thread.sleep(TWO_SECONDS);
application.manager.println("done!"); application.manager.println("done!");
} catch (IOException e) { } catch (final IOException e) {
throw new CommandRunException("manager closed", e, throw new CommandRunException("manager closed", e,
this); this);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
throw new CommandRunException("wait interrupted", e, throw new CommandRunException("wait interrupted", e,
this); this);
} }
} }
});
application.add(new Command("failingCmd") {
@Override @Override
public String tip() { public String tip() {
@ -107,9 +104,25 @@ public class ConsoleTestApplication implements ApplicationAttachement {
} }
@Override @Override
public void execute(String... args) throws CommandRunException { protected String usageDetail() {
return null;
}
});
application.add(new Command("failingCmd") {
@Override
public void execute(final String... args) throws CommandRunException {
throw new CommandRunException("Failing command", this); throw new CommandRunException("Failing command", this);
} }
@Override
public String tip() {
return "A long execution command";
}
@Override
protected String usageDetail() {
return null;
}
}); });
} catch (final InvalidCommandName e) { } catch (final InvalidCommandName e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -61,7 +61,7 @@ public class GCLCConstantsTest {
List<String> res; List<String> res;
try { try {
res = GCLCConstants.splitCommand("aCommand"); res = GCLCConstants.splitCommand("aCommand");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
fail("Unable to parse simple command " + e.getLocalizedMessage()); //$NON-NLS-1$ fail("Unable to parse simple command " + e.getLocalizedMessage()); //$NON-NLS-1$
return; return;
} }
@ -70,7 +70,7 @@ public class GCLCConstantsTest {
try { try {
res = GCLCConstants.splitCommand("aCommand with some arguments"); res = GCLCConstants.splitCommand("aCommand with some arguments");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
fail("Unable to parse command with arguments " + //$NON-NLS-1$ fail("Unable to parse command with arguments " + //$NON-NLS-1$
e.getLocalizedMessage()); e.getLocalizedMessage());
return; return;
@ -82,7 +82,7 @@ public class GCLCConstantsTest {
assertTrue(res.get(3).equals("arguments")); assertTrue(res.get(3).equals("arguments"));
try { try {
res = GCLCConstants.splitCommand("aCommand with some arguments"); res = GCLCConstants.splitCommand("aCommand with some arguments");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
fail("Unable to parse command with arguments and double whitspaces " + //$NON-NLS-1$ fail("Unable to parse command with arguments and double whitspaces " + //$NON-NLS-1$
e.getLocalizedMessage()); e.getLocalizedMessage());
return; return;
@ -95,7 +95,7 @@ public class GCLCConstantsTest {
try { try {
res = GCLCConstants res = GCLCConstants
.splitCommand("aCommand \"with some\" arguments"); .splitCommand("aCommand \"with some\" arguments");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
fail("Unable to parse command with string argument " + //$NON-NLS-1$ fail("Unable to parse command with string argument " + //$NON-NLS-1$
e.getLocalizedMessage()); e.getLocalizedMessage());
return; return;
@ -106,7 +106,7 @@ public class GCLCConstantsTest {
assertTrue(res.get(2).equals("arguments")); assertTrue(res.get(2).equals("arguments"));
try { try {
res = GCLCConstants.splitCommand("aCommand with\\ some arguments"); res = GCLCConstants.splitCommand("aCommand with\\ some arguments");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
fail("Unable to parse command with arguments with escaped whitspaces " + //$NON-NLS-1$ fail("Unable to parse command with arguments with escaped whitspaces " + //$NON-NLS-1$
e.getLocalizedMessage()); e.getLocalizedMessage());
return; return;
@ -118,7 +118,7 @@ public class GCLCConstantsTest {
try { try {
res = GCLCConstants res = GCLCConstants
.splitCommand("aCommand wi\\\"th some arguments"); .splitCommand("aCommand wi\\\"th some arguments");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
fail("Unable to parse command with string argument " + //$NON-NLS-1$ fail("Unable to parse command with string argument " + //$NON-NLS-1$
e.getLocalizedMessage()); e.getLocalizedMessage());
return; return;
@ -132,7 +132,7 @@ public class GCLCConstantsTest {
try { try {
res = GCLCConstants res = GCLCConstants
.splitCommand("aCommand with \"some arguments\""); .splitCommand("aCommand with \"some arguments\"");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
fail("Unable to parse command ending with string argument " + //$NON-NLS-1$ fail("Unable to parse command ending with string argument " + //$NON-NLS-1$
e.getLocalizedMessage()); e.getLocalizedMessage());
return; return;
@ -147,9 +147,8 @@ public class GCLCConstantsTest {
res = GCLCConstants res = GCLCConstants
.splitCommand("aCommand with \"some ar\"guments"); .splitCommand("aCommand with \"some ar\"guments");
fail("Parsing argument with string cut"); fail("Parsing argument with string cut");
} catch (CommandParsingException e) { } catch (final CommandParsingException e) {
// OK // OK
assertTrue(e.getLocalizedMessage(), true);
} }
} }

View File

@ -54,44 +54,49 @@ import fr.bigeon.gclc.manager.PipedConsoleManager;
public class CommandTest { public class CommandTest {
@Test @Test
public final void test() { public final void testCommand() {
try (PipedConsoleManager test = new PipedConsoleManager()) { try (PipedConsoleManager test = new PipedConsoleManager()) {
Command cmd; Command cmd;
cmd = new Command("name") { cmd = new Command("name") {
@Override
public void execute(final String... args) throws CommandRunException {
//
}
@Override @Override
public String tip() { public String tip() {
return null; return null;
} }
@Override @Override
public void execute(String... args) throws CommandRunException { protected String usageDetail() {
// return null;
} }
}; };
cmd.help(test); cmd.help(test);
cmd = new Command("name") { cmd = new Command("name") {
@Override
public void execute(final String... args) throws CommandRunException {
//
}
@Override @Override
public String tip() { public String tip() {
return ""; return "";
} }
@Override @Override
public void execute(String... args) throws CommandRunException { protected String usageDetail() {
// return null;
} }
}; };
cmd.help(test); cmd.help(test);
cmd = new Command("name") { cmd = new Command("name") {
@Override
public String tip() {
return "tip";
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#brief() */ * @see fr.bigeon.gclc.command.Command#brief() */
@Override @Override
@ -100,19 +105,24 @@ public class CommandTest {
} }
@Override @Override
public void execute(String... args) throws CommandRunException { public void execute(final String... args) throws CommandRunException {
// //
} }
};
cmd.help(test);
cmd = new Command("name") {
@Override @Override
public String tip() { public String tip() {
return "tip"; return "tip";
} }
@Override
protected String usageDetail() {
return null;
}
};
cmd.help(test);
cmd = new Command("name") {
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#brief() */ * @see fr.bigeon.gclc.command.Command#brief() */
@Override @Override
@ -121,14 +131,29 @@ public class CommandTest {
} }
@Override @Override
public void execute(String... args) throws CommandRunException { public void execute(final String... args) throws CommandRunException {
// //
} }
@Override
public String tip() {
return "tip";
}
@Override
protected String usageDetail() {
return null;
}
}; };
cmd.help(test); cmd.help(test);
cmd = new Command("name") { cmd = new Command("name") {
@Override
public void execute(final String... args) throws CommandRunException {
//
}
@Override @Override
public String tip() { public String tip() {
return "tip"; return "tip";
@ -140,16 +165,16 @@ public class CommandTest {
protected String usageDetail() { protected String usageDetail() {
return null; return null;
} }
@Override
public void execute(String... args) throws CommandRunException {
//
}
}; };
cmd.help(test); cmd.help(test);
cmd = new Command("name") { cmd = new Command("name") {
@Override
public void execute(final String... args) throws CommandRunException {
//
}
@Override @Override
public String tip() { public String tip() {
return "tip"; return "tip";
@ -161,15 +186,15 @@ public class CommandTest {
protected String usageDetail() { protected String usageDetail() {
return "details"; return "details";
} }
@Override
public void execute(String... args) throws CommandRunException {
//
}
}; };
cmd.help(test); cmd.help(test);
cmd = new Command("name") { cmd = new Command("name") {
@Override
public void execute(final String... args) throws CommandRunException {
//
}
@Override @Override
public String tip() { public String tip() {
return "tip"; return "tip";
@ -181,16 +206,16 @@ public class CommandTest {
protected String usageDetail() { protected String usageDetail() {
return "details" + System.lineSeparator(); return "details" + System.lineSeparator();
} }
@Override
public void execute(String... args) throws CommandRunException {
//
}
}; };
cmd.help(test); cmd.help(test);
cmd = new Command("name") { cmd = new Command("name") {
@Override
public void execute(final String... args) throws CommandRunException {
//
}
@Override @Override
public String tip() { public String tip() {
return "tip"; return "tip";
@ -202,15 +227,10 @@ public class CommandTest {
protected String usageDetail() { protected String usageDetail() {
return "\n"; return "\n";
} }
@Override
public void execute(String... args) throws CommandRunException {
//
}
}; };
cmd.help(test); cmd.help(test);
} catch (IOException e) { } catch (final IOException e) {
assertNull(e); assertNull(e);
} }
} }

View File

@ -42,6 +42,8 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.IOException;
import org.junit.Test; import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
@ -56,37 +58,18 @@ import fr.bigeon.gclc.manager.PipedConsoleManager;
*/ */
public class HelpExecutorTest { public class HelpExecutorTest {
/**
* Test method for {@link fr.bigeon.gclc.command.HelpExecutor#HelpExecutor(java.lang.String, fr.bigeon.gclc.manager.ConsoleManager, fr.bigeon.gclc.command.ICommand)}.
*/
@Test
public final void testHelpExecutor(){
HelpExecutor help;
try {
help = new HelpExecutor("?", null, new MockCommand("mock"));
fail("help is an interactive command, should need console manager");
} catch (Exception e) {
assertNotNull(e);
}
try (PipedConsoleManager test = new PipedConsoleManager()) {
help = new HelpExecutor("?", test, new MockCommand("mock"));
} catch (Exception e) {
assertNull(e);
}
}
/** /**
* Test method for {@link fr.bigeon.gclc.command.HelpExecutor#execute(java.lang.String[])}. * Test method for {@link fr.bigeon.gclc.command.HelpExecutor#execute(java.lang.String[])}.
*/ */
@Test @Test
public final void testExecute(){ public final void testExecute(){
try { try {
PipedConsoleManager test = new PipedConsoleManager(); final PipedConsoleManager test = new PipedConsoleManager();
HelpExecutor help = new HelpExecutor("?", test, final HelpExecutor help = new HelpExecutor("?", test,
new Command("mock") { new Command("mock") {
@Override @Override
public void execute(String... args) throws CommandRunException { public void execute(final String... args) throws CommandRunException {
// //
} }
@ -94,6 +77,10 @@ public class HelpExecutorTest {
public String tip() { public String tip() {
return ""; return "";
} }
@Override
protected String usageDetail() {
return null;
}
}); });
@ -103,33 +90,45 @@ public class HelpExecutorTest {
try { try {
help.execute(); help.execute();
fail("manager closed shall provoke failure of help command execution"); fail("manager closed shall provoke failure of help command execution");
} catch (Exception e) { } catch (final Exception e) {
assertNotNull(e); assertNotNull(e);
} }
} catch (Exception e) { } catch (final Exception e) {
assertNull(e); assertNull(e);
} }
} }
/** Test method for
* {@link fr.bigeon.gclc.command.HelpExecutor#HelpExecutor(java.lang.String, fr.bigeon.gclc.manager.ConsoleManager, fr.bigeon.gclc.command.ICommand)}.
*
* @throws IOException if an IO occurs */
@Test
public final void testHelpExecutor() throws IOException {
HelpExecutor help;
try (PipedConsoleManager test = new PipedConsoleManager()) {
help = new HelpExecutor("?", test, new MockCommand("mock"));
}
}
/** /**
* Test method for {@link fr.bigeon.gclc.command.HelpExecutor#tip()}. * Test method for {@link fr.bigeon.gclc.command.HelpExecutor#tip()}.
*/ */
@Test @Test
public final void testTip(){ public final void testTip(){
try (PipedConsoleManager test = new PipedConsoleManager()) { try (PipedConsoleManager test = new PipedConsoleManager()) {
HelpExecutor help = new HelpExecutor("?", test, final HelpExecutor help = new HelpExecutor("?", test,
new MockCommand("mock")); new MockCommand("mock"));
help.tip(); help.tip();
help.help(test); help.help(test);
} catch (Exception e) { } catch (final Exception e) {
assertNull(e); assertNull(e);
} }
try (PipedConsoleManager test = new PipedConsoleManager()) { try (PipedConsoleManager test = new PipedConsoleManager()) {
HelpExecutor help = new HelpExecutor("?", test, final HelpExecutor help = new HelpExecutor("?", test,
new SubedCommand("sub", new MockCommand("mock"))); new SubedCommand("sub", new MockCommand("mock")));
help.tip(); help.tip();
help.help(test); help.help(test);
} catch (Exception e) { } catch (final Exception e) {
assertNull(e); assertNull(e);
} }
} }

View File

@ -59,144 +59,47 @@ import fr.bigeon.gclc.manager.PipedConsoleManager;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class ParametrizedCommandTest { public class ParametrizedCommandTest {
/** Test method for
* {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */
@Test
public final void testParametrizedCommandConsoleManagerString() {
try (PipedConsoleManager test = new PipedConsoleManager()) {
ParametrizedCommand cmd = new ParametrizedCommand(test, "name") {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
assertTrue(cmd.isStrict());
assertTrue(cmd.isInteractive());
} catch (IOException e) {
fail("Unexpected exception in creation");
assertNull(e);
}
ParametrizedCommand cmd = new ParametrizedCommand(null, "name") {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
assertTrue(cmd.isStrict());
assertFalse(cmd.isInteractive());
cmd = new ParametrizedCommand("name") {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
assertTrue(cmd.isStrict());
assertFalse(cmd.isInteractive());
}
/** Test method for
* {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String, boolean)}. */
@Test
public final void testParametrizedCommandConsoleManagerStringBoolean() {
try (PipedConsoleManager test = new PipedConsoleManager()) {
ParametrizedCommand cmd = new ParametrizedCommand(test, "name",
false) {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
assertFalse(cmd.isStrict());
assertTrue(cmd.isInteractive());
} catch (IOException e) {
fail("Unexpected exception in creation");
assertNull(e);
}
ParametrizedCommand cmd = new ParametrizedCommand(null, "name", false) {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
assertFalse(cmd.isStrict());
assertFalse(cmd.isInteractive());
cmd = new ParametrizedCommand("name", false) {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
assertFalse(cmd.isStrict());
assertFalse(cmd.isInteractive());
}
/** Test method for /** 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)}. */
@Test @Test
public final void testAddParameter() { public final void testAddParameter() {
ParametrizedCommand cmd = new ParametrizedCommand(null, "name") { ParametrizedCommand cmd = new ParametrizedCommand(null, "name") {
@Override
protected void doExecute(final CommandParameters parameters) {
//
}
@Override @Override
public String tip() { public String tip() {
return null; return null;
} }
@Override @Override
protected void doExecute(CommandParameters parameters) { protected String usageDetail() {
// return null;
} }
}; };
cmd = new ParametrizedCommand(null, "name", true) { cmd = new ParametrizedCommand(null, "name", true) {
@Override
protected void doExecute(final CommandParameters parameters) {
//
}
@Override @Override
public String tip() { public String tip() {
return null; return null;
} }
@Override @Override
protected void doExecute(CommandParameters parameters) { protected String usageDetail() {
// return null;
} }
}; };
// 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
String str = "str"; final String str = "str";
try { try {
assertTrue(cmd.getBooleanParameters().isEmpty()); assertTrue(cmd.getBooleanParameters().isEmpty());
assertTrue(cmd.getStringParameters().isEmpty()); assertTrue(cmd.getStringParameters().isEmpty());
@ -218,7 +121,7 @@ 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 (InvalidParameterException e) { } catch (final InvalidParameterException e) {
fail("Unexpected error in addition of legitimate parameter"); fail("Unexpected error in addition of legitimate parameter");
assertNotNull(e); assertNotNull(e);
} }
@ -239,12 +142,7 @@ public class ParametrizedCommandTest {
private boolean evenCall = true; private boolean evenCall = true;
@Override @Override
public String tip() { protected void doExecute(final CommandParameters parameters) {
return "";
}
@Override
protected void doExecute(CommandParameters parameters) {
assertTrue(parameters.getBooleanArgumentKeys().isEmpty()); assertTrue(parameters.getBooleanArgumentKeys().isEmpty());
assertTrue(parameters.getStringArgumentKeys().isEmpty()); assertTrue(parameters.getStringArgumentKeys().isEmpty());
if (evenCall) { if (evenCall) {
@ -256,13 +154,23 @@ public class ParametrizedCommandTest {
evenCall = true; evenCall = true;
} }
} }
@Override
public String tip() {
return "";
}
@Override
protected String usageDetail() {
return null;
}
}; };
try { try {
cmd.execute(); cmd.execute();
cmd.execute("-" + addParam); cmd.execute("-" + addParam);
cmd.execute(addParam); cmd.execute(addParam);
cmd.execute("-" + addParam, addParam); cmd.execute("-" + addParam, addParam);
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unepected error");
} }
@ -275,19 +183,14 @@ public class ParametrizedCommandTest {
addStringParameter(str2, false); addStringParameter(str2, false);
addBooleanParameter(bool1); addBooleanParameter(bool1);
addBooleanParameter(bool2); addBooleanParameter(bool2);
} catch (InvalidParameterException e) { } catch (final InvalidParameterException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override @Override
public String tip() { protected void doExecute(final CommandParameters parameters) {
return "";
}
@Override
protected void doExecute(CommandParameters parameters) {
assertEquals(2, parameters.getBooleanArgumentKeys().size()); assertEquals(2, parameters.getBooleanArgumentKeys().size());
assertEquals(2, parameters.getStringArgumentKeys().size()); assertEquals(2, parameters.getStringArgumentKeys().size());
switch (call) { switch (call) {
@ -319,6 +222,16 @@ public class ParametrizedCommandTest {
break; break;
} }
} }
@Override
public String tip() {
return "";
}
@Override
protected String usageDetail() {
return null;
}
}; };
try { try {
cmd.execute(); cmd.execute();
@ -327,7 +240,7 @@ public class ParametrizedCommandTest {
cmd.execute("-" + addParam, addParam); cmd.execute("-" + addParam, addParam);
cmd.execute("-" + str1, str2); cmd.execute("-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1); cmd.execute("-" + str1, str2, "-" + bool1);
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unepected error");
} }
@ -340,19 +253,13 @@ public class ParametrizedCommandTest {
addStringParameter(str2, false); addStringParameter(str2, false);
addBooleanParameter(bool1); addBooleanParameter(bool1);
addBooleanParameter(bool2); addBooleanParameter(bool2);
} catch (InvalidParameterException e) { } catch (final InvalidParameterException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override @Override
public String tip() { protected void doExecute(final CommandParameters parameters) {
return "";
}
@Override
protected void doExecute(CommandParameters parameters) {
assertEquals(2, parameters.getBooleanArgumentKeys().size()); assertEquals(2, parameters.getBooleanArgumentKeys().size());
assertEquals(2, parameters.getStringArgumentKeys().size()); assertEquals(2, parameters.getStringArgumentKeys().size());
switch (call) { switch (call) {
@ -381,25 +288,35 @@ public class ParametrizedCommandTest {
break; break;
} }
} }
@Override
public String tip() {
return "";
}
@Override
protected String usageDetail() {
return null;
}
}; };
try { try {
cmd.execute(); cmd.execute();
cmd.execute("-" + str1, str2); cmd.execute("-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1); cmd.execute("-" + str1, str2, "-" + bool1);
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNull(e); assertNull(e);
fail("unexpected error"); fail("unexpected error");
} }
try { try {
cmd.execute(addParam); cmd.execute(addParam);
fail("Strict should fail with unexpected argument"); fail("Strict should fail with unexpected argument");
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
try { try {
cmd.execute("-" + addParam); cmd.execute("-" + addParam);
fail("Strict should fail with unexpected argument"); fail("Strict should fail with unexpected argument");
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
// Test on command with missing needed elements // Test on command with missing needed elements
@ -412,11 +329,15 @@ public class ParametrizedCommandTest {
addStringParameter(str2, false); addStringParameter(str2, false);
addBooleanParameter(bool1); addBooleanParameter(bool1);
addBooleanParameter(bool2); addBooleanParameter(bool2);
} catch (InvalidParameterException e) { } catch (final InvalidParameterException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override
protected void doExecute(final CommandParameters parameters) {
assertEquals(str2, parameters.get(str1));
}
@Override @Override
public String tip() { public String tip() {
@ -424,8 +345,8 @@ public class ParametrizedCommandTest {
} }
@Override @Override
protected void doExecute(CommandParameters parameters) { protected String usageDetail() {
assertEquals(str2, parameters.get(str1)); return null;
} }
}; };
try { try {
@ -434,14 +355,14 @@ public class ParametrizedCommandTest {
cmd.execute("-" + str1, str2, "-" + addParam); cmd.execute("-" + str1, str2, "-" + addParam);
cmd.execute("-" + str1, str2, addParam); cmd.execute("-" + str1, str2, addParam);
cmd.execute("-" + str1, str2, "-" + addParam, addParam); cmd.execute("-" + str1, str2, "-" + addParam, addParam);
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unepected error");
} }
try { try {
cmd.execute(); cmd.execute();
fail("needed " + str1 + " not provided shall fail"); fail("needed " + str1 + " not provided shall fail");
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
cmd = new ParametrizedCommand("name", true) { cmd = new ParametrizedCommand("name", true) {
@ -453,52 +374,57 @@ public class ParametrizedCommandTest {
addStringParameter(str2, false); addStringParameter(str2, false);
addBooleanParameter(bool1); addBooleanParameter(bool1);
addBooleanParameter(bool2); addBooleanParameter(bool2);
} catch (InvalidParameterException e) { } catch (final InvalidParameterException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override
protected void doExecute(final CommandParameters parameters) {
//
assertEquals(str2, parameters.get(str1));
}
@Override @Override
public String tip() { public String tip() {
return ""; return "";
} }
@Override @Override
protected void doExecute(CommandParameters parameters) { protected String usageDetail() {
// return null;
assertEquals(str2, parameters.get(str1));
} }
}; };
try { try {
cmd.execute("-" + str1, str2); cmd.execute("-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1); cmd.execute("-" + str1, str2, "-" + bool1);
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unepected error");
} }
try { try {
cmd.execute("-" + str1, str2, addParam); cmd.execute("-" + str1, str2, addParam);
fail("Additional parameter should cause failure"); fail("Additional parameter should cause failure");
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
try { try {
cmd.execute(); cmd.execute();
fail("needed " + str1 + " not provided shall fail"); fail("needed " + str1 + " not provided shall fail");
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
try { try {
cmd.execute("-" + str1, str2, "-" + addParam); cmd.execute("-" + str1, str2, "-" + addParam);
fail("unepected error"); fail("unepected error");
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
try { try {
cmd.execute("-" + str1, str2, "-" + addParam, addParam); cmd.execute("-" + str1, str2, "-" + addParam, addParam);
fail("unepected error"); fail("unepected error");
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
// TODO Test of interactive not providing and providing all needed // TODO Test of interactive not providing and providing all needed
@ -510,11 +436,15 @@ public class ParametrizedCommandTest {
addStringParameter(str2, false); addStringParameter(str2, false);
addBooleanParameter(bool1); addBooleanParameter(bool1);
addBooleanParameter(bool2); addBooleanParameter(bool2);
} catch (InvalidParameterException e) { } catch (final InvalidParameterException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override
protected void doExecute(final CommandParameters parameters) {
assertEquals(str2, parameters.get(str1));
}
@Override @Override
public String tip() { public String tip() {
@ -522,8 +452,8 @@ public class ParametrizedCommandTest {
} }
@Override @Override
protected void doExecute(CommandParameters parameters) { protected String usageDetail() {
assertEquals(str2, parameters.get(str1)); return null;
} }
}; };
try { try {
@ -532,7 +462,7 @@ public class ParametrizedCommandTest {
cmd.execute("-" + str1, str2, addParam); cmd.execute("-" + str1, str2, addParam);
cmd.execute("-" + str1, str2, "-" + addParam); cmd.execute("-" + str1, str2, "-" + addParam);
cmd.execute("-" + str1, str2, "-" + addParam, addParam); cmd.execute("-" + str1, str2, "-" + addParam, addParam);
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unepected error");
} }
@ -554,7 +484,7 @@ public class ParametrizedCommandTest {
"value of " + str1 + "? (cannot be empty) ", "value of " + str1 + "? (cannot be empty) ",
test.readNextLine()); test.readNextLine());
test.type(str2); test.type(str2);
} catch (IOException e) { } catch (final IOException e) {
assertNull(e); assertNull(e);
} }
} }
@ -573,7 +503,7 @@ public class ParametrizedCommandTest {
assertEquals("value of " + str1 + "? ", assertEquals("value of " + str1 + "? ",
test.readNextLine()); test.readNextLine());
test.type(str2); test.type(str2);
} catch (IOException e) { } catch (final IOException e) {
assertNull(e); assertNull(e);
} }
} }
@ -587,12 +517,12 @@ public class ParametrizedCommandTest {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unepected error");
} }
} catch (IOException e) { } catch (final IOException e) {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unepected error");
} }
try { try {
PipedConsoleManager test = new PipedConsoleManager(); final PipedConsoleManager test = new PipedConsoleManager();
cmd = new ParametrizedCommand(test, "name") { cmd = new ParametrizedCommand(test, "name") {
{ {
try { try {
@ -600,32 +530,168 @@ public class ParametrizedCommandTest {
addStringParameter(str2, false); addStringParameter(str2, false);
addBooleanParameter(bool1); addBooleanParameter(bool1);
addBooleanParameter(bool2); addBooleanParameter(bool2);
} catch (InvalidParameterException e) { } catch (final InvalidParameterException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override
protected void doExecute(final CommandParameters parameters) {
assertEquals(str2, parameters.get(str1));
}
@Override @Override
public String tip() { public String tip() {
return ""; return "";
} }
@Override @Override
protected void doExecute(CommandParameters parameters) { protected String usageDetail() {
assertEquals(str2, parameters.get(str1)); return null;
} }
}; };
test.close(); test.close();
cmd.execute("-" + str1, str2); cmd.execute("-" + str1, str2);
cmd.execute("-" + addParam); cmd.execute("-" + addParam);
fail("Closed manager shall cause error"); fail("Closed manager shall cause error");
} catch (IOException e) { } catch (final IOException e) {
assertNull(e); assertNull(e);
} catch (CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
} }
/** Test method for
* {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */
@Test
public final void testParametrizedCommandConsoleManagerString() {
try (PipedConsoleManager test = new PipedConsoleManager()) {
final ParametrizedCommand cmd = new ParametrizedCommand(test, "name") {
@Override
protected void doExecute(final CommandParameters parameters) {
//
}
@Override
public String tip() {
return null;
}
@Override
protected String usageDetail() {
return null;
}
};
assertTrue(cmd.isStrict());
assertTrue(cmd.isInteractive());
} catch (final IOException e) {
fail("Unexpected exception in creation");
assertNull(e);
}
ParametrizedCommand cmd = new ParametrizedCommand(null, "name") {
@Override
protected void doExecute(final CommandParameters parameters) {
//
}
@Override
public String tip() {
return null;
}
@Override
protected String usageDetail() {
return null;
}
};
assertTrue(cmd.isStrict());
assertFalse(cmd.isInteractive());
cmd = new ParametrizedCommand("name") {
@Override
protected void doExecute(final CommandParameters parameters) {
//
}
@Override
public String tip() {
return null;
}
@Override
protected String usageDetail() {
return null;
}
};
assertTrue(cmd.isStrict());
assertFalse(cmd.isInteractive());
}
/** Test method for
* {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String, boolean)}. */
@Test
public final void testParametrizedCommandConsoleManagerStringBoolean() {
try (PipedConsoleManager test = new PipedConsoleManager()) {
final ParametrizedCommand cmd = new ParametrizedCommand(test, "name",
false) {
@Override
protected void doExecute(final CommandParameters parameters) {
//
}
@Override
public String tip() {
return null;
}
@Override
protected String usageDetail() {
return null;
}
};
assertFalse(cmd.isStrict());
assertTrue(cmd.isInteractive());
} catch (final IOException e) {
fail("Unexpected exception in creation");
assertNull(e);
}
ParametrizedCommand cmd = new ParametrizedCommand(null, "name", false) {
@Override
protected void doExecute(final CommandParameters parameters) {
//
}
@Override
public String tip() {
return null;
}
@Override
protected String usageDetail() {
return null;
}
};
assertFalse(cmd.isStrict());
assertFalse(cmd.isInteractive());
cmd = new ParametrizedCommand("name", false) {
@Override
protected void doExecute(final CommandParameters parameters) {
//
}
@Override
public String tip() {
return null;
}
@Override
protected String usageDetail() {
return null;
}
};
assertFalse(cmd.isStrict());
assertFalse(cmd.isInteractive());
}
} }

View File

@ -68,20 +68,20 @@ public class ScriptExecutionTest {
PipedConsoleManager test; PipedConsoleManager test;
try { try {
test = new PipedConsoleManager(); test = new PipedConsoleManager();
} catch (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); assertNotNull(e2);
return; return;
} }
ConsoleApplication app = new ConsoleApplication( final ConsoleApplication app = new ConsoleApplication(
test, "", ""); test, "", "");
new ConsoleTestApplication().attach(app); new ConsoleTestApplication().attach(app);
ScriptExecution exec = new ScriptExecution("script", app, "#", //$NON-NLS-1$ //$NON-NLS-2$ final ScriptExecution exec = new ScriptExecution("script", app, "#", //$NON-NLS-1$ //$NON-NLS-2$
Charset.forName("UTF-8")); Charset.forName("UTF-8"));
try { try {
exec.execute(); exec.execute();
fail("execution of script command with no file should fail"); //$NON-NLS-1$ fail("execution of script command with no file should fail"); //$NON-NLS-1$
} catch (CommandRunException e1) { } catch (final CommandRunException e1) {
// ok // ok
assertEquals(exec, e1.getSource()); assertEquals(exec, e1.getSource());
assertEquals(CommandRunExceptionType.USAGE, e1.getType()); assertEquals(CommandRunExceptionType.USAGE, e1.getType());
@ -90,7 +90,7 @@ public class ScriptExecutionTest {
try { try {
exec.execute("src/test/resources/scripts/withprependSpace.txt"); //$NON-NLS-1$ exec.execute("src/test/resources/scripts/withprependSpace.txt"); //$NON-NLS-1$
fail("execution of script with lines begining with space should fail"); //$NON-NLS-1$ fail("execution of script with lines begining with space should fail"); //$NON-NLS-1$
} catch (CommandRunException e1) { } catch (final CommandRunException e1) {
// ok // ok
assertEquals(exec, e1.getSource()); assertEquals(exec, e1.getSource());
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
@ -99,7 +99,7 @@ public class ScriptExecutionTest {
try { try {
exec.execute("src/test/resources/scripts/invalidCmdParse.txt"); //$NON-NLS-1$ exec.execute("src/test/resources/scripts/invalidCmdParse.txt"); //$NON-NLS-1$
fail("execution of script with invalid command line should fail"); //$NON-NLS-1$ fail("execution of script with invalid command line should fail"); //$NON-NLS-1$
} catch (CommandRunException e1) { } catch (final CommandRunException e1) {
// ok // ok
assertEquals(exec, e1.getSource()); assertEquals(exec, e1.getSource());
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
@ -108,7 +108,7 @@ public class ScriptExecutionTest {
try { try {
exec.execute("src/test/resources/scripts/invalidCmd.txt"); //$NON-NLS-1$ exec.execute("src/test/resources/scripts/invalidCmd.txt"); //$NON-NLS-1$
fail("execution of script with invalid command should fail"); //$NON-NLS-1$ fail("execution of script with invalid command should fail"); //$NON-NLS-1$
} catch (CommandRunException e1) { } catch (final CommandRunException e1) {
// ok // ok
assertEquals(exec, e1.getSource()); assertEquals(exec, e1.getSource());
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
@ -117,7 +117,7 @@ public class ScriptExecutionTest {
try { try {
exec.execute("src/test/resources/scripts/failingCmdInvoc.txt"); //$NON-NLS-1$ exec.execute("src/test/resources/scripts/failingCmdInvoc.txt"); //$NON-NLS-1$
fail("execution of script with failing command should fail"); //$NON-NLS-1$ fail("execution of script with failing command should fail"); //$NON-NLS-1$
} catch (CommandRunException e1) { } catch (final CommandRunException e1) {
// ok // ok
assertEquals(exec, e1.getSource()); assertEquals(exec, e1.getSource());
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
@ -126,7 +126,7 @@ public class ScriptExecutionTest {
try { try {
exec.execute("src/test/resources/scripts/someNonExisting.file"); //$NON-NLS-1$ exec.execute("src/test/resources/scripts/someNonExisting.file"); //$NON-NLS-1$
fail("execution of script with unexisting file should fail"); //$NON-NLS-1$ fail("execution of script with unexisting file should fail"); //$NON-NLS-1$
} catch (CommandRunException e1) { } catch (final CommandRunException e1) {
// ok // ok
assertEquals(exec, e1.getSource()); assertEquals(exec, e1.getSource());
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
@ -138,38 +138,38 @@ public class ScriptExecutionTest {
exec.execute("src/test/resources/script3.txt"); //$NON-NLS-1$ exec.execute("src/test/resources/script3.txt"); //$NON-NLS-1$
exec.execute("src/test/resources/script4.txt"); //$NON-NLS-1$ exec.execute("src/test/resources/script4.txt"); //$NON-NLS-1$
exec.execute("src/test/resources/script5.txt", "test"); //$NON-NLS-1$ //$NON-NLS-2$ exec.execute("src/test/resources/script5.txt", "test"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (CommandRunException e) { } catch (final CommandRunException e) {
e.printStackTrace(); e.printStackTrace();
fail("execution of wellformed script should not fail"); //$NON-NLS-1$ fail("execution of wellformed script should not fail"); //$NON-NLS-1$
} }
try { try {
test.close(); test.close();
} catch (IOException e) { } catch (final IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
/** Test method for {@link fr.bigeon.gclc.command.ScriptExecution#tip()}. */
@Test
public void testTip() {
ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$
Charset.forName("UTF-8"));
exec.tip();
}
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.ScriptExecution#help(fr.bigeon.gclc.manager.ConsoleManager, String...)}. */ * {@link fr.bigeon.gclc.command.ScriptExecution#help(fr.bigeon.gclc.manager.ConsoleManager, String...)}. */
@Test @Test
public void testHelp() { public void testHelp() {
ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$ final ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$
Charset.forName("UTF-8")); Charset.forName("UTF-8"));
try (PipedConsoleManager test = new PipedConsoleManager()) { try (PipedConsoleManager test = new PipedConsoleManager()) {
exec.help(test); exec.help(test);
exec.help(test, "ignored element"); exec.help(test, "ignored element");
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
fail("unexpected error in help invocation"); //$NON-NLS-1$ fail("unexpected error in help invocation"); //$NON-NLS-1$
} }
} }
/** Test method for {@link fr.bigeon.gclc.command.ScriptExecution#tip()}. */
@Test
public void testTip() {
final ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$
Charset.forName("UTF-8"));
assertNotNull("Tip should not be null", exec.tip());
}
} }

View File

@ -59,6 +59,296 @@ import fr.bigeon.gclc.manager.PipedConsoleManager;
@SuppressWarnings("all") @SuppressWarnings("all")
public class SubedCommandTest { public class SubedCommandTest {
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#add(fr.bigeon.gclc.command.ICommand)}. */
@Test
public final void testAdd() {
final SubedCommand cmd = new SubedCommand("name");
try {
cmd.add(new MockCommand("id"));
} catch (final InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try {
cmd.add(new MockCommand("id"));
fail("addition of command with already used id succeeded");
} catch (final InvalidCommandName e) {
//
assertNotNull(e);
}
try {
cmd.add(new MockCommand(""));
fail("addition of command with invalid id succeeded");
} catch (final InvalidCommandName e) {
//
assertNotNull(e);
}
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#execute(java.lang.String[])}. */
@Test
public final void testExecute() {
SubedCommand cmd = new SubedCommand("name");
final MockCommand mock = new MockCommand("id");
try {
cmd.add(mock);
cmd.add(new Command("fail") {
@Override
public void execute(final String... args) throws CommandRunException {
throw new CommandRunException("Failing command", null);
}
@Override
public String tip() {
return null;
}
@Override
protected String usageDetail() {
return null;
}
});
} catch (final InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try {
cmd.execute("id");
} catch (final CommandRunException e) {
fail("Unexpected exception when running mock command");
assertNotNull(e);
}
try {
cmd.execute("fail");
fail("Fail command error should be re thrown");
} catch (final CommandRunException e) {
assertNotNull(e);
assertEquals(cmd, e.getSource());
}
try {
cmd.execute();
fail("Request for inexistent default command should fail");
} catch (final CommandRunException e) {
assertNotNull(e);
assertEquals(cmd, e.getSource());
}
cmd = new SubedCommand("name", mock);
try {
cmd.add(mock);
cmd.add(new Command("fail") {
@Override
public void execute(final String... args) throws CommandRunException {
throw new CommandRunException("Failing command", this);
}
@Override
public String tip() {
return null;
}
@Override
protected String usageDetail() {
return null;
}
});
} catch (final InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try {
cmd.execute("id");
} catch (final CommandRunException e) {
fail("Unexpected exception when running mock command");
assertNotNull(e);
}
try {
cmd.execute("fail");
fail("Fail command error should be re thrown");
} catch (final CommandRunException e) {
assertNotNull(e);
assertEquals(cmd.get("fail"), e.getSource());
}
try {
cmd.execute();
} catch (final CommandRunException e) {
fail("Request for default command should execute default command");
assertNotNull(e);
}
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#executeSub(java.lang.String, java.lang.String[])}. */
@Test
public final void testExecuteSub() {
final SubedCommand cmd = new SubedCommand("name");
final MockCommand mock = new MockCommand("id");
try {
cmd.add(mock);
cmd.add(new Command("fail") {
@Override
public void execute(final String... args) throws CommandRunException {
throw new CommandRunException("Failing command", this);
}
@Override
public String tip() {
return null;
}
@Override
protected String usageDetail() {
return null;
}
});
} catch (final InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try {
cmd.executeSub("id");
} catch (final CommandRunException e) {
fail("Unexpected exception when running mock command");
assertNotNull(e);
}
try {
cmd.executeSub("fail");
fail("Fail command error should be re thrown");
} catch (final CommandRunException e) {
assertNotNull(e);
assertEquals(cmd.get("fail"), e.getSource());
}
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#get(java.lang.String)}. */
@Test
public final void testGet() {
final SubedCommand cmd = new SubedCommand("name");
assertNull(cmd.get("id"));
final MockCommand mock = new MockCommand("id");
try {
cmd.add(mock);
} catch (final InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
assertEquals(mock, cmd.get("id"));
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#getCommandName()}. */
@Test
public final void testGetCommandName() {
SubedCommand cmd = new SubedCommand("name");
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name with spaces");
assertEquals("name with spaces", cmd.getCommandName());
cmd = new SubedCommand("name", "some tip");
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name", new MockCommand(""));
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name", new MockCommand(""), "some tip");
assertEquals("name", cmd.getCommandName());
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#help(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String[])}. */
@Test
public final void testHelp() {
SubedCommand cmd = new SubedCommand("name");
ICommand mock = new MockCommand("id");
try {
cmd.add(mock);
} catch (final InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try (PipedConsoleManager manager = new PipedConsoleManager();
PipedConsoleManager manager2 = new PipedConsoleManager()) {
cmd.help(manager);
assertEquals("\tid", manager.readNextLine());
cmd.help(manager, "id");
cmd.help(manager, "inexistent");
} catch (final IOException e) {
fail("Unexpected exception when running help");
assertNotNull(e);
}
cmd = new SubedCommand("name", mock);
try {
cmd.add(mock);
} catch (final InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try (PipedConsoleManager manager = new PipedConsoleManager();
PipedConsoleManager manager2 = new PipedConsoleManager()) {
cmd.help(manager);
assertEquals("\tid", manager.readNextLine());
} catch (final IOException e) {
fail("Unexpected exception when running help");
assertNotNull(e);
}
mock = new ICommand() {
@Override
public void execute(final String... args) throws CommandRunException {
//
}
@Override
public String getCommandName() {
return "id";
}
@Override
public void help(final ConsoleManager manager,
final String... args) throws IOException {
//
}
@Override
public String tip() {
return "tip";
}
};
cmd = new SubedCommand("name", mock);
try {
cmd.add(mock);
} catch (final InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try (PipedConsoleManager manager = new PipedConsoleManager();
PipedConsoleManager manager2 = new PipedConsoleManager()) {
cmd.help(manager);
assertEquals("\ttip", manager.readNextLine());
assertEquals("\tid: tip", manager.readNextLine());
} catch (final IOException e) {
fail("Unexpected exception when running help");
assertNotNull(e);
}
}
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String)}. */ * {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String)}. */
@Test @Test
@ -101,284 +391,6 @@ public class SubedCommandTest {
assertEquals("name with spaces", cmd.getCommandName()); assertEquals("name with spaces", cmd.getCommandName());
} }
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#add(fr.bigeon.gclc.command.ICommand)}. */
@Test
public final void testAdd() {
SubedCommand cmd = new SubedCommand("name");
try {
cmd.add(new MockCommand("id"));
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try {
cmd.add(new MockCommand("id"));
fail("addition of command with already used id succeeded");
} catch (InvalidCommandName e) {
//
assertNotNull(e);
}
try {
cmd.add(new MockCommand(""));
fail("addition of command with invalid id succeeded");
} catch (InvalidCommandName e) {
//
assertNotNull(e);
}
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#execute(java.lang.String[])}. */
@Test
public final void testExecute() {
SubedCommand cmd = new SubedCommand("name");
MockCommand mock = new MockCommand("id");
try {
cmd.add(mock);
cmd.add(new Command("fail") {
@Override
public String tip() {
return null;
}
@Override
public void execute(String... args) throws CommandRunException {
throw new CommandRunException("Failing command", null);
}
});
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try {
cmd.execute("id");
} catch (CommandRunException e) {
fail("Unexpected exception when running mock command");
assertNotNull(e);
}
try {
cmd.execute("fail");
fail("Fail command error should be re thrown");
} catch (CommandRunException e) {
assertNotNull(e);
assertEquals(cmd, e.getSource());
}
try {
cmd.execute();
fail("Request for inexistent default command should fail");
} catch (CommandRunException e) {
assertNotNull(e);
assertEquals(cmd, e.getSource());
}
cmd = new SubedCommand("name", mock);
try {
cmd.add(mock);
cmd.add(new Command("fail") {
@Override
public String tip() {
return null;
}
@Override
public void execute(String... args) throws CommandRunException {
throw new CommandRunException("Failing command", this);
}
});
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try {
cmd.execute("id");
} catch (CommandRunException e) {
fail("Unexpected exception when running mock command");
assertNotNull(e);
}
try {
cmd.execute("fail");
fail("Fail command error should be re thrown");
} catch (CommandRunException e) {
assertNotNull(e);
assertEquals(cmd.get("fail"), e.getSource());
}
try {
cmd.execute();
} catch (CommandRunException e) {
fail("Request for default command should execute default command");
assertNotNull(e);
}
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#executeSub(java.lang.String, java.lang.String[])}. */
@Test
public final void testExecuteSub() {
SubedCommand cmd = new SubedCommand("name");
MockCommand mock = new MockCommand("id");
try {
cmd.add(mock);
cmd.add(new Command("fail") {
@Override
public String tip() {
return null;
}
@Override
public void execute(String... args) throws CommandRunException {
throw new CommandRunException("Failing command", this);
}
});
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try {
cmd.executeSub("id");
} catch (CommandRunException e) {
fail("Unexpected exception when running mock command");
assertNotNull(e);
}
try {
cmd.executeSub("fail");
fail("Fail command error should be re thrown");
} catch (CommandRunException e) {
assertNotNull(e);
assertEquals(cmd.get("fail"), e.getSource());
}
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#get(java.lang.String)}. */
@Test
public final void testGet() {
SubedCommand cmd = new SubedCommand("name");
assertNull(cmd.get("id"));
MockCommand mock = new MockCommand("id");
try {
cmd.add(mock);
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
assertEquals(mock, cmd.get("id"));
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#getCommandName()}. */
@Test
public final void testGetCommandName() {
SubedCommand cmd = new SubedCommand("name");
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name with spaces");
assertEquals("name with spaces", cmd.getCommandName());
cmd = new SubedCommand("name", "some tip");
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name", new MockCommand(""));
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name", new MockCommand(""), "some tip");
assertEquals("name", cmd.getCommandName());
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#help(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String[])}. */
@Test
public final void testHelp() {
SubedCommand cmd = new SubedCommand("name");
ICommand mock = new MockCommand("id");
try {
cmd.add(mock);
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try (PipedConsoleManager manager = new PipedConsoleManager();
PipedConsoleManager manager2 = new PipedConsoleManager()) {
cmd.help(manager);
assertEquals("\tid", manager.readNextLine());
cmd.help(manager, "id");
cmd.help(manager, "inexistent");
} catch (IOException e) {
fail("Unexpected exception when running help");
assertNotNull(e);
}
cmd = new SubedCommand("name", mock);
try {
cmd.add(mock);
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try (PipedConsoleManager manager = new PipedConsoleManager();
PipedConsoleManager manager2 = new PipedConsoleManager()) {
cmd.help(manager);
assertEquals("\tid", manager.readNextLine());
} catch (IOException e) {
fail("Unexpected exception when running help");
assertNotNull(e);
}
mock = new ICommand() {
@Override
public String tip() {
return "tip";
}
@Override
public void help(ConsoleManager manager,
String... args) throws IOException {
//
}
@Override
public String getCommandName() {
return "id";
}
@Override
public void execute(String... args) throws CommandRunException {
//
}
};
cmd = new SubedCommand("name", mock);
try {
cmd.add(mock);
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try (PipedConsoleManager manager = new PipedConsoleManager();
PipedConsoleManager manager2 = new PipedConsoleManager()) {
cmd.help(manager);
assertEquals("\ttip", manager.readNextLine());
assertEquals("\tid: tip", manager.readNextLine());
} catch (IOException e) {
fail("Unexpected exception when running help");
assertNotNull(e);
}
}
/** Test method for {@link fr.bigeon.gclc.command.SubedCommand#tip()}. */ /** Test method for {@link fr.bigeon.gclc.command.SubedCommand#tip()}. */
@Test @Test
public final void testTip() { public final void testTip() {

View File

@ -38,6 +38,9 @@
*/ */
package fr.bigeon.gclc.proc; package fr.bigeon.gclc.proc;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import org.junit.Test; import org.junit.Test;
@ -49,9 +52,7 @@ import fr.bigeon.gclc.manager.PipedConsoleManager;
* <p> * <p>
* TODO * TODO
* *
* @author Emmanuel Bigeon * @author Emmanuel Bigeon */
*
*/
public class ProcessListTest { public class ProcessListTest {
/** Test method for /** Test method for
@ -61,56 +62,55 @@ public class ProcessListTest {
* @throws IOException if the manager could not be created */ * @throws IOException if the manager could not be created */
@Test @Test
public final void testExecute() throws CommandRunException, IOException { public final void testExecute() throws CommandRunException, IOException {
TaskPool pool = new TaskPool(); final TaskPool pool = new TaskPool();
ProcessList pl = new ProcessList("list", pool, try (PipedConsoleManager pcm = new PipedConsoleManager()) {
new PipedConsoleManager()); final ProcessList pl = new ProcessList("list", pool, pcm);
pl.execute(); pl.execute();
pool.add(new Task() { pool.add(new Task() {
@Override @Override
public void run() { public void addInterruptionListener(final InterruptionListener listener) {
// TODO Auto-generated method stub //
// }
throw new RuntimeException("Not implemented yet");
}
@Override @Override
public void setRunning(boolean running) { public String getName() {
// return "name";
} }
@Override @Override
public void rmInterruptionListener(InterruptionListener listener) { public boolean isRunning() {
// return false;
} }
@Override @Override
public boolean isRunning() { public void rmInterruptionListener(final InterruptionListener listener) {
return false; //
} }
@Override @Override
public String getName() { public void run() {
return "name"; // TODO Auto-generated method stub
} //
throw new RuntimeException("Not implemented yet");
}
@Override @Override
public void addInterruptionListener(InterruptionListener listener) { public void setRunning(final boolean running) {
// //
} }
}); });
pl.execute(); pl.execute();
assertTrue("List should give the process",
pcm.readNextLine().endsWith("name"));
}
} }
@Test @Test
public void testTip() { public void testTip() throws IOException {
try { try (PipedConsoleManager pcm = new PipedConsoleManager()) {
new ProcessList("list", new TaskPool(), new PipedConsoleManager()) assertNotNull("Tip should not be null", new ProcessList("list",
.tip(); new TaskPool(), pcm).tip());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
} }
} }

View File

@ -39,7 +39,6 @@
package fr.bigeon.gclc.proc; package fr.bigeon.gclc.proc;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import org.junit.Test; import org.junit.Test;
@ -55,26 +54,46 @@ public class TaskPoolTest {
* {@link fr.bigeon.gclc.proc.TaskPool#add(fr.bigeon.gclc.proc.Task)}. */ * {@link fr.bigeon.gclc.proc.TaskPool#add(fr.bigeon.gclc.proc.Task)}. */
@Test @Test
public final void testAdd() { public final void testAdd() {
TaskPool pool = new TaskPool(); final TaskPool pool = new TaskPool();
Task task = null; Task task = null;
try { try {
pool.add(task); pool.add(task);
fail("Expected a null pointer exception"); fail("Expected a null pointer exception");
} catch (NullPointerException e) { } catch (final IllegalArgumentException e) {
assertNotNull(e); // ok
} }
task = new Task() { task = new Task() {
private final Object lock = new Object(); private final Object lock = new Object();
private boolean running; private boolean running;
private InterruptionListener listener; private InterruptionListener listener;
@Override
public void addInterruptionListener(final InterruptionListener listener) {
this.listener = listener;
}
@Override
public String getName() {
return "Test";
}
@Override
public boolean isRunning() {
return running;
}
@Override
public void rmInterruptionListener(final InterruptionListener listener) {
//
}
@Override @Override
public void run() { public void run() {
synchronized (lock) { synchronized (lock) {
while (running) { while (running) {
try { try {
lock.wait(100); lock.wait(100);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
@ -84,45 +103,25 @@ public class TaskPoolTest {
} }
@Override @Override
public void setRunning(boolean running) { public void setRunning(final boolean running) {
synchronized (lock) { synchronized (lock) {
this.running = running; this.running = running;
} }
// //
} }
@Override
public void rmInterruptionListener(InterruptionListener listener) {
//
}
@Override
public boolean isRunning() {
return running;
}
@Override
public String getName() {
return "Test";
}
@Override
public void addInterruptionListener(InterruptionListener listener) {
this.listener = listener;
}
}; };
pool.add(task); pool.add(task);
assertEquals(1, pool.getPIDs().size()); assertEquals(1, pool.getPIDs().size());
for (String pid : pool.getPIDs()) { for (final String pid : pool.getPIDs()) {
assertEquals(task, pool.get(pid)); assertEquals(task, pool.get(pid));
} }
Thread th = new Thread(task); final Thread th = new Thread(task);
th.start(); th.start();
task.setRunning(false); task.setRunning(false);
try { try {
th.join(1000); th.join(1000);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }

View File

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