Code compliance huge changes.

* Fixed issues
CliPrompter:
------------
- print list size
- long text line prompt is in CliPromptMessages
- multi chhoice prompt from map gets the currect choice

CommandParameters:
------------------
- Get boolean null pointer exception fixed
- Access to arguments keys.

CommandProvider:
----------------
- Check command name on addition

ConsoleApplication
------------------
- run status update when exiting start()

HelpExecutor
------------
- help content depends on whether the element is a subed command or not

ParametrizedCommand
-------------------
- Check parameter for modification when adding already existing
parameter
- Remove need status for boolean arguments
- Added invalid command exception
- Fail if not interactive and missing needed parameter
- Added getters

PrintUtils
----------
- Remove last empty line in wrap

SystemConsoleManager
--------------------
- Added charset for streams
- Removal of NULL characters from stream

* Added test elements. Use test console manager rather that system one.

Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
This commit is contained in:
Emmanuel Bigeon 2016-11-19 17:28:25 -05:00
parent 1a207c8100
commit 5280ee98bd
38 changed files with 4124 additions and 185 deletions

View File

@ -36,6 +36,6 @@
<parent> <parent>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>
<artifactId>ebigeon-config</artifactId> <artifactId>ebigeon-config</artifactId>
<version>1.7.0</version> <version>1.7.1</version>
</parent> </parent>
</project> </project>

View File

@ -79,7 +79,7 @@ public class ExecSystemCommand extends Command {
} }
}); });
th.start(); th.start();
manager.setPrompt(new String()); manager.setPrompt("");
final OutputStream os = proc.getOutputStream(); final OutputStream os = proc.getOutputStream();
try (BufferedWriter writer = new BufferedWriter( try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os))) { new OutputStreamWriter(os))) {

View File

@ -100,7 +100,7 @@ public class ConsoleApplication implements ICommandProvider {
this.header = welcome; this.header = welcome;
this.footer = goodbye; this.footer = goodbye;
this.manager = manager; this.manager = manager;
root = new SubedCommand(new String()); root = new SubedCommand(""); //$NON-NLS-1$
} }
/** @param manager the manager /** @param manager the manager
@ -245,6 +245,7 @@ public class ConsoleApplication implements ICommandProvider {
if (footer != null) { if (footer != null) {
manager.println(footer); manager.println(footer);
} }
running = false;
LOGGER.fine("Exiting application."); //$NON-NLS-1$ LOGGER.fine("Exiting application."); //$NON-NLS-1$
} catch (IOException e) { } catch (IOException e) {
// The manager was closed // The manager was closed
@ -264,4 +265,14 @@ public class ConsoleApplication implements ICommandProvider {
public SubedCommand getRoot() { public SubedCommand getRoot() {
return root; return root;
} }
/** @return the header */
public String getHeader() {
return header;
}
/** @return the footer */
public String getFooter() {
return footer;
}
} }

View File

