Compare commits

..

47 Commits

Author SHA1 Message Date
bd311d185e [maven-release-plugin] prepare release gclc-2.0.12 2018-11-25 12:00:41 -05:00
aa26173f26 Update port
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-11-25 11:37:07 -05:00
df688b1a85 Code factoring
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-11-25 11:31:52 -05:00
bcd0faceef Fixed runnable to allow acces to pending messages
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-11-25 11:22:37 -05:00
5e5cc2a1cd Added tests
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-11-25 11:05:06 -05:00
b24b72f3e2 Fixed console input
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-11-25 11:05:00 -05:00
ad79e3ccb6 Change to Supplier. Fix tests
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-11-25 09:16:38 -05:00
ddd818d93b Fix test
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-11-25 00:40:54 -05:00
6993513f38 Improve exception mechanics. remove closure of stream.
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-11-25 00:27:30 -05:00
b9a7142c5c Added comments
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-11-24 23:37:27 -05:00
85ef68f6ae Added error storing in the forwarding runnable. Added tests
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-11-24 21:07:28 -05:00
dfca63b179 [maven-release-plugin] prepare for next development iteration 2018-10-27 17:17:47 -04:00
787f951ff7 [maven-release-plugin] prepare release process-0.0.5 2018-10-27 17:17:44 -04:00
a364b6442b Added javadoc
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 17:16:15 -04:00
211b965e9e [maven-release-plugin] prepare for next development iteration 2018-10-27 16:39:13 -04:00
e1d030c6c5 [maven-release-plugin] prepare release swt-1.1.6 2018-10-27 16:39:10 -04:00
8bc2b13a92 [maven-release-plugin] prepare for next development iteration 2018-10-27 15:58:12 -04:00
c1050b1b4f [maven-release-plugin] prepare release socket-1.1.13 2018-10-27 15:58:09 -04:00
a3e4758d1b [maven-release-plugin] prepare for next development iteration 2018-10-27 14:54:06 -04:00
c436b5af2f [maven-release-plugin] prepare release process-0.0.4 2018-10-27 14:54:03 -04:00
3272261be1 [maven-release-plugin] prepare for next development iteration 2018-10-27 14:42:49 -04:00
f82f0b9f16 [maven-release-plugin] prepare release system-0.0.2 2018-10-27 14:42:41 -04:00
1fa9ca213e Fix process forwarding of
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 14:42:22 -04:00
265f90526a Update dependency versions
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 14:38:07 -04:00
71b325508f [maven-release-plugin] prepare for next development iteration 2018-10-27 14:27:47 -04:00
98857e425a [maven-release-plugin] prepare release gclc-2.0.11 2018-10-27 14:27:44 -04:00
8c6b1d8884 minor conventions
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 14:18:32 -04:00
2972e82f4a fix interlocks
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 14:17:19 -04:00
0ab39b24f6 Fix available message test
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 14:02:31 -04:00
171f79518d Made port public constant
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 14:02:21 -04:00
0e422a81ce Added equals
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 14:01:53 -04:00
ea4164fbfb Added tests
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 14:01:42 -04:00
e2f45c77d9 Comment
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 09:56:07 -04:00
55bb54ca43 Added tool methods for most common uses
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 09:50:28 -04:00
cf29eb37cc Move test thread in test runnable
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 09:40:56 -04:00
579e85dcb3 Update pom
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-27 09:40:42 -04:00
7e36a378c4 documentation
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-26 16:09:04 -04:00
80242c79e8 Added test of command on linux system
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-26 15:39:54 -04:00
ab9a4c474b Made method static
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-26 15:37:25 -04:00
b8e5ea0b78 Fix pom order
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-26 11:27:09 -04:00
2637d99bce Update pom
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-26 11:14:54 -04:00
cfd3450afe [maven-release-plugin] prepare for next development iteration 2018-10-26 11:12:48 -04:00
20d5a84269 [maven-release-plugin] prepare release socket-1.1.12 2018-10-26 11:12:46 -04:00
637cfb8f43 increment in separate statement. string construction
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-26 11:11:24 -04:00
d7fbdfb66b Fix pom order
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-26 11:10:17 -04:00
22741104f5 update depencies
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2018-10-26 10:16:38 -04:00
45c5375118 [maven-release-plugin] prepare for next development iteration 2018-10-26 10:11:30 -04:00
50 changed files with 1853 additions and 730 deletions

View File

@@ -1,38 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- process, Distribution repositories and basic setup for Emmanuel Bigeon
projects -->
<!-- Copyright (C) 2014-2018 E. Bigeon -->
<!-- mailto:emmanuel@bigeon.fr -->
<!-- -->
<!-- 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. -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>net.bigeon.config</groupId> <groupId>net.bigeon.config</groupId>
@@ -42,7 +8,7 @@
<groupId>net.bigeon.gclc</groupId> <groupId>net.bigeon.gclc</groupId>
<artifactId>process</artifactId> <artifactId>process</artifactId>
<version>0.0.4-SNAPSHOT</version> <version>0.0.6-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>process</name> <name>process</name>
@@ -83,11 +49,22 @@
<dependency> <dependency>
<groupId>net.bigeon</groupId> <groupId>net.bigeon</groupId>
<artifactId>gclc</artifactId> <artifactId>gclc</artifactId>
<version>2.0.9</version> <version>2.0.11</version>
</dependency>
<dependency>
<groupId>net.bigeon.test</groupId>
<artifactId>junitmt</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<reporting> <reporting>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version>
</plugin>
<plugin> <plugin>
<groupId>com.github.sevntu-checkstyle</groupId> <groupId>com.github.sevntu-checkstyle</groupId>
<artifactId>dsm-maven-plugin</artifactId> <artifactId>dsm-maven-plugin</artifactId>

View File

@@ -132,16 +132,23 @@ public class CommandForeground extends ParametrizedCommand {
protected void doExecute(final ConsoleOutput out, final ConsoleInput in, protected void doExecute(final ConsoleOutput out, final ConsoleInput in,
final CommandParameters parameters) throws CommandRunException { final CommandParameters parameters) throws CommandRunException {
String string = parameters.get("pid"); String string = parameters.get("pid");
final List<String> additionals = parameters.getAdditionals(); if (string == null) {
if (string == null && !additionals.isEmpty()) { final List<String> additionals = parameters.getAdditionals();
if (additionals.isEmpty()) {
throw new CommandRunException(CommandRunExceptionType.USAGE,
"Missing process id");
}
string = additionals.get(0); string = additionals.get(0);
} }
if (string == null) { Integer pid;
try {
pid = Integer.valueOf(string);
} catch (final NumberFormatException e) {
throw new CommandRunException(CommandRunExceptionType.USAGE, throw new CommandRunException(CommandRunExceptionType.USAGE,
"Missing process id"); "PID should be an integer");
} }
// Join the command. // Join the command.
final Task cmd = pool.get(string); final Task cmd = pool.get(pid);
if (!(cmd instanceof ForkTask)) { if (!(cmd instanceof ForkTask)) {
throw new CommandRunException("No such forked process"); throw new CommandRunException("No such forked process");
} }
@@ -151,7 +158,8 @@ public class CommandForeground extends ParametrizedCommand {
delai = Long.parseLong(delaiOpt) * MILLIS_IN_A_SEC; delai = Long.parseLong(delaiOpt) * MILLIS_IN_A_SEC;
} }
if (delai < 0) { if (delai < 0) {
throw new CommandRunException("Join delai cannot be negative"); throw new CommandRunException(CommandRunExceptionType.USAGE,
"Join delai cannot be negative");
} }
((ForkTask) cmd).join(out, in, delai); ((ForkTask) cmd).join(out, in, delai);
} }

View File

@@ -4,6 +4,7 @@
*/ */
package net.bigeon.gclc.process; package net.bigeon.gclc.process;
import java.text.MessageFormat;
/*- /*-
* #%L * #%L
* process * process
@@ -43,6 +44,7 @@ import net.bigeon.gclc.command.Command;
import net.bigeon.gclc.command.ICommand; import net.bigeon.gclc.command.ICommand;
import net.bigeon.gclc.command.ICommandProvider; import net.bigeon.gclc.command.ICommandProvider;
import net.bigeon.gclc.exception.CommandRunException; import net.bigeon.gclc.exception.CommandRunException;
import net.bigeon.gclc.exception.CommandRunExceptionType;
import net.bigeon.gclc.manager.ConsoleInput; import net.bigeon.gclc.manager.ConsoleInput;
import net.bigeon.gclc.manager.ConsoleOutput; import net.bigeon.gclc.manager.ConsoleOutput;
@@ -95,12 +97,18 @@ public class CommandFork extends Command {
public void execute(final ConsoleOutput out, final ConsoleInput in, public void execute(final ConsoleOutput out, final ConsoleInput in,
final String... args) throws CommandRunException { final String... args) throws CommandRunException {
if (args.length < 1) { if (args.length < 1) {
throw new CommandRunException("No command to fork"); throw new CommandRunException(CommandRunExceptionType.USAGE,
"No command to fork");
}
final String string = args[0];
final ICommand cmd = provider.get(string);
if (cmd == null) {
throw new CommandRunException(CommandRunExceptionType.USAGE,
MessageFormat.format("No such command {0}", string));
} }
final ICommand cmd = provider.get(args[0]);
final String[] inner = Arrays.copyOfRange(args, 1, args.length); final String[] inner = Arrays.copyOfRange(args, 1, args.length);
final ForkTask task = new ForkCommandTask(cmd, inner, lines); final ForkTask task = new ForkCommandTask(cmd, inner, lines);
final Thread th = new Thread(task); final Thread th = new Thread(task, MessageFormat.format("fork [{0}]", string));
pool.add(task); pool.add(task);
th.start(); th.start();
} }

View File

@@ -85,7 +85,9 @@ public abstract class ForkTask implements Task {
/** THe listeners. */ /** THe listeners. */
private final Set<InterruptionListener> listeners = new HashSet<>(); private final Set<InterruptionListener> listeners = new HashSet<>();
/** The running state. */ /** The running state. */
private boolean running = false; private boolean running = true;
/** The running state. */
private boolean started = false;
/** The connecting input for this task */ /** The connecting input for this task */
protected final ConnectingConsoleInput in = new ConnectingConsoleInput(); protected final ConnectingConsoleInput in = new ConnectingConsoleInput();
/** The connecting output for this task */ /** The connecting output for this task */
@@ -169,7 +171,7 @@ public abstract class ForkTask implements Task {
@Override @Override
public final void run() { public final void run() {
synchronized (runLock) { synchronized (runLock) {
running = true; started = true;
} }
try { try {
doRun(); doRun();
@@ -192,4 +194,11 @@ public abstract class ForkTask implements Task {
runLock.notifyAll(); runLock.notifyAll();
} }
} }
/** @return the started */
public boolean isStarted() {
synchronized (runLock) {
return started;
}
}
} }

View File

