Update to next mechanism, with stream passed at command execution

Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
This commit is contained in:
Emmanuel Bigeon 2017-11-13 19:09:00 -05:00
parent 9747cf21b2
commit 89e849c27f
40 changed files with 1498 additions and 1585 deletions

View File

@ -35,7 +35,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>gclc</artifactId> <artifactId>gclc</artifactId>
<version>1.5.1-SNAPSHOT</version> <version>2.0.0-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<url>http://www.bigeon.fr/emmanuel</url> <url>http://www.bigeon.fr/emmanuel</url>
<properties> <properties>

View File

@ -52,7 +52,8 @@ 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.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.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
/** /**
* <p> * <p>
@ -62,8 +63,9 @@ import fr.bigeon.gclc.manager.ConsoleManager;
* 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 ConsoleOutput} out = new {@link fr.bigeon.gclc.manager.SystemConsoleOutput SystemConsoleOutput}();
* {@link ConsoleApplication} app = new {@link ConsoleApplication}(manager, "welcome", "see you latter")}; * {@link ConsoleInput} in = new {@link fr.bigeon.gclc.manager.SystemConsoleInput SystemConsoleInput}();
* {@link ConsoleApplication} app = new {@link ConsoleApplication}(out, in, "welcome", "see you latter")};
* app.{@link ConsoleApplication#add(ICommand) add}("my_command", new {@link ICommand MyCommand()}); * app.{@link ConsoleApplication#add(ICommand) add}("my_command", new {@link ICommand MyCommand()});
* app.{@link ConsoleApplication#start() start()}; * app.{@link ConsoleApplication#start() start()};
* </pre> * </pre>
@ -83,8 +85,10 @@ public final class ConsoleApplication implements ICommandProvider {
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 standard output for the application. */
public final ConsoleManager manager; private final ConsoleOutput out;
/** The standard input for the application. */
private final ConsoleInput in;
/** 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. */
@ -94,14 +98,17 @@ public final class ConsoleApplication implements ICommandProvider {
/** Create a console application. /** Create a console application.
* *
* @param manager the manager * @param out the output
* @param in the input
* @param welcome the welcoming message * @param welcome the welcoming message
* @param goodbye the goodbye message */ * @param goodbye the goodbye message */
public ConsoleApplication(final ConsoleManager manager, final String welcome, public ConsoleApplication(final ConsoleOutput out, final ConsoleInput in,
final String welcome,
final String goodbye) { final String goodbye) {
header = welcome; header = welcome;
footer = goodbye; footer = goodbye;
this.manager = manager; this.in = in;
this.out = out;
root = new SubedCommand(""); //$NON-NLS-1$ root = new SubedCommand(""); //$NON-NLS-1$
} }
@ -119,16 +126,27 @@ 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 void executeSub(final ConsoleOutput output, final ConsoleInput input,
final String command,
final String... args) throws CommandRunException {
root.executeSub(output, input, command, args);
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommandProvider#executeSub(java.lang.String, java.lang.String[])
*/
@Deprecated
@Override
public void executeSub(final String command, public void executeSub(final String command,
final String... args) throws CommandRunException { final String... args) throws CommandRunException {
root.executeSub(command, args); executeSub(out, in, 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 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(); in.interruptPrompt();
} }
/* (non-Javadoc) /* (non-Javadoc)
@ -145,21 +163,21 @@ public final class ConsoleApplication implements ICommandProvider {
try { try {
args = GCLCConstants.splitCommand(cmd); args = GCLCConstants.splitCommand(cmd);
} catch (final CommandParsingException e1) { } catch (final CommandParsingException e1) {
manager.println("Command line cannot be parsed"); //$NON-NLS-1$ out.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;
} }
if (!args.isEmpty()) { if (!args.isEmpty()) {
try { try {
executeSub(args.get(0), Arrays.copyOfRange( executeSub(out, in, args.get(0), Arrays.copyOfRange(
args.toArray(new String[0]), 1, args.size())); args.toArray(new String[0]), 1, args.size()));
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
LOGGER.log(Level.FINE, "Command failed: " + cmd, e); //$NON-NLS-1$ LOGGER.log(Level.FINE, "Command failed: " + cmd, e); //$NON-NLS-1$
manager.println(Messages out.println(Messages
.getString("ConsoleApplication.cmd.failed", cmd)); //$NON-NLS-1$ .getString("ConsoleApplication.cmd.failed", cmd)); //$NON-NLS-1$
manager.println(e.getLocalizedMessage()); out.println(e.getLocalizedMessage());
if (e.getType() == CommandRunExceptionType.USAGE) { if (e.getType() == CommandRunExceptionType.USAGE) {
e.getSource().help(manager); e.getSource().help(out);
} }
} }
} }
@ -181,7 +199,7 @@ public final class ConsoleApplication implements ICommandProvider {
* (restarting the loop). */ * (restarting the loop). */
private void runLoop() { private void runLoop() {
try { try {
final String cmd = manager.prompt(); final String cmd = in.prompt();
if (cmd == null || cmd.isEmpty()) { if (cmd == null || cmd.isEmpty()) {
return; return;
} }
@ -210,7 +228,7 @@ public final class ConsoleApplication implements ICommandProvider {
try { try {
running = true; running = true;
if (header != null) { if (header != null) {
manager.println(header); out.println(header);
} }
} catch (final IOException e) { } catch (final IOException e) {
// The manager was closed // The manager was closed
@ -227,7 +245,7 @@ public final class ConsoleApplication implements ICommandProvider {
} while (running); } while (running);
if (footer != null) { if (footer != null) {
try { try {
manager.println(footer); out.println(footer);
} catch (final IOException e) { } catch (final IOException e) {
// The manager was closed // The manager was closed
running = false; running = false;

View File

@ -40,7 +40,7 @@ package fr.bigeon.gclc.command;
import java.io.IOException; import java.io.IOException;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleOutput;
/** /**
* <p> * <p>
@ -93,7 +93,7 @@ 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(final ConsoleManager manager, public final void help(final ConsoleOutput manager,
final String... args) throws IOException { final String... args) throws IOException {
manager.println(getCommandName()); manager.println(getCommandName());
manager.println(brief()); manager.println(brief());

View File

@ -42,8 +42,13 @@ import java.util.List;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.InvalidCommandName; import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.i18n.Messages; import fr.bigeon.gclc.i18n.Messages;
import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
import fr.bigeon.gclc.manager.EmptyInput;
import fr.bigeon.gclc.manager.SinkOutput;
/** <p> /**
* <p>
* A command provider is a map of key word to command to execute * A command provider is a map of key word to command to execute
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
@ -89,12 +94,27 @@ public class CommandProvider implements ICommandProvider {
return commands.add(value); return commands.add(value);
} }
@Override
public final void executeSub(final ConsoleOutput out, final ConsoleInput in,
final String cmd,
final String... args) throws CommandRunException {
for (final ICommand command : commands) {
if (command.getCommandName().equals(cmd)) {
command.execute(out, in, args);
return;
}
}
throw new CommandRunException(
Messages.getString("CommandProvider.unrecognized", cmd), null); //$NON-NLS-1$
}
@Deprecated
@Override @Override
public final void executeSub(final String cmd, public final void executeSub(final String cmd,
final 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(SinkOutput.INSTANCE, EmptyInput.INSTANCE, args);
return; return;
} }
} }

View File

@ -41,7 +41,8 @@ package fr.bigeon.gclc.command;
import java.io.IOException; import java.io.IOException;
import fr.bigeon.gclc.ConsoleApplication; import fr.bigeon.gclc.ConsoleApplication;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
import fr.bigeon.gclc.prompt.CLIPrompterMessages; import fr.bigeon.gclc.prompt.CLIPrompterMessages;
/** <p> /** <p>
@ -71,7 +72,7 @@ public final class ExitCommand implements ICommand {
} }
@Override @Override
public void execute(final String... args) { public void execute(final ConsoleOutput output, final ConsoleInput input, final String... args) {
beforeExit(); beforeExit();
app.exit(); app.exit();
} }
@ -84,12 +85,11 @@ public final class ExitCommand implements ICommand {
} }
@Override @Override
public void help(final ConsoleManager manager, public void help(final ConsoleOutput manager,
final 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));
} }
@Override @Override
public String tip() { public String tip() {
return CLIPrompterMessages.getString(EXIT); return CLIPrompterMessages.getString(EXIT);

View File

@ -42,7 +42,8 @@ import java.io.IOException;
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.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
import fr.bigeon.gclc.prompt.CLIPrompterMessages; import fr.bigeon.gclc.prompt.CLIPrompterMessages;
/** A command to print help of an other command. /** A command to print help of an other command.
@ -54,17 +55,13 @@ 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;
/** The console manager */
private final ConsoleManager consoleManager;
/** @param cmdName the command name /** @param cmdName the command name
* @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(final String cmdName, final ConsoleManager consoleManager, public HelpExecutor(final String cmdName,
final ICommand cmd) { final ICommand cmd) {
super(cmdName); super(cmdName);
this.cmd = cmd; this.cmd = cmd;
this.consoleManager = consoleManager;
} }
/* (non-Javadoc) /* (non-Javadoc)
@ -78,11 +75,13 @@ public final class HelpExecutor extends Command {
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#execute(java.lang.String[]) */ * @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, java.lang.String[])
*/
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out, final ConsoleInput in,
final String... args) throws CommandRunException {
try { try {
cmd.help(consoleManager, args); cmd.help(out, args);
} catch (final IOException e) { } catch (final IOException e) {
throw new CommandRunException(CommandRunExceptionType.INTERACTION, throw new CommandRunException(CommandRunExceptionType.INTERACTION,
"Console manager closed", e, this); //$NON-NLS-1$ "Console manager closed", e, this); //$NON-NLS-1$

View File

@ -41,7 +41,8 @@ package fr.bigeon.gclc.command;
import java.io.IOException; import java.io.IOException;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
/** The contract of commands /** The contract of commands
* <p> * <p>
@ -50,10 +51,14 @@ import fr.bigeon.gclc.manager.ConsoleManager;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public interface ICommand { public interface ICommand {
/** @param args the arguments of the command (some expect an empty array) /** Execute the command on the given output and input.
* @throws CommandRunException if the execution of the command failed for *
* any reason */ * @param out the normal output
void execute(String... args) throws CommandRunException; * @param in the input
* @param args the arguments
* @throws CommandRunException if the command failed */
void execute(ConsoleOutput out, ConsoleInput in,
String... args) throws CommandRunException;
/** @return the command's name */ /** @return the command's name */
String getCommandName(); String getCommandName();
@ -72,10 +77,10 @@ public interface ICommand {
* [Usage details] * [Usage details]
* </pre> * </pre>
* *
* @param manager the manager to print the data * @param output the output to print the data
* @param args the arguments called with the help * @param args the arguments called with the help
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
void help(ConsoleManager manager, String... args) throws IOException; void help(ConsoleOutput output, String... args) throws IOException;
/** @return a tip on the command */ /** @return a tip on the command */
String tip(); String tip();

View File

@ -38,6 +38,8 @@ package fr.bigeon.gclc.command;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.InvalidCommandName; import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
/** <p> /** <p>
* An ICommadProvider is a provider of commands that can register commands under * An ICommadProvider is a provider of commands that can register commands under
@ -55,6 +57,23 @@ public interface ICommandProvider {
* @throws InvalidCommandName if the command name is invalid */ * @throws InvalidCommandName if the command name is invalid */
boolean add(ICommand value) throws InvalidCommandName; boolean add(ICommand value) throws InvalidCommandName;
/**
* <p>
* This method executes the command with the given name found. If no command
* with this name is found, an error command is usually executed. If there
* are several commands with the same name, the behavior is unspecified.
* Depending on the implementation, it may run an error command or prompt
* the user for a choice.
*
* @param out the output
* @param in the input
* @param command the name of the command the user wishes to execute
* @param args the arguments for the command
* @throws CommandRunException if the command failed to run */
void executeSub(ConsoleOutput out, ConsoleInput in,
String command,
String... args) throws CommandRunException;
/** <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
* with this name is found, an error command is usually executed. If there * with this name is found, an error command is usually executed. If there
@ -65,10 +84,12 @@ 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 */
@Deprecated
void executeSub(String command, void executeSub(String command,
String... args) throws CommandRunException; String... args) throws CommandRunException;
/** <p> /**
* <p>
* This method provide the command with the given name found. If no command * This method provide the command with the given name found. If no command
* with this name is found, an error command is usually returned. If there * with this name is found, an error command is usually returned. If there
* are several commands with the same name, the behavior is unspecified. * are several commands with the same name, the behavior is unspecified.

View File

@ -38,7 +38,9 @@
*/ */
package fr.bigeon.gclc.command; package fr.bigeon.gclc.command;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
/** This implement a command that does nothing. /** This implement a command that does nothing.
* <p> * <p>
@ -56,9 +58,11 @@ public final class MockCommand implements ICommand {
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */ * @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, java.lang.String[])
*/
@Override @Override
public void execute(final String... args) { public void execute(final ConsoleOutput out, final ConsoleInput in,
final String... args) throws CommandRunException {
// //
} }
@ -73,7 +77,7 @@ 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(final ConsoleManager manager, public void help(final ConsoleOutput manager,
final String... args) { final String... args) {
// //
} }

View File

@ -53,7 +53,9 @@ import fr.bigeon.gclc.exception.CommandParsingException;
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.InvalidParameterException; import fr.bigeon.gclc.exception.InvalidParameterException;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
import fr.bigeon.gclc.manager.EmptyInput;
/** A command relying on the {@link CommandParameters} to store parameters /** A command relying on the {@link CommandParameters} to store parameters
* values. * values.
@ -61,11 +63,6 @@ import fr.bigeon.gclc.manager.ConsoleManager;
* @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
* that were not provided on execution. */
private boolean interactive = true;
/** The 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. */
@ -76,38 +73,6 @@ public abstract class ParametrizedCommand extends Command {
* paramters in the status maps. */ * paramters in the status maps. */
private final boolean strict; private final boolean strict;
/** 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 */
public ParametrizedCommand(final ConsoleManager manager,
final String name) {
this(manager, 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 manager the manager
* @param name the name
* @param strict if the arguments are restricted to the declared ones */
public ParametrizedCommand(final ConsoleManager manager, final String name,
final boolean strict) {
super(name);
this.manager = manager;
interactive = manager != null;
this.strict = strict;
}
/** Create a parametrized command. /** Create a parametrized command.
* <p> * <p>
* Implementation are supposed to call the * Implementation are supposed to call the
@ -117,7 +82,7 @@ public abstract class ParametrizedCommand extends Command {
* *
* @param name the name */ * @param name the name */
public ParametrizedCommand(final String name) { public ParametrizedCommand(final String name) {
this(null, name, true); this(name, true);
} }
/** Create a parametrized command. /** Create a parametrized command.
@ -130,7 +95,8 @@ public abstract class ParametrizedCommand extends Command {
* @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(final String name, final boolean strict) { public ParametrizedCommand(final String name, final boolean strict) {
this(null, name, strict); super(name);
this.strict = strict;
} }
/** Add a boolean parameter to defined parmaters. /** Add a boolean parameter to defined parmaters.
@ -183,14 +149,19 @@ public abstract class ParametrizedCommand extends Command {
/** Actually performs the execution after parsing the parameters. /** Actually performs the execution after parsing the parameters.
* *
* @param out the output
* @param in the input
* @param parameters the command 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(ConsoleOutput out, ConsoleInput in,
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[]) */
@Override @Override
public final void execute(final String... args) throws CommandRunException { public final void execute(final ConsoleOutput output,
final ConsoleInput input,
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 {
@ -203,7 +174,7 @@ public abstract class ParametrizedCommand extends Command {
for (final Entry<String, Boolean> string : params.entrySet()) { for (final Entry<String, Boolean> string : params.entrySet()) {
if (string.getValue().booleanValue() && if (string.getValue().booleanValue() &&
parameters.get(string.getKey()) == null) { parameters.get(string.getKey()) == null) {
if (!interactive) { if (input == null || input == EmptyInput.INSTANCE) {
throw new CommandRunException( throw new CommandRunException(
CommandRunExceptionType.INTERACTION, CommandRunExceptionType.INTERACTION,
"Missing required parameter " + string.getKey(), //$NON-NLS-1$ "Missing required parameter " + string.getKey(), //$NON-NLS-1$
@ -213,26 +184,28 @@ public abstract class ParametrizedCommand extends Command {
} }
} }
// for each needed parameters that is missing, prompt the user. // for each needed parameters that is missing, prompt the user.
fillParameters(toProvide, parameters); fillParameters(input, toProvide, parameters);
doExecute(parameters); doExecute(output, input, parameters);
} }
/** Fill the undefined parameters. /** Fill the undefined parameters.
* <p> * <p>
* This method prompts the user to fill the needed parameters. * This method prompts the user to fill the needed parameters.
* *
* @param input the input to prompt through
* @param parameters the parameter list to complete * @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 final void fillParameters(final List<String> toProvide, private final void fillParameters(final ConsoleInput input,
final List<String> toProvide,
final 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 = input
.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(MessageFormat.format( value = input.prompt(MessageFormat.format(
"value of {0}? (cannot be empty) ", //$NON-NLS-1$ "value of {0}? (cannot be empty) ", //$NON-NLS-1$
string)); string));
} }
@ -266,15 +239,6 @@ public abstract class ParametrizedCommand extends Command {
return stringParams.keySet(); 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. /** Test if a parameter is needed.
* *
* @param param the parameter name * @param param the parameter name

View File

@ -52,6 +52,8 @@ import fr.bigeon.gclc.GCLCConstants;
import fr.bigeon.gclc.exception.CommandParsingException; import fr.bigeon.gclc.exception.CommandParsingException;
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.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
/** A command that will laucnh a series of command from a file /** A command that will laucnh a series of command from a file
* <p> * <p>
@ -94,10 +96,13 @@ public final class ScriptExecution extends Command {
} }
} }
/* (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(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out, final ConsoleInput in,
final String... args) throws CommandRunException {
checkArgs(args); checkArgs(args);
final String scriptFile = args[0]; final String scriptFile = args[0];
final String[] params = Arrays.copyOfRange(args, 1, args.length); final String[] params = Arrays.copyOfRange(args, 1, args.length);
@ -114,7 +119,8 @@ public final class ScriptExecution extends Command {
} }
final List<String> ps = GCLCConstants.splitCommand(cmdLine); final List<String> ps = GCLCConstants.splitCommand(cmdLine);
final String command = ps.remove(0); final String command = ps.remove(0);
application.executeSub(command, ps.toArray(new String[0])); application.executeSub(out, in, command,
ps.toArray(new String[0]));
} }
} catch (final CommandParsingException e) { } catch (final CommandParsingException e) {
throw new CommandRunException(MessageFormat.format( throw new CommandRunException(MessageFormat.format(

View File

@ -41,7 +41,8 @@ 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.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
/** /**
* <p> * <p>
@ -104,17 +105,19 @@ public final class SubedCommand extends CommandProvider implements ICommand {
/* (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(final String... args) throws CommandRunException { public void execute(final ConsoleOutput output, final ConsoleInput input,
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(output, input, args);
} else { } else {
throw new CommandRunException("Unrecognized command", this); //$NON-NLS-1$ throw new CommandRunException("Unrecognized command", this); //$NON-NLS-1$
} }
} else { } else {
try { try {
executeSub(args[0], Arrays.copyOfRange(args, 1, args.length)); executeSub(output, input, args[0],
Arrays.copyOfRange(args, 1, args.length));
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
if (e.getSource() != null) { if (e.getSource() != null) {
throw e; throw e;
@ -135,7 +138,7 @@ public final class SubedCommand extends CommandProvider implements ICommand {
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#help() */ * @see fr.bigeon.gclc.command.Command#help() */
@Override @Override
public void help(final ConsoleManager manager, public void help(final ConsoleOutput manager,
final 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
@ -172,5 +175,4 @@ public final class SubedCommand extends CommandProvider implements ICommand {
public String toString() { public String toString() {
return "SubedCommand " + super.toString(); //$NON-NLS-1$ return "SubedCommand " + super.toString(); //$NON-NLS-1$
} }
} }

View File

@ -33,71 +33,18 @@
* knowledge of the CeCILL license and that you accept its terms. * knowledge of the CeCILL license and that you accept its terms.
*/ */
/** /**
* gclc:fr.bigeon.gclc.ConsoleManager.java * gclc:fr.bigeon.gclc.manager.ConsoleInput.java
* Created on: Dec 19, 2014 * Created on: Nov 13, 2017
*/ */
package fr.bigeon.gclc.manager; package fr.bigeon.gclc.manager;
import java.io.IOException; import java.io.IOException;
import java.io.InterruptedIOException; import java.io.InterruptedIOException;
/** <p> /** A console application input.
* A console manager is in charge of the basic prompts and prints on a console.
* <p>
* Depending on the implementation, some manager may not support the prompt with
* a message, in that case, the usual behavior is to prompt normally.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel Bigeon */
public interface ConsoleManager extends AutoCloseable { public interface ConsoleInput extends AutoCloseable {
/** @return the prompt prefix */
String getPrompt();
/** @param text the message to print (without line break at the end).
* @throws IOException if the manager is closed or could not read the
* prompt */
void print(String text) throws IOException;
/** Prints an end of line
*
* @throws IOException if the manager is closed or could not read the
* prompt */
void println() throws IOException;
/** @param message the message to print
* @throws IOException if the manager is closed or could not read the
* prompt */
void println(String message) throws IOException;
/** @return the user inputed string
* @throws IOException if the manager is closed or could not read the prompt
* @throws InterruptedIOException if the prompt was interrupted */
String prompt() throws IOException;
/** @param timeout the time to wait in milliseconds
* @return the user inputed string, null if the timeout was reached
* @throws IOException if the manager is closed or could not read the prompt
* @throws InterruptedIOException if the prompt was interrupted */
String prompt(long timeout) throws IOException;
/** @param message the message to prompt the user
* @return the user inputed string
* @throws IOException if the manager is closed or could not read the prompt
* @throws InterruptedIOException if the prompt was interrupted */
String prompt(String message) throws IOException;
/** @param timeout the time to wait in milliseconds
* @param message the message to prompt the user
* @return the user inputed string, null if the timeout was reached
* @throws IOException if the manager is closed or could not read the prompt
* @throws InterruptedIOException if the prompt was interrupted */
String prompt(String message, long timeout) throws IOException;
/** <p>
* Set a prompting prefix.
*
* @param prompt the prompt */
void setPrompt(String prompt);
/** Closes the manager. /** Closes the manager.
* *
@ -105,8 +52,10 @@ public interface ConsoleManager extends AutoCloseable {
@Override @Override
void close() throws IOException; void close() throws IOException;
/** @return if the manager is closed. */ /** Get the prompt string.
boolean isClosed(); *
* @return the prompt prefix */
String getPrompt();
/** Indicate to the manager that is should interrompt the prompting, if /** Indicate to the manager that is should interrompt the prompting, if
* possible. * possible.
@ -116,4 +65,50 @@ public interface ConsoleManager extends AutoCloseable {
* (from the partial prompt content to an empty string or even a null * (from the partial prompt content to an empty string or even a null
* pointer). */ * pointer). */
void interruptPrompt(); void interruptPrompt();
/** Test if the input is closed.
* <p>
* If this is true, {@link #prompt()} methods will return immediatly and a
* null chain.
*
* @return if the manager is closed. */
boolean isClosed();
/** Prompt the user.
*
* @return the user inputed string
* @throws IOException if the manager is closed or could not read the prompt
* @throws InterruptedIOException if the prompt was interrupted */
String prompt() throws IOException;
/** Prompt the user, with an allotated time to answer.
*
* @param timeout the time to wait in milliseconds
* @return the user inputed string, null if the timeout was reached
* @throws IOException if the manager is closed or could not read the prompt
* @throws InterruptedIOException if the prompt was interrupted */
String prompt(long timeout) throws IOException;
/** Prompt the user, with a hint on what is prompted.
*
* @param message the message to prompt the user
* @return the user inputed string
* @throws IOException if the manager is closed or could not read the prompt
* @throws InterruptedIOException if the prompt was interrupted */
String prompt(String message) throws IOException;
/** Prompt the user, with a hint on what is prompted and an allotated time
* to answer.
*
* @param timeout the time to wait in milliseconds
* @param message the message to prompt the user
* @return the user inputed string, null if the timeout was reached
* @throws IOException if the manager is closed or could not read the prompt
* @throws InterruptedIOException if the prompt was interrupted */
String prompt(String message, long timeout) throws IOException;
/** Set a prompting prefix.
*
* @param prompt the prompt */
void setPrompt(String prompt);
} }

View File

@ -33,39 +33,45 @@
* knowledge of the CeCILL license and that you accept its terms. * knowledge of the CeCILL license and that you accept its terms.
*/ */
/** /**
* gclc:fr.bigeon.gclc.proc.ProcessList.java * gclc:fr.bigeon.gclc.manager.ConsoleOutput.java
* Created on: May 10, 2017 * Created on: Nov 13, 2017
*/ */
package fr.bigeon.gclc.proc; package fr.bigeon.gclc.manager;
import fr.bigeon.gclc.command.Command; import java.io.IOException;
/** An abstract command to generate a task and return the control to the user /**
* <p>
* TODO
*
* @author Emmanuel Bigeon
* *
* @author Emmanuel Bigeon */
public abstract class TaskSpawner extends Command {
/** The process pool */
private final TaskPool pool;
/** @param name the command name
* @param pool the pool */
public TaskSpawner(final String name, final TaskPool pool) {
super(name);
this.pool = pool;
}
/** @param args the arguments
* @return the process to start and add to the pool */
protected abstract Task createTask(String... args);
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[])
*/ */
public interface ConsoleOutput extends AutoCloseable {
/* (non-Javadoc)
* @see java.lang.AutoCloseable#close() */
@Override @Override
public final void execute(final String... args) { void close() throws IOException;
final Task task = createTask(args);
final Thread th = new Thread(task); /** Print a string.
th.start(); * @param text the message to print (without line break at the end).
pool.add(task); * @throws IOException if the manager is closed or could not read the
} * prompt */
void print(String text) throws IOException;
/** Prints an end of line
*
* @throws IOException if the manager is closed or could not read the
* prompt */
void println() throws IOException;
/** @param message the message to print
* @throws IOException if the manager is closed or could not read the
* prompt */
void println(String message) throws IOException;
/** @return if the manager is closed. */
boolean isClosed();
} }

View File

@ -0,0 +1,119 @@
/*
* 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.manager.EmptyInput.java
* Created on: Nov 13, 2017
*/
package fr.bigeon.gclc.manager;
import java.io.IOException;
/** A console input that return empty to all prompting.
*
* @author Emmanuel Bigeon */
public final class EmptyInput implements ConsoleInput {
/** The empty prompter. */
public static final ConsoleInput INSTANCE = new EmptyInput();
/** The empty input. */
private EmptyInput() {
//
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#close() */
@Override
public void close() throws IOException {
//
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#getPrompt() */
@Override
public String getPrompt() {
return ""; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#interruptPrompt() */
@Override
public void interruptPrompt() {
//
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#isClosed() */
@Override
public boolean isClosed() {
return false;
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#prompt() */
@Override
public String prompt() throws IOException {
return ""; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#prompt(long) */
@Override
public String prompt(final long timeout) throws IOException {
return ""; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String) */
@Override
public String prompt(final String message) throws IOException {
return ""; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String,
* long) */
@Override
public String prompt(final String message,
final long timeout) throws IOException {
return ""; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String) */
@Override
public void setPrompt(final String prompt) {
//
}
}

View File

@ -53,13 +53,13 @@ import java.nio.charset.StandardCharsets;
* used to test application behavior. * used to test application behavior.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class PipedConsoleManager public final class PipedConsoleInput
implements ConsoleManager { implements ConsoleInput {
/** The encoding between streams */ /** The encoding between streams */
private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$ private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
/** THe inner manager */ /** THe inner manager */
private final SystemConsoleManager innerManager; private final SystemConsoleInput innerManager;
/** The stream to pipe commands into */ /** The stream to pipe commands into */
private final PipedOutputStream commandInput; private final PipedOutputStream commandInput;
/** The reader to get application return from */ /** The reader to get application return from */
@ -78,7 +78,7 @@ public final class PipedConsoleManager
/** Create a manager that will write and read through piped stream. /** Create a manager that will write and read through piped stream.
* *
* @throws IOException if the piping failed for streams */ * @throws IOException if the piping failed for streams */
public PipedConsoleManager() throws IOException { public PipedConsoleInput() throws IOException {
commandInput = new PipedOutputStream(); commandInput = new PipedOutputStream();
in = new PipedInputStream(commandInput); in = new PipedInputStream(commandInput);
commandOutput = new PipedInputStream(); commandOutput = new PipedInputStream();
@ -86,7 +86,7 @@ public final class PipedConsoleManager
commandBuffOutput = new BufferedReader( commandBuffOutput = new BufferedReader(
new InputStreamReader(commandOutput, StandardCharsets.UTF_8)); new InputStreamReader(commandOutput, StandardCharsets.UTF_8));
outPrint = new PrintStream(out, true, UTF_8); outPrint = new PrintStream(out, true, UTF_8);
innerManager = new SystemConsoleManager(outPrint, in, innerManager = new SystemConsoleInput(outPrint, in,
StandardCharsets.UTF_8); StandardCharsets.UTF_8);
writing = new WritingRunnable(commandInput, StandardCharsets.UTF_8); writing = new WritingRunnable(commandInput, StandardCharsets.UTF_8);
reading = new ReadingRunnable(commandBuffOutput); reading = new ReadingRunnable(commandBuffOutput);
@ -139,21 +139,6 @@ public final class PipedConsoleManager
return innerManager.isClosed(); return innerManager.isClosed();
} }
@Override
public void print(final String object) throws IOException {
innerManager.print(object);
}
@Override
public void println() throws IOException {
innerManager.println();
}
@Override
public void println(final String object) throws IOException {
innerManager.println(object);
}
@Override @Override
public String prompt() throws IOException { public String prompt() throws IOException {
return innerManager return innerManager

View File

@ -0,0 +1,135 @@
/*
* 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-test:fr.bigeon.gclc.test.TestConsoleManager.java
* Created on: Nov 18, 2016
*/
package fr.bigeon.gclc.manager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
/** This console manager allows to enter commands and retrieve the output as an
* input.
* <p>
* This console manager is used to internally pilot an application. This can be
* used to test application behavior.
*
* @author Emmanuel Bigeon */
public final class PipedConsoleOutput
implements ConsoleOutput {
/** The encoding between streams */
private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
/** THe inner manager */
private final SystemConsoleOutput innerManager;
/** The reader to get application return from */
private final BufferedReader commandBuffOutput;
/** The stream to get application return from */
private final PipedInputStream commandOutput;
/** The print writer for application to write return to */
private final PrintStream outPrint;
/** The reading thread */
private final ReadingRunnable reading;
/** Create a manager that will write and read through piped stream.
*
* @throws IOException if the piping failed for streams */
public PipedConsoleOutput() throws IOException {
commandOutput = new PipedInputStream();
final PipedOutputStream out = new PipedOutputStream(commandOutput);
commandBuffOutput = new BufferedReader(
new InputStreamReader(commandOutput, StandardCharsets.UTF_8));
outPrint = new PrintStream(out, true, UTF_8);
innerManager = new SystemConsoleOutput(outPrint);
reading = new ReadingRunnable(commandBuffOutput);
final Thread th = new Thread(reading, "read"); //$NON-NLS-1$
th.setDaemon(true);
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);
innerManager.close();
outPrint.close();
commandBuffOutput.close();
commandOutput.close();
}
/** @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);
}
@Override
public boolean isClosed() {
return innerManager.isClosed();
}
@Override
public void print(final String object) throws IOException {
innerManager.print(object);
}
@Override
public void println() throws IOException {
innerManager.println();
}
@Override
public void println(final String object) throws IOException {
innerManager.println(object);
}
/** @return the content of the next line written by the application
* @throws IOException if the reading failed */
public String readNextLine() throws IOException {
return reading.getMessage();
}
}

View File

@ -69,7 +69,8 @@ public final 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(final Object obj, final Object start, final 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;
@ -214,7 +215,8 @@ public final class ReadingRunnable implements Runnable {
} }
final Object obj = messageBlocker.get(message); final Object obj = messageBlocker.get(message);
final Object start = new Object(); final Object start = new Object();
final ToWaitRunnable waitRunn = new ToWaitRunnable(obj, start, message); final ToWaitRunnable waitRunn = new ToWaitRunnable(obj, start,
message);
final Thread th = new Thread(waitRunn); final Thread th = new Thread(waitRunn);
synchronized (start) { synchronized (start) {
@ -294,14 +296,18 @@ public final class ReadingRunnable implements Runnable {
lock.notifyAll(); lock.notifyAll();
} }
} catch (final InterruptedIOException e) { } catch (final InterruptedIOException e) {
if (running) {
LOGGER.info("Reading interrupted"); //$NON-NLS-1$ LOGGER.info("Reading interrupted"); //$NON-NLS-1$
}
LOGGER.log(Level.FINER, LOGGER.log(Level.FINER,
"Read interruption was caused by an exception", e); //$NON-NLS-1$ "Read interruption was caused by an exception", e); //$NON-NLS-1$
} catch (final IOException e) { } 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$ LOGGER.log(Level.FINE, "The stream reading threw an exception", //$NON-NLS-1$
e); e);
if (running) {
LOGGER.severe("Unable to read from stream"); //$NON-NLS-1$
running = false; running = false;
}
return; return;
} }
} }

View File

@ -33,47 +33,59 @@
* knowledge of the CeCILL license and that you accept its terms. * knowledge of the CeCILL license and that you accept its terms.
*/ */
/** /**
* gclc:fr.bigeon.gclc.proc.ProcessList.java * gclc:fr.bigeon.gclc.manager.SinkOutput.java
* Created on: May 10, 2017 * Created on: Nov 13, 2017
*/ */
package fr.bigeon.gclc.proc; package fr.bigeon.gclc.manager;
import fr.bigeon.gclc.command.Command; import java.io.IOException;
/** A command that will flag a task to stop /** A console output that absorbs every message.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class ProcessKill extends Command { public class SinkOutput implements ConsoleOutput {
/** The taskpool */
private final TaskPool pool;
/** @param name the command name /** The sink output. */
* @param pool the pool */ public static final ConsoleOutput INSTANCE = new SinkOutput();
public ProcessKill(final String name, final TaskPool pool) {
super(name); /** Singleton constructor. */
this.pool = pool; private SinkOutput() {
//
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleOutput#close() */
@Override
public void close() throws IOException {
//
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */ * @see fr.bigeon.gclc.manager.ConsoleOutput#isClosed() */
@Override @Override
public void execute(final String... args) { public boolean isClosed() {
pool.get(args[0]).setRunning(false); return false;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#tip() */ * @see fr.bigeon.gclc.manager.ConsoleOutput#print(java.lang.String) */
@SuppressWarnings("nls")
@Override @Override
public String tip() { public void print(final String text) throws IOException {
return "Request a process to stop (softly)"; //
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail() */ * @see fr.bigeon.gclc.manager.ConsoleOutput#println() */
@Override @Override
protected String usageDetail() { public void println() throws IOException {
return null; //
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleOutput#println(java.lang.String)
*/
@Override
public void println(final String message) throws IOException {
//
} }
} }

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 { public final class SystemConsoleInput implements ConsoleInput {
/** The default prompt */ /** The default prompt */
public static final String DEFAULT_PROMPT = "> "; //$NON-NLS-1$ public static final String DEFAULT_PROMPT = "> "; //$NON-NLS-1$
@ -74,14 +74,14 @@ public final class SystemConsoleManager implements ConsoleManager {
/** This default constructor relies on the system defined standart output /** This default constructor relies on the system defined standart output
* and input stream. */ * and input stream. */
public SystemConsoleManager() { public SystemConsoleInput() {
this(System.out, System.in, Charset.defaultCharset()); this(System.out, System.in, Charset.defaultCharset());
} }
/** @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(final PrintStream out, final InputStream in, public SystemConsoleInput(final PrintStream out, final InputStream in,
final Charset charset) { final Charset charset) {
super(); super();
this.out = out; this.out = out;
@ -117,7 +117,7 @@ public final class SystemConsoleManager implements ConsoleManager {
/** Beware, in this implementation this is the same as closing the manager. /** Beware, in this implementation this is the same as closing the manager.
* *
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */ * @see fr.bigeon.gclc.manager.ConsoleInput#interruptPrompt() */
@Override @Override
public void interruptPrompt() { public void interruptPrompt() {
reading.interrupt(); reading.interrupt();
@ -130,30 +130,6 @@ public final class SystemConsoleManager implements ConsoleManager {
return closed; return closed;
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#print(java.lang.Object) */
@Override
public void print(final String object) throws IOException {
checkOpen();
out.print(object);
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#println() */
@Override
public void println() throws IOException {
checkOpen();
out.println();
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#println(java.lang.Object) */
@Override
public void println(final String object) throws IOException {
checkOpen();
out.println(object);
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#prompt() */ * @see fr.bigeon.gclc.ConsoleManager#prompt() */
@Override @Override

View File

@ -0,0 +1,116 @@
/*
* 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.system.SystemConsoleManager.java
* Created on: Dec 19, 2014
*/
package fr.bigeon.gclc.manager;
import java.io.IOException;
import java.io.PrintStream;
/** A console using the input stream and print stream.
* <p>
* The default constructor will use the system standart input and output.
*
* @author Emmanuel BIGEON */
public final class SystemConsoleOutput implements ConsoleOutput {
/** The default prompt */
public static final String DEFAULT_PROMPT = "> "; //$NON-NLS-1$
/** The print stream */
private final PrintStream out;
/** If the manager is closed */
private boolean closed = false;
/** This default constructor relies on the system defined standart output
* and input stream. */
public SystemConsoleOutput() {
this(System.out);
}
/** @param out the output stream */
public SystemConsoleOutput(final PrintStream out) {
super();
this.out = out;
}
/** @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;
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#isClosed() */
@Override
public boolean isClosed() {
return closed;
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#print(java.lang.Object) */
@Override
public void print(final String object) throws IOException {
checkOpen();
out.print(object);
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#println() */
@Override
public void println() throws IOException {
checkOpen();
out.println();
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#println(java.lang.Object) */
@Override
public void println(final String object) throws IOException {
checkOpen();
out.println(object);
}
}

View File

@ -1,47 +0,0 @@
/*
* 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.proc.InterruptionListener.java
* Created on: May 10, 2017
*/
package fr.bigeon.gclc.proc;
/** A listener for interruption
*
* @author Emmanuel Bigeon */
public interface InterruptionListener {
/** Notification of an interuption of a listened object */
void interrupted();
}

View File

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

View File

@ -1,81 +0,0 @@
/*
* 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.proc.ThreadCommand.java
* Created on: May 10, 2017
*/
package fr.bigeon.gclc.proc;
/** Tasks are named runnable that can be interrupted.
* <p>
* Good practice for those objects include an absence of interaction with the
* user (otherwise the user may not know from which running command comes
* information and requests) and unicity of the object to have a coherent
* control through the {@link #setRunning(boolean)} method.
* <p>
* Typical cases where such command can be useful is for an application that
* does long computations.
*
* @author Emmanuel Bigeon */
public interface Task extends Runnable {
/** Add a listener for this command end of execution
*
* @param listener the listener */
void addInterruptionListener(InterruptionListener listener);
/** Get the task name.
*
* @return the task name */
String getName();
/** Test the running status of the task.
*
* @return if the command is supposed to be running */
boolean isRunning();
/** Remove a listener of this command end of execution
*
* @param listener the listener */
void rmInterruptionListener(InterruptionListener listener);
/** Set the running state.
* <p>
* This method should be only called by external objects with the false
* argument. Calling this method with true has unspecified behavior and
* could do nothing as well as restart the command for example.
*
* @param running the running state */
void setRunning(boolean running);
}

View File

@ -1,118 +0,0 @@
/*
* 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.proc.TaskPool.java
* Created on: May 10, 2017
*/
package fr.bigeon.gclc.proc;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/** A process pool.
*
* @author Emmanuel Bigeon */
public final class TaskPool {
/** The running processes. */
private final Map<String, Task> running = new HashMap<>();
/** The count for process id. */
private int count = 0;
/** The lock for pid attribution synchronization. */
private final Object lock = new Object();
/** Default constructor. */
public TaskPool() {
//
}
/** Add a process in the pool.
*
* @param cmd the process
* @return the pid */
public String add(final Task cmd) {
if (cmd == null) {
throw new IllegalArgumentException("Task cannot be null"); //$NON-NLS-1$
}
final String pid = getPID();
synchronized (lock) {
running.put(pid, cmd);
}
cmd.addInterruptionListener(new InterruptionListener() {
@SuppressWarnings("synthetic-access")
@Override
public void interrupted() {
synchronized (lock) {
running.remove(pid);
count = Math.min(count, Integer.parseInt(pid));
}
cmd.rmInterruptionListener(this);
}
});
return pid;
}
/** Get a process by it associated identifier.
*
* @param pid the task id
* @return the task, if any, associated to this id */
public Task get(final String pid) {
synchronized (lock) {
return running.get(pid);
}
}
/** Get the next process id.
*
* @return the process id */
private String getPID() {
synchronized (lock) {
String pid;
do {
pid = Integer.toString(count++);
} while (running.containsKey(pid));
return pid;
}
}
/** Get the running processes' identifiers.
*
* @return the pids */
public Collection<String> getPIDs() {
return new HashSet<>(running.keySet());
}
}

View File

@ -43,7 +43,8 @@ import java.util.Map;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
/** /**
* <p> * <p>
@ -101,32 +102,34 @@ public final class CLIPrompter {
return false; return false;
} }
/** @param manager the manager /** @param output the manager
* @param choices the choices * @param choices the choices
* @param cancel the cancel option if it exists * @param cancel the cancel option if it exists
* @return the number of choices plus one (or the number of choices if there * @return the number of choices plus one (or the number of choices if there
* is a cancel) * is a cancel)
* @throws IOException if the manager was closed */ * @throws IOException if the manager was closed */
private static <U> Integer listChoices(final ConsoleManager manager, private static <U> Integer listChoices(final ConsoleOutput output,
final List<U> choices, final List<U> choices,
final String cancel) throws IOException { 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$ output.println(index++ + ") " + u); //$NON-NLS-1$
} }
if (cancel != null) { if (cancel != null) {
manager.println(index++ + ") " + cancel); //$NON-NLS-1$ output.println(index++ + ") " + cancel); //$NON-NLS-1$
} }
return Integer.valueOf(index - 1); return Integer.valueOf(index - 1);
} }
/** @param manager the manager /** @param manager the manager
* @param input the input
* @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(final ConsoleManager manager, public static boolean promptBoolean(final ConsoleOutput manager,
final ConsoleInput input,
final String message) throws IOException { final String message) throws IOException {
String result = manager String result = input
.prompt(message + CLIPrompterMessages.getString(BOOL_CHOICES)); .prompt(message + CLIPrompterMessages.getString(BOOL_CHOICES));
boolean first = true; boolean first = true;
final String choices = CLIPrompterMessages final String choices = CLIPrompterMessages
@ -145,7 +148,7 @@ public final class CLIPrompter {
manager.println(CLIPrompterMessages manager.println(CLIPrompterMessages
.getString("promptbool.choices.invalid", choices)); //$NON-NLS-1$ .getString("promptbool.choices.invalid", choices)); //$NON-NLS-1$
result = manager.prompt( result = input.prompt(
message + CLIPrompterMessages.getString(BOOL_CHOICES)); message + CLIPrompterMessages.getString(BOOL_CHOICES));
} }
first = false; first = false;
@ -157,6 +160,7 @@ public final class CLIPrompter {
} }
/** @param manager the manager /** @param manager the manager
* @param input the input
* @param keys the keys to be printed * @param keys the keys to be printed
* @param choices the real choices * @param choices the real choices
* @param message the message * @param message the message
@ -165,12 +169,13 @@ public final 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(final ConsoleManager manager, public static <U> U promptChoice(final ConsoleOutput manager,
final ConsoleInput input,
final List<String> keys, final List<String> keys,
final List<U> choices, final List<U> choices,
final String message, final String message,
final String cancel) throws IOException { final String cancel) throws IOException {
final Integer index = promptChoice(manager, keys, message, cancel); final Integer index = promptChoice(manager, input, keys, message, cancel);
if (index == null) { if (index == null) {
return null; return null;
} }
@ -178,6 +183,7 @@ public final class CLIPrompter {
} }
/** @param manager the manager /** @param manager the manager
* @param input the input
* @param <U> The choices labels type * @param <U> The choices labels type
* @param <T> The real choices objects * @param <T> The real choices objects
* @param choices the list of labels (in order to be displayed) * @param choices the list of labels (in order to be displayed)
@ -186,12 +192,14 @@ public final 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(final ConsoleManager manager, public static <U, T> T promptChoice(final ConsoleOutput manager,
final ConsoleInput input,
final List<U> choices, final List<U> choices,
final Map<U, T> choicesMap, final Map<U, T> choicesMap,
final String message, final String message,
final String cancel) throws IOException { final String cancel) throws IOException {
final Integer res = promptChoice(manager, choices, message, cancel); final Integer res = promptChoice(manager, input, choices, message,
cancel);
if (res == null) { if (res == null) {
return null; return null;
} }
@ -199,13 +207,15 @@ public final class CLIPrompter {
} }
/** @param manager the manager /** @param manager the manager
* @param input the input
* @param <U> the type of choices * @param <U> the type of choices
* @param choices the list of choices * @param choices the list of choices
* @param message the prompting message * @param message the prompting message
* @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 */
public static <U> Integer promptChoice(final ConsoleManager manager, public static <U> Integer promptChoice(final ConsoleOutput manager,
final ConsoleInput input,
final List<U> choices, final List<U> choices,
final String message, final String message,
final String cancel) throws IOException { final String cancel) throws IOException {
@ -215,7 +225,7 @@ public final class CLIPrompter {
boolean keepOn = true; boolean keepOn = true;
int r = -1; int r = -1;
while (keepOn) { while (keepOn) {
result = manager.prompt(CLIPrompterMessages.getString(PROMPT)); result = input.prompt(CLIPrompterMessages.getString(PROMPT));
try { try {
r = Integer.parseInt(result); r = Integer.parseInt(result);
if (r >= 0 && r <= index.intValue()) { if (r >= 0 && r <= index.intValue()) {
@ -240,6 +250,7 @@ public final class CLIPrompter {
} }
/** @param manager the manager /** @param manager the manager
* @param input the input
* @param <U> The choices labels type * @param <U> The choices labels type
* @param <T> The real choices objects * @param <T> The real choices objects
* @param choicesMap the map of label to actual objects * @param choicesMap the map of label to actual objects
@ -247,11 +258,13 @@ public final 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(final ConsoleManager manager, public static <U, T> T promptChoice(final ConsoleOutput manager,
final ConsoleInput input,
final Map<U, T> choicesMap, final Map<U, T> choicesMap,
final String message, final String message,
final String cancel) throws IOException { final String cancel) throws IOException {
return promptChoice(manager, new ArrayList<>(choicesMap.keySet()), return promptChoice(manager, input,
new ArrayList<>(choicesMap.keySet()),
choicesMap, message, cancel); choicesMap, message, cancel);
} }
@ -259,7 +272,7 @@ public final 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(final ConsoleManager manager, public static int promptInteger(final ConsoleInput manager,
final String message) throws IOException { final String message) throws IOException {
boolean still = true; boolean still = true;
int r = 0; int r = 0;
@ -284,23 +297,27 @@ public final class CLIPrompter {
/** This methods prompt the user for a list of elements /** This methods prompt the user for a list of elements
* *
* @param manager the manager * @param manager the manager
* @param input the input
* @param 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(final ConsoleManager manager, public static List<String> promptList(final ConsoleOutput manager,
final ConsoleInput input,
final String message) throws IOException { final String message) throws IOException {
return promptList(manager, message, return promptList(manager, input, message,
CLIPrompterMessages.getString("promptlist.exit.defaultkey")); //$NON-NLS-1$ CLIPrompterMessages.getString("promptlist.exit.defaultkey")); //$NON-NLS-1$
} }
/** This methods prompt the user for a list of elements /** This methods prompt the user for a list of elements
* *
* @param manager the manager * @param manager the manager
* @param input the input
* @param message the message * @param message the message
* @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(final ConsoleManager manager, public static List<String> promptList(final ConsoleOutput manager,
final ConsoleInput input,
final String message, final String message,
final String ender) throws IOException { final String ender) throws IOException {
final List<String> strings = new ArrayList<>(); final List<String> strings = new ArrayList<>();
@ -308,7 +325,7 @@ public final class CLIPrompter {
message + CLIPrompterMessages.getString(LIST_DISP_KEY, ender)); message + CLIPrompterMessages.getString(LIST_DISP_KEY, ender));
String res = null; String res = null;
while (!ender.equals(res)) { while (!ender.equals(res)) {
res = manager.prompt(CLIPrompterMessages.getString(PROMPT)); res = input.prompt(CLIPrompterMessages.getString(PROMPT));
if (!res.equals(ender)) { if (!res.equals(ender)) {
strings.add(res); strings.add(res);
} }
@ -319,23 +336,27 @@ public final class CLIPrompter {
/** Prompt for a text with several lines. /** Prompt for a text with several lines.
* *
* @param manager the manager * @param manager the manager
* @param input the input
* @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(final ConsoleManager manager, public static String promptLongText(final ConsoleOutput manager,
final ConsoleInput input,
final String message) throws IOException { final String message) throws IOException {
return promptLongText(manager, message, CLIPrompterMessages return promptLongText(manager, input, message, CLIPrompterMessages
.getString("promptlongtext.exit.defaultkey")); //$NON-NLS-1$ .getString("promptlongtext.exit.defaultkey")); //$NON-NLS-1$
} }
/** Prompt for a text with several lines. /** Prompt for a text with several lines.
* *
* @param manager the manager * @param manager the manager
* @param input the input
* @param message the prompting message * @param message the prompting message
* @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(final ConsoleManager manager, public static String promptLongText(final ConsoleOutput manager,
final ConsoleInput input,
final String message, final String message,
final String ender) throws IOException { final String ender) throws IOException {
manager.println(message + CLIPrompterMessages manager.println(message + CLIPrompterMessages
@ -343,7 +364,7 @@ public final class CLIPrompter {
final StringBuilder res = new StringBuilder(); final StringBuilder res = new StringBuilder();
String line; String line;
do { do {
line = manager.prompt(CLIPrompterMessages.getString(PROMPT)); line = input.prompt(CLIPrompterMessages.getString(PROMPT));
if (!line.equals(ender)) { if (!line.equals(ender)) {
res.append(line); res.append(line);
res.append(System.lineSeparator()); res.append(System.lineSeparator());
@ -353,17 +374,19 @@ public final class CLIPrompter {
} }
/** @param manager the manager /** @param manager the manager
* @param input the input
* @param keys the keys to be printed * @param keys the keys to be printed
* @param choices the real choices * @param choices the real choices
* @param message the message * @param message the message
* @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(final ConsoleManager manager, public static <U> List<U> promptMultiChoice(final ConsoleOutput manager,
final ConsoleInput input,
final List<String> keys, final List<String> keys,
final List<U> choices, final List<U> choices,
final String message) throws IOException { final String message) throws IOException {
final List<Integer> indices = promptMultiChoice(manager, keys, message); final List<Integer> indices = promptMultiChoice(manager, input, keys, message);
final List<U> userChoices = new ArrayList<>(); final List<U> userChoices = new ArrayList<>();
for (final Integer integer : indices) { for (final Integer integer : indices) {
userChoices.add(choices.get(integer.intValue())); userChoices.add(choices.get(integer.intValue()));
@ -372,6 +395,7 @@ public final class CLIPrompter {
} }
/** @param manager the manager /** @param manager the manager
* @param input the input
* @param <U> The choices labels type * @param <U> The choices labels type
* @param <T> The real choices objects * @param <T> The real choices objects
* @param choices the list of labels (in order to be displayed) * @param choices the list of labels (in order to be displayed)
@ -379,11 +403,13 @@ public final 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(final ConsoleManager manager, public static <U, T> List<T> promptMultiChoice(final ConsoleOutput manager,
final ConsoleInput input,
final List<U> choices, final List<U> choices,
final Map<U, T> choicesMap, final Map<U, T> choicesMap,
final String message) throws IOException { final String message) throws IOException {
final List<Integer> chs = promptMultiChoice(manager, choices, message); final List<Integer> chs = promptMultiChoice(manager, input, choices,
message);
final List<T> userChoices = new ArrayList<>(); final List<T> userChoices = new ArrayList<>();
for (final Integer integer : chs) { for (final Integer integer : chs) {
userChoices.add(choicesMap.get(choices.get(integer.intValue()))); userChoices.add(choicesMap.get(choices.get(integer.intValue())));
@ -392,12 +418,14 @@ public final class CLIPrompter {
} }
/** @param manager the manager /** @param manager the manager
* @param input the input
* @param <U> the type of choices * @param <U> the type of choices
* @param choices the list of choices * @param choices the list of choices
* @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 */
public static <U> List<Integer> promptMultiChoice(final ConsoleManager manager, public static <U> List<Integer> promptMultiChoice(final ConsoleOutput manager,
final ConsoleInput input,
final List<U> choices, final List<U> choices,
final String message) throws IOException { final String message) throws IOException {
manager.println(message); manager.println(message);
@ -407,7 +435,7 @@ public final class CLIPrompter {
final List<Integer> chs = new ArrayList<>(); final List<Integer> chs = new ArrayList<>();
while (keepOn) { while (keepOn) {
keepOn = false; keepOn = false;
result = manager.prompt(CLIPrompterMessages.getString(PROMPT)); result = input.prompt(CLIPrompterMessages.getString(PROMPT));
final String[] vals = result final String[] vals = result
.split(CLIPrompterMessages.getString(LIST_CHOICE_SEP)); .split(CLIPrompterMessages.getString(LIST_CHOICE_SEP));
for (final String val : vals) { for (final String val : vals) {
@ -435,16 +463,19 @@ public final class CLIPrompter {
} }
/** @param manager the manager /** @param manager the manager
* @param input the input
* @param <U> The choices labels type * @param <U> The choices labels type
* @param <T> The real choices objects * @param <T> The real choices objects
* @param choicesMap the map of label to actual objects * @param choicesMap the map of label to actual objects
* @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(final ConsoleManager manager, public static <U, T> List<T> promptMultiChoice(final ConsoleOutput manager,
final ConsoleInput input,
final Map<U, T> choicesMap, final Map<U, T> choicesMap,
final String message) throws IOException { final String message) throws IOException {
return promptMultiChoice(manager, new ArrayList<>(choicesMap.keySet()), return promptMultiChoice(manager, input,
new ArrayList<>(choicesMap.keySet()),
choicesMap, message); choicesMap, message);
} }
@ -453,7 +484,7 @@ public final 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(final ConsoleManager manager, public static String promptNonEmpty(final ConsoleInput manager,
final String prompt, final String prompt,
final String reprompt) throws IOException { final String reprompt) throws IOException {
String res = manager.prompt(prompt); String res = manager.prompt(prompt);

View File

@ -42,7 +42,7 @@ import java.io.IOException;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import fr.bigeon.gclc.manager.PipedConsoleManager; import fr.bigeon.gclc.manager.PipedConsoleOutput;
/** An incomplete implematation used to forward messages from a piped console. /** An incomplete implematation used to forward messages from a piped console.
* <p> * <p>
@ -57,14 +57,14 @@ public abstract class AOutputForwardRunnable implements Runnable {
/** The default timeout (one tenth of second). */ /** The default timeout (one tenth of second). */
private static final long DEFAULT_TIMEOUT = 100; private static final long DEFAULT_TIMEOUT = 100;
/** The manager. */ /** The manager. */
private final PipedConsoleManager manager; private final PipedConsoleOutput manager;
/** The timeout */ /** The timeout */
private final long timeout; private final long timeout;
/** Create a forwarding runnable. /** Create a forwarding runnable.
* *
* @param manager the manager */ * @param manager the manager */
public AOutputForwardRunnable(final PipedConsoleManager manager) { public AOutputForwardRunnable(final PipedConsoleOutput manager) {
super(); super();
this.manager = manager; this.manager = manager;
timeout = DEFAULT_TIMEOUT; timeout = DEFAULT_TIMEOUT;
@ -79,11 +79,12 @@ public abstract class AOutputForwardRunnable implements Runnable {
* likely to depend on the application and the use of it. * likely to depend on the application and the use of it.
* <p> * <p>
* If you do not know what timeout length to use, please use the * If you do not know what timeout length to use, please use the
* {@link #AOutputForwardRunnable(PipedConsoleManager)} constructor. * {@link #AOutputForwardRunnable(PipedConsoleOutput)} constructor.
* *
* @param manager the manager * @param manager the manager
* @param timeout the timeout between message requests. */ * @param timeout the timeout between message requests. */
public AOutputForwardRunnable(final PipedConsoleManager manager, final long timeout) { public AOutputForwardRunnable(final PipedConsoleOutput manager,
final long timeout) {
super(); super();
this.manager = manager; this.manager = manager;
this.timeout = timeout; this.timeout = timeout;

View File

@ -42,7 +42,8 @@ import java.io.IOException;
import fr.bigeon.gclc.command.ICommand; import fr.bigeon.gclc.command.ICommand;
import fr.bigeon.gclc.exception.InvalidCommandName; import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.PipedConsoleManager; import fr.bigeon.gclc.manager.PipedConsoleInput;
import fr.bigeon.gclc.manager.PipedConsoleOutput;
/** /**
* <p> * <p>
@ -56,12 +57,14 @@ public class CommandTestingApplication implements AutoCloseable {
private final ConsoleApplication application; private final ConsoleApplication application;
private final Thread th; private final Thread th;
private final PipedConsoleManager manager; private final PipedConsoleOutput out;
private final PipedConsoleInput in;
/** @throws IOException if the streams cannot be build */ /** @throws IOException if the streams cannot be build */
public CommandTestingApplication() throws IOException { public CommandTestingApplication() throws IOException {
manager = new PipedConsoleManager(); out = new PipedConsoleOutput();
application = new ConsoleApplication(manager, "", ""); in = new PipedConsoleInput();
application = new ConsoleApplication(out, in, "", "");
new ConsoleTestApplication().attach(application); new ConsoleTestApplication().attach(application);
th = new Thread(new Runnable() { th = new Thread(new Runnable() {
@ -75,49 +78,47 @@ public class CommandTestingApplication implements AutoCloseable {
th.start(); th.start();
} }
@Override
public void close() throws IOException {
application.exit();
manager.close();
}
public void sendCommand(String cmd) throws IOException {
manager.type(cmd);
}
/** @param cmd the command /** @param cmd the command
* @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
* @see fr.bigeon.gclc.ConsoleApplication#add(fr.bigeon.gclc.command.ICommand) */ * @see fr.bigeon.gclc.ConsoleApplication#add(fr.bigeon.gclc.command.ICommand) */
public final boolean add(ICommand cmd) throws InvalidCommandName { public final boolean add(final ICommand cmd) throws InvalidCommandName {
return application.add(cmd); return application.add(cmd);
} }
@Override
public void close() throws IOException {
application.exit();
out.close();
in.close();
}
/** @return the application */ /** @return the application */
public ConsoleApplication getApplication() { public ConsoleApplication getApplication() {
return application; return application;
} }
/** @return the next written line, null if it is the prompt
* @throws IOException if the reading failed
* @see fr.bigeon.gclc.manager.PipedConsoleManager#readNextLine() */
public String readNextLine() throws IOException {
final String ret = out.readNextLine();
return ret;
}
public void sendCommand(final String cmd) throws IOException {
in.type(cmd);
}
/** @throws IOException if the writing failed */ /** @throws IOException if the writing failed */
public void waitAndStop() throws IOException { public void waitAndStop() throws IOException {
manager.type(ConsoleTestApplication.EXIT); in.type(ConsoleTestApplication.EXIT);
try { try {
th.join(); th.join();
} catch (InterruptedException e) { } catch (final InterruptedException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
/** @return the next written line, null if it is the prompt
* @throws IOException if the reading failed
* @see fr.bigeon.gclc.manager.PipedConsoleManager#readNextLine() */
public String readNextLine() throws IOException {
String ret = manager.readNextLine();
if (ret.equals(manager.getPrompt())) {
return null;
}
return ret;
}
} }

View File

@ -55,8 +55,10 @@ 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.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.ConsoleInput;
import fr.bigeon.gclc.manager.PipedConsoleManager; import fr.bigeon.gclc.manager.ConsoleOutput;
import fr.bigeon.gclc.manager.PipedConsoleInput;
import fr.bigeon.gclc.manager.PipedConsoleOutput;
/** Test class for ConsoleApplication /** Test class for ConsoleApplication
* *
@ -71,8 +73,9 @@ public class ConsoleApplicationTest {
@Test @Test
public void testConsoleApplication() { public void testConsoleApplication() {
try (PipedConsoleManager manager = new PipedConsoleManager()) { try (PipedConsoleInput manager = new PipedConsoleInput()) {
final ConsoleApplication app = new ConsoleApplication(manager, "", ""); final ConsoleApplication app = new ConsoleApplication(null,
manager, "", "");
app.exit(); app.exit();
} catch (final IOException e) { } catch (final IOException e) {
fail("System Console Manager failed"); fail("System Console Manager failed");
@ -88,12 +91,9 @@ public class ConsoleApplicationTest {
assertEquals(application.getApplication().header, assertEquals(application.getApplication().header,
application.readNextLine()); application.readNextLine());
// Remove first prompt // Remove first prompt
assertNull(application.readNextLine());
application.sendCommand(""); application.sendCommand("");
assertNull(application.readNextLine());
application.sendCommand("test"); application.sendCommand("test");
assertEquals("Test command ran fine", application.readNextLine()); assertEquals("Test command ran fine", application.readNextLine());
assertNull(application.readNextLine());
application.sendCommand("toto"); application.sendCommand("toto");
assertEquals( assertEquals(
Messages.getString("ConsoleApplication.cmd.failed", "toto"), Messages.getString("ConsoleApplication.cmd.failed", "toto"),
@ -101,7 +101,6 @@ public class ConsoleApplicationTest {
assertEquals( assertEquals(
Messages.getString("CommandProvider.unrecognized", "toto"), Messages.getString("CommandProvider.unrecognized", "toto"),
application.readNextLine()); application.readNextLine());
assertNull(application.readNextLine());
application.sendCommand("long"); application.sendCommand("long");
assertEquals("Waita minute", application.readNextLine()); assertEquals("Waita minute", application.readNextLine());
assertEquals("done!", application.readNextLine()); assertEquals("done!", application.readNextLine());
@ -122,7 +121,6 @@ public class ConsoleApplicationTest {
}; };
application.getApplication().addListener(crl); application.getApplication().addListener(crl);
application.getApplication().addListener(crl2); application.getApplication().addListener(crl2);
assertNull(application.readNextLine());
application.sendCommand("test"); application.sendCommand("test");
assertEquals("Test command ran fine", application.readNextLine()); assertEquals("Test command ran fine", application.readNextLine());
application.getApplication().removeListener(crl2); application.getApplication().removeListener(crl2);
@ -131,7 +129,6 @@ public class ConsoleApplicationTest {
assertTrue(application.getApplication().isRunning()); assertTrue(application.getApplication().isRunning());
assertNull(application.readNextLine());
application.sendCommand("exit"); application.sendCommand("exit");
assertEquals(application.getApplication().footer, assertEquals(application.getApplication().footer,
application.readNextLine()); application.readNextLine());
@ -141,8 +138,10 @@ public class ConsoleApplicationTest {
} }
ConsoleApplication appli = null; ConsoleApplication appli = null;
try (PipedConsoleManager manager = new PipedConsoleManager()) { try (PipedConsoleOutput manager = new PipedConsoleOutput();
final ConsoleApplication app = new ConsoleApplication(manager, null, PipedConsoleInput in = new PipedConsoleInput()) {
final ConsoleApplication app = new ConsoleApplication(manager,
in, null,
null); null);
appli = app; appli = app;
app.add(new ExitCommand("exit", app)); app.add(new ExitCommand("exit", app));
@ -158,7 +157,7 @@ public class ConsoleApplicationTest {
th.start(); th.start();
manager.type("exit"); in.type("exit");
th.join(); th.join();
} catch (IOException | InvalidCommandName | } catch (IOException | InvalidCommandName |
@ -175,8 +174,10 @@ public class ConsoleApplicationTest {
@Test @Test
public void testInterpretCommand() { public void testInterpretCommand() {
try (PipedConsoleManager test = new PipedConsoleManager()) { try (PipedConsoleInput test = new PipedConsoleInput();
final ConsoleApplication appl = new ConsoleApplication(test, "", ""); PipedConsoleOutput out = new PipedConsoleOutput()) {
final ConsoleApplication appl = new ConsoleApplication(out, test,
"", "");
appl.interpretCommand("invalid cmd \"due to misplaced\"quote"); appl.interpretCommand("invalid cmd \"due to misplaced\"quote");
assertEquals("Command line cannot be parsed", test.readNextLine()); assertEquals("Command line cannot be parsed", test.readNextLine());
@ -187,8 +188,16 @@ public class ConsoleApplicationTest {
try { try {
appl.add(new ICommand() { appl.add(new ICommand() {
/* (non-Javadoc)
* @see
* fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc.
* manager.ConsoleOutput,
* fr.bigeon.gclc.manager.ConsoleInput,
* java.lang.String[]) */
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
throw new CommandRunException( throw new CommandRunException(
CommandRunExceptionType.USAGE, message, this); CommandRunExceptionType.USAGE, message, this);
} }
@ -199,7 +208,7 @@ public class ConsoleApplicationTest {
} }
@Override @Override
public void help(final ConsoleManager manager, public void help(final ConsoleOutput manager,
final String... args) throws IOException { final String... args) throws IOException {
manager.println(message); manager.println(message);
} }

View File

@ -41,6 +41,8 @@ import fr.bigeon.gclc.command.ExitCommand;
import fr.bigeon.gclc.command.HelpExecutor; import fr.bigeon.gclc.command.HelpExecutor;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.InvalidCommandName; import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
/** A test-purpose application /** A test-purpose application
* *
@ -58,14 +60,20 @@ public class ConsoleTestApplication implements ApplicationAttachement {
public void attach(final ConsoleApplication application) { public void attach(final ConsoleApplication application) {
try { try {
application.add(new ExitCommand(EXIT, application)); application.add(new ExitCommand(EXIT, application));
application.add(new HelpExecutor("help", application.manager, application.add(new HelpExecutor("help",
application.root)); application.root));
application.add(new Command("test") { application.add(new Command("test") {
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc.
* manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput,
* java.lang.String[]) */
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
try { try {
application.manager.println("Test command ran fine"); out.println("Test command ran fine");
} catch (final IOException e) { } catch (final IOException e) {
throw new CommandRunException("manager closed", e, throw new CommandRunException("manager closed", e,
this); this);
@ -83,12 +91,18 @@ public class ConsoleTestApplication implements ApplicationAttachement {
} }
}); });
application.add(new Command("long") { application.add(new Command("long") {
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc.
* manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput,
* java.lang.String[]) */
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
try { try {
application.manager.println("Waita minute"); out.println("Waita minute");
Thread.sleep(TWO_SECONDS); Thread.sleep(TWO_SECONDS);
application.manager.println("done!"); out.println("done!");
} catch (final IOException e) { } catch (final IOException e) {
throw new CommandRunException("manager closed", e, throw new CommandRunException("manager closed", e,
this); this);
@ -109,8 +123,14 @@ public class ConsoleTestApplication implements ApplicationAttachement {
} }
}); });
application.add(new Command("failingCmd") { application.add(new Command("failingCmd") {
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc.
* manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput,
* java.lang.String[]) */
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
throw new CommandRunException("Failing command", this); throw new CommandRunException("Failing command", this);
} }

View File

@ -45,7 +45,9 @@ import java.io.IOException;
import org.junit.Test; import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.manager.PipedConsoleManager; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
import fr.bigeon.gclc.manager.PipedConsoleOutput;
/** <p> /** <p>
* TODO * TODO
@ -55,12 +57,14 @@ public class CommandTest {
@Test @Test
public final void testCommand() { public final void testCommand() {
try (PipedConsoleManager test = new PipedConsoleManager()) { try (PipedConsoleOutput test = new PipedConsoleOutput()) {
Command cmd; Command cmd;
cmd = new Command("name") { cmd = new Command("name") {
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
// //
} }
@ -79,7 +83,9 @@ public class CommandTest {
cmd = new Command("name") { cmd = new Command("name") {
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
// //
} }
@ -105,7 +111,9 @@ public class CommandTest {
} }
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
// //
} }
@ -131,7 +139,9 @@ public class CommandTest {
} }
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
// //
} }
@ -150,7 +160,9 @@ public class CommandTest {
cmd = new Command("name") { cmd = new Command("name") {
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
// //
} }
@ -171,7 +183,9 @@ public class CommandTest {
cmd = new Command("name") { cmd = new Command("name") {
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
// //
} }
@ -191,7 +205,9 @@ public class CommandTest {
cmd = new Command("name") { cmd = new Command("name") {
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
// //
} }
@ -212,7 +228,9 @@ public class CommandTest {
cmd = new Command("name") { cmd = new Command("name") {
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
// //
} }

View File

@ -47,29 +47,30 @@ import java.io.IOException;
import org.junit.Test; import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.manager.PipedConsoleManager; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
import fr.bigeon.gclc.manager.PipedConsoleOutput;
/** /**
* <p> * <p>
* TODO * TODO
* *
* @author Emmanuel Bigeon * @author Emmanuel Bigeon */
*
*/
public class HelpExecutorTest { public class HelpExecutorTest {
/** /** Test method for
* Test method for {@link fr.bigeon.gclc.command.HelpExecutor#execute(java.lang.String[])}. * {@link fr.bigeon.gclc.command.HelpExecutor#execute(java.lang.String[])}. */
*/
@Test @Test
public final void testExecute(){ public final void testExecute() {
try { try {
final PipedConsoleManager test = new PipedConsoleManager(); final PipedConsoleOutput test = new PipedConsoleOutput();
final HelpExecutor help = new HelpExecutor("?", test, final HelpExecutor help = new HelpExecutor("?",
new Command("mock") { new Command("mock") {
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
// //
} }
@ -77,6 +78,7 @@ public class HelpExecutorTest {
public String tip() { public String tip() {
return ""; return "";
} }
@Override @Override
protected String usageDetail() { protected String usageDetail() {
return null; return null;
@ -84,11 +86,11 @@ public class HelpExecutorTest {
}); });
help.execute(); help.execute(test, null);
test.close(); test.close();
try { try {
help.execute(); help.execute(test, null);
fail("manager closed shall provoke failure of help command execution"); fail("manager closed shall provoke failure of help command execution");
} catch (final Exception e) { } catch (final Exception e) {
assertNotNull(e); assertNotNull(e);
@ -105,26 +107,22 @@ public class HelpExecutorTest {
@Test @Test
public final void testHelpExecutor() throws IOException { public final void testHelpExecutor() throws IOException {
HelpExecutor help; HelpExecutor help;
try (PipedConsoleManager test = new PipedConsoleManager()) { help = new HelpExecutor("?", new MockCommand("mock"));
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 (PipedConsoleOutput test = new PipedConsoleOutput()) {
final HelpExecutor help = new HelpExecutor("?", test, final HelpExecutor help = new HelpExecutor("?",
new MockCommand("mock")); new MockCommand("mock"));
help.tip(); help.tip();
help.help(test); help.help(test);
} catch (final Exception e) { } catch (final Exception e) {
assertNull(e); assertNull(e);
} }
try (PipedConsoleManager test = new PipedConsoleManager()) { try (PipedConsoleOutput test = new PipedConsoleOutput()) {
final HelpExecutor help = new HelpExecutor("?", test, final HelpExecutor help = new HelpExecutor("?",
new SubedCommand("sub", new MockCommand("mock"))); new SubedCommand("sub", new MockCommand("mock")));
help.tip(); help.tip();
help.help(test); help.help(test);

View File

@ -51,9 +51,13 @@ import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.InvalidParameterException; import fr.bigeon.gclc.exception.InvalidParameterException;
import fr.bigeon.gclc.manager.PipedConsoleManager; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.ConsoleOutput;
import fr.bigeon.gclc.manager.PipedConsoleInput;
import fr.bigeon.gclc.manager.PipedConsoleOutput;
/** <p> /**
* <p>
* TODO * TODO
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
@ -63,10 +67,12 @@ public class ParametrizedCommandTest {
* {@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("name") {
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final CommandParameters parameters) {
// //
} }
@ -80,10 +86,12 @@ public class ParametrizedCommandTest {
return null; return null;
} }
}; };
cmd = new ParametrizedCommand(null, "name", true) { cmd = new ParametrizedCommand("name", true) {
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final CommandParameters parameters) {
// //
} }
@ -142,7 +150,9 @@ public class ParametrizedCommandTest {
private boolean evenCall = true; private boolean evenCall = true;
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final CommandParameters parameters) {
assertTrue(parameters.getBooleanArgumentKeys().isEmpty()); assertTrue(parameters.getBooleanArgumentKeys().isEmpty());
assertTrue(parameters.getStringArgumentKeys().isEmpty()); assertTrue(parameters.getStringArgumentKeys().isEmpty());
if (evenCall) { if (evenCall) {
@ -166,10 +176,10 @@ public class ParametrizedCommandTest {
} }
}; };
try { try {
cmd.execute(); cmd.execute(null, null);
cmd.execute("-" + addParam); cmd.execute(null, null, "-" + addParam);
cmd.execute(addParam); cmd.execute(null, null, addParam);
cmd.execute("-" + addParam, addParam); cmd.execute(null, null, "-" + addParam, addParam);
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unepected error");
@ -190,7 +200,9 @@ public class ParametrizedCommandTest {
} }
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final 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) {
@ -234,12 +246,12 @@ public class ParametrizedCommandTest {
} }
}; };
try { try {
cmd.execute(); cmd.execute(null, null);
cmd.execute("-" + addParam); cmd.execute(null, null, "-" + addParam);
cmd.execute(addParam); cmd.execute(null, null, addParam);
cmd.execute("-" + addParam, addParam); cmd.execute(null, null, "-" + addParam, addParam);
cmd.execute("-" + str1, str2); cmd.execute(null, null, "-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1); cmd.execute(null, null, "-" + str1, str2, "-" + bool1);
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unepected error");
@ -258,8 +270,11 @@ public class ParametrizedCommandTest {
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final 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) {
@ -300,21 +315,21 @@ public class ParametrizedCommandTest {
} }
}; };
try { try {
cmd.execute(); cmd.execute(null, null);
cmd.execute("-" + str1, str2); cmd.execute(null, null, "-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1); cmd.execute(null, null, "-" + str1, str2, "-" + bool1);
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNull(e); assertNull(e);
fail("unexpected error"); fail("unexpected error");
} }
try { try {
cmd.execute(addParam); cmd.execute(null, null, addParam);
fail("Strict should fail with unexpected argument"); fail("Strict should fail with unexpected argument");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
try { try {
cmd.execute("-" + addParam); cmd.execute(null, null, "-" + addParam);
fail("Strict should fail with unexpected argument"); fail("Strict should fail with unexpected argument");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
@ -334,8 +349,11 @@ public class ParametrizedCommandTest {
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final CommandParameters parameters) {
assertEquals(str2, parameters.get(str1)); assertEquals(str2, parameters.get(str1));
} }
@ -350,17 +368,17 @@ public class ParametrizedCommandTest {
} }
}; };
try { try {
cmd.execute("-" + str1, str2); cmd.execute(null, null, "-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1); cmd.execute(null, null, "-" + str1, str2, "-" + bool1);
cmd.execute("-" + str1, str2, "-" + addParam); cmd.execute(null, null, "-" + str1, str2, "-" + addParam);
cmd.execute("-" + str1, str2, addParam); cmd.execute(null, null, "-" + str1, str2, addParam);
cmd.execute("-" + str1, str2, "-" + addParam, addParam); cmd.execute(null, null, "-" + str1, str2, "-" + addParam, addParam);
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unepected error");
} }
try { try {
cmd.execute(); cmd.execute(null, null);
fail("needed " + str1 + " not provided shall fail"); fail("needed " + str1 + " not provided shall fail");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
@ -381,7 +399,9 @@ public class ParametrizedCommandTest {
} }
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final CommandParameters parameters) {
// //
assertEquals(str2, parameters.get(str1)); assertEquals(str2, parameters.get(str1));
} }
@ -397,39 +417,40 @@ public class ParametrizedCommandTest {
} }
}; };
try { try {
cmd.execute("-" + str1, str2); cmd.execute(null, null, "-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1); cmd.execute(null, null, "-" + str1, str2, "-" + bool1);
} catch (final 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(null, null, "-" + str1, str2, addParam);
fail("Additional parameter should cause failure"); fail("Additional parameter should cause failure");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
try { try {
cmd.execute(); cmd.execute(null, null);
fail("needed " + str1 + " not provided shall fail"); fail("needed " + str1 + " not provided shall fail");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
try { try {
cmd.execute("-" + str1, str2, "-" + addParam); cmd.execute(null, null, "-" + str1, str2, "-" + addParam);
fail("unepected error"); fail("unepected error");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
try { try {
cmd.execute("-" + str1, str2, "-" + addParam, addParam); cmd.execute(null, null, "-" + str1, str2, "-" + addParam, addParam);
fail("unepected error"); fail("unepected error");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
} }
// TODO Test of interactive not providing and providing all needed // TODO Test of interactive not providing and providing all needed
try (PipedConsoleManager test = new PipedConsoleManager()) { try (PipedConsoleOutput out = new PipedConsoleOutput();
cmd = new ParametrizedCommand(test, "name", false) { PipedConsoleInput in = new PipedConsoleInput()) {
cmd = new ParametrizedCommand("name", false) {
{ {
try { try {
addStringParameter(str1, true); addStringParameter(str1, true);
@ -441,8 +462,11 @@ public class ParametrizedCommandTest {
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final CommandParameters parameters) {
assertEquals(str2, parameters.get(str1)); assertEquals(str2, parameters.get(str1));
} }
@ -457,11 +481,12 @@ public class ParametrizedCommandTest {
} }
}; };
try { try {
cmd.execute("-" + str1, str2); cmd.execute(out, in, "-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1); cmd.execute(out, in, "-" + str1, str2, "-" + bool1);
cmd.execute("-" + str1, str2, addParam); cmd.execute(out, in, "-" + str1, str2, addParam);
cmd.execute("-" + str1, str2, "-" + addParam); cmd.execute(out, in, "-" + str1, str2, "-" + addParam);
cmd.execute("-" + str1, str2, "-" + addParam, addParam); cmd.execute(out, in, "-" + str1, str2, "-" + addParam,
addParam);
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unepected error");
@ -474,16 +499,16 @@ public class ParametrizedCommandTest {
public void run() { public void run() {
try { try {
assertEquals("value of " + str1 + "? ", assertEquals("value of " + str1 + "? ",
test.readNextLine()); in.readNextLine());
test.type(""); in.type("");
assertEquals( assertEquals(
"value of " + str1 + "? (cannot be empty) ", "value of " + str1 + "? (cannot be empty) ",
test.readNextLine()); in.readNextLine());
test.type(""); in.type("");
assertEquals( assertEquals(
"value of " + str1 + "? (cannot be empty) ", "value of " + str1 + "? (cannot be empty) ",
test.readNextLine()); in.readNextLine());
test.type(str2); in.type(str2);
} catch (final IOException e) { } catch (final IOException e) {
assertNull(e); assertNull(e);
} }
@ -491,7 +516,7 @@ public class ParametrizedCommandTest {
}); });
th.start(); th.start();
cmd.execute(); cmd.execute(out, in);
th.join(); th.join();
@ -501,8 +526,8 @@ public class ParametrizedCommandTest {
public void run() { public void run() {
try { try {
assertEquals("value of " + str1 + "? ", assertEquals("value of " + str1 + "? ",
test.readNextLine()); in.readNextLine());
test.type(str2); in.type(str2);
} catch (final IOException e) { } catch (final IOException e) {
assertNull(e); assertNull(e);
} }
@ -510,7 +535,7 @@ public class ParametrizedCommandTest {
}); });
th.start(); th.start();
cmd.execute("-" + addParam); cmd.execute(out, in, "-" + addParam);
th.join(); th.join();
} catch (CommandRunException | InterruptedException e) { } catch (CommandRunException | InterruptedException e) {
@ -522,8 +547,9 @@ public class ParametrizedCommandTest {
fail("unepected error"); fail("unepected error");
} }
try { try {
final PipedConsoleManager test = new PipedConsoleManager(); final PipedConsoleOutput out = new PipedConsoleOutput();
cmd = new ParametrizedCommand(test, "name") { final PipedConsoleInput test = new PipedConsoleInput();
cmd = new ParametrizedCommand("name") {
{ {
try { try {
addStringParameter(str1, true); addStringParameter(str1, true);
@ -537,7 +563,9 @@ public class ParametrizedCommandTest {
} }
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final CommandParameters parameters) {
assertEquals(str2, parameters.get(str1)); assertEquals(str2, parameters.get(str1));
} }
@ -552,8 +580,9 @@ public class ParametrizedCommandTest {
} }
}; };
test.close(); test.close();
cmd.execute("-" + str1, str2); out.close();
cmd.execute("-" + addParam); cmd.execute(out, test, "-" + str1, str2);
cmd.execute(out, test, "-" + addParam);
fail("Closed manager shall cause error"); fail("Closed manager shall cause error");
} catch (final IOException e) { } catch (final IOException e) {
assertNull(e); assertNull(e);
@ -567,32 +596,12 @@ public class ParametrizedCommandTest {
* {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */ * {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */
@Test @Test
public final void testParametrizedCommandConsoleManagerString() { public final void testParametrizedCommandConsoleManagerString() {
try (PipedConsoleManager test = new PipedConsoleManager()) { ParametrizedCommand cmd = new ParametrizedCommand("name") {
final ParametrizedCommand cmd = new ParametrizedCommand(test, "name") {
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
// final ConsoleInput in,
} 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) {
// //
} }
@ -607,10 +616,30 @@ public class ParametrizedCommandTest {
} }
}; };
assertTrue(cmd.isStrict()); assertTrue(cmd.isStrict());
assertFalse(cmd.isInteractive());
cmd = new ParametrizedCommand("name") { cmd = new ParametrizedCommand("name") {
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final CommandParameters parameters) {
//
}
@Override
public String tip() {
return null;
}
@Override
protected String usageDetail() {
return null;
}
};
assertTrue(cmd.isStrict());
cmd = new ParametrizedCommand("name") {
@Override
protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final CommandParameters parameters) {
// //
} }
@ -625,18 +654,17 @@ public class ParametrizedCommandTest {
} }
}; };
assertTrue(cmd.isStrict()); assertTrue(cmd.isStrict());
assertFalse(cmd.isInteractive());
} }
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String, boolean)}. */ * {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String, boolean)}. */
@Test @Test
public final void testParametrizedCommandConsoleManagerStringBoolean() { public final void testParametrizedCommandConsoleManagerStringBoolean() {
try (PipedConsoleManager test = new PipedConsoleManager()) { ParametrizedCommand cmd = new ParametrizedCommand("name", false) {
final ParametrizedCommand cmd = new ParametrizedCommand(test, "name",
false) {
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final CommandParameters parameters) {
// //
} }
@ -651,32 +679,30 @@ public class ParametrizedCommandTest {
} }
}; };
assertFalse(cmd.isStrict()); 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) { cmd = new ParametrizedCommand("name", false) {
@Override @Override
protected void doExecute(final CommandParameters parameters) { protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final CommandParameters parameters) {
//
}
@Override
public String tip() {
return null;
}
@Override
protected String usageDetail() {
return null;
}
};
assertFalse(cmd.isStrict());
cmd = new ParametrizedCommand("name", false) {
@Override
protected void doExecute(final ConsoleOutput out,
final ConsoleInput in,
final CommandParameters parameters) {
// //
} }
@ -691,7 +717,6 @@ public class ParametrizedCommandTest {
} }
}; };
assertFalse(cmd.isStrict()); assertFalse(cmd.isStrict());
assertFalse(cmd.isInteractive());
} }
} }

View File

@ -51,7 +51,8 @@ import fr.bigeon.gclc.ConsoleApplication;
import fr.bigeon.gclc.ConsoleTestApplication; import fr.bigeon.gclc.ConsoleTestApplication;
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.manager.PipedConsoleManager; import fr.bigeon.gclc.manager.PipedConsoleInput;
import fr.bigeon.gclc.manager.PipedConsoleOutput;
/** <p> /** <p>
* Test class for {@link ScriptExecution} * Test class for {@link ScriptExecution}
@ -65,21 +66,23 @@ public class ScriptExecutionTest {
*/ */
@Test @Test
public void testExecute() { public void testExecute() {
PipedConsoleManager test; PipedConsoleOutput test;
PipedConsoleInput in;
try { try {
test = new PipedConsoleManager(); in = new PipedConsoleInput();
test = new PipedConsoleOutput();
} catch (final IOException e2) { } catch (final IOException e2) {
fail("creation of console manager failed"); //$NON-NLS-1$ fail("creation of console manager failed"); //$NON-NLS-1$
assertNotNull(e2); assertNotNull(e2);
return; return;
} }
final ConsoleApplication app = new ConsoleApplication( final ConsoleApplication app = new ConsoleApplication(
test, "", ""); test, in, "", "");
new ConsoleTestApplication().attach(app); new ConsoleTestApplication().attach(app);
final 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(test, in);
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 (final CommandRunException e1) { } catch (final CommandRunException e1) {
// ok // ok
@ -88,7 +91,8 @@ public class ScriptExecutionTest {
} }
try { try {
exec.execute("src/test/resources/scripts/withprependSpace.txt"); //$NON-NLS-1$ exec.execute(test, in,
"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 (final CommandRunException e1) { } catch (final CommandRunException e1) {
// ok // ok
@ -97,7 +101,8 @@ public class ScriptExecutionTest {
} }
try { try {
exec.execute("src/test/resources/scripts/invalidCmdParse.txt"); //$NON-NLS-1$ exec.execute(test, in,
"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 (final CommandRunException e1) { } catch (final CommandRunException e1) {
// ok // ok
@ -106,7 +111,8 @@ public class ScriptExecutionTest {
} }
try { try {
exec.execute("src/test/resources/scripts/invalidCmd.txt"); //$NON-NLS-1$ exec.execute(test, in,
"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 (final CommandRunException e1) { } catch (final CommandRunException e1) {
// ok // ok
@ -115,7 +121,8 @@ public class ScriptExecutionTest {
} }
try { try {
exec.execute("src/test/resources/scripts/failingCmdInvoc.txt"); //$NON-NLS-1$ exec.execute(test, in,
"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 (final CommandRunException e1) { } catch (final CommandRunException e1) {
// ok // ok
@ -124,7 +131,8 @@ public class ScriptExecutionTest {
} }
try { try {
exec.execute("src/test/resources/scripts/someNonExisting.file"); //$NON-NLS-1$ exec.execute(test, in,
"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 (final CommandRunException e1) { } catch (final CommandRunException e1) {
// ok // ok
@ -133,11 +141,11 @@ public class ScriptExecutionTest {
} }
try { try {
exec.execute("src/test/resources/script1.txt"); //$NON-NLS-1$ exec.execute(test, in, "src/test/resources/script1.txt"); //$NON-NLS-1$
exec.execute("src/test/resources/script2.txt"); //$NON-NLS-1$ exec.execute(test, in, "src/test/resources/script2.txt"); //$NON-NLS-1$
exec.execute("src/test/resources/script3.txt"); //$NON-NLS-1$ exec.execute(test, in, "src/test/resources/script3.txt"); //$NON-NLS-1$
exec.execute("src/test/resources/script4.txt"); //$NON-NLS-1$ exec.execute(test, in, "src/test/resources/script4.txt"); //$NON-NLS-1$
exec.execute("src/test/resources/script5.txt", "test"); //$NON-NLS-1$ //$NON-NLS-2$ exec.execute(test, in, "src/test/resources/script5.txt", "test"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (final 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$
@ -156,7 +164,7 @@ public class ScriptExecutionTest {
public void testHelp() { public void testHelp() {
final 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 (PipedConsoleOutput test = new PipedConsoleOutput()) {
exec.help(test); exec.help(test);
exec.help(test, "ignored element"); exec.help(test, "ignored element");
} catch (final IOException e) { } catch (final IOException e) {

View File

@ -49,10 +49,12 @@ import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.InvalidCommandName; import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleInput;
import fr.bigeon.gclc.manager.PipedConsoleManager; import fr.bigeon.gclc.manager.ConsoleOutput;
import fr.bigeon.gclc.manager.PipedConsoleOutput;
/** <p> /**
* <p>
* TODO * TODO
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
@ -100,9 +102,12 @@ public class SubedCommandTest {
cmd.add(new Command("fail") { cmd.add(new Command("fail") {
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
throw new CommandRunException("Failing command", null); throw new CommandRunException("Failing command", null);
} }
@Override @Override
public String tip() { public String tip() {
return null; return null;
@ -119,20 +124,20 @@ public class SubedCommandTest {
} }
try { try {
cmd.execute("id"); cmd.execute(null, null, "id");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
fail("Unexpected exception when running mock command"); fail("Unexpected exception when running mock command");
assertNotNull(e); assertNotNull(e);
} }
try { try {
cmd.execute("fail"); cmd.execute(null, null, "fail");
fail("Fail command error should be re thrown"); fail("Fail command error should be re thrown");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
assertEquals(cmd, e.getSource()); assertEquals(cmd, e.getSource());
} }
try { try {
cmd.execute(); cmd.execute(null, null);
fail("Request for inexistent default command should fail"); fail("Request for inexistent default command should fail");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
@ -145,9 +150,12 @@ public class SubedCommandTest {
cmd.add(new Command("fail") { cmd.add(new Command("fail") {
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
throw new CommandRunException("Failing command", this); throw new CommandRunException("Failing command", this);
} }
@Override @Override
public String tip() { public String tip() {
return null; return null;
@ -164,20 +172,20 @@ public class SubedCommandTest {
} }
try { try {
cmd.execute("id"); cmd.execute(null, null, "id");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
fail("Unexpected exception when running mock command"); fail("Unexpected exception when running mock command");
assertNotNull(e); assertNotNull(e);
} }
try { try {
cmd.execute("fail"); cmd.execute(null, null, "fail");
fail("Fail command error should be re thrown"); fail("Fail command error should be re thrown");
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
assertNotNull(e); assertNotNull(e);
assertEquals(cmd.get("fail"), e.getSource()); assertEquals(cmd.get("fail"), e.getSource());
} }
try { try {
cmd.execute(); cmd.execute(null, null);
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
fail("Request for default command should execute default command"); fail("Request for default command should execute default command");
assertNotNull(e); assertNotNull(e);
@ -196,9 +204,12 @@ public class SubedCommandTest {
cmd.add(new Command("fail") { cmd.add(new Command("fail") {
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out,
final ConsoleInput in,
final String... args) throws CommandRunException {
throw new CommandRunException("Failing command", this); throw new CommandRunException("Failing command", this);
} }
@Override @Override
public String tip() { public String tip() {
return null; return null;
@ -277,8 +288,7 @@ public class SubedCommandTest {
assertNotNull(e); assertNotNull(e);
} }
try (PipedConsoleManager manager = new PipedConsoleManager(); try (PipedConsoleOutput manager = new PipedConsoleOutput()) {
PipedConsoleManager manager2 = new PipedConsoleManager()) {
cmd.help(manager); cmd.help(manager);
assertEquals("\tid", manager.readNextLine()); assertEquals("\tid", manager.readNextLine());
cmd.help(manager, "id"); cmd.help(manager, "id");
@ -297,8 +307,7 @@ public class SubedCommandTest {
assertNotNull(e); assertNotNull(e);
} }
try (PipedConsoleManager manager = new PipedConsoleManager(); try (PipedConsoleOutput manager = new PipedConsoleOutput()) {
PipedConsoleManager manager2 = new PipedConsoleManager()) {
cmd.help(manager); cmd.help(manager);
assertEquals("\tid", manager.readNextLine()); assertEquals("\tid", manager.readNextLine());
} catch (final IOException e) { } catch (final IOException e) {
@ -309,7 +318,8 @@ public class SubedCommandTest {
mock = new ICommand() { mock = new ICommand() {
@Override @Override
public void execute(final String... args) throws CommandRunException { public void execute(final ConsoleOutput out, final ConsoleInput in,
final String... args) throws CommandRunException {
// //
} }
@ -319,7 +329,7 @@ public class SubedCommandTest {
} }
@Override @Override
public void help(final ConsoleManager manager, public void help(final ConsoleOutput manager,
final String... args) throws IOException { final String... args) throws IOException {
// //
} }
@ -338,8 +348,7 @@ public class SubedCommandTest {
assertNotNull(e); assertNotNull(e);
} }
try (PipedConsoleManager manager = new PipedConsoleManager(); try (PipedConsoleOutput manager = new PipedConsoleOutput()) {
PipedConsoleManager manager2 = new PipedConsoleManager()) {
cmd.help(manager); cmd.help(manager);
assertEquals("\ttip", manager.readNextLine()); assertEquals("\ttip", manager.readNextLine());
assertEquals("\tid: tip", manager.readNextLine()); assertEquals("\tid: tip", manager.readNextLine());

View File

@ -60,6 +60,45 @@ import org.junit.Test;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class SystemConsoleManagerTest { public class SystemConsoleManagerTest {
/** Test method for
* {@link fr.bigeon.gclc.manager.SystemConsoleManager#isClosed()}. */
@Test
public final void testIsClosed() {
try {
final PipedOutputStream outStream = new PipedOutputStream();
final InputStream in = new PipedInputStream(outStream);
final PrintStream out = new PrintStream(outStream);
final String test = "test";
final SystemConsoleInput manager = new SystemConsoleInput(
System.out,
in, Charset.forName("UTF-8"));
final Thread th = new Thread(new Runnable() {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
out.println(test);
}
});
th.start();
assertEquals(test, manager.prompt());
assertFalse(manager.isClosed());
manager.close();
assertTrue(manager.isClosed());
try {
manager.prompt();
fail("prompt on closed manager");
} catch (final IOException e) {
assertNotNull(e);
}
th.join();
} catch (IOException | InterruptedException e) {
assertNull(e);
}
}
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.manager.SystemConsoleManager#prompt()}. */ * {@link fr.bigeon.gclc.manager.SystemConsoleManager#prompt()}. */
@Test @Test
@ -69,10 +108,10 @@ public class SystemConsoleManagerTest {
try (PipedOutputStream outStream = new PipedOutputStream(); try (PipedOutputStream outStream = new PipedOutputStream();
InputStream in = new PipedInputStream(outStream); InputStream in = new PipedInputStream(outStream);
final PrintStream out = new PrintStream(outStream); final PrintStream out = new PrintStream(outStream);
SystemConsoleManager manager = new SystemConsoleManager(System.out, SystemConsoleInput manager = new SystemConsoleInput(System.out,
in, Charset.forName("UTF-8"))) { in, Charset.forName("UTF-8"))) {
Thread th = new Thread(new Runnable() { final Thread th = new Thread(new Runnable() {
@SuppressWarnings("synthetic-access") @SuppressWarnings("synthetic-access")
@Override @Override
@ -97,57 +136,13 @@ public class SystemConsoleManagerTest {
try (PipedOutputStream outStream = new PipedOutputStream(); try (PipedOutputStream outStream = new PipedOutputStream();
InputStream in = new PipedInputStream(outStream); InputStream in = new PipedInputStream(outStream);
final PrintStream out = new PrintStream(outStream); final PrintStream out = new PrintStream(outStream);
SystemConsoleManager manager = new SystemConsoleManager(System.out, SystemConsoleInput manager = new SystemConsoleInput(System.out,
in, Charset.forName("UTF-8"))) { in, Charset.forName("UTF-8"))) {
String prt = "++"; final String prt = "++";
manager.setPrompt(prt); manager.setPrompt(prt);
assertEquals(prt, manager.getPrompt()); assertEquals(prt, manager.getPrompt());
} catch (IOException e) { } catch (final IOException e) {
assertNull(e);
}
}
/** Test method for
* {@link fr.bigeon.gclc.manager.SystemConsoleManager#isClosed()}. */
@Test
public final void testIsClosed() {
try {
PipedOutputStream outStream = new PipedOutputStream();
InputStream in = new PipedInputStream(outStream);
final PrintStream out = new PrintStream(outStream);
final String test = "test";
SystemConsoleManager manager = new SystemConsoleManager(System.out,
in, Charset.forName("UTF-8"));
Thread th = new Thread(new Runnable() {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
out.println(test);
}
});
th.start();
assertEquals(test, manager.prompt());
assertFalse(manager.isClosed());
manager.close();
assertTrue(manager.isClosed());
try {
manager.prompt();
fail("prompt on closed manager");
} catch (IOException e) {
assertNotNull(e);
}
try {
manager.println(test);
fail("prompt on closed manager");
} catch (IOException e) {
assertNotNull(e);
}
th.join();
} catch (IOException | InterruptedException e) {
assertNull(e); assertNull(e);
} }
} }

View File

@ -1,116 +0,0 @@
/*
* 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.proc.ProcessListTest.java
* Created on: Aug 19, 2017
*/
package fr.bigeon.gclc.proc;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.manager.PipedConsoleManager;
/**
* <p>
* TODO
*
* @author Emmanuel Bigeon */
public class ProcessListTest {
/** Test method for
* {@link fr.bigeon.gclc.proc.ProcessList#execute(java.lang.String[])}.
*
* @throws CommandRunException if an error occured in the execution
* @throws IOException if the manager could not be created */
@Test
public final void testExecute() throws CommandRunException, IOException {
final TaskPool pool = new TaskPool();
try (PipedConsoleManager pcm = new PipedConsoleManager()) {
final ProcessList pl = new ProcessList("list", pool, pcm);
pl.execute();
pool.add(new Task() {
@Override
public void addInterruptionListener(final InterruptionListener listener) {
//
}
@Override
public String getName() {
return "name";
}
@Override
public boolean isRunning() {
return false;
}
@Override
public void rmInterruptionListener(final InterruptionListener listener) {
//
}
@Override
public void run() {
// TODO Auto-generated method stub
//
throw new RuntimeException("Not implemented yet");
}
@Override
public void setRunning(final boolean running) {
//
}
});
pl.execute();
assertTrue("List should give the process",
pcm.readNextLine().endsWith("name"));
}
}
@Test
public void testTip() throws IOException {
try (PipedConsoleManager pcm = new PipedConsoleManager()) {
assertNotNull("Tip should not be null", new ProcessList("list",
new TaskPool(), pcm).tip());
}
}
}

View File

@ -1,131 +0,0 @@
/*
* 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.proc.TaskPoolTest.java
* Created on: Aug 19, 2017
*/
package fr.bigeon.gclc.proc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
/**
* <p>
* TODO
*
* @author Emmanuel Bigeon */
public class TaskPoolTest {
/** Test method for
* {@link fr.bigeon.gclc.proc.TaskPool#add(fr.bigeon.gclc.proc.Task)}. */
@Test
public final void testAdd() {
final TaskPool pool = new TaskPool();
Task task = null;
try {
pool.add(task);
fail("Expected a null pointer exception");
} catch (final IllegalArgumentException e) {
// ok
}
task = new Task() {
private final Object lock = new Object();
private boolean running;
private InterruptionListener listener;
@Override
public void addInterruptionListener(final InterruptionListener listener) {
this.listener = listener;
}
@Override
public String getName() {
return "Test";
}
@Override
public boolean isRunning() {
return running;
}
@Override
public void rmInterruptionListener(final InterruptionListener listener) {
//
}
@Override
public void run() {
synchronized (lock) {
while (running) {
try {
lock.wait(100);
} catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
listener.interrupted();
}
@Override
public void setRunning(final boolean running) {
synchronized (lock) {
this.running = running;
}
//
}
};
pool.add(task);
assertEquals(1, pool.getPIDs().size());
for (final String pid : pool.getPIDs()) {
assertEquals(task, pool.get(pid));
}
final Thread th = new Thread(task);
th.start();
task.setRunning(false);
try {
th.join(1000);
} catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertEquals(0, pool.getPIDs().size());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -44,7 +44,7 @@ import java.io.IOException;
import org.junit.Test; import org.junit.Test;
import fr.bigeon.gclc.manager.PipedConsoleManager; import fr.bigeon.gclc.manager.PipedConsoleOutput;
/** <p> /** <p>
* TODO * TODO
@ -62,24 +62,19 @@ public class AOutputForwardRunnableTest {
private String message; private String message;
/** @param manager */ /** @param manager */
private AOutputForwardTestRunnable(PipedConsoleManager manager) { private AOutputForwardTestRunnable(final PipedConsoleOutput manager) {
super(manager); super(manager);
} }
@Override @Override
protected boolean isRunning() { protected void forwardLine(final String m) {
return count != 0;
}
@Override
protected void forwardLine(String m) {
// Do nothing // Do nothing
message = m; message = m;
synchronized (this) { synchronized (this) {
notify(); notify();
try { try {
wait(); wait();
} catch (InterruptedException e) { } catch (final InterruptedException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
@ -92,13 +87,13 @@ public class AOutputForwardRunnableTest {
synchronized (this) { synchronized (this) {
try { try {
wait(); wait();
} catch (InterruptedException e) { } catch (final InterruptedException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
String m = message; final String m = message;
count--; count--;
message = null; message = null;
synchronized (this) { synchronized (this) {
@ -106,17 +101,22 @@ public class AOutputForwardRunnableTest {
} }
return m; return m;
} }
@Override
protected boolean isRunning() {
return count != 0;
}
} }
/** Test method for /** Test method for
* {@link fr.bigeon.gclc.tools.AOutputForwardRunnable#run()}. */ * {@link fr.bigeon.gclc.tools.AOutputForwardRunnable#run()}. */
@Test @Test
public final void testRun() { public final void testRun() {
try (PipedConsoleManager manager = new PipedConsoleManager()) { try (PipedConsoleOutput manager = new PipedConsoleOutput()) {
AOutputForwardTestRunnable runnable = new AOutputForwardTestRunnable( final AOutputForwardTestRunnable runnable = new AOutputForwardTestRunnable(
manager); manager);
Thread th = new Thread(runnable, "forward"); final Thread th = new Thread(runnable, "forward");
manager.println("before"); manager.println("before");
th.start(); th.start();