@ -69,6 +69,8 @@ public abstract class Command implements ICommand {
* *
*/ */
private static final String EOL_LINUX = "\n"; //$NON-NLS-1$ private static final String EOL_LINUX = "\n"; //$NON-NLS-1$
/** The empty string constant */
private static final String EMPTY = ""; //$NON-NLS-1$
/** The name of the command */ /** The name of the command */
protected final String name; protected final String name;
@ -119,7 +121,7 @@ public abstract class Command implements ICommand {
* @return the detailed help (should end with end of line or be empty) */ * @return the detailed help (should end with end of line or be empty) */
@SuppressWarnings("static-method") @SuppressWarnings("static-method")
protected String usageDetail() { protected String usageDetail() {
return new String(); return EMPTY;
} }
/** <p> /** <p>

View File

@ -56,9 +56,9 @@ public class CommandParameters {
*/ */
private static final int STRINGARG_NUMBER_OF_ELEMENTS = 2; private static final int STRINGARG_NUMBER_OF_ELEMENTS = 2;
/** Boolean arguments */ /** Boolean arguments */
private final Map<String, Boolean> boolArgs = new HashMap<>(); private final Map<String, Boolean> booleanArguments = new HashMap<>();
/** String arguments */ /** String arguments */
private final Map<String, String> stringArgs = new HashMap<>(); private final Map<String, String> stringArguments = new HashMap<>();
/** Arguments restriction on the named ones */ /** Arguments restriction on the named ones */
private final boolean strict; private final boolean strict;
/** additional (unnamed) parameters */ /** additional (unnamed) parameters */
@ -71,10 +71,10 @@ public class CommandParameters {
public CommandParameters(Set<String> bools, Set<String> strings, public CommandParameters(Set<String> bools, Set<String> strings,
boolean strict) { boolean strict) {
for (final String string : bools) { for (final String string : bools) {
boolArgs.put(string, false); booleanArguments.put(string, false);
} }
for (final String string : strings) { for (final String string : strings) {
stringArgs.put(string, null); stringArguments.put(string, null);
} }
this.strict = strict; this.strict = strict;
} }
@ -82,7 +82,7 @@ public class CommandParameters {
/** @param key the key /** @param key the key
* @return the associated value, null if it was not specified */ * @return the associated value, null if it was not specified */
public String get(String key) { public String get(String key) {
return stringArgs.get(key); return stringArguments.get(key);
} }
/** @return additional non parsed parameters */ /** @return additional non parsed parameters */
@ -92,9 +92,9 @@ public class CommandParameters {
/** @param key the key /** @param key the key
* @return if the key was specified */ * @return if the key was specified */
@SuppressWarnings("boxing")
public boolean getBool(String key) { public boolean getBool(String key) {
return boolArgs.get(key); return booleanArguments.containsKey(key) &&
booleanArguments.get(key).booleanValue();
} }
/** @param args the arguments to parse /** @param args the arguments to parse
@ -129,11 +129,11 @@ public class CommandParameters {
return 1; return 1;
} }
String name = arg.substring(1); String name = arg.substring(1);
if (boolArgs.containsKey(name)) { if (booleanArguments.containsKey(name)) {
boolArgs.put(name, Boolean.TRUE); booleanArguments.put(name, Boolean.TRUE);
return 1; return 1;
} }
if (stringArgs.containsKey(name)) { if (stringArguments.containsKey(name)) {
return parseStringArg(name, next); return parseStringArg(name, next);
} }
if (strict) { if (strict) {
@ -152,7 +152,7 @@ public class CommandParameters {
if (next == null) { if (next == null) {
return 0; return 0;
} }
stringArgs.put(name, next); stringArguments.put(name, next);
return STRINGARG_NUMBER_OF_ELEMENTS; return STRINGARG_NUMBER_OF_ELEMENTS;
} }
@ -160,16 +160,26 @@ public class CommandParameters {
* @param value the value */ * @param value the value */
@SuppressWarnings("boxing") @SuppressWarnings("boxing")
public void set(String string, boolean value) { public void set(String string, boolean value) {
if (boolArgs.containsKey(string)) { if (booleanArguments.containsKey(string)) {
boolArgs.put(string, value); booleanArguments.put(string, value);
} }
} }
/** @param string the key /** @param string the key
* @param value the value */ * @param value the value */
public void set(String string, String value) { public void set(String string, String value) {
if (stringArgs.containsKey(string)) { if (stringArguments.containsKey(string)) {
stringArgs.put(string, value); stringArguments.put(string, value);
} }
} }
/** @return the boolean arguments */
public Set<String> getBooleanArgumentKeys() {
return booleanArguments.keySet();
}
/** @return the boolean arguments */
public Set<String> getStringArgumentKeys() {
return stringArguments.keySet();
}
} }

View File

@ -67,15 +67,28 @@ public class CommandProvider implements ICommandProvider {
@Override @Override
public boolean add(ICommand value) throws InvalidCommandName { public boolean add(ICommand value) throws InvalidCommandName {
final String name = value.getCommandName(); final String name = value.getCommandName();
if (name == null || name.startsWith(MINUS) || name.contains(SPACE)) { testCommandName(name);
throw new InvalidCommandName();
}
if (commands.contains(value)) { if (commands.contains(value)) {
return true; return true;
} }
for (ICommand iCommand : commands) {
if (iCommand.getCommandName().equals(value.getCommandName())) {
throw new InvalidCommandName(
"Name already used: " + value.getCommandName()); //$NON-NLS-1$
}
}
return commands.add(value); return commands.add(value);
} }
/** @param name the command name
* @throws InvalidCommandName if the name is invalid */
private static void testCommandName(String name) throws InvalidCommandName {
if (name == null || name.isEmpty() || name.startsWith(MINUS) ||
name.contains(SPACE)) {
throw new InvalidCommandName();
}
}
@Override @Override
public void executeSub(String cmd, public void executeSub(String cmd,
String... args) throws CommandRunException { String... args) throws CommandRunException {

View File

@ -87,15 +87,21 @@ public class HelpExecutor extends Command {
* @see fr.bigeon.gclc.command.Command#brief() */ * @see fr.bigeon.gclc.command.Command#brief() */
@Override @Override
protected String brief() { protected String brief() {
if (cmd instanceof SubedCommand) {
return " A command to get help for other commands"; //$NON-NLS-1$ return " A command to get help for other commands"; //$NON-NLS-1$
} }
return " A command to retrieve help for " + cmd.getCommandName(); //$NON-NLS-1$
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usagePattern() */ * @see fr.bigeon.gclc.command.Command#usagePattern() */
@Override @Override
protected String usagePattern() { protected String usagePattern() {
if (cmd instanceof SubedCommand) {
return getCommandName() + " <otherCommand>"; //$NON-NLS-1$ return getCommandName() + " <otherCommand>"; //$NON-NLS-1$
} }
return getCommandName();
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#tip() */ * @see fr.bigeon.gclc.command.Command#tip() */

View File

@ -0,0 +1,91 @@
/*
* 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.command.MockCommand.java
* Created on: Nov 18, 2016
*/
package fr.bigeon.gclc.command;
import java.io.IOException;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.manager.ConsoleManager;
/** This implement a command that does nothing.
* <p>
* This class is intended for testing purpose only.
*
* @author Emmanuel Bigeon */
public final class MockCommand implements ICommand {
/** The command name */
private final String name;
/** @param name the command name */
public MockCommand(String name) {
this.name = name;
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */
@Override
public void execute(String... args) throws CommandRunException {
//
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#tip() */
@Override
public String tip() {
return null;
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#getCommandName() */
@Override
public String getCommandName() {
return name;
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#help(fr.bigeon.gclc.manager.
* ConsoleManager, java.lang.String[]) */
@Override
public void help(ConsoleManager manager,
String... args) throws IOException {
//
}
}

View File

@ -40,12 +40,17 @@ package fr.bigeon.gclc.command;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
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.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
/** <p> /** <p>
@ -61,7 +66,7 @@ public abstract class ParametrizedCommand extends Command {
/** The manager */ /** The manager */
protected final ConsoleManager manager; protected final ConsoleManager manager;
/** The boolean parameters mandatory status */ /** The boolean parameters mandatory status */
private final Map<String, Boolean> boolParams = new HashMap<>(); private final Set<String> boolParams = new HashSet<>();
/** The string parameters mandatory status */ /** The string parameters mandatory status */
private final Map<String, Boolean> stringParams = new HashMap<>(); private final Map<String, Boolean> stringParams = new HashMap<>();
/** The parameters mandatory status */ /** The parameters mandatory status */
@ -77,6 +82,11 @@ public abstract class ParametrizedCommand extends Command {
this(manager, name, true); this(manager, name, true);
} }
/** @param name the name */
public ParametrizedCommand(String name) {
this(null, name, true);
}
/** @param manager the manager /** @param manager the manager
* @param name the name * @param name the name
* @param strict if the arguments are restricted to the declared ones */ * @param strict if the arguments are restricted to the declared ones */
@ -88,26 +98,59 @@ public abstract class ParametrizedCommand extends Command {
this.strict = strict; this.strict = strict;
} }
/** @param name the name
* @param strict if the arguments are restricted to the declared ones */
public ParametrizedCommand(String name, boolean strict) {
this(null, name, strict);
}
/** <p> /** <p>
* Add a parameter to the defined parameters * Add a parameter to the defined parameters
* *
* @param param the parameter identification * @param param the parameter identification
* @param stringOrBool if the parameter is a parameter with an argument * @param stringParameter if the parameter is a parameter with an argument
* @param needed if the parameter is required */ * @param needed if the parameter is required
@SuppressWarnings("boxing") * @throws InvalidParameterException if the parameter was invalid */
protected void addParameter(String param, boolean stringOrBool, protected void addParameter(String param, boolean stringParameter,
boolean needed) { boolean needed) throws InvalidParameterException {
if (params.containsKey(param)) { if (params.containsKey(param)) {
checkParam(param, stringParameter, needed);
return; return;
} }
params.put(param, needed); if (stringParameter) {
if (stringOrBool) { stringParams.put(param, Boolean.valueOf(needed));
stringParams.put(param, needed); params.put(param, Boolean.valueOf(needed));
} else { } else {
if (needed) { if (needed) {
// ERROR the boolean parameters cannot be needed // ERROR the boolean parameters cannot be needed
throw new InvalidParameterException(
"Boolean parameter are present by their very nature. They should not be defined as needed"); //$NON-NLS-1$
} }
boolParams.put(param, needed); boolParams.add(param);
params.put(param, Boolean.valueOf(false));
}
}
/** @param param the parameter
* @param stringParameter the string parameter type
* @param needed if the parameter is needed
* @throws InvalidParameterException if the new definition is invalid */
private void checkParam(String param, boolean stringParameter,
boolean needed) throws InvalidParameterException {
if (stringParameter) {
if (stringParams.containsKey(param)) {
Boolean need = Boolean.valueOf(
needed || stringParams.get(param).booleanValue());
stringParams.put(param, need);
params.put(param, need);
return;
}
throw new InvalidParameterException(
"Parameter is already defined as boolean"); //$NON-NLS-1$
}
if (stringParams.containsKey(param) || needed) {
throw new InvalidParameterException(
"Parameter is already defined as string"); //$NON-NLS-1$
} }
} }
@ -120,19 +163,22 @@ public abstract class ParametrizedCommand extends Command {
@Override @Override
public final void execute(String... args) throws CommandRunException { public final void execute(String... args) throws CommandRunException {
final CommandParameters parameters = new CommandParameters( final CommandParameters parameters = new CommandParameters(
boolParams.keySet(), stringParams.keySet(), strict); boolParams, stringParams.keySet(), strict);
if (!parameters.parseArgs(args)) { if (!parameters.parseArgs(args)) {
// ERROR the parameters could not be correctly parsed // the parameters could not be correctly parsed
throw new CommandRunException(CommandRunExceptionType.USAGE, throw new CommandRunException(CommandRunExceptionType.USAGE,
"Unable to read arguments", this); //$NON-NLS-1$ "Unable to read arguments", this); //$NON-NLS-1$
} }
final List<String> toProvide = new ArrayList<>(); final List<String> toProvide = new ArrayList<>();
for (final String string : params.keySet()) { for (final Entry<String, Boolean> string : params.entrySet()) {
if (params.get(string) && parameters.get(string) == null) { if (string.getValue() && parameters.get(string.getKey()) == null) {
if (!interactive) { if (!interactive) {
return; throw new CommandRunException(
CommandRunExceptionType.INTERACTION,
"Missing required parameter " + string.getKey(), //$NON-NLS-1$
this);
} }
toProvide.add(string); toProvide.add(string.getKey());
} }
} }
// for each needed parameters that is missing, prompt the user. // for each needed parameters that is missing, prompt the user.
@ -160,4 +206,35 @@ public abstract class ParametrizedCommand extends Command {
parameters.set(string, value); parameters.set(string, value);
} }
} }
/** @return the set of boolean parameters */
public Set<String> getBooleanParameters() {
return Collections.unmodifiableSet(boolParams);
}
/** @return the stringParams */
public Set<String> getStringParameters() {
return stringParams.keySet();
}
/** @return the stringParams */
public Set<String> getParameters() {
return params.keySet();
}
/** @param param the parameter name
* @return if the parameter is needed */
public boolean isNeeded(String param) {
return params.containsKey(param) && params.get(param).booleanValue();
}
/** @return the strict */
public boolean isStrict() {
return strict;
}
/** @return the interactive */
public boolean isInteractive() {
return interactive;
}
} }

View File

@ -39,9 +39,10 @@
package fr.bigeon.gclc.command; package fr.bigeon.gclc.command;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -60,65 +61,50 @@ import fr.bigeon.gclc.exception.CommandRunExceptionType;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class ScriptExecution extends Command { public class ScriptExecution extends Command {
/** The tab character */
private static final String TAB = "\t"; //$NON-NLS-1$
/** the space character */
private static final String SPACE = " "; //$NON-NLS-1$
/** The application */ /** The application */
private final ConsoleApplication application; private final ConsoleApplication application;
/** The commenting prefix */ /** The commenting prefix */
private final String commentPrefix; private final String commentPrefix;
/** The charset for files */
private final Charset charset;
/** @param name the name of the command /** @param name the name of the command
* @param application the application * @param application the application
* @param commentPrefix the comment prefix in the script files */ * @param commentPrefix the comment prefix in the script files
* @param charset the charset to use for files */
public ScriptExecution(String name, ConsoleApplication application, public ScriptExecution(String name, ConsoleApplication application,
String commentPrefix) { String commentPrefix, Charset charset) {
super(name); super(name);
this.application = application; this.application = application;
this.commentPrefix = commentPrefix; this.commentPrefix = commentPrefix;
this.charset = charset;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */ * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */
@SuppressWarnings("resource")
@Override @Override
public void execute(String... args) throws CommandRunException { public void execute(String... args) throws CommandRunException {
if (args.length == 0) { checkArgs(args);
throw new CommandRunException(CommandRunExceptionType.USAGE,
"Expecting a file", this); //$NON-NLS-1$
}
String scriptFile = args[0]; String scriptFile = args[0];
Object[] params = Arrays.copyOfRange(args, 1, args.length); String[] params = Arrays.copyOfRange(args, 1, args.length);
try (FileReader fReader = new FileReader(new File(scriptFile));
BufferedReader reader = new BufferedReader(fReader)) {
String cmd; String cmd;
for (int i = 1; i < args.length; i++) {
params[i - 1] = args[i];
}
int lineNo = -1; int lineNo = -1;
try (InputStreamReader fReader = new InputStreamReader(
new FileInputStream(scriptFile), charset);
BufferedReader reader = new BufferedReader(fReader)) {
while ((cmd = reader.readLine()) != null) { while ((cmd = reader.readLine()) != null) {
lineNo++; lineNo++;
if (cmd.startsWith(" ") || cmd.startsWith("\t")) { //$NON-NLS-1$ //$NON-NLS-2$ String cmdLine = readCommandLine(cmd, params);
reader.close(); if (cmdLine == null) {
fReader.close();
throw new CommandRunException(
"Invalid command in script (line starts with space character)", //$NON-NLS-1$
this);
}
if (cmd.isEmpty() || cmd.startsWith(commentPrefix)) {
continue; continue;
} }
String cmdLine = MessageFormat.format(cmd, params);
List<String> ps = GCLCConstants.splitCommand(cmdLine); List<String> ps = GCLCConstants.splitCommand(cmdLine);
String command = ps.remove(0); String command = ps.remove(0);
try {
application.executeSub(command, ps.toArray(new String[0])); application.executeSub(command, ps.toArray(new String[0]));
} catch (CommandRunException e) {
// TODO: handle exception
throw new CommandRunException(
CommandRunExceptionType.EXECUTION,
MessageFormat.format(
"The script could not complete due to command failure at line {0} ({1})",
lineNo, e.getLocalizedMessage()),
e, this);
}
} }
} catch (CommandParsingException e) { } catch (CommandParsingException e) {
throw new CommandRunException("Invalid command in script (" + //$NON-NLS-1$ throw new CommandRunException("Invalid command in script (" + //$NON-NLS-1$
@ -127,9 +113,57 @@ public class ScriptExecution extends Command {
} catch (IOException e) { } catch (IOException e) {
throw new CommandRunException("Unable to read script", //$NON-NLS-1$ throw new CommandRunException("Unable to read script", //$NON-NLS-1$
e, this); e, this);
} catch (CommandRunException e) {
throw manageRunException(e, lineNo);
} }
} }
/** @param args the arguments
* @throws CommandRunException if the arguments were not the ones
* expected */
private void checkArgs(String[] args) throws CommandRunException {
if (args.length == 0) {
throw new CommandRunException(CommandRunExceptionType.USAGE,
"Expecting a file", this); //$NON-NLS-1$
}
}
/** This method will create the correct exception. The exception source must
* be this command.
*
* @param e the exception
* @param lineNo the line nu;ber
* @return the exception to actually throw */
private CommandRunException manageRunException(CommandRunException e,
int lineNo) {
if (e.getSource() == this) {
// ensure closing?
return e;
}
return new CommandRunException(CommandRunExceptionType.EXECUTION,
MessageFormat.format(
"The script could not complete due to command failure at line {0} ({1})", //$NON-NLS-1$
Integer.valueOf(lineNo), e.getLocalizedMessage()),
e, this);
}
/** @param cmd the line
* @param params the formatting parameters
* @return the command if it is indeed one, null otherwise
* @throws CommandRunException if the line stqrted with a space character */
private String readCommandLine(String cmd,
Object[] params) throws CommandRunException {
if (cmd.startsWith(SPACE) || cmd.startsWith(TAB)) {
throw new CommandRunException(
"Invalid command in script (line starts with space character)", //$NON-NLS-1$
this);
}
if (cmd.isEmpty() || cmd.startsWith(commentPrefix)) {
return null;
}
return MessageFormat.format(cmd, params);
}
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail() */ * @see fr.bigeon.gclc.command.Command#usageDetail() */
@Override @Override

View File

@ -38,13 +38,9 @@
*/ */
package fr.bigeon.gclc.exception; package fr.bigeon.gclc.exception;
/** /** The command run exception possible types
* <p>
* TODO
* *
* @author Emmanuel Bigeon * @author Emmanuel Bigeon */
*
*/
public enum CommandRunExceptionType { public enum CommandRunExceptionType {
/** Type of exception due to a wrong usage */ /** Type of exception due to a wrong usage */
USAGE, USAGE,

View File

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

View File

@ -0,0 +1,71 @@
/*
* 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.exception.InvalidParameterException.java
* Created on: Nov 19, 2016
*/
package fr.bigeon.gclc.exception;
/** This exception is thrown during command definitions to indicate a wrong
* parameter definition.
* <p>
* This class is particularly used by
* {@link fr.bigeon.gclc.command.ParametrizedCommand parameterized commands}.
*
* @author Emmanuel Bigeon */
public class InvalidParameterException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
/** @param message the message
* @param cause the cause */
public InvalidParameterException(String message, Throwable cause) {
super(message, cause);
}
/** @param message the message */
public InvalidParameterException(String message) {
super(message);
}
/** @param cause the cause */
public InvalidParameterException(Throwable cause) {
super(cause);
}
}

View File

@ -43,6 +43,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.PrintStream; import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -60,6 +61,9 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
private static final Logger LOGGER = Logger private static final Logger LOGGER = Logger
.getLogger(SystemConsoleManager.class.getName()); .getLogger(SystemConsoleManager.class.getName());
/** The empty string constant */
private static final String EMPTY = ""; //$NON-NLS-1$
/** The command prompt. It can be changed. */ /** The command prompt. It can be changed. */
private String prompt = DEFAULT_PROMPT; private String prompt = DEFAULT_PROMPT;
@ -74,15 +78,17 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
/** 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 SystemConsoleManager() {
this(System.out, System.in); 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
public SystemConsoleManager(PrintStream out, InputStream in) { * @param charset the charset for the input */
public SystemConsoleManager(PrintStream out, InputStream in,
Charset charset) {
super(); super();
this.out = out; this.out = out;
this.in = new BufferedReader(new InputStreamReader(in)); this.in = new BufferedReader(new InputStreamReader(in, charset));
} }
/** @return the prompt */ /** @return the prompt */
@ -95,19 +101,22 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
* @see fr.bigeon.gclc.ConsoleManager#print(java.lang.Object) */ * @see fr.bigeon.gclc.ConsoleManager#print(java.lang.Object) */
@Override @Override
public void print(String object) throws IOException { public void print(String object) throws IOException {
checkOpen();
out.print(object);
}
/** @throws IOException if the stream was closed */
private void checkOpen() throws IOException {
if (closed) { if (closed) {
throw new IOException(); throw new IOException();
} }
out.print(object);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#println() */ * @see fr.bigeon.gclc.ConsoleManager#println() */
@Override @Override
public void println() throws IOException { public void println() throws IOException {
if (closed) { checkOpen();
throw new IOException();
}
out.println(); out.println();
} }
@ -115,9 +124,7 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
* @see fr.bigeon.gclc.ConsoleManager#println(java.lang.Object) */ * @see fr.bigeon.gclc.ConsoleManager#println(java.lang.Object) */
@Override @Override
public void println(String object) throws IOException { public void println(String object) throws IOException {
if (closed) { checkOpen();
throw new IOException();
}
out.println(object); out.println(object);
} }
@ -125,20 +132,22 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
* @see fr.bigeon.gclc.ConsoleManager#prompt() */ * @see fr.bigeon.gclc.ConsoleManager#prompt() */
@Override @Override
public String prompt() throws IOException { public String prompt() throws IOException {
return prompt(new String() + prompt); return prompt(prompt);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */ * @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */
@Override @Override
public String prompt(String message) throws IOException { public String prompt(String message) throws IOException {
if (closed) { checkOpen();
throw new IOException(); String result = EMPTY;
} out.print(message);
String result = new String();
out.print(message + ' ');
try { try {
result = in.readLine(); result = in.readLine();
while (result != null && result.length() > 0 &&
result.charAt(0) == 0) {
result = result.substring(1);
}
} catch (final IOException e) { } catch (final IOException e) {
LOGGER.log(Level.SEVERE, "Unable to read prompt", e); //$NON-NLS-1$ LOGGER.log(Level.SEVERE, "Unable to read prompt", e); //$NON-NLS-1$
} }

View File

@ -90,9 +90,9 @@ public class CLIPrompter {
manager.println(index++ + ") " + u); //$NON-NLS-1$ manager.println(index++ + ") " + u); //$NON-NLS-1$
} }
if (cancel != null) { if (cancel != null) {
manager.println(index + ") " + cancel); //$NON-NLS-1$ manager.println(index++ + ") " + cancel); //$NON-NLS-1$
} }
return index; return index - 1;
} }
/** @param manager the manager /** @param manager the manager
@ -311,10 +311,10 @@ public class CLIPrompter {
String ender) throws IOException { String ender) throws IOException {
manager.println(message + CLIPrompterMessages manager.println(message + CLIPrompterMessages
.getString("promptlongtext.exit.dispkey", ender)); //$NON-NLS-1$ .getString("promptlongtext.exit.dispkey", ender)); //$NON-NLS-1$
String res = manager.prompt(PROMPT); String res = manager.prompt(CLIPrompterMessages.getString(PROMPT));
String line = res; String line = res;
while (!line.equals(ender)) { while (!line.equals(ender)) {
line = manager.prompt(PROMPT); line = manager.prompt(CLIPrompterMessages.getString(PROMPT));
if (!line.equals(ender)) { if (!line.equals(ender)) {
res += System.lineSeparator() + line; res += System.lineSeparator() + line;
} }
@ -356,7 +356,7 @@ public class CLIPrompter {
final List<Integer> chs = promptMultiChoice(manager, choices, message); final List<Integer> chs = promptMultiChoice(manager, choices, message);
final List<T> userChoices = new ArrayList<>(); final List<T> userChoices = new ArrayList<>();
for (final Integer integer : chs) { for (final Integer integer : chs) {
userChoices.add(choicesMap.get(integer)); userChoices.add(choicesMap.get(choices.get(integer.intValue())));
} }
return userChoices; return userChoices;
} }
@ -416,7 +416,7 @@ public class CLIPrompter {
} }
final int r; final int r;
r = Integer.parseInt(val); r = Integer.parseInt(val);
if (r >= 0 && r < index) { if (r >= 0 && r <= index) {
chs.add(Integer.valueOf(r)); chs.add(Integer.valueOf(r));
return true; return true;
} }

View File

@ -50,6 +50,8 @@ public class PrintUtils {
private static final String CONT_DOT = "..."; //$NON-NLS-1$ private static final String CONT_DOT = "..."; //$NON-NLS-1$
/** The continuation dot string length */ /** The continuation dot string length */
private static final int CONT_DOT_LENGTH = CONT_DOT.length(); private static final int CONT_DOT_LENGTH = CONT_DOT.length();
/** The empty string constant */
private static final String EMPTY = ""; //$NON-NLS-1$
/** Utility class */ /** Utility class */
private PrintUtils() { private PrintUtils() {
@ -101,8 +103,9 @@ public class PrintUtils {
toCut = toCut.substring(index + 1); toCut = toCut.substring(index + 1);
} }
result.add(toCut); result.add(toCut);
result.add(new String()); result.add(EMPTY);
} }
result.remove(result.size() - 1);
return result; return result;
} }
} }

View File

@ -1,11 +1,12 @@
exit.tip=Exit the application exit.tip=Exit the application
help.cmd.tip=Display an help tip help.cmd.tip=Display an help tip
prompt.lineprompt=> prompt.lineprompt=>\
promptlist.exit.defaultkey=\\q promptlist.exit.defaultkey=\\q
promptlist.exit.dispkey=\ (exit with a new line made of "{0}") promptlist.exit.dispkey=\ (exit with a new line made of "{0}")
promptlist.prompt=>\ promptlist.prompt=>\
promptlist.multi.sepkey=\
promptbool.choices=\ (Y/N) promptbool.choices=\ (Y/N)
promptbool.choices.invalid=Invalid input. Please input one of {0}. promptbool.choices.invalid=Invalid input. Please input one of {0}.

View File

@ -39,14 +39,10 @@
package fr.bigeon.gclc; package fr.bigeon.gclc;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter;
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.SystemConsoleManager; import fr.bigeon.gclc.test.utils.TestConsoleManager;
/** /**
* <p> * <p>
@ -56,20 +52,16 @@ import fr.bigeon.gclc.manager.SystemConsoleManager;
* *
*/ */
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class CommandTestingApplication { public class CommandTestingApplication implements AutoCloseable {
private final PrintWriter writer;
private final ConsoleTestApplication application; private final ConsoleTestApplication application;
private final Thread th; private final Thread th;
private final TestConsoleManager manager;
/** @throws IOException if the streams cannot be build */ /** @throws IOException if the streams cannot be build */
@SuppressWarnings("resource")
public CommandTestingApplication() throws IOException { public CommandTestingApplication() throws IOException {
final PipedOutputStream src = new PipedOutputStream(); manager = new TestConsoleManager();
InputStream in = new PipedInputStream(src); application = new ConsoleTestApplication(manager);
application = new ConsoleTestApplication(
new SystemConsoleManager(System.out, in));
th = new Thread(new Runnable() { th = new Thread(new Runnable() {
@SuppressWarnings("synthetic-access") @SuppressWarnings("synthetic-access")
@ -80,16 +72,16 @@ public class CommandTestingApplication {
}); });
th.start(); th.start();
writer = new PrintWriter(src, true);
} }
public void stop() { @Override
public void close() throws IOException {
application.exit(); application.exit();
writer.println(); manager.close();
} }
public void sendCommand(String cmd) { public void sendCommand(String cmd) throws IOException {
writer.println(cmd); manager.type(cmd);
} }
/** @param cmd the command /** @param cmd the command
@ -105,11 +97,9 @@ public class CommandTestingApplication {
return application; return application;
} }
/** /** @throws IOException if the writing failed */
* public void waitAndStop() throws IOException {
*/ manager.type(ConsoleTestApplication.EXIT);
public void waitAndStop() {
writer.println(ConsoleTestApplication.EXIT);
try { try {
th.join(); th.join();
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -117,4 +107,16 @@ public class CommandTestingApplication {
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.test.utils.TestConsoleManager#readNextLine() */
public String readNextLine() throws IOException {
String ret = manager.readNextLine();
if (ret.equals(manager.getPrompt())) {
return null;
}
return ret;
}
} }

View File

@ -38,22 +38,30 @@
*/ */
package fr.bigeon.gclc; package fr.bigeon.gclc;
import static org.junit.Assert.fail; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter;
import org.junit.Test; import org.junit.Test;
import fr.bigeon.gclc.command.ExitCommand;
import fr.bigeon.gclc.command.ICommand;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.i18n.Messages;
import fr.bigeon.gclc.manager.ConsoleManager;
import fr.bigeon.gclc.manager.SystemConsoleManager; import fr.bigeon.gclc.manager.SystemConsoleManager;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
/** Test class for ConsoleApplication /** Test class for ConsoleApplication
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
@SuppressWarnings({"resource", "javadoc", "nls", "static-method"}) @SuppressWarnings({"javadoc", "nls", "static-method"})
public class ConsoleApplicationTest { public class ConsoleApplicationTest {
/** 3 seconds in milliseconds */ /** 3 seconds in milliseconds */
@ -69,27 +77,74 @@ public class ConsoleApplicationTest {
@Test @Test
public void executionTest() { public void executionTest() {
try { try (CommandTestingApplication application = new CommandTestingApplication()) {
CommandTestingApplication application = new CommandTestingApplication();
// remove welcome
assertEquals(application.getApplication().getHeader(),
application.readNextLine());
// Remove first prompt
assertNull(application.readNextLine());
application.sendCommand("");
assertNull(application.readNextLine());
application.sendCommand("test"); application.sendCommand("test");
assertEquals("Test command ran fine", application.readNextLine());
assertNull(application.readNextLine());
application.sendCommand("toto"); application.sendCommand("toto");
assertEquals(
Messages.getString("ConsoleApplication.cmd.failed", "toto"),
application.readNextLine());
assertEquals(
Messages.getString("CommandProvider.unrecognized", "toto"),
application.readNextLine());
assertNull(application.readNextLine());
application.sendCommand("long"); application.sendCommand("long");
application.sendCommand("exit"); assertEquals("Waita minute", application.readNextLine());
assertEquals("done!", application.readNextLine());
CommandRequestListener crl = new CommandRequestListener() {
@Override
public void commandRequest(String command) {
//
}
};
CommandRequestListener crl2 = new CommandRequestListener() {
@Override
public void commandRequest(String command) {
//
}
};
application.getApplication().addListener(crl);
application.getApplication().addListener(crl2);
assertNull(application.readNextLine());
application.sendCommand("test");
assertEquals("Test command ran fine", application.readNextLine());
application.getApplication().removeListener(crl2);
application.getApplication().removeListener(crl);
application.getApplication().removeListener(crl);
assertTrue(application.getApplication().isRunning());
assertNull(application.readNextLine());
application.sendCommand("exit");
assertEquals(application.getApplication().getFooter(),
application.readNextLine());
assertFalse(application.getApplication().isRunning());
} catch (IOException e1) { } catch (IOException e1) {
// TODO Auto-generated catch block assertNull(e1);
e1.printStackTrace();
} }
try { ConsoleApplication appli = null;
final PipedOutputStream src = new PipedOutputStream(); try (TestConsoleManager manager = new TestConsoleManager()) {
InputStream in = new PipedInputStream(src); final ConsoleApplication app = new ConsoleApplication(manager, null,
null);
appli = app;
app.add(new ExitCommand("exit", app));
final ConsoleTestApplication app = new ConsoleTestApplication(
new SystemConsoleManager(System.out, in));
Thread th = new Thread(new Runnable() { Thread th = new Thread(new Runnable() {
@SuppressWarnings("synthetic-access")
@Override @Override
public void run() { public void run() {
app.start(); app.start();
@ -98,33 +153,67 @@ public class ConsoleApplicationTest {
th.start(); th.start();
Thread test = new Thread(new Runnable() { manager.type("exit");
th.join();
} catch (IOException | InvalidCommandName | InterruptedException e) {
assertNull(e);
}
assertNotNull(appli);
appli.start();
assertFalse(appli.isRunning());
}
@Test
public void interpretCommandTest() {
try (TestConsoleManager test = new TestConsoleManager()) {
ConsoleApplication appl = new ConsoleApplication(test, "", "");
appl.interpretCommand("invalid cmd \"due to misplaced\"quote");
assertEquals("Command line cannot be parsed", test.readNextLine());
appl.interpretCommand("");
final String message = "message";
try {
appl.add(new ICommand() {
@Override @Override
public void run() { public void execute(String... args) throws CommandRunException {
try (PrintWriter writer = new PrintWriter(src, true)) { throw new CommandRunException(
writer.println("test"); CommandRunExceptionType.USAGE, message, this);
writer.println("toto");
writer.println("long");
writer.println("exit");
} }
@Override
public String getCommandName() {
return "fail";
} }
@Override
public void help(ConsoleManager manager,
String... args) throws IOException {
manager.println(message);
}
@Override
public String tip() {
return "";
}
}); });
test.start(); } catch (InvalidCommandName e) {
try { assertNull(e);
th.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
test.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
appl.interpretCommand("fail");
assertEquals(
Messages.getString("ConsoleApplication.cmd.failed", "fail"),
test.readNextLine());
assertEquals(message, test.readNextLine());
assertEquals(message, test.readNextLine());
} catch (IOException e) { } catch (IOException e) {
fail("pipe creation " + e.getLocalizedMessage()); //$NON-NLS-1$ assertNull(e);
} }
} }
} }

View File

@ -100,6 +100,18 @@ public class ConsoleTestApplication extends ConsoleApplication {
} }
} }
}); });
add(new Command("failingCmd") {
@Override
public String tip() {
return "A long execution command";
}
@Override
public void execute(String... args) throws CommandRunException {
throw new CommandRunException("Failing command", this);
}
});
} catch (final InvalidCommandName e) { } catch (final InvalidCommandName e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -0,0 +1,283 @@
/*
* 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.command.CommandParametersTest.java
* Created on: Nov 18, 2016
*/
package fr.bigeon.gclc.command;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
/**
* <p>
* TODO
*
* @author Emmanuel Bigeon
*
*/
public class CommandParametersTest {
/**
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#CommandParameters(java.util.Set, java.util.Set, boolean)}.
*/
@Test
public final void testCommandParameters(){
Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>();
CommandParameters parameters = new CommandParameters(bools, strings,
true);
assertFalse(parameters.parseArgs("-ungivenFlag"));
parameters = new CommandParameters(bools, strings, false);
assertTrue(parameters.parseArgs("-ungivenFlag"));
}
/**
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#get(java.lang.String)}.
*/
@Test
public final void testGet(){
Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>();
bools.add("boolFlag");
strings.add("str");
CommandParameters parameters = new CommandParameters(bools, strings,
true);
assertNull(parameters.get("ungiven"));
assertNull(parameters.get("str"));
parameters.parseArgs("-ungiven", "val");
assertNull(parameters.get("ungiven"));
assertNull(parameters.get("str"));
parameters.parseArgs("-str", "val");
assertNull(parameters.get("ungiven"));
assertEquals("val", parameters.get("str"));
parameters.parseArgs("-ungiven");
assertNull(parameters.get("ungiven"));
assertEquals("val", parameters.get("str"));
}
/**
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#getAdditionals()}.
*/
@Test
public final void testGetAdditionals(){
Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>();
bools.add("boolFlag");
strings.add("str");
CommandParameters parameters = new CommandParameters(bools, strings,
true);
parameters.parseArgs("-boolFlag");
assertTrue(parameters.getAdditionals().isEmpty());
parameters.parseArgs("-ungiven");
assertTrue(parameters.getAdditionals().isEmpty());
parameters = new CommandParameters(bools, strings, false);
parameters.parseArgs("-boolFlag");
assertTrue(parameters.getAdditionals().isEmpty());
parameters.parseArgs("-ungiven");
assertTrue(parameters.getAdditionals().contains("ungiven"));
assertEquals(1, parameters.getAdditionals().size());
}
/**
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#getBool(java.lang.String)}.
*/
@Test
public final void testGetBool(){
Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>();
bools.add("boolFlag");
strings.add("str");
CommandParameters parameters = new CommandParameters(bools, strings,
true);
assertFalse(parameters.getBool("ungiven"));
assertFalse(parameters.getBool("boolFlag"));
parameters.parseArgs("-boolFlag");
assertTrue(parameters.getBool("boolFlag"));
assertFalse(parameters.getBool("ungiven"));
parameters.parseArgs("-ungiven");
assertFalse(parameters.getBool("ungiven"));
assertTrue(parameters.getBool("boolFlag"));
parameters = new CommandParameters(bools, strings, false);
assertFalse(parameters.getBool("ungiven"));
assertFalse(parameters.getBool("boolFlag"));
parameters.parseArgs("-boolFlag");
assertTrue(parameters.getBool("boolFlag"));
assertFalse(parameters.getBool("ungiven"));
parameters.parseArgs("-ungiven");
assertFalse(parameters.getBool("ungiven"));
assertTrue(parameters.getBool("boolFlag"));
}
/**
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#parseArgs(java.lang.String[])}.
*/
@Test
public final void testParseArgs(){
Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>();
bools.add("boolFlag");
strings.add("str");
CommandParameters parameters = new CommandParameters(bools, strings,
true);
assertFalse(parameters.parseArgs("-ungivenFlag"));
assertFalse(parameters.parseArgs("-str"));
assertTrue(parameters.parseArgs("-boolFlag"));
assertTrue(parameters.parseArgs("-str", "-boolFlag"));
assertTrue(parameters.parseArgs("-boolFlag", "-str", "val"));
}
/**
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, boolean)}.
*/
@Test
public final void testSetStringBoolean(){
Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>();
bools.add("boolFlag");
strings.add("str");
CommandParameters parameters = new CommandParameters(bools, strings,
true);
assertFalse(parameters.getBool("ungiven"));
assertFalse(parameters.getBool("boolFlag"));
parameters.set("boolFlag", true);
assertTrue(parameters.getBool("boolFlag"));
assertFalse(parameters.getBool("ungiven"));
parameters.set("ungiven", true);
assertFalse(parameters.getBool("ungiven"));
assertTrue(parameters.getBool("boolFlag"));
parameters = new CommandParameters(bools, strings, false);
assertFalse(parameters.getBool("ungiven"));
assertFalse(parameters.getBool("boolFlag"));
parameters.set("boolFlag", true);
assertTrue(parameters.getBool("boolFlag"));
assertFalse(parameters.getBool("ungiven"));
parameters.set("ungiven", true);
assertFalse(parameters.getBool("ungiven"));
assertTrue(parameters.getBool("boolFlag"));
}
/**
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, java.lang.String)}.
*/
@Test
public final void testSetStringString(){
Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>();
bools.add("boolFlag");
strings.add("str");
CommandParameters parameters = new CommandParameters(bools, strings,
true);
assertNull(parameters.get("ungiven"));
assertNull(parameters.get("str"));
parameters.set("ungiven", "val");
assertNull(parameters.get("ungiven"));
assertNull(parameters.get("str"));
parameters.set("str", "val");
assertNull(parameters.get("ungiven"));
assertEquals("val", parameters.get("str"));
parameters.set("ungiven", "val");
assertNull(parameters.get("ungiven"));
assertEquals("val", parameters.get("str"));
parameters = new CommandParameters(bools, strings, false);
assertNull(parameters.get("ungiven"));
assertNull(parameters.get("str"));
parameters.set("ungiven", "val");
assertNull(parameters.get("ungiven"));
assertNull(parameters.get("str"));
parameters.set("str", "val");
assertNull(parameters.get("ungiven"));
assertEquals("val", parameters.get("str"));
parameters.set("ungiven", "val");
assertNull(parameters.get("ungiven"));
assertEquals("val", parameters.get("str"));
}
}

View File

@ -0,0 +1,105 @@
/*
* 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.command.CommandProviderTest.java
* Created on: Nov 19, 2016
*/
package fr.bigeon.gclc.command;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import org.junit.Test;
import fr.bigeon.gclc.exception.InvalidCommandName;
/** <p>
* TODO
*
* @author Emmanuel Bigeon */
public class CommandProviderTest {
/** Test method for
* {@link fr.bigeon.gclc.command.CommandProvider#add(fr.bigeon.gclc.command.ICommand)}. */
@Test
public final void testAdd() {
CommandProvider provider = new CommandProvider();
try {
provider.add(new MockCommand(null));
fail("null name for command should be rejected");
} catch (InvalidCommandName e) {
assertNotNull(e);
}
try {
provider.add(new MockCommand(""));
fail("null name for command should be rejected");
} catch (InvalidCommandName e) {
assertNotNull(e);
}
try {
provider.add(new MockCommand("-name"));
fail("name with minus as starting character for command should be rejected");
} catch (InvalidCommandName e) {
assertNotNull(e);
}
try {
provider.add(new MockCommand("name command"));
fail("name with space for command should be rejected");
} catch (InvalidCommandName e) {
assertNotNull(e);
}
ICommand mock = new MockCommand("name");
try {
provider.add(mock);
} catch (InvalidCommandName e) {
assertNull(e);
}
try {
provider.add(new MockCommand(mock.getCommandName()));
fail("already existing command name should be rejected");
} catch (InvalidCommandName e) {
assertNotNull(e);
}
try {
provider.add(mock);
} catch (InvalidCommandName e) {
assertNotNull(e);
}
}
}

View File

@ -0,0 +1,217 @@
/*
* 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.command.CommandTest.java
* Created on: Nov 19, 2016
*/
package fr.bigeon.gclc.command;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
/** <p>
* TODO
*
* @author Emmanuel Bigeon */
public class CommandTest {
@Test
public final void test() {
try (TestConsoleManager test = new TestConsoleManager()) {
Command cmd;
cmd = new Command("name") {
@Override
public String tip() {
return null;
}
@Override
public void execute(String... args) throws CommandRunException {
//
}
};
cmd.help(test);
cmd = new Command("name") {
@Override
public String tip() {
return "";
}
@Override
public void execute(String... args) throws CommandRunException {
//
}
};
cmd.help(test);
cmd = new Command("name") {
@Override
public String tip() {
return "tip";
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#brief() */
@Override
protected String brief() {
return null;
}
@Override
public void execute(String... args) throws CommandRunException {
//
}
};
cmd.help(test);
cmd = new Command("name") {
@Override
public String tip() {
return "tip";
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#brief() */
@Override
protected String brief() {
return "brief";
}
@Override
public void execute(String... args) throws CommandRunException {
//
}
};
cmd.help(test);
cmd = new Command("name") {
@Override
public String tip() {
return "tip";
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail() */
@Override
protected String usageDetail() {
return null;
}
@Override
public void execute(String... args) throws CommandRunException {
//
}
};
cmd.help(test);
cmd = new Command("name") {
@Override
public String tip() {
return "tip";
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail() */
@Override
protected String usageDetail() {
return "details";
}
@Override
public void execute(String... args) throws CommandRunException {
//
}
};
cmd.help(test);
cmd = new Command("name") {
@Override
public String tip() {
return "tip";
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail() */
@Override
protected String usageDetail() {
return "details" + System.lineSeparator();
}
@Override
public void execute(String... args) throws CommandRunException {
//
}
};
cmd.help(test);
cmd = new Command("name") {
@Override
public String tip() {
return "tip";
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail() */
@Override
protected String usageDetail() {
return "\n";
}
@Override
public void execute(String... args) throws CommandRunException {
//
}
};
cmd.help(test);
} catch (IOException e) {
assertNull(e);
}
}
}

View File

@ -0,0 +1,137 @@
/*
* 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.command.HelpExecutorTest.java
* Created on: Nov 19, 2016
*/
package fr.bigeon.gclc.command;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
/**
* <p>
* TODO
*
* @author Emmanuel Bigeon
*
*/
public class HelpExecutorTest {
/**
* Test method for {@link fr.bigeon.gclc.command.HelpExecutor#HelpExecutor(java.lang.String, fr.bigeon.gclc.manager.ConsoleManager, fr.bigeon.gclc.command.ICommand)}.
*/
@Test
public final void testHelpExecutor(){
HelpExecutor help;
try {
help = new HelpExecutor("?", null, new MockCommand("mock"));
fail("help is an interactive command, should need console manager");
} catch (Exception e) {
assertNotNull(e);
}
try (TestConsoleManager test = new TestConsoleManager()) {
help = new HelpExecutor("?", test, new MockCommand("mock"));
} catch (Exception e) {
assertNull(e);
}
}
/**
* Test method for {@link fr.bigeon.gclc.command.HelpExecutor#execute(java.lang.String[])}.
*/
@Test
public final void testExecute(){
try {
TestConsoleManager test = new TestConsoleManager();
HelpExecutor help = new HelpExecutor("?", test,
new Command("mock") {
@Override
public void execute(String... args) throws CommandRunException {
//
}
@Override
public String tip() {
return "";
}
});
help.execute();
test.close();
try {
help.execute();
fail("manager closed shall provoke failure of help command execution");
} catch (Exception e) {
assertNotNull(e);
}
} catch (Exception e) {
assertNull(e);
}
}
/**
* Test method for {@link fr.bigeon.gclc.command.HelpExecutor#tip()}.
*/
@Test
public final void testTip(){
try (TestConsoleManager test = new TestConsoleManager()) {
HelpExecutor help = new HelpExecutor("?", test,
new MockCommand("mock"));
help.tip();
help.help(test);
} catch (Exception e) {
assertNull(e);
}
try (TestConsoleManager test = new TestConsoleManager()) {
HelpExecutor help = new HelpExecutor("?", test,
new SubedCommand("sub", new MockCommand("mock")));
help.tip();
help.help(test);
} catch (Exception e) {
assertNull(e);
}
}
}

View File

@ -0,0 +1,649 @@
/*
* 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.command.ParametrizedCommandTest.java
* Created on: Nov 18, 2016
*/
package fr.bigeon.gclc.command;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.InvalidParameterException;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
/** <p>
* TODO
*
* @author Emmanuel Bigeon */
public class ParametrizedCommandTest {
/** Test method for
* {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */
@Test
public final void testParametrizedCommandConsoleManagerString() {
try (TestConsoleManager test = new TestConsoleManager()) {
ParametrizedCommand cmd = new ParametrizedCommand(test, "name") {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
assertTrue(cmd.isStrict());
assertTrue(cmd.isInteractive());
} catch (IOException e) {
fail("Unexpected exception in creation");
assertNull(e);
}
ParametrizedCommand cmd = new ParametrizedCommand(null, "name") {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
assertTrue(cmd.isStrict());
assertFalse(cmd.isInteractive());
cmd = new ParametrizedCommand("name") {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
assertTrue(cmd.isStrict());
assertFalse(cmd.isInteractive());
}
/** Test method for
* {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String, boolean)}. */
@Test
public final void testParametrizedCommandConsoleManagerStringBoolean() {
try (TestConsoleManager test = new TestConsoleManager()) {
ParametrizedCommand cmd = new ParametrizedCommand(test, "name",
false) {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
assertFalse(cmd.isStrict());
assertTrue(cmd.isInteractive());
} catch (IOException e) {
fail("Unexpected exception in creation");
assertNull(e);
}
ParametrizedCommand cmd = new ParametrizedCommand(null, "name", false) {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
assertFalse(cmd.isStrict());
assertFalse(cmd.isInteractive());
cmd = new ParametrizedCommand("name", false) {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
assertFalse(cmd.isStrict());
assertFalse(cmd.isInteractive());
}
/** Test method for
* {@link fr.bigeon.gclc.command.ParametrizedCommand#addParameter(java.lang.String, boolean, boolean)}. */
@Test
public final void testAddParameter() {
ParametrizedCommand cmd = new ParametrizedCommand(null, "name") {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
cmd = new ParametrizedCommand(null, "name", true) {
@Override
public String tip() {
return null;
}
@Override
protected void doExecute(CommandParameters parameters) {
//
}
};
// XXX Boolean flag should not be specified mandatory! They are by
// nature qualified
try {
cmd.addParameter("boolFlag", false, true);
fail("Boolean parameters should never be needed specified");
} catch (InvalidParameterException e) {
// OK
assertNotNull(e);
}
String str = "str";
try {
assertTrue(cmd.getBooleanParameters().isEmpty());
assertTrue(cmd.getStringParameters().isEmpty());
cmd.addParameter("boolFlag", false, false);
assertEquals(1, cmd.getBooleanParameters().size());
assertTrue(cmd.getStringParameters().isEmpty());
cmd.addParameter(str, true, false);
assertEquals(1, cmd.getBooleanParameters().size());
assertEquals(1, cmd.getStringParameters().size());
assertFalse(cmd.isNeeded(str));
cmd.addParameter("boolFlag", false, false);
assertEquals(1, cmd.getBooleanParameters().size());
assertEquals(1, cmd.getStringParameters().size());
cmd.addParameter(str, true, true);
assertEquals(1, cmd.getBooleanParameters().size());
assertEquals(1, cmd.getStringParameters().size());
assertTrue(cmd.isNeeded(str));
cmd.addParameter(str, true, false);
assertEquals(1, cmd.getBooleanParameters().size());
assertEquals(1, cmd.getStringParameters().size());
assertTrue(cmd.isNeeded(str));
} catch (InvalidParameterException e) {
fail("Unexpected error in addition of legitimate parameter");
assertNotNull(e);
}
try {
cmd.addParameter(str, false, false);
fail("parameter type conversion shall fail");
} catch (InvalidParameterException e) {
// OK
assertNotNull(e);
}
try {
cmd.addParameter("boolFlag", true, false);
fail("parameter type conversion shall fail");
} catch (InvalidParameterException e) {
// OK
assertNotNull(e);
}
try {
cmd.addParameter("boolFlag", false, true);
fail("parameter type conversion shall fail");
} catch (InvalidParameterException e) {
// OK
assertNotNull(e);
}
try {
cmd.addParameter("boolFlag", true, true);
fail("parameter type conversion shall fail");
} catch (InvalidParameterException e) {
// OK
assertNotNull(e);
}
}
/** Test method for
* {@link fr.bigeon.gclc.command.ParametrizedCommand#execute(java.lang.String[])}. */
@Test
public final void testExecute() {
final String addParam = "additional";
final String str1 = "str1";
final String str2 = "str2";
final String bool1 = "bool1";
final String bool2 = "bool2";
// Test on command with no needed elements
ParametrizedCommand cmd = new ParametrizedCommand("name", false) {
private boolean evenCall = true;
@Override
public String tip() {
return "";
}
@Override
protected void doExecute(CommandParameters parameters) {
assertTrue(parameters.getBooleanArgumentKeys().isEmpty());
assertTrue(parameters.getStringArgumentKeys().isEmpty());
if (evenCall) {
assertTrue(parameters.getAdditionals().isEmpty());
evenCall = false;
} else {
assertEquals(1, parameters.getAdditionals().size());
assertTrue(parameters.getAdditionals().contains(addParam));
evenCall = true;
}
}
};
try {
cmd.execute();
cmd.execute("-" + addParam);
cmd.execute(addParam);
cmd.execute("-" + addParam, addParam);
} catch (CommandRunException e) {
assertNull(e);
fail("unepected error");
}
cmd = new ParametrizedCommand("name", false) {
private int call = 0;
{
try {
addParameter(str1, true, false);
addParameter(str2, true, false);
addParameter(bool1, false, false);
addParameter(bool2, false, false);
} catch (InvalidParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public String tip() {
return "";
}
@Override
protected void doExecute(CommandParameters parameters) {
assertEquals(2, parameters.getBooleanArgumentKeys().size());
assertEquals(2, parameters.getStringArgumentKeys().size());
switch (call) {
case 0:
case 1:
case 2:
case 3:
assertNull(parameters.get(str1));
assertNull(parameters.get(str2));
assertFalse(parameters.getBool(bool1));
assertFalse(parameters.getBool(bool2));
call++;
break;
case 4:
assertEquals(str2, parameters.get(str1));
assertNull(parameters.get(str2));
assertFalse(parameters.getBool(bool1));
assertFalse(parameters.getBool(bool2));
call++;
break;
case 5:
assertEquals(str2, parameters.get(str1));
assertNull(parameters.get(str2));
assertTrue(parameters.getBool(bool1));
assertFalse(parameters.getBool(bool2));
call = 0;
break;
default:
break;
}
}
};
try {
cmd.execute();
cmd.execute("-" + addParam);
cmd.execute(addParam);
cmd.execute("-" + addParam, addParam);
cmd.execute("-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1);
} catch (CommandRunException e) {
assertNull(e);
fail("unepected error");
}
cmd = new ParametrizedCommand("name", true) {
private int call = 0;
{
try {
addParameter(str1, true, false);
addParameter(str2, true, false);
addParameter(bool1, false, false);
addParameter(bool2, false, false);
} catch (InvalidParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public String tip() {
return "";
}
@Override
protected void doExecute(CommandParameters parameters) {
assertEquals(2, parameters.getBooleanArgumentKeys().size());
assertEquals(2, parameters.getStringArgumentKeys().size());
switch (call) {
case 0:
case 1:
assertNull(parameters.get(str1));
assertNull(parameters.get(str2));
assertFalse(parameters.getBool(bool1));
assertFalse(parameters.getBool(bool2));
call++;
break;
case 2:
assertEquals(str2, parameters.get(str1));
assertNull(parameters.get(str2));
assertFalse(parameters.getBool(bool1));
assertFalse(parameters.getBool(bool2));
call++;
break;
case 3:
assertEquals(str2, parameters.get(str1));
assertNull(parameters.get(str2));
assertTrue(parameters.getBool(bool1));
assertFalse(parameters.getBool(bool2));
call = 0;
break;
default:
break;
}
}
};
try {
cmd.execute();
cmd.execute(addParam);
cmd.execute("-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1);
} catch (CommandRunException e) {
assertNull(e);
fail("unepected error");
}
try {
cmd.execute("-" + addParam);
fail("Strict should fail with unexpected argument");
} catch (CommandRunException e) {
assertNotNull(e);
}
// Test on command with missing needed elements
cmd = new ParametrizedCommand("name", false) {
private final int call = 0;
{
try {
addParameter(str1, true, true);
addParameter(str2, true, false);
addParameter(bool1, false, false);
addParameter(bool2, false, false);
} catch (InvalidParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public String tip() {
return "";
}
@Override
protected void doExecute(CommandParameters parameters) {
assertEquals(str2, parameters.get(str1));
}
};
try {
cmd.execute("-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1);
cmd.execute("-" + str1, str2, "-" + addParam);
cmd.execute("-" + str1, str2, addParam);
cmd.execute("-" + str1, str2, "-" + addParam, addParam);
} catch (CommandRunException e) {
assertNull(e);
fail("unepected error");
}
try {
cmd.execute();
fail("needed " + str1 + " not provided shall fail");
} catch (CommandRunException e) {
assertNotNull(e);
}
cmd = new ParametrizedCommand("name", true) {
private final int call = 0;
{
try {
addParameter(str1, true, true);
addParameter(str2, true, false);
addParameter(bool1, false, false);
addParameter(bool2, false, false);
} catch (InvalidParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public String tip() {
return "";
}
@Override
protected void doExecute(CommandParameters parameters) {
//
assertEquals(str2, parameters.get(str1));
}
};
try {
cmd.execute("-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1);
cmd.execute("-" + str1, str2, addParam);
} catch (CommandRunException e) {
assertNull(e);
fail("unepected error");
}
try {
cmd.execute();
fail("needed " + str1 + " not provided shall fail");
} catch (CommandRunException e) {
assertNotNull(e);
}
try {
cmd.execute("-" + str1, str2, "-" + addParam);
fail("unepected error");
} catch (CommandRunException e) {
assertNotNull(e);
}
try {
cmd.execute("-" + str1, str2, "-" + addParam, addParam);
fail("unepected error");
} catch (CommandRunException e) {
assertNotNull(e);
}
// TODO Test of interactive not providing and providing all needed
try (TestConsoleManager test = new TestConsoleManager()) {
cmd = new ParametrizedCommand(test, "name", false) {
{
try {
addParameter(str1, true, true);
addParameter(str2, true, false);
addParameter(bool1, false, false);
addParameter(bool2, false, false);
} catch (InvalidParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public String tip() {
return "";
}
@Override
protected void doExecute(CommandParameters parameters) {
assertEquals(str2, parameters.get(str1));
}
};
try {
cmd.execute("-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1);
cmd.execute("-" + str1, str2, addParam);
cmd.execute("-" + str1, str2, "-" + addParam);
cmd.execute("-" + str1, str2, "-" + addParam, addParam);
} catch (CommandRunException e) {
assertNull(e);
fail("unepected error");
}
try {
Thread th = new Thread(new Runnable() {
@Override
public void run() {
try {
assertEquals(str1, test.readNextLine());
test.type("");
assertEquals(str1, test.readNextLine());
test.type(str2);
} catch (IOException e) {
assertNull(e);
}
}
});
th.start();
cmd.execute();
th.join();
th = new Thread(new Runnable() {
@Override
public void run() {
try {
assertEquals(str1, test.readNextLine());
test.type(str2);
} catch (IOException e) {
assertNull(e);
}
}
});
th.start();
cmd.execute("-" + addParam);
th.join();
} catch (CommandRunException | InterruptedException e) {
assertNull(e);
fail("unepected error");
}
} catch (IOException e) {
assertNull(e);
fail("unepected error");
}
try {
TestConsoleManager test = new TestConsoleManager();
cmd = new ParametrizedCommand(test, "name") {
{
try {
addParameter(str1, true, true);
addParameter(str2, true, false);
addParameter(bool1, false, false);
addParameter(bool2, false, false);
} catch (InvalidParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public String tip() {
return "";
}
@Override
protected void doExecute(CommandParameters parameters) {
assertEquals(str2, parameters.get(str1));
}
};
test.close();
cmd.execute("-" + str1, str2);
cmd.execute("-" + addParam);
fail("Closed manager shall cause error");
} catch (IOException e) {
assertNull(e);
} catch (CommandRunException e) {
assertNotNull(e);
}
}
}

View File

@ -38,14 +38,19 @@
*/ */
package fr.bigeon.gclc.command; package fr.bigeon.gclc.command;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset;
import org.junit.Test; import org.junit.Test;
import fr.bigeon.gclc.CommandTestingApplication; import fr.bigeon.gclc.ConsoleTestApplication;
import fr.bigeon.gclc.exception.InvalidCommandName; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
/** /**
* <p> * <p>
@ -62,24 +67,110 @@ public class ScriptExecutionTest {
*/ */
@Test @Test
public void testExecute() { public void testExecute() {
TestConsoleManager test;
try { try {
CommandTestingApplication application = new CommandTestingApplication(); test = new TestConsoleManager();
} catch (IOException e2) {
fail("creation of console manager failed"); //$NON-NLS-1$
assertNotNull(e2);
return;
}
ConsoleTestApplication app = new ConsoleTestApplication(
test);
ScriptExecution exec = new ScriptExecution("script", app, "#", //$NON-NLS-1$ //$NON-NLS-2$
Charset.forName("UTF-8"));
try {
exec.execute();
fail("execution of script command with no file should fail"); //$NON-NLS-1$
} catch (CommandRunException e1) {
// ok
assertEquals(exec, e1.getSource());
assertEquals(CommandRunExceptionType.USAGE, e1.getType());
}
application.add(new ScriptExecution("script", //$NON-NLS-1$ try {
application.getApplication(), "#")); //$NON-NLS-1$ exec.execute("src/test/resources/scripts/withprependSpace.txt"); //$NON-NLS-1$
fail("execution of script with lines begining with space should fail"); //$NON-NLS-1$
} catch (CommandRunException e1) {
// ok
assertEquals(exec, e1.getSource());
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
}
application.sendCommand("script src/test/resources/script1.txt"); //$NON-NLS-1$ try {
application.sendCommand("script src/test/resources/script2.txt"); //$NON-NLS-1$ exec.execute("src/test/resources/scripts/invalidCmdParse.txt"); //$NON-NLS-1$
application.sendCommand("script src/test/resources/script3.txt"); //$NON-NLS-1$ fail("execution of script with invalid command line should fail"); //$NON-NLS-1$
application.sendCommand("script src/test/resources/script4.txt"); //$NON-NLS-1$ } catch (CommandRunException e1) {
application // ok
.sendCommand("script src/test/resources/script5.txt test"); //$NON-NLS-1$ assertEquals(exec, e1.getSource());
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
}
application.waitAndStop(); try {
exec.execute("src/test/resources/scripts/invalidCmd.txt"); //$NON-NLS-1$
fail("execution of script with invalid command should fail"); //$NON-NLS-1$
} catch (CommandRunException e1) {
// ok
assertEquals(exec, e1.getSource());
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
}
} catch (IOException | InvalidCommandName e) { try {
fail("Unexpected exception " + e.getLocalizedMessage()); //$NON-NLS-1$ exec.execute("src/test/resources/scripts/failingCmdInvoc.txt"); //$NON-NLS-1$
fail("execution of script with failing command should fail"); //$NON-NLS-1$
} catch (CommandRunException e1) {
// ok
assertEquals(exec, e1.getSource());
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
}
try {
exec.execute("src/test/resources/scripts/someNonExisting.file"); //$NON-NLS-1$
fail("execution of script with unexisting file should fail"); //$NON-NLS-1$
} catch (CommandRunException e1) {
// ok
assertEquals(exec, e1.getSource());
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
}
try {
exec.execute("src/test/resources/script1.txt"); //$NON-NLS-1$
exec.execute("src/test/resources/script2.txt"); //$NON-NLS-1$
exec.execute("src/test/resources/script3.txt"); //$NON-NLS-1$
exec.execute("src/test/resources/script4.txt"); //$NON-NLS-1$
exec.execute("src/test/resources/script5.txt", "test"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (CommandRunException e) {
e.printStackTrace();
fail("execution of wellformed script should not fail"); //$NON-NLS-1$
}
try {
test.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
} }
/** Test method for {@link fr.bigeon.gclc.command.ScriptExecution#tip()}. */
@Test
public void testTip() {
ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$
Charset.forName("UTF-8"));
exec.tip();
}
/** Test method for
* {@link fr.bigeon.gclc.command.ScriptExecution#help(fr.bigeon.gclc.manager.ConsoleManager, String...)}. */
@Test
public void testHelp() {
ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$
Charset.forName("UTF-8"));
try (TestConsoleManager test = new TestConsoleManager()) {
exec.help(test);
exec.help(test, "ignored element");
} catch (IOException e) {
e.printStackTrace();
fail("unexpected error in help invocation"); //$NON-NLS-1$
}
}
} }

View File

@ -0,0 +1,390 @@
/*
* 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.command.SubedCommandTest.java
* Created on: Nov 18, 2016
*/
package fr.bigeon.gclc.command;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.ConsoleManager;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
/** <p>
* TODO
*
* @author Emmanuel Bigeon */
@SuppressWarnings("all")
public class SubedCommandTest {
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String)}. */
@Test
public final void testSubedCommandString() {
SubedCommand cmd = new SubedCommand("name");
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name with spaces");
assertNull(cmd.tip());
assertEquals("name with spaces", cmd.getCommandName());
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String, fr.bigeon.gclc.command.ICommand)}. */
@Test
public final void testSubedCommandStringICommand() {
SubedCommand cmd = new SubedCommand("name", new MockCommand(""));
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name with spaces", new MockCommand(""));
assertNull(cmd.tip());
assertEquals("name with spaces", cmd.getCommandName());
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String, fr.bigeon.gclc.command.ICommand, java.lang.String)}. */
@Test
public final void testSubedCommandStringICommandString() {
SubedCommand cmd = new SubedCommand("name", new MockCommand(""), "tip");
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name with spaces", new MockCommand(""), "tip");
assertEquals("name with spaces", cmd.getCommandName());
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String, java.lang.String)}. */
@Test
public final void testSubedCommandStringString() {
SubedCommand cmd = new SubedCommand("name", "tip");
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name with spaces", "tip");
assertEquals("name with spaces", cmd.getCommandName());
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#add(fr.bigeon.gclc.command.ICommand)}. */
@Test
public final void testAdd() {
SubedCommand cmd = new SubedCommand("name");
try {
cmd.add(new MockCommand("id"));
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try {
cmd.add(new MockCommand("id"));
fail("addition of command with already used id succeeded");
} catch (InvalidCommandName e) {
//
assertNotNull(e);
}
try {
cmd.add(new MockCommand(""));
fail("addition of command with invalid id succeeded");
} catch (InvalidCommandName e) {
//
assertNotNull(e);
}
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#execute(java.lang.String[])}. */
@Test
public final void testExecute() {
SubedCommand cmd = new SubedCommand("name");
MockCommand mock = new MockCommand("id");
try {
cmd.add(mock);
cmd.add(new Command("fail") {
@Override
public String tip() {
return null;
}
@Override
public void execute(String... args) throws CommandRunException {
throw new CommandRunException("Failing command", null);
}
});
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try {
cmd.execute("id");
} catch (CommandRunException e) {
fail("Unexpected exception when running mock command");
assertNotNull(e);
}
try {
cmd.execute("fail");
fail("Fail command error should be re thrown");
} catch (CommandRunException e) {
assertNotNull(e);
assertEquals(cmd, e.getSource());
}
try {
cmd.execute();
fail("Request for inexistent default command should fail");
} catch (CommandRunException e) {
assertNotNull(e);
assertEquals(cmd, e.getSource());
}
cmd = new SubedCommand("name", mock);
try {
cmd.add(mock);
cmd.add(new Command("fail") {
@Override
public String tip() {
return null;
}
@Override
public void execute(String... args) throws CommandRunException {
throw new CommandRunException("Failing command", this);
}
});
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try {
cmd.execute("id");
} catch (CommandRunException e) {
fail("Unexpected exception when running mock command");
assertNotNull(e);
}
try {
cmd.execute("fail");
fail("Fail command error should be re thrown");
} catch (CommandRunException e) {
assertNotNull(e);
assertEquals(cmd.get("fail"), e.getSource());
}
try {
cmd.execute();
} catch (CommandRunException e) {
fail("Request for default command should execute default command");
assertNotNull(e);
}
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#executeSub(java.lang.String, java.lang.String[])}. */
@Test
public final void testExecuteSub() {
SubedCommand cmd = new SubedCommand("name");
MockCommand mock = new MockCommand("id");
try {
cmd.add(mock);
cmd.add(new Command("fail") {
@Override
public String tip() {
return null;
}
@Override
public void execute(String... args) throws CommandRunException {
throw new CommandRunException("Failing command", this);
}
});
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try {
cmd.executeSub("id");
} catch (CommandRunException e) {
fail("Unexpected exception when running mock command");
assertNotNull(e);
}
try {
cmd.executeSub("fail");
fail("Fail command error should be re thrown");
} catch (CommandRunException e) {
assertNotNull(e);
assertEquals(cmd.get("fail"), e.getSource());
}
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#get(java.lang.String)}. */
@Test
public final void testGet() {
SubedCommand cmd = new SubedCommand("name");
assertNull(cmd.get("id"));
MockCommand mock = new MockCommand("id");
try {
cmd.add(mock);
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
assertEquals(mock, cmd.get("id"));
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#getCommandName()}. */
@Test
public final void testGetCommandName() {
SubedCommand cmd = new SubedCommand("name");
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name with spaces");
assertEquals("name with spaces", cmd.getCommandName());
cmd = new SubedCommand("name", "some tip");
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name", new MockCommand(""));
assertEquals("name", cmd.getCommandName());
cmd = new SubedCommand("name", new MockCommand(""), "some tip");
assertEquals("name", cmd.getCommandName());
}
/** Test method for
* {@link fr.bigeon.gclc.command.SubedCommand#help(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String[])}. */
@Test
public final void testHelp() {
SubedCommand cmd = new SubedCommand("name");
ICommand mock = new MockCommand("id");
try {
cmd.add(mock);
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try (TestConsoleManager manager = new TestConsoleManager();
TestConsoleManager manager2 = new TestConsoleManager()) {
cmd.help(manager);
assertEquals("\tid", manager.readNextLine());
cmd.help(manager, "id");
cmd.help(manager, "inexistent");
} catch (IOException e) {
fail("Unexpected exception when running help");
assertNotNull(e);
}
cmd = new SubedCommand("name", mock);
try {
cmd.add(mock);
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try (TestConsoleManager manager = new TestConsoleManager();
TestConsoleManager manager2 = new TestConsoleManager()) {
cmd.help(manager);
assertEquals("\tid", manager.readNextLine());
} catch (IOException e) {
fail("Unexpected exception when running help");
assertNotNull(e);
}
mock = new ICommand() {
@Override
public String tip() {
return "tip";
}
@Override
public void help(ConsoleManager manager,
String... args) throws IOException {
//
}
@Override
public String getCommandName() {
return "id";
}
@Override
public void execute(String... args) throws CommandRunException {
//
}
};
cmd = new SubedCommand("name", mock);
try {
cmd.add(mock);
} catch (InvalidCommandName e) {
fail("addition of command with valid id failed");
assertNotNull(e);
}
try (TestConsoleManager manager = new TestConsoleManager();
TestConsoleManager manager2 = new TestConsoleManager()) {
cmd.help(manager);
assertEquals("\ttip", manager.readNextLine());
assertEquals("\tid: tip", manager.readNextLine());
} catch (IOException e) {
fail("Unexpected exception when running help");
assertNotNull(e);
}
}
/** Test method for {@link fr.bigeon.gclc.command.SubedCommand#tip()}. */
@Test
public final void testTip() {
SubedCommand cmd = new SubedCommand("name");
assertNull(cmd.tip());
cmd = new SubedCommand("name with spaces", new MockCommand(""), "tip");
assertEquals("tip", cmd.tip());
}
}

View File

@ -0,0 +1,75 @@
/*
* 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.exception.CommandRunExceptionTest.java
* Created on: Nov 19, 2016
*/
package fr.bigeon.gclc.exception;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import fr.bigeon.gclc.command.ICommand;
import fr.bigeon.gclc.command.MockCommand;
/**
* <p>
* TODO
*
* @author Emmanuel Bigeon
*
*/
public class CommandRunExceptionTest {
/**
* Test method for {@link fr.bigeon.gclc.exception.CommandRunException#getLocalizedMessage()}.
*/
@Test
public final void testGetLocalizedMessage() {
CommandRunException e;
ICommand cmd = new MockCommand("name");
String messageInner = "inner";
String message = "message";
e = new CommandRunException(message,
new CommandRunException(messageInner, new MockCommand("name")), //$NON-NLS-1$
cmd);
assertEquals(message + ": " + messageInner, e.getLocalizedMessage());
e = new CommandRunException(message, cmd);
assertEquals(message, e.getLocalizedMessage());
}
}

View File

@ -0,0 +1,148 @@
/*
* 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.SystemConsoleManagerTest.java
* Created on: Nov 19, 2016
*/
package fr.bigeon.gclc.manager;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import org.junit.Test;
/** <p>
* TODO
*
* @author Emmanuel Bigeon */
public class SystemConsoleManagerTest {
/** Test method for
* {@link fr.bigeon.gclc.manager.SystemConsoleManager#prompt()}. */
@Test
public final void testPrompt() {
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());
th.join();
} catch (IOException | InterruptedException e) {
assertNull(e);
}
}
/** Test method for
* {@link fr.bigeon.gclc.manager.SystemConsoleManager#setPrompt(java.lang.String)}. */
@Test
public final void testSetPrompt() {
SystemConsoleManager manager = new SystemConsoleManager();
String prt = "++";
manager.setPrompt(prt);
assertEquals(prt, manager.getPrompt());
}
/** 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);
}
}
}

View File

@ -0,0 +1,67 @@
/*
* 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.prompt.CLIPrompterMessagesTest.java
* Created on: Nov 19, 2016
*/
package fr.bigeon.gclc.prompt;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* <p>
* TODO
*
* @author Emmanuel Bigeon
*
*/
public class CLIPrompterMessagesTest {
/**
* Test method for {@link fr.bigeon.gclc.prompt.CLIPrompterMessages#getString(java.lang.String, java.lang.Object[])}.
*/
@Test
public final void testGetString() {
String key = "bad.key";
assertEquals('!' + key + '!', CLIPrompterMessages.getString(key));
assertEquals('!' + key + '!',
CLIPrompterMessages.getString(key, "some arg"));
assertEquals('!' + key + '!',
CLIPrompterMessages.getString(key, new Object[] {}));
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,144 @@
/*
* 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.test.utils;
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.ByteBuffer;
import java.nio.charset.Charset;
import fr.bigeon.gclc.manager.ConsoleManager;
import fr.bigeon.gclc.manager.SystemConsoleManager;
/** 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 class TestConsoleManager implements ConsoleManager, AutoCloseable {
private final SystemConsoleManager innerManager;
private final PipedOutputStream commandInput;
private final BufferedReader commandBuffOutput;
private final PipedInputStream commandOutput;
private final PrintStream outPrint;
private final PipedInputStream in;
/** @throws IOException if the piping failed for streams */
public TestConsoleManager() throws IOException {
commandInput = new PipedOutputStream();
in = new PipedInputStream(commandInput);
commandOutput = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(commandOutput);
commandBuffOutput = new BufferedReader(
new InputStreamReader(commandOutput, Charset.defaultCharset()));
outPrint = new PrintStream(out);
innerManager = new SystemConsoleManager(outPrint, in,
Charset.forName("UTF-8"));
}
@Override
public String getPrompt() {
return innerManager.getPrompt();
}
@Override
public void print(String object) throws IOException {
innerManager.print(object);
}
@Override
public void println() throws IOException {
innerManager.println();
}
@Override
public void println(String object) throws IOException {
innerManager.println(object);
}
@Override
public String prompt() throws IOException {
return innerManager
.prompt(innerManager.getPrompt() + System.lineSeparator());
}
@Override
public String prompt(String message) throws IOException {
return innerManager.prompt(message + System.lineSeparator());
}
@Override
public void setPrompt(String prompt) {
innerManager.setPrompt(prompt);
}
@Override
public void close() throws IOException {
innerManager.close();
outPrint.close();
commandBuffOutput.close();
commandOutput.close();
in.close();
commandInput.close();
}
@Override
public boolean isClosed() {
return innerManager.isClosed();
}
public void type(String content) throws IOException {
ByteBuffer buff = Charset.defaultCharset()
.encode(content + System.lineSeparator());
if (buff.hasArray()) {
commandInput.write(buff.array());
}
}
public String readNextLine() throws IOException {
return commandBuffOutput.readLine();
}
}

View File

@ -0,0 +1,94 @@
/*
* 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.tools.PrintUtilsTest.java
* Created on: Nov 19, 2016
*/
package fr.bigeon.gclc.tools;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Test;
/** <p>
* TODO
*
* @author Emmanuel Bigeon */
public class PrintUtilsTest {
/** Test method for
* {@link fr.bigeon.gclc.tools.PrintUtils#print(java.lang.String, int, boolean)}. */
@Test
public final void testPrint() {
String text = "Some text";
String longText = text + " that may be abbreviated";
assertEquals(text, PrintUtils.print(text, text.length(), true));
assertEquals(text, PrintUtils.print(text, text.length(), false));
assertEquals(text + " ",
PrintUtils.print(text, text.length() + 3, false));
assertEquals(text + " ",
PrintUtils.print(text, text.length() + 3, true));
assertEquals(text, PrintUtils.print(longText, text.length(), false));
assertEquals(text + "...",
PrintUtils.print(longText, text.length() + 3, true));
}
/** Test method for
* {@link fr.bigeon.gclc.tools.PrintUtils#wrap(java.lang.String, int)}. */
@Test
public final void testWrap() {
String[] line = {"A text separated", "on several lines", "with cuts at",
"whitespace", "characters"};
String text = line[0] + " " + line[1] + " " + line[2] + " " + line[3] +
" " + line[4];
assertEquals(Arrays.asList(line),
PrintUtils.wrap(text, line[0].length() + 1));
assertEquals(Arrays.asList(line),
PrintUtils.wrap(text, line[0].length()));
// test with split word
line = new String[] {"A text separated", "on several lines", "",
"with cuts at", "whitespacecharac", "ters"};
text = line[0] + " " + line[1] + System.lineSeparator() + line[3] +
" " + line[4] + line[5];
assertEquals(Arrays.asList(line),
PrintUtils.wrap(text, line[0].length()));
assertEquals(Arrays.asList(""),
PrintUtils.wrap("", line[0].length()));
}
}

View File

@ -3,3 +3,5 @@ test
# and comments # and comments
long long
# interwined # interwined
# with empty line too

View File

@ -0,0 +1,2 @@
# a script invoking a failing command
failingCmd

View File

@ -0,0 +1,2 @@
# a script with invalid commands
invalid

View File

@ -0,0 +1,2 @@
# a script with invalid commands
test "po"m

View File

@ -0,0 +1,3 @@
# a script with space in begining
test
should never be reached