@@ -92,7 +92,7 @@ public final class ProcessClear extends Command {
@Override @Override
public void execute(final ConsoleOutput out, final ConsoleInput in, public void execute(final ConsoleOutput out, final ConsoleInput in,
final String... args) { final String... args) {
for (final String id : pool.getPIDs()) { for (final Integer id : pool.getPIDs()) {
if (!pool.get(id).isRunning()) { if (!pool.get(id).isRunning()) {
pool.remove(id); pool.remove(id);
} }
@@ -103,14 +103,15 @@ public final class ProcessClear extends Command {
* @see fr.bigeon.gclc.command.ICommand#tip() */ * @see fr.bigeon.gclc.command.ICommand#tip() */
@Override @Override
public String tip() { public String tip() {
return "Request a process to stop (softly)"; return "Remove non running processes from pool";
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail() */ * @see fr.bigeon.gclc.command.Command#usageDetail() */
@Override @Override
protected String usageDetail() { protected String usageDetail() {
return null; return " All processes in the pool have their running status checked and the "
+ "non running ones are removed from the list of tasks.";
} }
} }

View File

@@ -69,6 +69,8 @@ package net.bigeon.gclc.process;
* #L% * #L%
*/ */
import net.bigeon.gclc.command.Command; import net.bigeon.gclc.command.Command;
import net.bigeon.gclc.exception.CommandRunException;
import net.bigeon.gclc.exception.CommandRunExceptionType;
import net.bigeon.gclc.manager.ConsoleInput; import net.bigeon.gclc.manager.ConsoleInput;
import net.bigeon.gclc.manager.ConsoleOutput; import net.bigeon.gclc.manager.ConsoleOutput;
@@ -91,8 +93,12 @@ public final class ProcessKill extends Command {
* ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, java.lang.String[]) */ * ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, java.lang.String[]) */
@Override @Override
public void execute(final ConsoleOutput out, final ConsoleInput in, public void execute(final ConsoleOutput out, final ConsoleInput in,
final String... args) { final String... args) throws CommandRunException {
pool.get(args[0]).setRunning(false); if (args.length < 1) {
throw new CommandRunException(CommandRunExceptionType.USAGE,
"A pid should be specified.");
}
pool.get(Integer.parseInt(args[0])).setRunning(false);
} }
/* (non-Javadoc) /* (non-Javadoc)
@@ -106,7 +112,13 @@ public final class ProcessKill extends Command {
* @see fr.bigeon.gclc.command.Command#usageDetail() */ * @see fr.bigeon.gclc.command.Command#usageDetail() */
@Override @Override
protected String usageDetail() { protected String usageDetail() {
return null; return " <pid> is the identification of the process to request the stop to in the pool";
} }
/* (non-Javadoc)
* @see net.bigeon.gclc.command.Command#usagePattern() */
@Override
protected String usagePattern() {
return super.usagePattern() + " <pid>";
}
} }

View File

@@ -99,9 +99,9 @@ public final class ProcessList extends Command {
@Override @Override
public void execute(final ConsoleOutput out, final ConsoleInput in, public void execute(final ConsoleOutput out, final ConsoleInput in,
final String... args) throws CommandRunException { final String... args) throws CommandRunException {
final ArrayList<String> pids = new ArrayList<>(pool.getPIDs()); final ArrayList<Integer> pids = new ArrayList<>(pool.getPIDs());
Collections.sort(pids); Collections.sort(pids);
for (final String string : pids) { for (final Integer string : pids) {
try { try {
out.println(MessageFormat.format("{0}\t{1}", string, //$NON-NLS-1$ out.println(MessageFormat.format("{0}\t{1}", string, //$NON-NLS-1$
pool.get(string).getName())); pool.get(string).getName()));
@@ -124,7 +124,7 @@ public final class ProcessList extends Command {
* @see fr.bigeon.gclc.command.Command#usageDetail() */ * @see fr.bigeon.gclc.command.Command#usageDetail() */
@Override @Override
protected String usageDetail() { protected String usageDetail() {
return null; return " No argument is considered by this command";
} }
} }

View File

@@ -78,7 +78,7 @@ import java.util.Map;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class TaskPool { public final class TaskPool {
/** The running processes. */ /** The running processes. */
private final Map<String, Task> running = new HashMap<>(); private final Map<Integer, Task> running = new HashMap<>();
/** The count for process id. */ /** The count for process id. */
private int count = 0; private int count = 0;
/** The lock for pid attribution synchronization. */ /** The lock for pid attribution synchronization. */
@@ -99,11 +99,11 @@ public final class TaskPool {
* *
* @param cmd the process * @param cmd the process
* @return the pid */ * @return the pid */
public String add(final Task cmd) { public int add(final Task cmd) {
if (cmd == null) { if (cmd == null) {
throw new IllegalArgumentException("Task cannot be null"); //$NON-NLS-1$ throw new IllegalArgumentException("Task cannot be null"); //$NON-NLS-1$
} }
final String pid; final int pid;
synchronized (lock) { synchronized (lock) {
pid = getPID(); pid = getPID();
running.put(pid, cmd); running.put(pid, cmd);
@@ -124,21 +124,21 @@ public final class TaskPool {
* *
* @param pid the task id * @param pid the task id
* @return the task, if any, associated to this id */ * @return the task, if any, associated to this id */
public Task get(final String pid) { public Task get(final int pid) {
synchronized (lock) { synchronized (lock) {
return running.get(pid); return running.get(Integer.valueOf(pid));
} }
} }
/** Get the next process id. /** Get the next process id.
* *
* @return the process id */ * @return the process id */
private String getPID() { private int getPID() {
synchronized (lock) { synchronized (lock) {
String pid; int pid;
do { do {
pid = Integer.toString(count++); pid = count++;
} while (running.containsKey(pid)); } while (running.containsKey(Integer.valueOf(pid)));
return pid; return pid;
} }
} }
@@ -146,7 +146,7 @@ public final class TaskPool {
/** Get the running processes' identifiers. /** Get the running processes' identifiers.
* *
* @return the pids */ * @return the pids */
public Collection<String> getPIDs() { public Collection<Integer> getPIDs() {
return new HashSet<>(running.keySet()); return new HashSet<>(running.keySet());
} }
@@ -158,10 +158,10 @@ public final class TaskPool {
/** Remove a task from the pool /** Remove a task from the pool
* *
* @param pid the task id */ * @param pid the task id */
public void remove(final String pid) { public void remove(final int pid) {
synchronized (lock) { synchronized (lock) {
running.remove(pid); running.remove(Integer.valueOf(pid));
count = Math.min(count, Integer.parseInt(pid)); count = Math.min(count, (pid));
} }
} }

View File

@@ -68,7 +68,6 @@ package net.bigeon.gclc.process.io;
* #L% * #L%
*/ */
import java.io.IOException; import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import net.bigeon.gclc.manager.ConsoleInput; import net.bigeon.gclc.manager.ConsoleInput;
@@ -90,15 +89,21 @@ public final class ConnectingConsoleInput implements ConsoleInput {
private boolean close = false; private boolean close = false;
/** The prompt string. */ /** The prompt string. */
private StringProvider prompt = EMPTY_STRING; private StringProvider prompt = EMPTY_STRING;
/** If the input is currently in prompting state. */ /** If the input is currently in prompting state.
* <p>
* To change it you should be in a promptLock. */
private boolean prompting = false; private boolean prompting = false;
/** The synchronization lock for the rompting status. */ /** The synchronization lock for the prompting status. */
private final Object promptLock = new Object(); private final Object promptLock = new Object();
/** The synchronization lock for the connection status. */ /** The synchronization lock for the connection status. */
private final Object connectionLock = new Object(); private final Object connectionLock = new Object();
/** The connected console input. */ /** The connected console input.
* <p>
* To use it, you should be in a promptLock and connectionLock. */
private ConsoleInput connected = null; private ConsoleInput connected = null;
/** The connection state. */ /** The connection state.
* <p>
* To read or modify it, you should be in a connectionLock synchronize block. */
private boolean disconnection = false; private boolean disconnection = false;
/* (non-Javadoc) /* (non-Javadoc)
@@ -114,20 +119,23 @@ public final class ConnectingConsoleInput implements ConsoleInput {
public void connect(final ConsoleInput input) { public void connect(final ConsoleInput input) {
disconnect(); disconnect();
synchronized (promptLock) { synchronized (promptLock) {
connected = input;
promptLock.notifyAll(); promptLock.notifyAll();
synchronized (connectionLock) {
connected = input;
connectionLock.notifyAll();
}
} }
} }
/** Disconnect the current input. */ /** Disconnect the current input. */
public void disconnect() { public void disconnect() {
synchronized (connectionLock) { synchronized (connectionLock) {
if (connected != null) { synchronized (promptLock) {
disconnection = true; if (connected != null) {
synchronized (promptLock) { disconnection = true;
connected.interruptPrompt(); connected.interruptPrompt();
connected = null;
} }
connected = null;
} }
} }
} }
@@ -143,12 +151,15 @@ public final class ConnectingConsoleInput implements ConsoleInput {
* @see fr.bigeon.gclc.manager.ConsoleInput#interruptPrompt() */ * @see fr.bigeon.gclc.manager.ConsoleInput#interruptPrompt() */
@Override @Override
public void interruptPrompt() { public void interruptPrompt() {
synchronized (promptLock) { synchronized (connectionLock) {
prompting = false; synchronized (promptLock) {
if (connected != null) { connectionLock.notifyAll();
connected.interruptPrompt(); if (connected != null) {
connected.interruptPrompt();
}
prompting = false;
promptLock.notifyAll();
} }
promptLock.notifyAll();
} }
} }
@@ -185,23 +196,23 @@ public final class ConnectingConsoleInput implements ConsoleInput {
if (!prompting) { if (!prompting) {
return null; return null;
} }
if (connected == null) { }
try { getConnection(0);
promptLock.wait(); boolean connect;
} catch (final InterruptedException e) { ConsoleInput actualConnected;
LOGGER.log(Level.WARNING, "Inerruption of console thread", e); synchronized (connectionLock) {
Thread.currentThread().interrupt(); connect = connected != null;
} actualConnected = connected;
} else { }
final String res = connected.prompt(message); if (connect) {
synchronized (connectionLock) { final String res = actualConnected.prompt(message);
if (disconnection) { synchronized (promptLock) {
disconnection = false; if (disconnection) {
} else if (prompting) { disconnection = false;
return res; } else if (prompting) {
} else { return res;
// prompt interrupted, lose the result. } else {
} // prompt interrupted, lose the result.
} }
} }
} }
@@ -219,32 +230,48 @@ public final class ConnectingConsoleInput implements ConsoleInput {
synchronized (promptLock) { synchronized (promptLock) {
prompting = true; prompting = true;
} }
while (true) { do {
synchronized (promptLock) { synchronized (promptLock) {
if (!prompting) { if (!prompting) {
return null; break;
} }
if (connected == null) { }
try { getConnection(timeout);
promptLock.wait(); boolean connect;
} catch (final InterruptedException e) { ConsoleInput actualConnected;
LOGGER.log(Level.WARNING, "Inerruption of console thread", e); synchronized (connectionLock) {
Thread.currentThread().interrupt(); connect = connected != null;
} actualConnected = connected;
} else { }
final String res = connected.prompt(message, if (connect) {
synchronized (promptLock) {
final String res = actualConnected.prompt(message,
end - System.currentTimeMillis()); end - System.currentTimeMillis());
synchronized (connectionLock) { if (disconnection) {
if (disconnection) { disconnection = false;
disconnection = false; } else if (prompting) {
} else if (prompting) { return res;
return res; } else {
} else { // prompt interrupted, lose the result.
// prompt interrupted, lose the result.
}
} }
} }
} }
} while (System.currentTimeMillis() < end);
return null;
}
private void getConnection(final long timeout) {
boolean connect;
synchronized (connectionLock) {
connect = connected != null;
if (!connect) {
try {
connectionLock.wait(timeout);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} }
} }
@@ -252,12 +279,7 @@ public final class ConnectingConsoleInput implements ConsoleInput {
* @see fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String) */ * @see fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String) */
@Override @Override
public void setPrompt(final String prompt) { public void setPrompt(final String prompt) {
this.prompt = new StringProvider() { this.prompt = new ConstantString(prompt);
@Override
public String apply() {
return prompt;
}
};
} }
/* (non-Javadoc) /* (non-Javadoc)

View File

@@ -0,0 +1,90 @@
/**
*
*/
package net.bigeon.gclc.process;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.junit.Test;
import net.bigeon.gclc.exception.CommandRunException;
import net.bigeon.gclc.exception.CommandRunExceptionType;
import net.bigeon.gclc.process.mocks.ForkTaskMock;
/**
* @author Emmanuel Bigeon
*
*/
public class CommandForegroundTest {
/**
* Test method for {@link net.bigeon.gclc.process.CommandForeground#CommandForeground(java.lang.String, net.bigeon.gclc.process.TaskPool)}.
*/
@Test
public void testCommandForeground() {
final CommandForeground pl = new CommandForeground("fg", new TaskPool());
assertEquals("Command name should be kept as specified", "fg",
pl.getCommandName());
}
/** Test method for
* {@link net.bigeon.gclc.process.CommandForeground#doExecute(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, net.bigeon.gclc.command.CommandParameters)}.
*
* @throws CommandRunException if a valid command failed */
@Test
public void testDoExecuteConsoleOutputConsoleInputCommandParameters()
throws CommandRunException {
final TaskPool pool = new TaskPool(false);
final CommandForeground pl = new CommandForeground("fg", pool);
try {
pl.execute(null, null, "-delai", "1");
fail("PID should be mandatory");
} catch (final CommandRunException e) {
assertEquals("No pid specified is a usage error",
CommandRunExceptionType.USAGE, e.getType());
}
try {
pl.execute(null, null, "-pid", "invalid", "-delai", "1");
fail("PID should be a number");
} catch (final CommandRunException e) {
assertEquals("Invalid pid specified is a usage error",
CommandRunExceptionType.USAGE, e.getType());
}
try {
pl.execute(null, null, "-pid", "2", "-delai", "1");
fail("PID should exist");
} catch (final CommandRunException e) {
assertEquals("Inexistent pid specified is a run error",
CommandRunExceptionType.EXECUTION, e.getType());
}
final ForkTaskMock cmd = new ForkTaskMock();
final int id = pool.add(cmd);
pl.execute(null, null, "-pid", Integer.toString(id), "-delai", "1");
try {
pl.execute(null, null, "-pid", Integer.toString(id), "-delai", "-1");
fail("delai should be a posistive number");
} catch (final CommandRunException e) {
assertEquals("Negative delai specified is a usage error",
CommandRunExceptionType.USAGE, e.getType());
}
assert cmd.getRunCall() == 0;
}
/**
* Test method for {@link net.bigeon.gclc.process.CommandForeground#tip()}.
*/
@Test
public void testTip() {
final CommandForeground pl = new CommandForeground("fg", new TaskPool());
assertNotNull("Command tip should be defined", pl.tip());
assertNotNull("Command usage should be defined", pl.usagePattern());
assertNotNull("Command usage should be defined", pl.usageDetail());
}
}

View File

@@ -0,0 +1,86 @@
/**
*
*/
package net.bigeon.gclc.process;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.junit.Test;
import net.bigeon.gclc.command.ICommandProvider;
import net.bigeon.gclc.command.SubedCommand;
import net.bigeon.gclc.exception.CommandRunException;
import net.bigeon.gclc.exception.CommandRunExceptionType;
import net.bigeon.gclc.exception.InvalidCommandName;
import net.bigeon.gclc.process.mocks.CommandMock;
/**
* @author Emmanuel Bigeon
*
*/
public class CommandForkTest {
/**
* Test method for {@link net.bigeon.gclc.process.CommandFork#CommandFork(java.lang.String, net.bigeon.gclc.command.ICommandProvider, net.bigeon.gclc.process.TaskPool)}.
*/
@Test
public void testCommandForkStringICommandProviderTaskPool() {
final TaskPool pool = new TaskPool();
final ICommandProvider provider = new SubedCommand("test");
final CommandFork pl = new CommandFork("fork", provider, pool);
assertEquals("Command name should be preserved", "fork", pl.getCommandName());
}
/** Test method for
* {@link net.bigeon.gclc.process.CommandFork#execute(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, java.lang.String[])}.
*
* @throws InvalidCommandName if the test init failed
* @throws CommandRunException if the command execution failed in the test */
@Test
public void testExecute() throws InvalidCommandName, CommandRunException {
final TaskPool pool = new TaskPool(false);
final ICommandProvider provider = new SubedCommand("test");
final CommandFork pl = new CommandFork("fork", provider, pool);
try {
pl.execute(null, null);
fail("No command specified should through an exception");
} catch (final CommandRunException e) {
assertEquals("No command specified is a usage error",
CommandRunExceptionType.USAGE, e.getType());
}
try {
pl.execute(null, null, "invalid");
fail("Invalid command specified should through an exception");
} catch (final CommandRunException e) {
assertEquals("Invalid command specified is a usage error",
CommandRunExceptionType.USAGE, e.getType());
}
final CommandMock mock = new CommandMock();
provider.add(mock);
pl.execute(null, null, mock.getCommandName());
final ForkTask task = (ForkTask) pool.get(pool.getPIDs().iterator().next());
task.join(null, null, 1000);
assertEquals("Command should be executed when forked", 1, mock.getExecuteCall());
}
/**
* Test method for {@link net.bigeon.gclc.process.CommandFork#tip()}.
*/
@Test
public void testTip() {
final TaskPool pool = new TaskPool();
final ICommandProvider provider = new SubedCommand("test");
final CommandFork pl = new CommandFork("fork", provider, pool);
assertNotNull("Command tip should be defined", pl.tip());
assertNotNull("Command usage should be defined", pl.usagePattern());
assertNotNull("Command usage should be defined", pl.usageDetail());
}
}

View File

@@ -0,0 +1,35 @@
/**
*
*/
package net.bigeon.gclc.process;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import net.bigeon.gclc.process.mocks.CommandMock;
/**
* @author Emmanuel Bigeon
*
*/
public class ForkCommandTaskTest {
/** Test method for
* {@link net.bigeon.gclc.process.ForkCommandTask#ForkCommandTask(net.bigeon.gclc.command.ICommand, java.lang.String[], int)}.
*
* @throws InterruptedException if there is an error in the thread join */
@Test
public void testForkCommandTask() throws InterruptedException {
final CommandMock cmd = new CommandMock();
final ForkCommandTask task = new ForkCommandTask(cmd, new String[0], 1);
final Thread th = new Thread(task);
th.start();
th.join();
assertEquals("Task should be executed once", 1, cmd.getExecuteCall());
assertEquals("Names should be consistent between task and command",
cmd.getCommandName(), task.getName());
}
}

View File

@@ -0,0 +1,62 @@
/**
*
*/
package net.bigeon.gclc.process;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.io.IOException;
import org.junit.Test;
import net.bigeon.gclc.exception.CommandRunException;
import net.bigeon.gclc.exception.CommandRunExceptionType;
import net.bigeon.gclc.utils.PipedConsoleInput;
import net.bigeon.gclc.utils.PipedConsoleOutput;
/** @author Emmanuel Bigeon */
public class ForkTaskTest {
@Test
public void testGenericForkTask() throws IOException {
final ForkTask task = new ForkTask(5) {
@Override
public String getName() {
return "name";
}
@Override
protected void doRun() throws CommandRunException {
String msg;
try {
msg = in.prompt();
} catch (final IOException e) {
throw new CommandRunException(CommandRunExceptionType.INTERACTION,
"Unable to prompt user");
}
if ("ok".equals(msg)) {
out.println("Message");
} else {
out.println("fail");
}
}
};
final Thread execThread = new Thread(task);
execThread.start();
try (PipedConsoleOutput pco = new PipedConsoleOutput();
PipedConsoleInput pci = new PipedConsoleInput(null)) {
pci.type("ok");
while (!pco.available()) {
task.join(pco, pci, 1000);
}
assertEquals("Execution should work", "Message", pco.readNextLine());
}
assertFalse("Running state should be updated by task on its completion",
task.isRunning());
}
}

View File

@@ -0,0 +1,34 @@
/**
*
*/
package net.bigeon.gclc.process;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import net.bigeon.gclc.command.SubedCommand;
import net.bigeon.gclc.exception.InvalidCommandName;
/**
* @author Emmanuel Bigeon
*
*/
public class ProcessAttachementTest {
/** Test method for
* {@link net.bigeon.gclc.process.ProcessAttachement#attach(net.bigeon.gclc.command.ICommandProvider)}.
*
* @throws InvalidCommandName if the command has already some subcommand that is
* incompatible */
@Test
public void testAttach() throws InvalidCommandName {
final TaskPool pool = new TaskPool();
final ProcessAttachement attachement = new ProcessAttachement(pool);
final SubedCommand testPoint = new SubedCommand("test");
attachement.attach(testPoint);
assertNotNull("Commands should be added", testPoint.get("kill"));
assertNotNull("Commands should be added", testPoint.get("list"));
}
}

View File

@@ -0,0 +1,53 @@
/**
*
*/
package net.bigeon.gclc.process;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import net.bigeon.gclc.process.mocks.TaskMock;
/**
* @author Emmanuel Bigeon
*
*/
public class ProcessClearTest {
/**
* Test method for {@link net.bigeon.gclc.process.ProcessClear#ProcessClear(java.lang.String, net.bigeon.gclc.process.TaskPool)}.
*/
@Test
public void testProcessClear() {
final ProcessClear pl = new ProcessClear("clear", new TaskPool());
assertEquals("Command name should be kept as specified", "clear",
pl.getCommandName());
}
/**
* Test method for {@link net.bigeon.gclc.process.ProcessClear#execute(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, java.lang.String[])}.
*/
@Test
public void testExecute() {
final TaskPool pool = new TaskPool();
final TaskMock task = new TaskMock();
pool.add(task);
final ProcessClear pl = new ProcessClear("clear", pool);
pl.execute(null, null);
assertTrue("cleared pool should be empty", pool.getPIDs().isEmpty());
}
/**
* Test method for {@link net.bigeon.gclc.process.ProcessClear#tip()}.
*/
@Test
public void testTip() {
final ProcessClear pl = new ProcessClear("clear", new TaskPool());
assertNotNull("Command tip should be defined", pl.tip());
assertNotNull("Command usage should be defined", pl.usageDetail());
}
}

View File

@@ -0,0 +1,62 @@
/**
*
*/
package net.bigeon.gclc.process;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.junit.Test;
import net.bigeon.gclc.exception.CommandRunException;
import net.bigeon.gclc.exception.CommandRunExceptionType;
import net.bigeon.gclc.process.mocks.TaskMock;
/** @author Emmanuel Bigeon */
public class ProcessKillTest {
/** Test method for
* {@link net.bigeon.gclc.process.ProcessKill#ProcessKill(java.lang.String, net.bigeon.gclc.process.TaskPool)}. */
@Test
public void testProcessKill() {
final ProcessList pl = new ProcessList("kill", new TaskPool());
assertEquals("Command name should be kept as specified", "kill",
pl.getCommandName());
}
/** Test method for
* {@link net.bigeon.gclc.process.ProcessKill#execute(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, java.lang.String[])}.
*
* @throws CommandRunException if an error occured in test */
@Test
public void testExecute() throws CommandRunException {
final TaskPool pool = new TaskPool();
final TaskMock task = new TaskMock();
final int id = pool.add(task);
final ProcessKill pl = new ProcessKill("kill", pool);
task.reset();
try {
pl.execute(null, null);
fail("Execution with no pid should raise exception");
} catch (final CommandRunException e) {
assertEquals("Usage exception expected", CommandRunExceptionType.USAGE,
e.getType());
}
pl.execute(null, null, Integer.toString(id));
assertEquals("Task should be shutdown", 1, task.getNumberSetRunning());
task.reset();
pl.execute(null, null, Integer.toString(id));
assertEquals("Task should be shutdown", 1, task.getNumberSetRunning());
}
/** Test method for {@link net.bigeon.gclc.process.ProcessKill#tip()}. */
@Test
public void testTip() {
final ProcessKill pl = new ProcessKill("kill", new TaskPool());
assertNotNull("Command tip should be defined", pl.tip());
assertNotNull("Command usage should be defined", pl.usagePattern());
assertNotNull("Command usage should be defined", pl.usageDetail());
}
}

View File

@@ -0,0 +1,67 @@
/**
*
*/
package net.bigeon.gclc.process;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.junit.Test;
import net.bigeon.gclc.exception.CommandRunException;
import net.bigeon.gclc.exception.CommandRunExceptionType;
import net.bigeon.gclc.process.mocks.TaskMock;
import net.bigeon.gclc.utils.PipedConsoleOutput;
/** @author Emmanuel Bigeon */
public class ProcessListTest {
/** Test method for
* {@link net.bigeon.gclc.process.ProcessList#ProcessList(java.lang.String, net.bigeon.gclc.process.TaskPool)}. */
@Test
public void testProcessList() {
final ProcessList pl = new ProcessList("list", new TaskPool());
assertEquals("Command name should be kept as specified", "list",
pl.getCommandName());
}
/** Test method for
* {@link net.bigeon.gclc.process.ProcessList#execute(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, java.lang.String[])}.
*
* @throws CommandRunException if an error occured
* @throws IOException if an error in initialization of console occured */
@Test
public void testExecute() throws CommandRunException, IOException {
final TaskPool pool = new TaskPool();
final TaskMock task = new TaskMock();
pool.add(task);
final ProcessList pl = new ProcessList("list", pool);
final PipedConsoleOutput out = new PipedConsoleOutput();
pl.execute(out, null);
assertTrue("Task should be contained in list",
out.readNextLine().contains(task.getName()));
out.close();
try {
pl.execute(out, null);
fail("Printing element to closed console should raise interaction exception");
} catch (final CommandRunException e) {
assertEquals("Console printing error should be an interaction error",
CommandRunExceptionType.INTERACTION, e.getType());
}
}
/** Test method for {@link net.bigeon.gclc.process.ProcessList#tip()}. */
@Test
public void testTip() {
final ProcessList pl = new ProcessList("list", new TaskPool());
assertNotNull("Command tip should be defined", pl.tip());
assertNotNull("Command usage should be defined", pl.usageDetail());
}
}

View File

@@ -0,0 +1,33 @@
/**
*
*/
package net.bigeon.gclc.process;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import net.bigeon.gclc.command.SubedCommand;
import net.bigeon.gclc.exception.InvalidCommandName;
/** @author Emmanuel Bigeon */
public class ScreenAttachementTest {
/** Test method for
* {@link net.bigeon.gclc.process.ScreenAttachement#attach(net.bigeon.gclc.command.ICommandProvider)}.
*
* @throws InvalidCommandName if an error occured in attachement */
@Test
public void testAttach() throws InvalidCommandName {
final TaskPool pool = new TaskPool();
final ScreenAttachement attachement = new ScreenAttachement(pool, 15);
final SubedCommand testPoint = new SubedCommand("test");
attachement.attach(testPoint);
assertNotNull("Commands should be added", testPoint.get("terminate"));
assertNotNull("Commands should be added", testPoint.get("list"));
assertNotNull("Commands should be added", testPoint.get("clear"));
assertNotNull("Commands should be added", testPoint.get("fg"));
assertNotNull("Commands should be added", testPoint.get("fork"));
}
}

View File

@@ -0,0 +1,77 @@
package net.bigeon.gclc.process;
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 org.junit.Test;
import net.bigeon.gclc.process.mocks.TaskMock;
public class TaskPoolTest {
public TaskMock task = new TaskMock();
public TaskPool pool = new TaskPool(false);
@Test
public void testTaskPool() {
assertFalse("task pool should not auto clear if specified",
pool.isAutoClearing());
pool = new TaskPool();
assertTrue("Default task pool should not auto clear", pool.isAutoClearing());
}
@Test
public void testAdd() {
final int id = pool.add(task);
assertTrue("Added task pid should be in pool", pool.getPIDs().contains(id));
assertEquals("Added task should be in pool", task, pool.get(id));
}
@Test
public void testGet() {
assertNull("Inexistent task id should provide null as task in pool",
pool.get(60));
final int id = pool.add(task);
assertEquals("Added task should be in pool at its id", task, pool.get(id));
assertNull("Added task should be in pool at its id", pool.get(id + 1));
}
@Test
public void testGetPIDs() {
assertTrue("new pool should be empty", pool.getPIDs().isEmpty());
final int id = pool.add(task);
assertNull("Added task should be in pool at its id", pool.get(id + 1));
assertEquals(
"Pool task addition should change the pid collection size accordingly", 1,
pool.getPIDs().size());
}
@Test
public void testRemove() {
assertTrue("new pool should be empty", pool.getPIDs().isEmpty());
pool.remove(60);
assertTrue("removal of inexistent task should be NOP", pool.getPIDs().isEmpty());
final int id = pool.add(task);
assertEquals(
"Pool task addition should change the pid collection size accordingly", 1,
pool.getPIDs().size());
pool.remove(id + 1);
assertEquals("removal of inexistent task should be NOP", 1,
pool.getPIDs().size());
pool.remove(id);
assertTrue("removal of task should reduce the number of tasks",
pool.getPIDs().isEmpty());
}
@Test
public void testShutdown() {
final int id = pool.add(task);
task.reset();
pool.shutdown();
assertEquals("Shutdown should request shut down of tasks, only once", 1,
task.getNumberSetRunning());
}
}

View File

@@ -0,0 +1,80 @@
/**
*
*/
package net.bigeon.gclc.process;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Test;
import net.bigeon.gclc.exception.CommandRunException;
import net.bigeon.gclc.manager.ConsoleInput;
import net.bigeon.gclc.manager.ConsoleOutput;
/** @author Emmanuel Bigeon */
public class TaskSpawnerTest {
/** Test method for
* {@link net.bigeon.gclc.process.TaskSpawner#execute(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, java.lang.String[])}.
*
* @throws CommandRunException if an error occurred */
@Test
public void testExecute() throws CommandRunException {
final Task task = new Task() {
@Override
public void run() {
//
}
@Override
public void setRunning(final boolean running) {
//
}
@Override
public void rmInterruptionListener(final InterruptionListener listener) {
//
}
@Override
public boolean isRunning() {
return false;
}
@Override
public String getName() {
return "abc";
}
@Override
public void addInterruptionListener(final InterruptionListener listener) {
//
}
};
final TaskPool pool = new TaskPool();
assertTrue("Pool not empty", pool.getPIDs().isEmpty());
final ExecutorService service = Executors.newSingleThreadExecutor();
final TaskSpawner spawner = new TaskSpawner("name", pool, service) {
@Override
public String tip() {
return "tip";
}
@Override
protected String usageDetail() {
return "no details";
}
@Override
protected Task createTask(final ConsoleOutput out, final ConsoleInput in,
final String... args) throws CommandRunException {
return task;
}
};
spawner.execute(null, null);
assertEquals("Added the task", 1, pool.getPIDs().size());
final Integer id = pool.getPIDs().iterator().next();
assertEquals("Added task is not the one", task, pool.get(id));
}
}

View File

@@ -0,0 +1,137 @@
package net.bigeon.gclc.process.io;
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.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Test;
import net.bigeon.gclc.tools.ConstantString;
import net.bigeon.gclc.utils.PipedConsoleInput;
import net.bigeon.gclc.utils.StreamConsoleInput;
import net.bigeon.test.junitmt.ATestRunnable;
import net.bigeon.test.junitmt.FunctionalTestRunnable;
import net.bigeon.test.junitmt.TestFunction;
import net.bigeon.test.junitmt.ThreadTest;
public class ConnectingConsoleInputTest {
@Test
public void testConnect() throws IOException {
final ConnectingConsoleInput in = new ConnectingConsoleInput();
final PipedConsoleInput pci = new PipedConsoleInput(null);
assertNull("Inputs should not transmit before connection", in.prompt(1000));
in.connect(pci);
pci.type("Some message");
assertEquals("Messages should be buffered", "Some message", in.prompt());
}
@Test
public void testDisconnect() throws IOException {
final ConnectingConsoleInput in = new ConnectingConsoleInput();
final PipedConsoleInput pci = new PipedConsoleInput(null);
assertNull("Inputs should not transmit before connection", in.prompt(1000));
in.connect(pci);
pci.type("Some message");
assertEquals("Messages should be buffered", "Some message", in.prompt());
in.disconnect();
assertNull("Disconnected inputs should not transmit anymore", in.prompt(1000));
}
@Test
public void testIsClosed() throws IOException {
final ConnectingConsoleInput in = new ConnectingConsoleInput();
assertFalse("New input should not be closed", in.isClosed());
final PipedConsoleInput pci = new PipedConsoleInput(null);
in.connect(pci);
pci.close();
assertFalse("Connected input closing should not close connecting", in.isClosed());
final PipedConsoleInput pci2 = new PipedConsoleInput(null);
in.connect(pci2);
in.close();
assertTrue("Input should close on request", in.isClosed());
assertFalse("Connected input should not be closed by connecting closure",
pci2.isClosed());
}
@Test
public void testCoveragePrompt() {
final ConnectingConsoleInput in = new ConnectingConsoleInput();
in.setPrompt("test");
assertEquals("Prompt should be set correctly", "test",
((ConstantString) in.getPrompt()).apply());
final ConstantString prompt = new ConstantString("other");
in.setPrompt(prompt);
assertEquals("Prompt should be set correctly", prompt, in.getPrompt());
}
@Test
public void testPromptSequence() throws IOException, InterruptedException {
final ConnectingConsoleInput in = new ConnectingConsoleInput();
// Unconnected
final AtomicBoolean ended = new AtomicBoolean(false);
final TestFunction one = new TestFunction() {
@Override
public void apply() throws Exception {
assertNull("Interrupted should return null", in.prompt("m1", -1));
assertNull("Interrupted should return null", in.prompt("m2", 5000));
ended.set(true);
assertNull("Overtime should return null", in.prompt("m3", 200));
}
};
final ATestRunnable runnable = new FunctionalTestRunnable(one);
final Thread th = new Thread(runnable);
final Thread inter = new Thread(new Runnable() {
@Override
public void run() {
while (!ended.get()) {
try {
th.join(500);
} catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in.interruptPrompt();
}
}
});
th.start();
inter.start();
ThreadTest.assertRuns(th, runnable);
inter.join();
ended.set(false);
final PipedOutputStream os = new PipedOutputStream();
final PipedInputStream pis = new PipedInputStream(os);
in.connect(new StreamConsoleInput(System.out, pis, StandardCharsets.UTF_8));
final ATestRunnable runnable2 = new FunctionalTestRunnable(one);
final Thread th2 = new Thread(runnable2);
final Thread inter2 = new Thread(new Runnable() {
@Override
public void run() {
while (!ended.get()) {
try {
th2.join(500);
} catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in.interruptPrompt();
}
}
});
th2.start();
inter2.start();
ThreadTest.assertRuns(th2, runnable2);
}
}

View File

@@ -0,0 +1,88 @@
package net.bigeon.gclc.process.io;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.junit.Test;
import net.bigeon.gclc.utils.PipedConsoleOutput;
public class ConnectingConsoleOutputTest {
@Test
public void testConnect() throws IOException {
final ConnectingConsoleOutput out = new ConnectingConsoleOutput(
ConnectingConsoleOutput.QUEUE, 10);
final PipedConsoleOutput output = new PipedConsoleOutput();
out.println("Some message");
assertFalse("Message should not be transmitted", output.available());
// Connect
out.connect(output);
// Connected outputs should receive data
final String res = output.readNextLine();
assertEquals("Message should be correctly transmitted", "Some message", res);
}
@Test
public void testDisconnect() throws IOException {
final ConnectingConsoleOutput out = new ConnectingConsoleOutput(
ConnectingConsoleOutput.QUEUE, 10);
final PipedConsoleOutput output = new PipedConsoleOutput();
// NOP disconnection when no connection
out.disconnect();
// Connect
out.connect(output);
// Connected outputs should receive data
out.println("Some message");
final String res = output.readNextLine();
assertEquals("Message should be correctly transmitted", "Some message", res);
out.disconnect();
out.println("Some message");
assertFalse("Message should not be transmitted", output.available());
}
@Test
public void testIsClosed() throws IOException {
final ConnectingConsoleOutput out = new ConnectingConsoleOutput(
ConnectingConsoleOutput.QUEUE, 10);
final PipedConsoleOutput output = new PipedConsoleOutput();
assertFalse("New output should not be closed", out.isClosed());
// Connect
out.connect(output);
output.close();
assertFalse("Output should not close when connected outputs do", out.isClosed());
final PipedConsoleOutput output2 = new PipedConsoleOutput();
out.connect(output2);
out.close();
assertTrue("Output should close on request", out.isClosed());
assertFalse("Output should not close connected output when they do",
output2.isClosed());
}
@Test
public void testPrint() throws IOException {
final ConnectingConsoleOutput out = new ConnectingConsoleOutput(
ConnectingConsoleOutput.PERSIST, 10);
out.print("Some text");
out.println();
final PipedConsoleOutput output = new PipedConsoleOutput();
out.connect(output);
String res = output.readNextLine();
assertEquals("Message should be correctly transmitted", "Some text", res);
out.disconnect();
// Persist should be reprinted on any connect
out.connect(output);
res = output.readNextLine();
assertEquals("Message should be correctly transmitted", "Some text", res);
out.disconnect();
}
}

View File

@@ -0,0 +1,60 @@
/**
*
*/
package net.bigeon.gclc.process.mocks;
import java.io.IOException;
import net.bigeon.gclc.command.ICommand;
import net.bigeon.gclc.exception.CommandRunException;
import net.bigeon.gclc.manager.ConsoleInput;
import net.bigeon.gclc.manager.ConsoleOutput;
/** @author Emmanuel Bigeon */
public class CommandMock implements ICommand {
private int executeCall = 0;
private int tipCall = 0;
private int helpCall = 0;
private int commandNameCall = 0;
/* (non-Javadoc)
* @see net.bigeon.gclc.command.ICommand#execute(net.bigeon.gclc.manager.
* ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, java.lang.String[]) */
@Override
public void execute(final ConsoleOutput out, final ConsoleInput in,
final String... args) throws CommandRunException {
executeCall++;
}
/* (non-Javadoc)
* @see net.bigeon.gclc.command.ICommand#getCommandName() */
@Override
public String getCommandName() {
commandNameCall++;
return "name";
}
/* (non-Javadoc)
* @see
* net.bigeon.gclc.command.ICommand#help(net.bigeon.gclc.manager.ConsoleOutput,
* java.lang.String[]) */
@Override
public void help(final ConsoleOutput output, final String... args)
throws IOException {
helpCall++;
}
/* (non-Javadoc)
* @see net.bigeon.gclc.command.ICommand#tip() */
@Override
public String tip() {
tipCall++;
return "tip";
}
/** @return the executeCall */
public int getExecuteCall() {
return executeCall;
}
}

View File

@@ -0,0 +1,43 @@
/**
*
*/
package net.bigeon.gclc.process.mocks;
import net.bigeon.gclc.exception.CommandRunException;
import net.bigeon.gclc.process.ForkTask;
import net.bigeon.gclc.process.Task;
/**
* @author Emmanuel Bigeon
*
*/
public class ForkTaskMock extends ForkTask implements Task {
private int runCall = 0;
/** Default constructor. */
public ForkTaskMock() {
super(10);
}
/* (non-Javadoc)
* @see net.bigeon.gclc.process.Task#getName()
*/
@Override
public String getName() {
return "name";
}
/* (non-Javadoc)
* @see net.bigeon.gclc.process.ForkTask#doRun()
*/
@Override
protected void doRun() throws CommandRunException {
runCall++;
}
/** @return the runCall */
public int getRunCall() {
return runCall;
}
}

View File

@@ -0,0 +1,57 @@
package net.bigeon.gclc.process.mocks;
import net.bigeon.gclc.process.InterruptionListener;
import net.bigeon.gclc.process.Task;
public class TaskMock implements Task {
private int runCall = 0;
private int setRunningCall = 0;
@Override
public void run() {
runCall++;
}
@Override
public void addInterruptionListener(final InterruptionListener listener) {
// TODO Auto-generated method stub
}
@Override
public String getName() {
return "name";
}
@Override
public boolean isRunning() {
// TODO Auto-generated method stub
return false;
}
@Override
public void rmInterruptionListener(final InterruptionListener listener) {
// TODO Auto-generated method stub
}
@Override
public void setRunning(final boolean running) {
setRunningCall++;
}
/**
*
*/
public void reset() {
runCall = 0;
setRunningCall = 0;
}
/** @return the number of calls to set running method */
public int getNumberSetRunning() {
return setRunningCall;
}
}

View File

@@ -0,0 +1,4 @@
/** Mock definitions for testing.
*
* @author Emmanuel Bigeon */
package net.bigeon.gclc.process.mocks;

View File

@@ -1,63 +1,22 @@
<!-- GCLC Socket, Socket implementation of GCLC -->
<!-- Copyright (C) 2014-2017 E. Bigeon -->
<!-- mailto:emmanuel@bigeon.fr -->
<!-- -->
<!-- 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. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>socket</artifactId>
<version>1.1.12-SNAPSHOT</version>
<packaging>jar</packaging>
<url>https://bigeon.net/projects/gclc.html</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.scm.id>git.code.bigeon.net</project.scm.id>
<license.licenseName>cecill_2.1</license.licenseName>
</properties>
<dependencies>
<dependency>
<groupId>net.bigeon</groupId>
<artifactId>gclc</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>net.bigeon</groupId>
<artifactId>smu</artifactId>
<version>1.0.5</version>
</dependency>
</dependencies>
<parent> <parent>
<groupId>net.bigeon.config</groupId> <groupId>net.bigeon.config</groupId>
<artifactId>ebigeon-config</artifactId> <artifactId>ebigeon-config</artifactId>
<version>1.8.21</version> <version>1.8.21</version>
</parent> </parent>
<groupId>net.bigeon.gclc</groupId>
<artifactId>socket</artifactId>
<version>1.1.14-SNAPSHOT</version>
<packaging>jar</packaging>
<name>GCLC Socket</name>
<description>Socket implementation of GCLC</description>
<url>https://bigeon.net/projects/gclc.html</url>
<inceptionYear>2016</inceptionYear>
<organization>
<name>Bigeon</name>
<url>https://bigeon.net/</url>
</organization>
<licenses> <licenses>
<license> <license>
<distribution>manual</distribution> <distribution>manual</distribution>
@@ -65,15 +24,6 @@
<url>https://cecill.info/licences/Licence_CeCILL_V2.1-en.html</url> <url>https://cecill.info/licences/Licence_CeCILL_V2.1-en.html</url>
</license> </license>
</licenses> </licenses>
<reporting>
<plugins>
<plugin>
<groupId>com.github.sevntu-checkstyle</groupId>
<artifactId>dsm-maven-plugin</artifactId>
<version>2.2.0</version>
</plugin>
</plugins>
</reporting>
<developers> <developers>
<developer> <developer>
<email>emmanuel@bigeon.fr</email> <email>emmanuel@bigeon.fr</email>
@@ -84,16 +34,45 @@
</roles> </roles>
</developer> </developer>
</developers> </developers>
<name>GCLC Socket</name>
<description>Socket implementation of GCLC</description>
<scm> <scm>
<developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection> <developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection>
<tag>HEAD</tag> <tag>HEAD</tag>
</scm> </scm>
<groupId>net.bigeon.gclc</groupId> <properties>
<inceptionYear>2016</inceptionYear> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<organization> <project.scm.id>git.code.bigeon.net</project.scm.id>
<name>Bigeon</name> <license.licenseName>cecill_2.1</license.licenseName>
<url>https://bigeon.net/</url> </properties>
</organization> <dependencies>
<dependency>
<groupId>net.bigeon</groupId>
<artifactId>gclc</artifactId>
<version>2.0.11</version>
</dependency>
<dependency>
<groupId>net.bigeon</groupId>
<artifactId>smu</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>net.bigeon.test</groupId>
<artifactId>junitmt</artifactId>
<version>1.0.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version>
</plugin>
<plugin>
<groupId>com.github.sevntu-checkstyle</groupId>
<artifactId>dsm-maven-plugin</artifactId>
<version>2.2.0</version>
</plugin>
</plugins>
</reporting>
</project> </project>

View File

@@ -143,7 +143,8 @@ public final class DConnexionManager<T> implements ConnexionManager<T> {
* *
* @return a new ID */ * @return a new ID */
private String newID() { private String newID() {
return "Client " + count++; //$NON-NLS-1$ final int c = count++;
return "Client " + c; //$NON-NLS-1$
} }
/* (non-Javadoc) /* (non-Javadoc)

View File

@@ -123,8 +123,7 @@ public final class RemoteDisconnectCommand<T> extends Command {
@Override @Override
protected String usageDetail() { protected String usageDetail() {
return MessageFormat.format( return MessageFormat.format(
" If arguments are provided the corresponding connexions are closed, " " If arguments are provided the corresponding connexions are closed, otherwise\n{0} are.",
+ "otherwise{0}{1} are.", all ? "all connexions" : "none");
System.lineSeparator(), all ? "all connexions" : "none");
} }
} }

View File

@@ -77,7 +77,7 @@ public class SocketConsoleApplicationTest {
Thread server; Thread server;
server = TestServer.getServer(); server = TestServer.getServer();
final String hostName = "127.0.0.1"; final String hostName = "127.0.0.1";
final int portNumber = 3300; final int portNumber = 12345;
try (Socket kkSocket = new Socket(hostName, portNumber); try (Socket kkSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true); PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true);

View File

@@ -46,6 +46,7 @@ import net.bigeon.gclc.ConsoleApplication;
@SuppressWarnings({ "javadoc", "nls" }) @SuppressWarnings({ "javadoc", "nls" })
public class TestServer { public class TestServer {
public static final int PORT = 3300;
private static SocketConsoleApplicationShell SHELL; private static SocketConsoleApplicationShell SHELL;
private static ConnexionManager<Socket> manager; private static ConnexionManager<Socket> manager;
@@ -75,7 +76,7 @@ public class TestServer {
input.setPrompt("> \n"); input.setPrompt("> \n");
output = new PluggableConsoleOutput(); output = new PluggableConsoleOutput();
manager = new DConnexionManager<>(); manager = new DConnexionManager<>();
SHELL = new SocketConsoleApplicationShell(3300, SHELL = new SocketConsoleApplicationShell(PORT,
InetAddress.getByName("127.0.0.1")); InetAddress.getByName("127.0.0.1"));
final ConsoleApplication app = ConsoleTestApplication.create(output, input, final ConsoleApplication app = ConsoleTestApplication.create(output, input,
manager); manager);
@@ -91,13 +92,13 @@ public class TestServer {
}); });
th.start(); th.start();
try { try {
Object waiting = new Object(); final Object waiting = new Object();
synchronized (waiting) { synchronized (waiting) {
while (!input.isPrompting()) { while (!input.isPrompting()) {
waiting.wait(50); waiting.wait(50);
} }
} }
} catch (InterruptedException e) { } catch (final InterruptedException e) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} }

View File

@@ -1,6 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>net.bigeon.config</groupId> <groupId>net.bigeon.config</groupId>
@@ -9,12 +7,12 @@
</parent> </parent>
<groupId>net.bigeon.gclc</groupId> <groupId>net.bigeon.gclc</groupId>
<artifactId>swt</artifactId> <artifactId>swt</artifactId>
<version>1.1.6-SNAPSHOT</version> <version>1.1.7-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>GCLC swt</name> <name>GCLC swt</name>
<description>A swt window for console applications</description> <description>A swt window for console applications</description>
<inceptionYear>2015</inceptionYear>
<url>https://bigeon.net/projects/gclc.html</url> <url>https://bigeon.net/projects/gclc.html</url>
<inceptionYear>2015</inceptionYear>
<organization> <organization>
<name>Bigeon</name> <name>Bigeon</name>
<url>https://bigeon.net/</url> <url>https://bigeon.net/</url>
@@ -50,17 +48,22 @@
<dependency> <dependency>
<groupId>net.bigeon</groupId> <groupId>net.bigeon</groupId>
<artifactId>gclc</artifactId> <artifactId>gclc</artifactId>
<version>2.0.9</version> <version>2.0.11</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.bigeon</groupId> <groupId>net.bigeon</groupId>
<artifactId>collections</artifactId> <artifactId>collections</artifactId>
<version>1.1.4</version> <version>1.1.6</version>
</dependency> </dependency>
</dependencies> </dependencies>
<reporting> <reporting>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version>
</plugin>
<plugin> <plugin>
<groupId>com.github.sevntu-checkstyle</groupId> <groupId>com.github.sevntu-checkstyle</groupId>
<artifactId>dsm-maven-plugin</artifactId> <artifactId>dsm-maven-plugin</artifactId>

View File

@@ -1,6 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>net.bigeon.config</groupId> <groupId>net.bigeon.config</groupId>
@@ -9,7 +7,7 @@
</parent> </parent>
<groupId>net.bigeon.gclc</groupId> <groupId>net.bigeon.gclc</groupId>
<artifactId>system</artifactId> <artifactId>system</artifactId>
<version>0.0.2-SNAPSHOT</version> <version>0.0.3-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>GCLC system command</name> <name>GCLC system command</name>
<description>Provide an exec command to execute system commands</description> <description>Provide an exec command to execute system commands</description>
@@ -45,25 +43,37 @@
<copyright.email>emmanuel@bigeon.fr</copyright.email> <copyright.email>emmanuel@bigeon.fr</copyright.email>
<license.licenseName>cecill_2.1</license.licenseName> <license.licenseName>cecill_2.1</license.licenseName>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>net.bigeon</groupId> <groupId>net.bigeon</groupId>
<artifactId>gclc</artifactId> <artifactId>gclc</artifactId>
<version>2.0.9</version> <version>2.0.11</version>
</dependency> </dependency>
</dependencies> <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.23.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
</plugins>
</build>
<reporting> <reporting>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version>
</plugin>
<plugin> <plugin>
<groupId>com.github.sevntu-checkstyle</groupId> <groupId>com.github.sevntu-checkstyle</groupId>
<artifactId>dsm-maven-plugin</artifactId> <artifactId>dsm-maven-plugin</artifactId>
<version>2.2.0</version> <version>2.2.0</version>
</plugin> </plugin>
</plugins> </plugins>
</reporting><build> </reporting>
<plugins>
</plugins>
</build>
</project> </project>

View File

@@ -39,7 +39,6 @@ package net.bigeon.gclc.system;
*/ */
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
@@ -92,15 +91,17 @@ public class ExecSystemCommand extends Command {
} }
// Stream forwarding to the application's console // Stream forwarding to the application's console
// This is started in a parallel thread. // This is started in a parallel thread.
final InputStream is = proc.getInputStream(); final Thread th = ForwardingRunnable.connect(proc.getInputStream(), out,
final Thread th = new Thread(new ForwardingRunnable(out, is)); "Command output");
th.start(); // Set the empty prompt for the processes promptings.
in.setPrompt(""); //$NON-NLS-1$ in.setPrompt(""); //$NON-NLS-1$
// Forward console input to the process. // Forward console input to the process, whether the process is waiting or not
// for input.
final OutputStream os = proc.getOutputStream(); final OutputStream os = proc.getOutputStream();
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os))) { try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os))) {
while (th.isAlive()) { while (th.isAlive()) {
final String user = in.prompt(); final String user = in.prompt();
// Avoid interruption being sent to process.
if (!user.isEmpty()) { if (!user.isEmpty()) {
writer.write(user + EOL); writer.write(user + EOL);
} }
@@ -125,7 +126,7 @@ public class ExecSystemCommand extends Command {
return " The system command is a system dependend command like sh on linux or" + //$NON-NLS-1$ return " The system command is a system dependend command like sh on linux or" + //$NON-NLS-1$
System.lineSeparator() + "powershell on windows." + //$NON-NLS-1$ System.lineSeparator() + "powershell on windows." + //$NON-NLS-1$
System.lineSeparator() + System.lineSeparator() System.lineSeparator() + System.lineSeparator()
+ " As an example if you give \"cat /etc/hostname\" as argument, on a linux" //$NON-NLS-1$ + " As an example if you give \"cat\", \"/etc/hostname\" as arguments, on a linux" //$NON-NLS-1$
+ System.lineSeparator() + "system, you would get the computer name." + //$NON-NLS-1$ + System.lineSeparator() + "system, you would get the computer name." + //$NON-NLS-1$
System.lineSeparator(); System.lineSeparator();
} }
@@ -136,5 +137,4 @@ public class ExecSystemCommand extends Command {
protected String usagePattern() { protected String usagePattern() {
return " CMD <system command>"; //$NON-NLS-1$ return " CMD <system command>"; //$NON-NLS-1$
} }
} }

View File

@@ -44,6 +44,12 @@ import net.bigeon.gclc.exception.CommandRunExceptionType;
import net.bigeon.gclc.manager.ConsoleOutput; import net.bigeon.gclc.manager.ConsoleOutput;
/** A class forwarding the content of a stream into a console output. /** A class forwarding the content of a stream into a console output.
* <p>
* This class is useful for processes that run in a different environment than
* the application but return an output. Such processes include command
* processes and socket communications for example.
* <p>
* In the current library is is used to retrieve a system command output.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class ForwardingRunnable implements Runnable { public final class ForwardingRunnable implements Runnable {
@@ -57,6 +63,7 @@ public final class ForwardingRunnable implements Runnable {
private final ConsoleOutput out; private final ConsoleOutput out;
/** The input stream. */ /** The input stream. */
private final InputStream is; private final InputStream is;
private Exception error;
/** Create the runnable. /** Create the runnable.
* *
@@ -72,31 +79,32 @@ public final class ForwardingRunnable implements Runnable {
@Override @Override
public void run() { public void run() {
try { try {
readToEnd(out, is); readToEnd();
is.close();
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
LOGGER.log(Level.WARNING, LOGGER.log(Level.WARNING, "Manager was closed in the meantime...", e); //$NON-NLS-1$
"Manager was closed in the meantime...", e); //$NON-NLS-1$ setError(e);
} catch (final IOException e) {
LOGGER.log(Level.WARNING, "Input stream was closed...", e); //$NON-NLS-1$
} }
} }
/** Read the input until its end. /** Read the input until its end.
* <p>
* This method actually perform a loop on the input stream to read the next
* character and then print int on the screen.
* <p>
* When the stream returns a negative value, it will exit its loop and return.
* *
* @param is the input stream
* @throws CommandRunException if the manager was closed while writing the * @throws CommandRunException if the manager was closed while writing the
* stream */ * stream */
private void readToEnd(final ConsoleOutput out, final InputStream is) private void readToEnd() throws CommandRunException {
throws CommandRunException {
int c; int c;
try { try {
while ((c = is.read()) >= 0) { while ((c = is.read()) >= 0) {
// Print the chaeacter in the output // Print the character in the output
printCharacter(out, (char) c); printCharacter(out, (char) c);
} }
} catch (final IOException e) { } catch (final IOException e) {
LOGGER.log(Level.INFO, "input stream reading failed", e); //$NON-NLS-1$ LOGGER.log(Level.INFO, "input stream reading failed", e); //$NON-NLS-1$
setError(e);
} }
} }
@@ -114,4 +122,44 @@ public final class ForwardingRunnable implements Runnable {
MANAGER_WAS_CLOSED, e); // $NON-NLS-1$ MANAGER_WAS_CLOSED, e); // $NON-NLS-1$
} }
} }
/** Tool method to connect an input stream to a console output.
*
* @param stream the stream
* @param output the output
* @param name the identification of the thread
* @return the thread the forwarding runnable runs into. */
public static Thread connect(final InputStream stream, final ConsoleOutput output,
final String name) {
final Thread th = new Thread(new ForwardingRunnable(output, stream), name);
th.start();
return th;
}
/** Tool method to connect an input stream to a console output.
*
* @param stream the stream
* @param output the output
* @return the thread the forwarding runnable runs into. */
public static Thread connect(final InputStream stream, final ConsoleOutput output) {
return connect(stream, output, "Forwarding");
}
/** Get the error in this runnable execution if any.
* <p>
* In the current implementation, this error can be an {@link IOException} if
* the input stream failed or a {@link CommandRunException} if the output was
* closed.
*
* @return the error */
public synchronized Exception getError() {
return error;
}
/** Set the error that caused this runnable to stop executing.
*
* @param error the error to set */
private synchronized void setError(final Exception error) {
this.error = error;
}
} }

View File

@@ -33,8 +33,9 @@ package net.bigeon.gclc.system;
* knowledge of the CeCILL license and that you accept its terms. * knowledge of the CeCILL license and that you accept its terms.
* #L% * #L%
*/ */
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.*; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.junit.Test; import org.junit.Test;
@@ -46,29 +47,35 @@ import net.bigeon.gclc.utils.SinkOutput;
public class ExecSystemCommandTest { public class ExecSystemCommandTest {
/** Test the help methods of the command. */
@Test @Test
public void testExecSystemCommand() { public void testExecSystemCommand() {
ExecSystemCommand cmd = new ExecSystemCommand("test"); final ExecSystemCommand cmd = new ExecSystemCommand("test");
assertEquals("Name should be preserved", "test", cmd.getCommandName()); assertEquals("Name should be preserved", "test", cmd.getCommandName());
assertNotNull("tip should be defined", cmd.tip()); assertNotNull("tip should be defined", cmd.tip());
assertNotNull("usage should be defined", cmd.usagePattern()); assertNotNull("usage should be defined", cmd.usagePattern());
assertNotNull("usage should be defined", cmd.usageDetail()); assertNotNull("usage should be defined", cmd.usageDetail());
} }
/** Test the execution of the command.
*
* @throws CommandRunException if the command fails */
@Test @Test
public void testExecute() throws CommandRunException { public void testExecute() throws CommandRunException {
ConsoleOutput out = SinkOutput.INSTANCE; final ConsoleOutput out = SinkOutput.INSTANCE;
ConsoleInput in = EmptyInput.INSTANCE; final ConsoleInput in = EmptyInput.INSTANCE;
ExecSystemCommand cmd = new ExecSystemCommand(); final ExecSystemCommand cmd = new ExecSystemCommand();
if (System.getProperty("os.name").contains("indows")) { if (System.getProperty("os.name").contains("indows")) {
cmd.execute(out, in, "cmd", "/C", "dir"); cmd.execute(out, in, "cmd", "/C", "dir");
try { } else if (System.getProperty("os.name").contains("inux")) {
cmd.execute(out, in, "inexistent"); cmd.execute(out, in, "ls");
fail("Able to execute inexistent command in system"); }
} catch (CommandRunException e) { try {
// ok cmd.execute(out, in, "inexistent");
} fail("Able to execute inexistent command in system");
} catch (final CommandRunException e) {
// ok
} }
} }

View File

@@ -0,0 +1,44 @@
/**
*
*/
package net.bigeon.gclc.system;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import org.mockito.Mockito;
import net.bigeon.gclc.exception.CommandRunException;
import net.bigeon.gclc.utils.SinkOutput;
import net.bigeon.gclc.utils.StreamConsoleOutput;
/** @author Emmanuel Bigeon */
public class ForwardingRunnableTest {
public void testClosedOutput() {
final StreamConsoleOutput out = new StreamConsoleOutput();
out.close();
final InputStream is = new ByteArrayInputStream(new byte[] { 1, 2, 3 });
final ForwardingRunnable runnable = new ForwardingRunnable(out, is);
// Runnable should close immediatly.
runnable.run();
assertTrue("Error should be a CommandRunException",
runnable.getError() instanceof CommandRunException);
}
@Test
public void testIOInInput() throws IOException {
final InputStream is = Mockito.mock(InputStream.class);
Mockito.when(is.read()).thenThrow(new IOException());
final ForwardingRunnable runnable = new ForwardingRunnable(SinkOutput.INSTANCE,
is);
// Runnable should close immediatly.
runnable.run();
assertTrue("Error should be an IO", runnable.getError() instanceof IOException);
}
}

View File

@@ -8,7 +8,7 @@
</parent> </parent>
<groupId>net.bigeon</groupId> <groupId>net.bigeon</groupId>
<artifactId>gclc</artifactId> <artifactId>gclc</artifactId>
<version>2.0.10</version> <version>2.0.12</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>Generic Command Ligne console</name> <name>Generic Command Ligne console</name>
<description>A generic framework for console applications, with customized command input and output streams.</description> <description>A generic framework for console applications, with customized command input and output streams.</description>
@@ -37,7 +37,7 @@
</developers> </developers>
<scm> <scm>
<developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection> <developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection>
<tag>gclc-2.0.10</tag> <tag>gclc-2.0.12</tag>
</scm> </scm>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@@ -47,26 +47,12 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>net.bigeon.test</groupId>
<artifactId>junit</artifactId> <artifactId>junitmt</artifactId>
<version>4.11</version> <version>1.0.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<reporting>
<plugins>
<plugin>
<groupId>com.github.sevntu-checkstyle</groupId>
<artifactId>dsm-maven-plugin</artifactId>
<version>2.2.0</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jdepend-maven-plugin</artifactId>
<version>2.0</version>
</plugin>
</plugins>
</reporting>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
@@ -81,4 +67,18 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<reporting>
<plugins>
<plugin>
<groupId>com.github.sevntu-checkstyle</groupId>
<artifactId>dsm-maven-plugin</artifactId>
<version>2.2.0</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jdepend-maven-plugin</artifactId>
<version>2.0</version>
</plugin>
</plugins>
</reporting>
</project> </project>

View File

@@ -73,8 +73,7 @@ package net.bigeon.gclc.manager;
*/ */
import java.io.IOException; import java.io.IOException;
import java.io.InterruptedIOException; import java.io.InterruptedIOException;
import java.util.function.Supplier;
import net.bigeon.gclc.tools.StringProvider;
/** A console application input. /** A console application input.
* *
@@ -90,7 +89,7 @@ public interface ConsoleInput extends AutoCloseable {
/** Get the prompt string. /** Get the prompt string.
* *
* @return the prompt prefix */ * @return the prompt prefix */
StringProvider getPrompt(); Supplier<String> getPrompt();
/** Indicate to the input that is should interrompt the prompting, if possible. /** Indicate to the input that is should interrompt the prompting, if possible.
* <p> * <p>
@@ -148,5 +147,5 @@ public interface ConsoleInput extends AutoCloseable {
/** Set the prompting string. /** Set the prompting string.
* *
* @param string the prompt string */ * @param string the prompt string */
void setPrompt(StringProvider string); void setPrompt(Supplier<String> string);
} }

View File

@@ -34,6 +34,9 @@
*/ */
package net.bigeon.gclc.tools; package net.bigeon.gclc.tools;
import java.util.Objects;
import java.util.function.Supplier;
/*- /*-
* #%L * #%L
* Generic Command Ligne console * Generic Command Ligne console
@@ -68,23 +71,45 @@ package net.bigeon.gclc.tools;
* #L% * #L%
*/ */
/** A {@link StringProvider} that hold a constant string. /** A supplier of string that hold a constant string.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class ConstantString implements StringProvider { public class ConstantString implements Supplier<String> {
private final String string; private final String string;
/** Create a provider for a string. /** Create a provider for a string.
* *
* @param string the string */ * @param string the string */
public ConstantString(String string) { public ConstantString(final String string) {
this.string = string; this.string = string;
} }
/* (non-Javadoc)
* @see net.bigeon.gclc.tools.StringProvider#apply() */
@Override @Override
public String apply() { public String get() {
return string; return string;
} }
/* (non-Javadoc)
* @see java.lang.Object#hashCode() */
@Override
public int hashCode() {
return Objects.hash(string);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object) */
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ConstantString other = (ConstantString) obj;
return Objects.equals(string, other.string);
}
} }

View File

@@ -1,83 +0,0 @@
/*
* Copyright Bigeon Emmanuel (2014)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a generic framework for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
package net.bigeon.gclc.tools;
/*-
* #%L
* Generic Command Ligne console
* %%
* Copyright (C) 2014 - 2018 bigeon.fr
* %%
* 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.
* #L%
*/
/** A string providing object.
* <p>
* Implementations of this interface will provide a string, this internal state
* of the object may be so that successive calls to the apply method return
* different results.
*
* @author Emmanuel */
public interface StringProvider {
/** Provide a string.
*
* @return the string */
String apply();
}

View File

@@ -38,6 +38,8 @@
*/ */
package net.bigeon.gclc.utils; package net.bigeon.gclc.utils;
import java.util.function.Supplier;
import net.bigeon.gclc.manager.ConsoleInput; import net.bigeon.gclc.manager.ConsoleInput;
/*- /*-
@@ -75,7 +77,6 @@ import net.bigeon.gclc.manager.ConsoleInput;
*/ */
import net.bigeon.gclc.tools.ConstantString; import net.bigeon.gclc.tools.ConstantString;
import net.bigeon.gclc.tools.StringProvider;
/** A console input that return empty to all prompting. /** A console input that return empty to all prompting.
* *
@@ -101,8 +102,8 @@ public final class EmptyInput implements ConsoleInput {
/* (non-Javadoc) /* (non-Javadoc)
* @see net.bigeon.gclc.manager.ConsoleInput#getPrompt() */ * @see net.bigeon.gclc.manager.ConsoleInput#getPrompt() */
@Override @Override
public StringProvider getPrompt() { public Supplier<String> getPrompt() {
return CONSTANT_STRING; //$NON-NLS-1$ return CONSTANT_STRING;
} }
/* (non-Javadoc) /* (non-Javadoc)
@@ -155,7 +156,7 @@ public final class EmptyInput implements ConsoleInput {
} }
@Override @Override
public void setPrompt(StringProvider string) { public void setPrompt(final Supplier<String> string) {
// //
} }
} }

View File

@@ -76,9 +76,9 @@ import java.io.PipedInputStream;
import java.io.PipedOutputStream; import java.io.PipedOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;
import net.bigeon.gclc.manager.ConsoleInput; import net.bigeon.gclc.manager.ConsoleInput;
import net.bigeon.gclc.tools.StringProvider;
/** This console input allows to enter commands and retrieve the output as an /** This console input allows to enter commands and retrieve the output as an
* input. * input.
@@ -120,7 +120,7 @@ public final class PipedConsoleInput implements ConsoleInput {
} }
@Override @Override
public StringProvider getPrompt() { public Supplier<String> getPrompt() {
return innerManager.getPrompt(); return innerManager.getPrompt();
} }
@@ -174,7 +174,7 @@ public final class PipedConsoleInput implements ConsoleInput {
} }
@Override @Override
public void setPrompt(StringProvider string) { public void setPrompt(final Supplier<String> string) {
innerManager.setPrompt(string); innerManager.setPrompt(string);
} }

View File

@@ -145,6 +145,9 @@ public final class ReadingRunnable implements Runnable {
* @throws IOException if the pipe is closed */ * @throws IOException if the pipe is closed */
public String getMessage() throws IOException { public String getMessage() throws IOException {
synchronized (lock) { synchronized (lock) {
if (!messages.isEmpty()) {
return messages.poll();
}
if (!running) { if (!running) {
throw new IOException(CLOSED_PIPE); throw new IOException(CLOSED_PIPE);
} }
@@ -164,6 +167,9 @@ public final class ReadingRunnable implements Runnable {
* @throws IOException if the input was closed */ * @throws IOException if the input was closed */
public String getNextMessage(final long timeout) throws IOException { public String getNextMessage(final long timeout) throws IOException {
synchronized (lock) { synchronized (lock) {
if (!messages.isEmpty()) {
return messages.poll();
}
if (!running) { if (!running) {
throw new IOException(CLOSED_PIPE); throw new IOException(CLOSED_PIPE);
} }
@@ -177,7 +183,7 @@ public final class ReadingRunnable implements Runnable {
} }
} }
public void waitForDelivery(String message) throws InterruptedException { public void waitForDelivery(final String message) throws InterruptedException {
Object mLock; Object mLock;
synchronized (messageBlockerLock) { synchronized (messageBlockerLock) {
if (!messageBlocker.containsKey(message)) { if (!messageBlocker.containsKey(message)) {
@@ -196,10 +202,11 @@ public final class ReadingRunnable implements Runnable {
* @throws IOException if the pipe is closed */ * @throws IOException if the pipe is closed */
public boolean hasMessage() throws IOException { public boolean hasMessage() throws IOException {
synchronized (lock) { synchronized (lock) {
if (!running) { final boolean empty = messages.isEmpty();
if (!running && empty) {
throw new IOException(CLOSED_PIPE); throw new IOException(CLOSED_PIPE);
} }
return !messages.isEmpty(); return !empty;
} }
} }

View File

@@ -77,10 +77,10 @@ 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.nio.charset.Charset;
import java.util.function.Supplier;
import net.bigeon.gclc.manager.ConsoleInput; import net.bigeon.gclc.manager.ConsoleInput;
import net.bigeon.gclc.tools.ConstantString; import net.bigeon.gclc.tools.ConstantString;
import net.bigeon.gclc.tools.StringProvider;
/** A console using the input stream and print stream. /** A console using the input stream and print stream.
* <p> * <p>
@@ -90,10 +90,10 @@ import net.bigeon.gclc.tools.StringProvider;
public final class StreamConsoleInput implements ConsoleInput { public final class StreamConsoleInput implements ConsoleInput {
/** The default prompt. */ /** The default prompt. */
public static final StringProvider DEFAULT_PROMPT = new ConstantString("> "); //$NON-NLS-1$ public static final Supplier<String> DEFAULT_PROMPT = new ConstantString("> "); //$NON-NLS-1$
/** The command prompt. It can be changed. */ /** The command prompt. It can be changed. */
private StringProvider prompt = DEFAULT_PROMPT; private Supplier<String> prompt = DEFAULT_PROMPT;
/** The print stream. */ /** The print stream. */
private final PrintStream out; private final PrintStream out;
@@ -152,7 +152,7 @@ public final class StreamConsoleInput implements ConsoleInput {
/* (non-Javadoc) /* (non-Javadoc)
* @see net.bigeon.gclc.manager.ConsoleInput#getPrompt() */ * @see net.bigeon.gclc.manager.ConsoleInput#getPrompt() */
@Override @Override
public StringProvider getPrompt() { public Supplier<String> getPrompt() {
return prompt; return prompt;
} }
@@ -175,14 +175,14 @@ public final class StreamConsoleInput implements ConsoleInput {
* @see net.bigeon.gclc.ConsoleManager#prompt() */ * @see net.bigeon.gclc.ConsoleManager#prompt() */
@Override @Override
public String prompt() throws IOException { public String prompt() throws IOException {
return prompt(prompt.apply()); return prompt(prompt.get());
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see net.bigeon.gclc.manager.ConsoleManager#prompt(long) */ * @see net.bigeon.gclc.manager.ConsoleManager#prompt(long) */
@Override @Override
public String prompt(final long timeout) throws IOException { public String prompt(final long timeout) throws IOException {
return prompt(prompt.apply(), timeout); return prompt(prompt.get(), timeout);
} }
/* (non-Javadoc) /* (non-Javadoc)
@@ -217,7 +217,7 @@ public final class StreamConsoleInput implements ConsoleInput {
} }
@Override @Override
public void setPrompt(StringProvider string) { public void setPrompt(final Supplier<String> string) {
prompt = string; prompt = string;
} }
} }

View File

@@ -93,6 +93,10 @@ import net.bigeon.gclc.manager.ConsoleInput;
import net.bigeon.gclc.manager.ConsoleOutput; import net.bigeon.gclc.manager.ConsoleOutput;
import net.bigeon.gclc.utils.PipedConsoleInput; import net.bigeon.gclc.utils.PipedConsoleInput;
import net.bigeon.gclc.utils.PipedConsoleOutput; import net.bigeon.gclc.utils.PipedConsoleOutput;
import net.bigeon.test.junitmt.ATestRunnable;
import net.bigeon.test.junitmt.FunctionalTestRunnable;
import net.bigeon.test.junitmt.TestFunction;
import net.bigeon.test.junitmt.ThreadTest;
/** /**
* <p> * <p>
@@ -509,29 +513,28 @@ public class ParametrizedCommandTest {
cmd.execute(out, in, "-" + str1, str2, "-" + addParam); cmd.execute(out, in, "-" + str1, str2, "-" + addParam);
cmd.execute(out, in, "-" + str1, str2, "-" + addParam, addParam); cmd.execute(out, in, "-" + str1, str2, "-" + addParam, addParam);
final Thread th = new Thread(new Runnable() { final TestFunction function = new TestFunction() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertEquals("value of " + str1 + "? ", buf.readLine());
assertEquals("value of " + str1 + "? ", buf.readLine()); in.type("");
in.type(""); assertEquals("value of " + str1 + "? (cannot be empty) ",
assertEquals("value of " + str1 + "? (cannot be empty) ", buf.readLine());
buf.readLine()); in.type("");
in.type(""); assertEquals("value of " + str1 + "? (cannot be empty) ",
assertEquals("value of " + str1 + "? (cannot be empty) ", buf.readLine());
buf.readLine()); in.type(str2);
in.type(str2);
} catch (final IOException e) {
assertNull(e);
}
} }
}); };
final ATestRunnable testConsole = new FunctionalTestRunnable(function);
final Thread th = new Thread(testConsole);
th.start(); th.start();
cmd.execute(out, in); cmd.execute(out, in);
th.join(); ThreadTest.assertRuns(th, testConsole);
} }
try (PipedConsoleOutput out = new PipedConsoleOutput(); try (PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
@@ -540,23 +543,22 @@ public class ParametrizedCommandTest {
new InputStreamReader(pis, StandardCharsets.UTF_8)); new InputStreamReader(pis, StandardCharsets.UTF_8));
PipedConsoleInput in = new PipedConsoleInput(new PrintStream(pout))) { PipedConsoleInput in = new PipedConsoleInput(new PrintStream(pout))) {
final Thread th = new Thread(new Runnable() { final TestFunction function = new TestFunction() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertEquals("value of " + str1 + "? ", buf.readLine());
assertEquals("value of " + str1 + "? ", buf.readLine()); in.type(str2);
in.type(str2);
} catch (final IOException e) {
assertNull(e);
}
} }
}); };
final ATestRunnable testConsole = new FunctionalTestRunnable(function);
final Thread th = new Thread(testConsole);
th.start(); th.start();
cmd.execute(out, in, "-" + addParam); cmd.execute(out, in, "-" + addParam);
th.join(); ThreadTest.assertRuns(th, testConsole);
} }
try { try {
final PipedConsoleOutput out = new PipedConsoleOutput(); final PipedConsoleOutput out = new PipedConsoleOutput();

View File

@@ -38,6 +38,7 @@
*/ */
package net.bigeon.gclc.manager; package net.bigeon.gclc.manager;
import static org.junit.Assert.assertEquals;
/*- /*-
* #%L * #%L
* Generic Command Ligne console * Generic Command Ligne console
@@ -75,12 +76,15 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PipedInputStream; import java.io.PipedInputStream;
import java.io.PipedOutputStream; import java.io.PipedOutputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -131,13 +135,13 @@ public class ReadingRunnableTest {
final ReadingRunnable runnable = new ReadingRunnable(reader); final ReadingRunnable runnable = new ReadingRunnable(reader);
final Thread th0 = new Thread(runnable, "read"); final Thread th0 = new Thread(runnable, "read");
th0.start(); th0.start();
Thread th = new Thread(new Runnable() { final Thread th = new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
runnable.waitForDelivery("msg"); runnable.waitForDelivery("msg");
} catch (InterruptedException e) { } catch (final InterruptedException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
@@ -186,4 +190,36 @@ public class ReadingRunnableTest {
} }
} }
/** Test method for {@link net.bigeon.gclc.utils.ReadingRunnable#hasMessage()}.
*
* @throws IOException if an error occurred
* @throws InterruptedException if an error occured in the reading thread */
@Test
public final void testGetPendingMessages() throws IOException, InterruptedException {
final PipedOutputStream out = new PipedOutputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(new PipedInputStream(out), StandardCharsets.UTF_8));
final ReadingRunnable runnable = new ReadingRunnable(reader);
final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
writer.write("one");
writer.newLine();
writer.write("two");
writer.close();
out.close();
final Thread th = new Thread(runnable);
th.start();
th.join();
assertEquals("Pending messages should be retrievable", "one",
runnable.getMessage());
assertEquals("Pending messages should be retrievable", "two",
runnable.getMessage());
try {
runnable.getMessage();
fail("reading from closed runnable");
} catch (final IOException e) {
// ok
}
}
} }

View File

@@ -174,7 +174,7 @@ public class SystemConsoleManagerTest {
final String prt = "++"; final String prt = "++";
manager.setPrompt(prt); manager.setPrompt(prt);
assertEquals(prt, manager.getPrompt().apply()); assertEquals(prt, manager.getPrompt().get());
} }
} }

View File

@@ -94,6 +94,10 @@ import org.junit.Test;
import net.bigeon.gclc.utils.PipedConsoleInput; import net.bigeon.gclc.utils.PipedConsoleInput;
import net.bigeon.gclc.utils.PipedConsoleOutput; import net.bigeon.gclc.utils.PipedConsoleOutput;
import net.bigeon.test.junitmt.ATestRunnable;
import net.bigeon.test.junitmt.FunctionalTestRunnable;
import net.bigeon.test.junitmt.TestFunction;
import net.bigeon.test.junitmt.ThreadTest;
/** /**
* <p> * <p>
@@ -115,30 +119,29 @@ public class CLIPrompterTest {
} }
/** Test method for /** Test method for
* {@link net.bigeon.gclc.prompt.CLIPrompter#promptBoolean(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, String)}. */ * {@link net.bigeon.gclc.prompt.CLIPrompter#promptBoolean(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, String)}.
*
* @throws IOException if an io occurs */
@Test @Test
public final void testPromptBoolean() { public final void testPromptBoolean() throws IOException {
try (final PipedConsoleOutput out = new PipedConsoleOutput(); try (final PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
BufferedReader buf = new BufferedReader( BufferedReader buf = new BufferedReader(
new InputStreamReader(pis, StandardCharsets.UTF_8)); new InputStreamReader(pis, StandardCharsets.UTF_8));
PipedConsoleInput in = new PipedConsoleInput(new PrintStream(pout))) { PipedConsoleInput in = new PipedConsoleInput(new PrintStream(pout))) {
final Thread th = new Thread(new Runnable() { final TestFunction func = new TestFunction() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertTrue(CLIPrompter.promptBoolean(out, in, "My message")); //$NON-NLS-1$
assertTrue(CLIPrompter.promptBoolean(out, in, "My message")); //$NON-NLS-1$ assertTrue(CLIPrompter.promptBoolean(out, in, "My message")); //$NON-NLS-1$
assertTrue(CLIPrompter.promptBoolean(out, in, "My message")); //$NON-NLS-1$ assertFalse(CLIPrompter.promptBoolean(out, in, "My message")); //$NON-NLS-1$
assertFalse(CLIPrompter.promptBoolean(out, in, "My message")); //$NON-NLS-1$ assertFalse(CLIPrompter.promptBoolean(out, in, "My message")); //$NON-NLS-1$
assertFalse(CLIPrompter.promptBoolean(out, in, "My message")); //$NON-NLS-1$
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable target = new FunctionalTestRunnable(func);
final Thread th = new Thread(target);
th.start(); th.start();
assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$
in.type(""); //$NON-NLS-1$ in.type(""); //$NON-NLS-1$
@@ -151,18 +154,18 @@ public class CLIPrompterTest {
in.type("N"); //$NON-NLS-1$ in.type("N"); //$NON-NLS-1$
assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$
in.type("nO"); //$NON-NLS-1$ in.type("nO"); //$NON-NLS-1$
th.join(); ThreadTest.assertRuns(th, target);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
/** Test method for /** Test method for
* {@link net.bigeon.gclc.prompt.CLIPrompter#promptChoice(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, List, List, String, String)}. */ * {@link net.bigeon.gclc.prompt.CLIPrompter#promptChoice(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, List, List, String, String)}.
*
* @throws IOException if an IO occurred */
@Test @Test
public final void testPromptChoiceConsoleManagerListOfStringListOfUStringString() { public final void testPromptChoiceConsoleManagerListOfStringListOfUStringString()
throws IOException {
try (final PipedConsoleOutput out = new PipedConsoleOutput(); try (final PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
@@ -178,26 +181,23 @@ public class CLIPrompterTest {
final String cancel = "Cancel"; //$NON-NLS-1$ final String cancel = "Cancel"; //$NON-NLS-1$
final String message = "My message"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$
final Thread th = new Thread(new Runnable() { final TestFunction func = new TestFunction() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", choices.get(0), CLIPrompter.promptChoice(out, in, keys,
choices.get(0), CLIPrompter.promptChoice(out, in, keys, choices, message, cancel));
choices, message, cancel)); assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", choices.get(0), CLIPrompter.promptChoice(out, in, keys,
choices.get(0), CLIPrompter.promptChoice(out, in, keys, choices, message, null));
choices, message, null)); assertEquals("Asserted provided value to be retrieved", null,
assertEquals("Asserted provided value to be retrieved", null, CLIPrompter.promptChoice(out, in, keys, choices, message,
CLIPrompter.promptChoice(out, in, keys, choices, message, cancel));
cancel));
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable target = new FunctionalTestRunnable(func);
final Thread th = new Thread(target);
th.start(); th.start();
assertTrue(out.readNextLine().startsWith(message)); assertTrue(out.readNextLine().startsWith(message));
assertTrue(out.readNextLine().contains(keys.get(0))); assertTrue(out.readNextLine().contains(keys.get(0)));
@@ -241,15 +241,13 @@ public class CLIPrompterTest {
assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$
buf.readLine()); buf.readLine());
in.type("2"); //$NON-NLS-1$ in.type("2"); //$NON-NLS-1$
th.join(); ThreadTest.assertRuns(th, target);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
@Test @Test
public final void testPromptChoiceConsoleManagerListOfUMapOfUTStringString() { public final void testPromptChoiceConsoleManagerListOfUMapOfUTStringString()
throws IOException {
try (final PipedConsoleOutput out = new PipedConsoleOutput(); try (final PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
@@ -264,27 +262,23 @@ public class CLIPrompterTest {
choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$
final String cancel = "Cancel"; //$NON-NLS-1$ final String cancel = "Cancel"; //$NON-NLS-1$
final String message = "My message"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$
final TestFunction func = new TestFunction() {
final Thread th = new Thread(new Runnable() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", choices.get(keys.get(0)), CLIPrompter.promptChoice(out, in,
choices.get(keys.get(0)), CLIPrompter.promptChoice(out, keys, choices, message, cancel));
in, keys, choices, message, cancel)); assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", choices.get(keys.get(0)), CLIPrompter.promptChoice(out, in,
choices.get(keys.get(0)), CLIPrompter.promptChoice(out, keys, choices, message, null));
in, keys, choices, message, null)); assertEquals("Asserted provided value to be retrieved", null,
assertEquals("Asserted provided value to be retrieved", null, CLIPrompter.promptChoice(out, in, keys, choices, message,
CLIPrompter.promptChoice(out, in, keys, choices, message, cancel));
cancel));
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable target = new FunctionalTestRunnable(func);
final Thread th = new Thread(target);
th.start(); th.start();
assertTrue(out.readNextLine().startsWith(message)); assertTrue(out.readNextLine().startsWith(message));
assertTrue(out.readNextLine().contains(keys.get(0).toString())); assertTrue(out.readNextLine().contains(keys.get(0).toString()));
@@ -328,15 +322,13 @@ public class CLIPrompterTest {
assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$
buf.readLine()); buf.readLine());
in.type("2"); //$NON-NLS-1$ in.type("2"); //$NON-NLS-1$
th.join(); ThreadTest.assertRuns(th, target);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
@Test @Test
public final void testPromptChoiceConsoleManagerListOfUStringString() { public final void testPromptChoiceConsoleManagerListOfUStringString()
throws IOException {
try (final PipedConsoleOutput out = new PipedConsoleOutput(); try (final PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
@@ -348,29 +340,26 @@ public class CLIPrompterTest {
keys.add("An other"); //$NON-NLS-1$ keys.add("An other"); //$NON-NLS-1$
final String cancel = "Cancel"; //$NON-NLS-1$ final String cancel = "Cancel"; //$NON-NLS-1$
final String message = "My message"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$
final TestFunction func = new TestFunction() {
final Thread th = new Thread(new Runnable() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", Integer.valueOf(0),
Integer.valueOf(0), CLIPrompter.promptChoice(out, in, keys, message, cancel));
CLIPrompter.promptChoice(out, in, keys, message, cancel)); assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", Integer.valueOf(0),
Integer.valueOf(0), CLIPrompter.promptChoice(out, in, keys, message, null));
CLIPrompter.promptChoice(out, in, keys, message, null)); assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", Integer.valueOf(1),
Integer.valueOf(1), CLIPrompter.promptChoice(out, in, keys, message, null));
CLIPrompter.promptChoice(out, in, keys, message, null)); assertEquals("Asserted provided value to be retrieved", null,
assertEquals("Asserted provided value to be retrieved", null, CLIPrompter.promptChoice(out, in, keys, message, cancel));
CLIPrompter.promptChoice(out, in, keys, message, cancel));
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable target = new FunctionalTestRunnable(func);
final Thread th = new Thread(target);
th.start(); th.start();
assertTrue(out.readNextLine().startsWith(message)); assertTrue(out.readNextLine().startsWith(message));
assertTrue(out.readNextLine().contains(keys.get(0).toString())); assertTrue(out.readNextLine().contains(keys.get(0).toString()));
@@ -421,17 +410,17 @@ public class CLIPrompterTest {
assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$
buf.readLine()); buf.readLine());
in.type("2"); //$NON-NLS-1$ in.type("2"); //$NON-NLS-1$
th.join(); ThreadTest.assertRuns(th, target);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
/** Test method for /** Test method for
* {@link net.bigeon.gclc.prompt.CLIPrompter#promptChoice(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, Map, String, String)}. */ * {@link net.bigeon.gclc.prompt.CLIPrompter#promptChoice(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, Map, String, String)}.
*
* @throws IOException if errors */
@Test @Test
public final void testPromptChoiceConsoleManagerMapOfUTStringString() { public final void testPromptChoiceConsoleManagerMapOfUTStringString()
throws IOException {
try (final PipedConsoleOutput out = new PipedConsoleOutput(); try (final PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
@@ -447,26 +436,23 @@ public class CLIPrompterTest {
final String cancel = "Cancel"; //$NON-NLS-1$ final String cancel = "Cancel"; //$NON-NLS-1$
final String message = "My message"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$
final Thread th = new Thread(new Runnable() { final TestFunction func = new TestFunction() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", choices.get(keys.get(0)), CLIPrompter.promptChoice(out, in,
choices.get(keys.get(0)), CLIPrompter.promptChoice(out, keys, choices, message, cancel));
in, keys, choices, message, cancel)); assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", choices.get(keys.get(0)), CLIPrompter.promptChoice(out, in,
choices.get(keys.get(0)), CLIPrompter.promptChoice(out, keys, choices, message, null));
in, keys, choices, message, null)); assertEquals("Asserted provided value to be retrieved", null,
assertEquals("Asserted provided value to be retrieved", null, CLIPrompter.promptChoice(out, in, keys, choices, message,
CLIPrompter.promptChoice(out, in, keys, choices, message, cancel));
cancel));
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable runnable = new FunctionalTestRunnable(func);
final Thread th = new Thread(runnable);
th.start(); th.start();
assertTrue(out.readNextLine().startsWith(message)); assertTrue(out.readNextLine().startsWith(message));
final String readNextLine = out.readNextLine(); final String readNextLine = out.readNextLine();
@@ -512,37 +498,33 @@ public class CLIPrompterTest {
assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$
buf.readLine()); buf.readLine());
in.type("2"); //$NON-NLS-1$ in.type("2"); //$NON-NLS-1$
th.join(); ThreadTest.assertRuns(th, runnable);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
/** Test method for /** Test method for
* {@link net.bigeon.gclc.prompt.CLIPrompter#promptInteger(net.bigeon.gclc.manager.ConsoleInput, String)}. */ * {@link net.bigeon.gclc.prompt.CLIPrompter#promptInteger(net.bigeon.gclc.manager.ConsoleInput, String)}.
*
* @throws IOException if errors */
@Test @Test
public final void testPromptInteger() { public final void testPromptInteger() throws IOException {
try (PipedOutputStream pout = new PipedOutputStream(); try (PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
BufferedReader buf = new BufferedReader( BufferedReader buf = new BufferedReader(
new InputStreamReader(pis, StandardCharsets.UTF_8)); new InputStreamReader(pis, StandardCharsets.UTF_8));
PipedConsoleInput in = new PipedConsoleInput(new PrintStream(pout))) { PipedConsoleInput in = new PipedConsoleInput(new PrintStream(pout))) {
final Thread th = new Thread(new Runnable() { final TestFunction func = new TestFunction() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertEquals("Asserted provided value to be retrieved", 10,
assertEquals("Asserted provided value to be retrieved", 10, CLIPrompter.promptInteger(in, "My message")); //$NON-NLS-1$
CLIPrompter.promptInteger(in, "My message")); //$NON-NLS-1$ assertEquals("Asserted provided value to be retrieved", -15,
assertEquals("Asserted provided value to be retrieved", -15, CLIPrompter.promptInteger(in, "My message")); //$NON-NLS-1$
CLIPrompter.promptInteger(in, "My message")); //$NON-NLS-1$
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable runnable = new FunctionalTestRunnable(func);
final Thread th = new Thread(runnable);
th.start(); th.start();
assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$
in.type(""); //$NON-NLS-1$ in.type(""); //$NON-NLS-1$
@@ -552,18 +534,16 @@ public class CLIPrompterTest {
in.type("10"); //$NON-NLS-1$ in.type("10"); //$NON-NLS-1$
assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$
in.type("-15"); //$NON-NLS-1$ in.type("-15"); //$NON-NLS-1$
th.join(); ThreadTest.assertRuns(th, runnable);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
/** Test method for /** Test method for
* {@link net.bigeon.gclc.prompt.CLIPrompter#promptList(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, String)}. */ * {@link net.bigeon.gclc.prompt.CLIPrompter#promptList(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, String)}.
*
* @throws IOException if errors */
@Test @Test
public final void testPromptListConsoleManagerString() { public final void testPromptListConsoleManagerString() throws IOException {
try (final PipedConsoleOutput out = new PipedConsoleOutput(); try (final PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
@@ -575,22 +555,19 @@ public class CLIPrompterTest {
keys.add("An other"); //$NON-NLS-1$ keys.add("An other"); //$NON-NLS-1$
final String message = "My message"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$
final Thread th = new Thread(new Runnable() { final TestFunction func = new TestFunction() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", new ArrayList<String>(),
new ArrayList<String>(), CLIPrompter.promptList(out, in, message));
CLIPrompter.promptList(out, in, message)); assertEquals("Asserted provided value to be retrieved", keys,
assertEquals("Asserted provided value to be retrieved", keys, CLIPrompter.promptList(out, in, message));
CLIPrompter.promptList(out, in, message));
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable runnable = new FunctionalTestRunnable(func);
final Thread th = new Thread(runnable);
th.start(); th.start();
String nLine = out.readNextLine(); String nLine = out.readNextLine();
assertTrue(nLine.startsWith(message)); assertTrue(nLine.startsWith(message));
@@ -614,17 +591,16 @@ public class CLIPrompterTest {
buf.readLine()); buf.readLine());
} }
in.type(CLIPrompterMessages.getString("promptlist.exit.defaultkey")); //$NON-NLS-1$ in.type(CLIPrompterMessages.getString("promptlist.exit.defaultkey")); //$NON-NLS-1$
th.join(); ThreadTest.assertRuns(th, runnable);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
/** Test method for /** Test method for
* {@link net.bigeon.gclc.prompt.CLIPrompter#promptList(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, String, String)}. */ * {@link net.bigeon.gclc.prompt.CLIPrompter#promptList(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, String, String)}.
*
* @throws IOException if errors */
@Test @Test
public final void testPromptListConsoleManagerStringString() { public final void testPromptListConsoleManagerStringString() throws IOException {
try (final PipedConsoleOutput out = new PipedConsoleOutput(); try (final PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
@@ -637,22 +613,19 @@ public class CLIPrompterTest {
final String ender = "*"; //$NON-NLS-1$ final String ender = "*"; //$NON-NLS-1$
final String message = "My message"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$
final Thread th = new Thread(new Runnable() { final TestFunction func = new TestFunction() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", new ArrayList<String>(),
new ArrayList<String>(), CLIPrompter.promptList(out, in, message, ender));
CLIPrompter.promptList(out, in, message, ender)); assertEquals("Asserted provided value to be retrieved", keys,
assertEquals("Asserted provided value to be retrieved", keys, CLIPrompter.promptList(out, in, message, ender));
CLIPrompter.promptList(out, in, message, ender));
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable runnable = new FunctionalTestRunnable(func);
final Thread th = new Thread(runnable);
th.start(); th.start();
String nLine = out.readNextLine(); String nLine = out.readNextLine();
assertTrue(nLine.startsWith(message)); assertTrue(nLine.startsWith(message));
@@ -674,17 +647,16 @@ public class CLIPrompterTest {
buf.readLine()); buf.readLine());
} }
in.type(ender); in.type(ender);
th.join(); ThreadTest.assertRuns(th, runnable);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
/** Test method for /** Test method for
* {@link net.bigeon.gclc.prompt.CLIPrompter#promptLongText(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, String)}. */ * {@link net.bigeon.gclc.prompt.CLIPrompter#promptLongText(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, String)}.
*
* @throws IOException if errors */
@Test @Test
public final void testPromptLongTextConsoleManagerString() { public final void testPromptLongTextConsoleManagerString() throws IOException {
try (final PipedConsoleOutput out = new PipedConsoleOutput(); try (final PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
@@ -696,22 +668,19 @@ public class CLIPrompterTest {
+ "line feeds and other" + System.lineSeparator() + "line feeds and other" + System.lineSeparator()
+ System.lineSeparator() + " \tspecial characters"; + System.lineSeparator() + " \tspecial characters";
final Thread th = new Thread(new Runnable() { final TestFunction func = new TestFunction() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertEquals("Asserted provided value to be retrieved", "",
assertEquals("Asserted provided value to be retrieved", "", CLIPrompter.promptLongText(out, in, message));
CLIPrompter.promptLongText(out, in, message)); assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", longText + System.lineSeparator(),
longText + System.lineSeparator(), CLIPrompter.promptLongText(out, in, message));
CLIPrompter.promptLongText(out, in, message));
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable runnable = new FunctionalTestRunnable(func);
final Thread th = new Thread(runnable);
th.start(); th.start();
String nLine = out.readNextLine(); String nLine = out.readNextLine();
assertTrue(nLine.startsWith(message)); assertTrue(nLine.startsWith(message));
@@ -736,17 +705,16 @@ public class CLIPrompterTest {
buf.readLine()); buf.readLine());
} }
in.type(CLIPrompterMessages.getString("promptlongtext.exit.defaultkey")); in.type(CLIPrompterMessages.getString("promptlongtext.exit.defaultkey"));
th.join(); ThreadTest.assertRuns(th, runnable);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
/** Test method for /** Test method for
* {@link net.bigeon.gclc.prompt.CLIPrompter#promptLongText(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, String, String)}. */ * {@link net.bigeon.gclc.prompt.CLIPrompter#promptLongText(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, String, String)}.
*
* @throws IOException if errors */
@Test @Test
public final void testPromptLongTextConsoleManagerStringString() { public final void testPromptLongTextConsoleManagerStringString() throws IOException {
try (final PipedConsoleOutput out = new PipedConsoleOutput(); try (final PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
@@ -760,22 +728,19 @@ public class CLIPrompterTest {
final String longText = text[0] + System.lineSeparator() + text[1] final String longText = text[0] + System.lineSeparator() + text[1]
+ System.lineSeparator() + text[2]; + System.lineSeparator() + text[2];
final Thread th = new Thread(new Runnable() { final TestFunction func = new TestFunction() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertEquals("Asserted provided value to be retrieved", //$NON-NLS-1$
assertEquals("Asserted provided value to be retrieved", //$NON-NLS-1$ "", CLIPrompter.promptLongText(out, in, message, ender));
"", CLIPrompter.promptLongText(out, in, message, ender)); assertEquals("Asserted provided value to be retrieved",
assertEquals("Asserted provided value to be retrieved", longText + System.lineSeparator(),
longText + System.lineSeparator(), CLIPrompter.promptLongText(out, in, message, ender));
CLIPrompter.promptLongText(out, in, message, ender));
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable runnable = new FunctionalTestRunnable(func);
final Thread th = new Thread(runnable);
th.start(); th.start();
String nLine = out.readNextLine(); String nLine = out.readNextLine();
assertTrue(nLine.startsWith(message)); assertTrue(nLine.startsWith(message));
@@ -797,17 +762,17 @@ public class CLIPrompterTest {
buf.readLine()); buf.readLine());
} }
in.type(ender); in.type(ender);
th.join(); ThreadTest.assertRuns(th, runnable);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
/** Test method for /** Test method for
* {@link net.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, List, List, String)}. */ * {@link net.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, List, List, String)}.
*
* @throws IOException if errors */
@Test @Test
public final void testPromptMultiChoiceConsoleManagerListOfStringListOfUString() { public final void testPromptMultiChoiceConsoleManagerListOfStringListOfUString()
throws IOException {
try (final PipedConsoleOutput out = new PipedConsoleOutput(); try (final PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
@@ -822,29 +787,24 @@ public class CLIPrompterTest {
choices.add("The actual other"); //$NON-NLS-1$ choices.add("The actual other"); //$NON-NLS-1$
final String message = "My message"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$
final Thread th = new Thread(new Runnable() { final TestFunction func = new TestFunction() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertTrue("Asserted provided value to be retrieved",
assertTrue("Asserted provided value to be retrieved", CLIPrompter CLIPrompter.promptMultiChoice(out, in, keys, choices, message)
.promptMultiChoice(out, in, keys, choices, message) .isEmpty());
.isEmpty()); final ArrayList<Object> l = new ArrayList<>();
final ArrayList<Object> l = new ArrayList<>(); l.add(choices.get(0));
l.add(choices.get(0)); assertEquals("Asserted provided value to be retrieved", l, CLIPrompter
assertEquals("Asserted provided value to be retrieved", l, .promptMultiChoice(out, in, keys, choices, message));
CLIPrompter.promptMultiChoice(out, in, keys, choices, l.add(choices.get(1));
message)); assertEquals("Asserted provided value to be retrieved", l, CLIPrompter
l.add(choices.get(1)); .promptMultiChoice(out, in, keys, choices, message));
assertEquals("Asserted provided value to be retrieved", l,
CLIPrompter.promptMultiChoice(out, in, keys, choices,
message));
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable runnable = new FunctionalTestRunnable(func);
final Thread th = new Thread(runnable);
th.start(); th.start();
assertTrue(out.readNextLine().startsWith(message)); assertTrue(out.readNextLine().startsWith(message));
assertTrue(out.readNextLine().contains(keys.get(0))); assertTrue(out.readNextLine().contains(keys.get(0)));
@@ -885,17 +845,17 @@ public class CLIPrompterTest {
assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$
buf.readLine()); buf.readLine());
in.type("0 1"); //$NON-NLS-1$ in.type("0 1"); //$NON-NLS-1$
th.join(); ThreadTest.assertRuns(th, runnable);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
/** Test method for /** Test method for
* {@link net.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, List, Map, String)}. */ * {@link net.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, List, Map, String)}.
*
* @throws IOException if errors */
@Test @Test
public final void testPromptMultiChoiceConsoleManagerListOfUMapOfUTString() { public final void testPromptMultiChoiceConsoleManagerListOfUMapOfUTString()
throws IOException {
try (final PipedConsoleOutput out = new PipedConsoleOutput(); try (final PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
@@ -909,30 +869,24 @@ public class CLIPrompterTest {
keys.add("An other"); //$NON-NLS-1$ keys.add("An other"); //$NON-NLS-1$
choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$
final String message = "My message"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$
final TestFunction func = new TestFunction() {
final Thread th = new Thread(new Runnable() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertTrue("Asserted provided value to be retrieved",
assertTrue("Asserted provided value to be retrieved", CLIPrompter CLIPrompter.promptMultiChoice(out, in, keys, choices, message)
.promptMultiChoice(out, in, keys, choices, message) .isEmpty());
.isEmpty()); final ArrayList<Object> l = new ArrayList<>();
final ArrayList<Object> l = new ArrayList<>(); l.add(choices.get(keys.get(0)));
l.add(choices.get(keys.get(0))); assertEquals("Asserted provided value to be retrieved", l, CLIPrompter
assertEquals("Asserted provided value to be retrieved", l, .promptMultiChoice(out, in, keys, choices, message));
CLIPrompter.promptMultiChoice(out, in, keys, choices, l.add(choices.get(keys.get(1)));
message)); assertEquals("Asserted provided value to be retrieved", l, CLIPrompter
l.add(choices.get(keys.get(1))); .promptMultiChoice(out, in, keys, choices, message));
assertEquals("Asserted provided value to be retrieved", l,
CLIPrompter.promptMultiChoice(out, in, keys, choices,
message));
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable target = new FunctionalTestRunnable(func);
final Thread th = new Thread(target);
th.start(); th.start();
assertTrue(out.readNextLine().startsWith(message)); assertTrue(out.readNextLine().startsWith(message));
assertTrue(out.readNextLine().contains(keys.get(0).toString())); assertTrue(out.readNextLine().contains(keys.get(0).toString()));
@@ -973,17 +927,17 @@ public class CLIPrompterTest {
assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$
buf.readLine()); buf.readLine());
in.type("0 1"); //$NON-NLS-1$ in.type("0 1"); //$NON-NLS-1$
th.join(); ThreadTest.assertRuns(th, target);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
/** Test method for /** Test method for
* {@link net.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, List, String)}. */ * {@link net.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(net.bigeon.gclc.manager.ConsoleOutput, net.bigeon.gclc.manager.ConsoleInput, List, String)}.
*
* @throws IOException if error */
@Test @Test
public final void testPromptMultiChoiceConsoleManagerListOfUString() { public final void testPromptMultiChoiceConsoleManagerListOfUString()
throws IOException {
try (final PipedConsoleOutput out = new PipedConsoleOutput(); try (final PipedConsoleOutput out = new PipedConsoleOutput();
PipedOutputStream pout = new PipedOutputStream(); PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pout); PipedInputStream pis = new PipedInputStream(pout);
@@ -994,27 +948,23 @@ public class CLIPrompterTest {
keys.add("A choice"); //$NON-NLS-1$ keys.add("A choice"); //$NON-NLS-1$
keys.add("An other"); //$NON-NLS-1$ keys.add("An other"); //$NON-NLS-1$
final String message = "My message"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$
final TestFunction func = new TestFunction() {
final Thread th = new Thread(new Runnable() {
@Override @Override
public void run() { public void apply() throws Exception {
try { assertTrue("Asserted provided value to be retrieved", CLIPrompter
assertTrue("Asserted provided value to be retrieved", CLIPrompter .promptMultiChoice(out, in, keys, message).isEmpty());
.promptMultiChoice(out, in, keys, message).isEmpty()); final ArrayList<Integer> l = new ArrayList<>();
final ArrayList<Integer> l = new ArrayList<>(); l.add(0);
l.add(0); assertEquals("Asserted provided value to be retrieved", l,
assertEquals("Asserted provided value to be retrieved", l, CLIPrompter.promptMultiChoice(out, in, keys, message));
CLIPrompter.promptMultiChoice(out, in, keys, message)); l.add(1);
l.add(1); assertEquals("Asserted provided value to be retrieved", l,
assertEquals("Asserted provided value to be retrieved", l, CLIPrompter.promptMultiChoice(out, in, keys, message));
CLIPrompter.promptMultiChoice(out, in, keys, message));
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final ATestRunnable target = new FunctionalTestRunnable(func);
final Thread th = new Thread(target);
th.start(); th.start();
assertTrue(out.readNextLine().startsWith(message)); assertTrue(out.readNextLine().startsWith(message));
assertTrue(out.readNextLine().contains(keys.get(0).toString())); assertTrue(out.readNextLine().contains(keys.get(0).toString()));
@@ -1055,10 +1005,7 @@ public class CLIPrompterTest {
assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$
buf.readLine()); buf.readLine());
in.type("0 1"); //$NON-NLS-1$ in.type("0 1"); //$NON-NLS-1$
th.join(); ThreadTest.assertRuns(th, target);
} catch (IOException | InterruptedException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace();
} }
} }
@@ -1080,11 +1027,10 @@ public class CLIPrompterTest {
choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$
final String message = "My message"; //$NON-NLS-1$ final String message = "My message"; //$NON-NLS-1$
final Thread th = new Thread(new Runnable() { final ATestRunnable target = new ATestRunnable() {
@Override @Override
public void run() { public void testRun() throws IOException {
try {
assertTrue("Asserted provided value to be retrieved", CLIPrompter assertTrue("Asserted provided value to be retrieved", CLIPrompter
.promptMultiChoice(out, in, keys, choices, message) .promptMultiChoice(out, in, keys, choices, message)
.isEmpty()); .isEmpty());
@@ -1097,12 +1043,9 @@ public class CLIPrompterTest {
assertEquals("Asserted provided value to be retrieved", l, assertEquals("Asserted provided value to be retrieved", l,
CLIPrompter.promptMultiChoice(out, in, keys, choices, CLIPrompter.promptMultiChoice(out, in, keys, choices,
message)); message));
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final Thread th = new Thread(target);
th.start(); th.start();
assertTrue(out.readNextLine().startsWith(message)); assertTrue(out.readNextLine().startsWith(message));
final String readNextLine = out.readNextLine(); final String readNextLine = out.readNextLine();
@@ -1135,8 +1078,8 @@ public class CLIPrompterTest {
assertTrue(out.readNextLine().contains(keys.get(0).toString())); assertTrue(out.readNextLine().contains(keys.get(0).toString()));
assertTrue(out.readNextLine().contains(keys.get(1).toString())); assertTrue(out.readNextLine().contains(keys.get(1).toString()));
in.type("0 1"); //$NON-NLS-1$ in.type("0 1"); //$NON-NLS-1$
th.join(); ThreadTest.assertRuns(th, target);
} catch (IOException | InterruptedException e) { } catch (final IOException e) {
fail("Unexpected excpetion, the other thread probably failed"); //$NON-NLS-1$ fail("Unexpected excpetion, the other thread probably failed"); //$NON-NLS-1$
e.printStackTrace(); e.printStackTrace();
} }
@@ -1152,28 +1095,24 @@ public class CLIPrompterTest {
new InputStreamReader(pis, StandardCharsets.UTF_8)); new InputStreamReader(pis, StandardCharsets.UTF_8));
PipedConsoleInput in = new PipedConsoleInput(new PrintStream(pout))) { PipedConsoleInput in = new PipedConsoleInput(new PrintStream(pout))) {
final String res = "some content"; //$NON-NLS-1$ final String res = "some content"; //$NON-NLS-1$
final Thread th = new Thread(new Runnable() { final ATestRunnable target = new ATestRunnable() {
@Override @Override
public void run() { public void testRun() throws IOException {
try {
assertEquals("Expected provided message to be returned", res, assertEquals("Expected provided message to be returned", res,
CLIPrompter.promptNonEmpty(in, "My message", //$NON-NLS-1$ CLIPrompter.promptNonEmpty(in, "My message", //$NON-NLS-1$
"my reprompt")); //$NON-NLS-1$ "my reprompt")); //$NON-NLS-1$
} catch (final IOException e) {
fail("Unexpected io excpetion"); //$NON-NLS-1$
e.printStackTrace();
}
} }
}); };
final Thread th = new Thread(target);
th.start(); th.start();
assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$
in.type(""); //$NON-NLS-1$ in.type(""); //$NON-NLS-1$
assertTrue(buf.readLine().startsWith("my reprompt")); //$NON-NLS-1$ assertTrue(buf.readLine().startsWith("my reprompt")); //$NON-NLS-1$
in.type(res); in.type(res);
th.join(); ThreadTest.assertRuns(th, target);
} catch (IOException | InterruptedException e) { } catch (final IOException e) {
fail("Unexpected excpetion"); //$NON-NLS-1$ fail("Unexpected excpetion"); //$NON-NLS-1$
e.printStackTrace(); e.printStackTrace();
} }

View File

@@ -1,6 +1,7 @@
package net.bigeon.gclc.utils; package net.bigeon.gclc.utils;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.io.IOException; import java.io.IOException;
@@ -8,13 +9,12 @@ import org.junit.Test;
import net.bigeon.gclc.manager.ConsoleInput; import net.bigeon.gclc.manager.ConsoleInput;
import net.bigeon.gclc.tools.ConstantString; import net.bigeon.gclc.tools.ConstantString;
import net.bigeon.gclc.utils.EmptyInput;
public class EmptyInputTest { public class EmptyInputTest {
@Test @Test
public void testClose() throws IOException { public void testClose() throws IOException {
ConsoleInput input = EmptyInput.INSTANCE; final ConsoleInput input = EmptyInput.INSTANCE;
// several close operation shold create no error // several close operation shold create no error
input.close(); input.close();
input.close(); input.close();
@@ -24,19 +24,19 @@ public class EmptyInputTest {
@Test @Test
public void testGetPrompt() { public void testGetPrompt() {
ConsoleInput input = EmptyInput.INSTANCE; final ConsoleInput input = EmptyInput.INSTANCE;
String init = input.getPrompt().apply(); final String init = input.getPrompt().get();
input.setPrompt("some prompt different from "+init); input.setPrompt("some prompt different from "+init);
assertEquals("Prompts should not be changed", init, input.getPrompt().apply()); assertEquals("Prompts should not be changed", init, input.getPrompt().get());
input.setPrompt(new ConstantString("some other prompt different from "+init)); input.setPrompt(new ConstantString("some other prompt different from "+init));
assertEquals("Prompts should not be changed", init, input.getPrompt().apply()); assertEquals("Prompts should not be changed", init, input.getPrompt().get());
} }
@Test @Test
public void testInterruptPrompt() { public void testInterruptPrompt() {
// Nothing to test, really... // Nothing to test, really...
ConsoleInput input = EmptyInput.INSTANCE; final ConsoleInput input = EmptyInput.INSTANCE;
// several close operation shold create no error // several close operation shold create no error
input.interruptPrompt(); input.interruptPrompt();
assertFalse("This source input should never be closed", input.isClosed()); assertFalse("This source input should never be closed", input.isClosed());
@@ -44,7 +44,7 @@ public class EmptyInputTest {
@Test @Test
public void testIsClosed() throws IOException { public void testIsClosed() throws IOException {
ConsoleInput input = EmptyInput.INSTANCE; final ConsoleInput input = EmptyInput.INSTANCE;
// several close operation shold create no error // several close operation shold create no error
assertFalse("This source input should never be closed", input.isClosed()); assertFalse("This source input should never be closed", input.isClosed());
input.close(); input.close();
@@ -55,7 +55,7 @@ public class EmptyInputTest {
@Test @Test
public void testPrompt() throws IOException { public void testPrompt() throws IOException {
ConsoleInput input = EmptyInput.INSTANCE; final ConsoleInput input = EmptyInput.INSTANCE;
// several close operation shold create no error // several close operation shold create no error
assertEquals("Any prompt should return the empty value", "", input.prompt()); assertEquals("Any prompt should return the empty value", "", input.prompt());
assertEquals("Any prompt should return the empty value", "", input.prompt(0)); assertEquals("Any prompt should return the empty value", "", input.prompt(0));