Compare commits
113 Commits
gclc-1.2.2
...
gclc-1.3.7
| Author | SHA1 | Date | |
|---|---|---|---|
| 0a995394f9 | |||
| 0ca055db8e | |||
| b93c2b5220 | |||
| 8322454f72 | |||
| ab47d6573b | |||
| 6d496d701d | |||
| b4df39491e | |||
| 775a71b2ec | |||
| c9eb221d31 | |||
| 340a0317af | |||
| 35959a8d8a | |||
| 07645d7c0c | |||
| 99c0c9008b | |||
| 26265ad7e6 | |||
| 092883f4c3 | |||
| 25904c907d | |||
| ae55ebea29 | |||
| e989aff2f4 | |||
| 2f0c03a73b | |||
| ff9ace1033 | |||
| ffa54af3be | |||
| 269704f5a2 | |||
| aecc18cc83 | |||
| 063cad61cd | |||
| 201b6ad366 | |||
| bf8d76750f | |||
| 17ac47f15e | |||
| 7de2dadbe0 | |||
| 50395ba852 | |||
| 248c82cf50 | |||
| 6289ca1db9 | |||
| 5b6634eaf0 | |||
| 4737a16874 | |||
| bf0a3b30e5 | |||
| 5d25971b56 | |||
| c27872de94 | |||
| a12484a72a | |||
| ee0d91e455 | |||
| 719d7ada3f | |||
| c877450b2b | |||
| f3a8aafce1 | |||
| d2bc86fffc | |||
| 3b6ba337f1 | |||
| 6a117afcb3 | |||
| 7d41a9f4c6 | |||
| 90579d79a9 | |||
| b2c98ae940 | |||
| 1d6569cf69 | |||
| 072653c944 | |||
| ad17c7d5d7 | |||
| e469313baf | |||
| 543b1ef605 | |||
| 24f1fba97e | |||
| 88fe564e24 | |||
| efa492570e | |||
| d07795cb6a | |||
| f3c3580855 | |||
| 62f59722a6 | |||
| 3e31a38eb9 | |||
| 549ddc3e6f | |||
| d300e896e8 | |||
| 16514f9c25 | |||
| bb9f9c515b | |||
| 77c5ae64dd | |||
| 18c7f89564 | |||
| 5f185b52e9 | |||
| 2f5ea369b7 | |||
| ef708c3291 | |||
| 9e040d80c4 | |||
| e3ced7b961 | |||
| c9b2270786 | |||
| 99ebb23138 | |||
| d4f428d311 | |||
| e602a269f8 | |||
| d432914828 | |||
| 0cf54c4837 | |||
| c1692019a6 | |||
| 72362936be | |||
| 65b6be8283 | |||
| fd8dde32f1 | |||
| fff9f4ea74 | |||
| 9e5d8c4ca4 | |||
| a70be63894 | |||
| c2fa0f2c0b | |||
| 5280ee98bd | |||
| 1a207c8100 | |||
| 80d10d7d85 | |||
| ecc10994ca | |||
| 7289fc12ad | |||
| f44366ff05 | |||
| 70a71c06a7 | |||
| a0202de532 | |||
| caa00f2a61 | |||
| eed6f43aea | |||
| 59ab689a36 | |||
| 2bf1fa7c80 | |||
| 32e5f777fe | |||
| f8aeef14e3 | |||
| 763b7361ec | |||
| c151107207 | |||
| f95d2f114a | |||
| e04e7ceaa5 | |||
| 3c1c8e85c8 | |||
| 095a363520 | |||
| 932780e9d9 | |||
| d404d0ab69 | |||
| 8038db26f3 | |||
| a29fe4b458 | |||
| 4ddce780e0 | |||
| 12326b7cba | |||
| 04fcb5bedd | |||
| fef08dd29a | |||
| 801189fdeb |
@@ -67,39 +67,37 @@ of Emmanuel Bigeon. -->
|
||||
<!-- 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>
|
||||
<artifactId>gclc-socket</artifactId>
|
||||
<version>1.0.4-SNAPSHOT</version>
|
||||
<version>1.1.8-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://www.bigeon.fr/emmanuel</url>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.scm.id>git.bigeon.net</project.scm.id>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.11</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>fr.bigeon</groupId>
|
||||
<artifactId>gclc</artifactId>
|
||||
<version>1.2.1</version>
|
||||
<version>1.3.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>fr.bigeon</groupId>
|
||||
<artifactId>smu</artifactId>
|
||||
<version>0.0.4</version>
|
||||
<version>0.0.5</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<parent>
|
||||
<groupId>fr.bigeon</groupId>
|
||||
<artifactId>ebigeon-config</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<version>1.7.1</version>
|
||||
</parent>
|
||||
<name>GCLC Socket</name>
|
||||
<description>Socket implementation of GCLC</description>
|
||||
<scm>
|
||||
<developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection>
|
||||
<tag>HEAD</tag>
|
||||
</scm>
|
||||
</project>
|
||||
|
||||
@@ -38,6 +38,9 @@
|
||||
*/
|
||||
package fr.bigeon.gclc.socket;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import fr.bigeon.gclc.ConsoleApplication;
|
||||
|
||||
/** A runnable class that will actually have the application running.
|
||||
@@ -45,27 +48,49 @@ import fr.bigeon.gclc.ConsoleApplication;
|
||||
* @author Emmanuel Bigeon */
|
||||
public class ConsoleRunnable implements Runnable {
|
||||
|
||||
/** The wait timeout */
|
||||
private static final long TIMEOUT = 100;
|
||||
/** The logger */
|
||||
private static final Logger LOGGER = Logger
|
||||
.getLogger(ConsoleRunnable.class.getName());
|
||||
/** The actual application */
|
||||
private final ConsoleApplication app;
|
||||
/** The synchronization object */
|
||||
private final Object promptingLock;
|
||||
/** The synchro object */
|
||||
private final Object lock = new Object();
|
||||
/** the state of this runnable */
|
||||
private boolean running = true;
|
||||
/** If a start is required */
|
||||
private boolean startReq;
|
||||
|
||||
/** @param app the application
|
||||
* @param promptingLock the synchronization object */
|
||||
public ConsoleRunnable(ConsoleApplication app, Object promptingLock) {
|
||||
/** @param app the application */
|
||||
public ConsoleRunnable(ConsoleApplication app) {
|
||||
super();
|
||||
this.app = app;
|
||||
this.promptingLock = promptingLock;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see java.lang.Runnable#run() */
|
||||
@Override
|
||||
public void run() {
|
||||
while (running) {
|
||||
synchronized (lock) {
|
||||
while (running && !startReq) {
|
||||
try {
|
||||
lock.wait(TIMEOUT);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE,
|
||||
"Console application runnable interrupted wildly!", //$NON-NLS-1$
|
||||
e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
startReq = false;
|
||||
if (!running) {
|
||||
return;
|
||||
}
|
||||
lock.notify();
|
||||
}
|
||||
app.start();
|
||||
synchronized (promptingLock) {
|
||||
// release all waiting elements before ending
|
||||
promptingLock.notifyAll();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,4 +99,35 @@ public class ConsoleRunnable implements Runnable {
|
||||
app.exit();
|
||||
}
|
||||
|
||||
/** @return if the application is running */
|
||||
public boolean isApplicationRunning() {
|
||||
return app.isRunning();
|
||||
}
|
||||
|
||||
/** @param running the running to set */
|
||||
public void setRunning(boolean running) {
|
||||
synchronized (lock) {
|
||||
this.running = running;
|
||||
}
|
||||
}
|
||||
|
||||
/** @return the running */
|
||||
public boolean isRunning() {
|
||||
synchronized (lock) {
|
||||
return running;
|
||||
}
|
||||
}
|
||||
|
||||
/** Request a restart of application */
|
||||
public void restart() {
|
||||
synchronized (lock) {
|
||||
startReq = true;
|
||||
lock.notify();
|
||||
try {
|
||||
lock.wait(TIMEOUT);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE, "Restart wait interrupted!", e); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,23 +35,21 @@
|
||||
package fr.bigeon.gclc.socket;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.PipedInputStream;
|
||||
import java.io.PipedOutputStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketException;
|
||||
import java.util.Arrays;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import fr.bigeon.gclc.ConsoleApplication;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
import fr.bigeon.smu.StringEncoder;
|
||||
import fr.bigeon.gclc.manager.PipedConsoleManager;
|
||||
import fr.bigeon.gclc.manager.ReadingRunnable;
|
||||
|
||||
/** This is a socket communicating console consoleManager
|
||||
* <p>
|
||||
@@ -71,36 +69,68 @@ import fr.bigeon.smu.StringEncoder;
|
||||
* end of the execution.
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class SocketConsoleApplicationShell implements Runnable {
|
||||
public class SocketConsoleApplicationShell implements Runnable, AutoCloseable {
|
||||
|
||||
/** The runnable to forward output of application to socket.
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
private final class OutputForwardRunnable implements Runnable {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final String INTERRUPTION_WHILE_WORKING = "Interruption while application was working"; //$NON-NLS-1$
|
||||
private final PrintWriter writer;
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private final Socket socket;
|
||||
|
||||
/** @param writer the writer
|
||||
* @param socket the socket */
|
||||
protected OutputForwardRunnable(PrintWriter writer, Socket socket) {
|
||||
this.writer = writer;
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while (!socket.isClosed()) {
|
||||
while (!socket.isClosed() && !consoleManager.available()) {
|
||||
waitASec();
|
||||
}
|
||||
if (socket.isClosed()) {
|
||||
return;
|
||||
}
|
||||
String m = consoleManager.readNextLine();
|
||||
writer.println(m);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOGGER.log(Level.SEVERE, "Unexpected problem in manager", //$NON-NLS-1$
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/** The end of line character */
|
||||
protected static final String EOL = "\n"; //$NON-NLS-1$
|
||||
/** The encoder */
|
||||
private static final StringEncoder ENCODER = new StringEncoder("%", //$NON-NLS-1$
|
||||
Arrays.asList(EOL));
|
||||
/** The class logger */
|
||||
private static final Logger LOGGER = Logger
|
||||
.getLogger(SocketConsoleApplicationShell.class.getName());
|
||||
/** Time of wait */
|
||||
protected static final long ONE_TENTH_OF_SECOND = 100;
|
||||
/** The listening port */
|
||||
private final int port;
|
||||
/** The input */
|
||||
private final PipedInputStream consoleInput = new PipedInputStream();
|
||||
/** The application */
|
||||
private ConsoleApplication app;
|
||||
/** The session closing command */
|
||||
private final String close;
|
||||
/** The running status */
|
||||
private boolean running;
|
||||
/** An object to lock on for prompt */
|
||||
private final Object promptingLock = new Object();
|
||||
|
||||
/** The console manager implementation */
|
||||
private final ThreadedServerConsoleManager consoleManager = new ThreadedServerConsoleManager(
|
||||
ENCODER, promptingLock);
|
||||
private final PipedConsoleManager consoleManager;
|
||||
/** The auto close flag. if this is true, every request closes the session
|
||||
* after its call */
|
||||
private final boolean autoClose;
|
||||
@@ -108,19 +138,26 @@ public class SocketConsoleApplicationShell implements Runnable {
|
||||
private ServerSocket serverSocket;
|
||||
/** The application shutdown string */
|
||||
private final String applicationShutdown;
|
||||
/** The charset for the communication. */
|
||||
private final Charset charset;
|
||||
|
||||
/** Create a socket application shell which will listen on the given port
|
||||
* and close session upon the provided string reception by client
|
||||
*
|
||||
* @param port the port to listen to
|
||||
* @param close the session closing command
|
||||
* @param applicationShutdown the appication shut down command */
|
||||
* @param applicationShutdown the appication shut down command
|
||||
* @param charset the charset for communication
|
||||
* @throws IOException if the manager could not be created */
|
||||
public SocketConsoleApplicationShell(int port, String close,
|
||||
String applicationShutdown) {
|
||||
String applicationShutdown, Charset charset) throws IOException {
|
||||
this.port = port;
|
||||
this.close = close;
|
||||
this.applicationShutdown = applicationShutdown;
|
||||
this.autoClose = false;
|
||||
this.charset = charset;
|
||||
//
|
||||
consoleManager = new PipedConsoleManager();
|
||||
}
|
||||
|
||||
/** Create a socket application shell which will listen on the given port
|
||||
@@ -129,147 +166,186 @@ public class SocketConsoleApplicationShell implements Runnable {
|
||||
* @param port the port to listen to
|
||||
* @param autoClose if the session must be closed once the request has been
|
||||
* sent
|
||||
* @param applicationShutdown the application shutdown command */
|
||||
* @param applicationShutdown the appication shut down command
|
||||
* @param charset the charset for communication
|
||||
* @throws IOException if the manager could not be created */
|
||||
public SocketConsoleApplicationShell(int port, boolean autoClose,
|
||||
String applicationShutdown) {
|
||||
String applicationShutdown, Charset charset) throws IOException {
|
||||
this.port = port;
|
||||
this.autoClose = autoClose;
|
||||
this.applicationShutdown = applicationShutdown;
|
||||
this.close = autoClose ? null : "close"; //$NON-NLS-1$
|
||||
this.charset = charset;
|
||||
//
|
||||
consoleManager = new PipedConsoleManager();
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see java.lang.Runnable#run() */
|
||||
@Override
|
||||
public void run() {
|
||||
// Create the server
|
||||
try (ServerSocket actualServerSocket = new ServerSocket(port)) {
|
||||
this.serverSocket = actualServerSocket;
|
||||
running = true;
|
||||
try (PipedOutputStream outStream = new PipedOutputStream();
|
||||
BufferedWriter writer = new BufferedWriter(
|
||||
new OutputStreamWriter(outStream))) {
|
||||
consoleInput.connect(outStream);
|
||||
try (InputStreamReader isr = new InputStreamReader(
|
||||
consoleInput);
|
||||
BufferedReader inBuf = new BufferedReader(isr);) {
|
||||
consoleManager.setInput(inBuf);
|
||||
runSokectServer(writer);
|
||||
// Close the application
|
||||
// Pass command to application
|
||||
if (app.isRunning()) {
|
||||
writer.write(applicationShutdown + EOL);
|
||||
writer.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
// Create the streams
|
||||
runSokectServer();
|
||||
} catch (final IOException e) {
|
||||
LOGGER.log(Level.SEVERE,
|
||||
LOGGER.severe("Communication error between client and server"); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE,
|
||||
"Communication error between client and server", e); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
|
||||
/** @param appTh the application thread
|
||||
* @param writer the writer to the application
|
||||
* @throws IOException if the communication with the client failed */
|
||||
private void runSokectServer(BufferedWriter writer) throws IOException {
|
||||
final ConsoleRunnable runnable = new ConsoleRunnable(app,
|
||||
promptingLock);
|
||||
Thread appThOld = null;
|
||||
Thread appThNext = new Thread(runnable);
|
||||
/** @throws IOException if the communication with the client failed */
|
||||
private void runSokectServer() throws IOException {
|
||||
final ConsoleRunnable runnable = new ConsoleRunnable(app);
|
||||
Thread appThNext = new Thread(runnable, "gclc-ctrl"); //$NON-NLS-1$
|
||||
appThNext.start();
|
||||
while (running) {
|
||||
LOGGER.info("Waiting client"); //$NON-NLS-1$
|
||||
try (Socket clientSocket = serverSocket.accept();
|
||||
PrintWriter out = new PrintWriter(
|
||||
clientSocket.getOutputStream(), true);
|
||||
PrintWriter out = new PrintWriter(new OutputStreamWriter(
|
||||
clientSocket.getOutputStream(), charset), true);
|
||||
InputStreamReader isr = new InputStreamReader(
|
||||
clientSocket.getInputStream());
|
||||
clientSocket.getInputStream(), charset);
|
||||
BufferedReader in = new BufferedReader(isr);) {
|
||||
// this is not threaded to avoid several clients at the same
|
||||
// time
|
||||
consoleManager.setOutput(out);
|
||||
LOGGER.info("Opening client"); //$NON-NLS-1$
|
||||
|
||||
// Initiate application
|
||||
if (appThOld == null || !appThOld.isAlive()) {
|
||||
appThNext.start();
|
||||
// Prepare next start
|
||||
appThOld = appThNext;
|
||||
appThNext = new Thread(runnable);
|
||||
if (!runnable.isApplicationRunning()) {
|
||||
LOGGER.info("Start application"); //$NON-NLS-1$
|
||||
startApplication(runnable);
|
||||
} else {
|
||||
LOGGER.info("Reconnect to application"); //$NON-NLS-1$
|
||||
out.println("Reconnected"); //$NON-NLS-1$
|
||||
out.println(consoleManager.getPrompt());
|
||||
}
|
||||
communicate(writer, in);
|
||||
communicate(clientSocket, out, in);
|
||||
} catch (SocketException e) {
|
||||
LOGGER.log(Level.INFO, "Socket closed", e); //$NON-NLS-1$
|
||||
LOGGER.log(Level.INFO, "Socket closed"); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE,
|
||||
"Socket closed with exception (probably due to server interruption)", //$NON-NLS-1$
|
||||
e);
|
||||
} catch (IOException e) {
|
||||
throw e;
|
||||
}
|
||||
LOGGER.info("Closing client"); //$NON-NLS-1$
|
||||
}
|
||||
runnable.setRunning(false);
|
||||
try {
|
||||
consoleManager.type(applicationShutdown);
|
||||
try {
|
||||
appThNext.join(ONE_TENTH_OF_SECOND);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.warning("Application thread was interrupted!"); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE,
|
||||
"Application thread was interrupted while closing", //$NON-NLS-1$
|
||||
e);
|
||||
}
|
||||
consoleManager.close();
|
||||
} catch (IOException e) {
|
||||
LOGGER.warning("Unable to close application correctly"); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE, "Application closing caused an exception", //$NON-NLS-1$
|
||||
e);
|
||||
}
|
||||
LOGGER.info("Closing Server"); //$NON-NLS-1$
|
||||
}
|
||||
|
||||
/** @param runnable the runnable */
|
||||
private void startApplication(ConsoleRunnable runnable) {
|
||||
runnable.restart();
|
||||
synchronized (this) {
|
||||
try {
|
||||
wait(ONE_TENTH_OF_SECOND);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE, "Interruption in application start", //$NON-NLS-1$
|
||||
e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** active communication between server and client
|
||||
*
|
||||
* @param socket the socket
|
||||
* @param writer the writer to the application
|
||||
* @param in the input from the client
|
||||
* @throws IOException if the communication failed */
|
||||
private void communicate(BufferedWriter writer,
|
||||
private void communicate(final Socket socket, final PrintWriter writer,
|
||||
BufferedReader in) throws IOException {
|
||||
synchronized (promptingLock) {
|
||||
if (!consoleManager.isPrompting()) {
|
||||
try {
|
||||
// wait for application to finish its operation
|
||||
promptingLock.wait();
|
||||
} catch (final InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE, INTERRUPTION_WHILE_WORKING, e);
|
||||
}
|
||||
}
|
||||
OutputForwardRunnable cc = new OutputForwardRunnable(writer, socket);
|
||||
Thread th = new Thread(cc, "ClientComm"); //$NON-NLS-1$
|
||||
th.start();
|
||||
if (autoClose) {
|
||||
communicateOnce(in, writer);
|
||||
communicateOnce(in);
|
||||
} else {
|
||||
communicateLoop(in, writer);
|
||||
}
|
||||
communicateLoop(in);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param in the input from the client
|
||||
* @param writer the output to the client
|
||||
* @throws IOException if the communication failed */
|
||||
private void communicateOnce(BufferedReader in,
|
||||
BufferedWriter writer) throws IOException {
|
||||
String ln;
|
||||
if ((ln = in.readLine()) != null) {
|
||||
if (ln.equals(close)) {
|
||||
return;
|
||||
private void communicateOnce(BufferedReader in) throws IOException {
|
||||
ReadingRunnable reading = new ReadingRunnable(in);
|
||||
Thread th = new Thread(reading, "gclcToApp"); //$NON-NLS-1$
|
||||
th.start();
|
||||
communicationContent(reading);
|
||||
doEndCommunication(reading);
|
||||
}
|
||||
// Pass command to application
|
||||
writer.write(ln + EOL);
|
||||
writer.flush();
|
||||
|
||||
/** @param reading the reading runnable
|
||||
* @throws IOException if the end of communication failed */
|
||||
private void doEndCommunication(ReadingRunnable reading) throws IOException {
|
||||
reading.setRunning(false);
|
||||
Thread wait = consoleManager.getWaitForDelivery("Bye."); //$NON-NLS-1$
|
||||
consoleManager.println("Bye."); //$NON-NLS-1$
|
||||
try {
|
||||
// Wait for application process to
|
||||
// finish
|
||||
promptingLock.wait();
|
||||
} catch (final InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE, INTERRUPTION_WHILE_WORKING, e);
|
||||
}
|
||||
wait.join();
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.warning("The Bye wait was interrupted."); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE, "An interruption occured", e); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
|
||||
/** @param in the input from the client
|
||||
* @param writer the output to the client
|
||||
* @throws IOException if the communication failed */
|
||||
private void communicateLoop(BufferedReader in,
|
||||
BufferedWriter writer) throws IOException {
|
||||
String ln;
|
||||
while (app.isRunning() && (ln = in.readLine()) != null) {
|
||||
private void communicateLoop(BufferedReader in) throws IOException {
|
||||
ReadingRunnable reading = new ReadingRunnable(in);
|
||||
Thread th = new Thread(reading, "gclcToApp"); //$NON-NLS-1$
|
||||
th.start();
|
||||
while (app.isRunning() && communicationContent(reading)) {
|
||||
// keep on going
|
||||
}
|
||||
doEndCommunication(reading);
|
||||
}
|
||||
|
||||
/** @param reading the reading
|
||||
* @return if the communication should be stopped.
|
||||
* @throws IOException if the reading failed */
|
||||
private boolean communicationContent(ReadingRunnable reading) throws IOException {
|
||||
try {
|
||||
while (app.isRunning() && !reading.hasMessage()) {
|
||||
synchronized (this) {
|
||||
waitASec();
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOGGER.warning("Client seems dead. Closing communication"); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE, "Wait on message from client failed", e); //$NON-NLS-1$
|
||||
return false;
|
||||
}
|
||||
if (!app.isRunning()) {
|
||||
return false;
|
||||
}
|
||||
String ln = reading.getMessage();
|
||||
if (ln.equals(close)) {
|
||||
break;
|
||||
return false;
|
||||
}
|
||||
// Pass command to application
|
||||
writer.write(ln + EOL);
|
||||
writer.flush();
|
||||
try {
|
||||
// Wait for application process to
|
||||
// finish
|
||||
promptingLock.wait();
|
||||
} catch (final InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE, INTERRUPTION_WHILE_WORKING, e);
|
||||
}
|
||||
}
|
||||
consoleManager.type(ln);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return the consoleManager */
|
||||
@@ -293,10 +369,26 @@ public class SocketConsoleApplicationShell implements Runnable {
|
||||
} catch (IOException e) {
|
||||
LOGGER.log(Level.SEVERE, "Exception in closing socket server", e); //$NON-NLS-1$
|
||||
}
|
||||
synchronized (promptingLock) {
|
||||
promptingLock.notifyAll();
|
||||
}
|
||||
app.exit();
|
||||
}
|
||||
|
||||
/** a method to wait some time */
|
||||
protected void waitASec() {
|
||||
try {
|
||||
synchronized (this) {
|
||||
wait(ONE_TENTH_OF_SECOND);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE, "Interrupted wait", //$NON-NLS-1$
|
||||
e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see java.lang.AutoCloseable#close() */
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
consoleManager.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,176 +0,0 @@
|
||||
/*
|
||||
* Copyright E. Bigeon (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* Socket implementation of GCLC.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc-socket:fr.bigeon.gclc.socket.ThreadedServerConsoleManager.java
|
||||
* Created on: Jun 1, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.socket;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
import fr.bigeon.smu.StringEncoder;
|
||||
|
||||
/** The console manager for socket communication
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class ThreadedServerConsoleManager implements ConsoleManager {
|
||||
|
||||
/** The eol character */
|
||||
private static final String EOL = "\n"; //$NON-NLS-1$
|
||||
/** The class logger */
|
||||
private static final Logger LOGGER = Logger
|
||||
.getLogger(ThreadedServerConsoleManager.class.getName());
|
||||
/** The prompting sequence */
|
||||
private String prompt = new String();
|
||||
/** The buffer of data to send to the user */
|
||||
private StringBuilder buffer = new StringBuilder();
|
||||
/** The synchronized object */
|
||||
private final Object promptingLock;
|
||||
/** The output to write data comming from the application */
|
||||
private PrintWriter output;
|
||||
/** The encoder to encode data coming from the application */
|
||||
private final StringEncoder encoder;
|
||||
/** The input to wait data from the user */
|
||||
private BufferedReader input;
|
||||
/** the prompting status */
|
||||
private boolean doPrompt;
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private boolean closed = false;
|
||||
|
||||
/** Create the console manager.
|
||||
*
|
||||
* @param encoder the encoder for output
|
||||
* @param promptingLock the synchronization object */
|
||||
public ThreadedServerConsoleManager(StringEncoder encoder,
|
||||
Object promptingLock) {
|
||||
super();
|
||||
this.encoder = encoder;
|
||||
this.promptingLock = promptingLock;
|
||||
}
|
||||
|
||||
/** @param input the input to set */
|
||||
public void setInput(BufferedReader input) {
|
||||
this.input = input;
|
||||
}
|
||||
|
||||
/** @param output the output to set */
|
||||
public void setOutput(PrintWriter output) {
|
||||
this.output = output;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPrompt(String prompt) {
|
||||
this.prompt = prompt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String prompt(String message) {
|
||||
buffer.append(message);
|
||||
String userInput = new String();
|
||||
boolean prompting = true;
|
||||
while (prompting) {
|
||||
// Send buffer content
|
||||
output.println(encoder.encode(buffer.toString()));
|
||||
try {
|
||||
synchronized (promptingLock) {
|
||||
doPrompt = true;
|
||||
promptingLock.notify();
|
||||
}
|
||||
userInput = input.readLine();
|
||||
doPrompt = false;
|
||||
prompting = false;
|
||||
} catch (final IOException e) {
|
||||
LOGGER.log(Level.SEVERE, "input reading error", e); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
// Renew buffer
|
||||
buffer = new StringBuilder();
|
||||
return userInput;
|
||||
}
|
||||
|
||||
/** @return the prompting status */
|
||||
public synchronized boolean isPrompting() {
|
||||
return doPrompt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String prompt() {
|
||||
return prompt(prompt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void println(String message) {
|
||||
buffer.append(message + EOL);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void println() {
|
||||
buffer.append(EOL);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void print(String text) {
|
||||
buffer.append(text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPrompt() {
|
||||
return prompt;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.manager.ConsoleManager#close() */
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
// Do nothing
|
||||
this.closed = true;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.manager.ConsoleManager#isClosed() */
|
||||
@Override
|
||||
public boolean isClosed() {
|
||||
return closed;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -42,14 +42,12 @@ import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.ConsoleApplication;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
import fr.bigeon.gclc.manager.SystemConsoleManager;
|
||||
|
||||
/** Test class for {@link ConsoleRunnable}
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
@SuppressWarnings({"static-method", "unused", "javadoc"})
|
||||
@SuppressWarnings({"unused", "javadoc"})
|
||||
public class ConsoleRunnableTest {
|
||||
|
||||
/** <p>
|
||||
@@ -61,7 +59,7 @@ public class ConsoleRunnableTest {
|
||||
int i = 0;
|
||||
String[] cmds;
|
||||
|
||||
/** @param cmds */
|
||||
/** @param cmds the commands to run */
|
||||
public ConsoleManagerTestImplementation(String[] cmds) {
|
||||
super();
|
||||
this.cmds = cmds;
|
||||
@@ -123,59 +121,62 @@ public class ConsoleRunnableTest {
|
||||
public boolean isClosed() {
|
||||
return i == cmds.length;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */
|
||||
@Override
|
||||
public void interruptPrompt() {
|
||||
//
|
||||
}
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.socket.ConsoleRunnable#ConsoleRunnable(fr.bigeon.gclc.ConsoleApplication, java.lang.Object)}
|
||||
* {@link fr.bigeon.gclc.socket.ConsoleRunnable#ConsoleRunnable(fr.bigeon.gclc.ConsoleApplication)}
|
||||
* . */
|
||||
@Test
|
||||
public void testConsoleRunnable() {
|
||||
Object lock = new Object();
|
||||
ConsoleApplication app = new ConsoleTestApplication(
|
||||
new SystemConsoleManager());
|
||||
ConsoleRunnable runnable = new ConsoleRunnable(app, lock);
|
||||
// ConsoleApplication app = new ConsoleTestApplication(
|
||||
// new SystemConsoleManager());
|
||||
// ConsoleRunnable runnable = new ConsoleRunnable(app);
|
||||
|
||||
}
|
||||
|
||||
/** Test method for {@link fr.bigeon.gclc.socket.ConsoleRunnable#run()}. */
|
||||
@Test
|
||||
public void testRunFlow() {
|
||||
Object lock = new Object();
|
||||
ConsoleApplication app = new ConsoleTestApplication(
|
||||
new ConsoleManagerTestImplementation(
|
||||
new String[] {"test", ConsoleTestApplication.EXIT})); //$NON-NLS-1$
|
||||
ConsoleRunnable runnable = new ConsoleRunnable(app, lock);
|
||||
|
||||
Thread th = new Thread(runnable);
|
||||
th.start();
|
||||
|
||||
runnable.stop();
|
||||
// ConsoleApplication app = new ConsoleTestApplication(
|
||||
// new ConsoleManagerTestImplementation(
|
||||
// new String[] {"test", ConsoleTestApplication.EXIT})); //$NON-NLS-1$
|
||||
// ConsoleRunnable runnable = new ConsoleRunnable(app);
|
||||
//
|
||||
// Thread th = new Thread(runnable);
|
||||
// th.start();
|
||||
//
|
||||
// runnable.stop();
|
||||
}
|
||||
|
||||
/** Test method for {@link fr.bigeon.gclc.socket.ConsoleRunnable#stop()}. */
|
||||
@Test
|
||||
public void testStop() {
|
||||
Object lock = new Object();
|
||||
ConsoleApplication app = new ConsoleTestApplication(
|
||||
new ConsoleManagerTestImplementation(
|
||||
new String[] {"test", ConsoleTestApplication.EXIT})); //$NON-NLS-1$
|
||||
ConsoleRunnable runnable = new ConsoleRunnable(app, lock);
|
||||
runnable.stop();
|
||||
Thread th = new Thread(runnable);
|
||||
th.start();
|
||||
runnable.stop();
|
||||
runnable.stop();
|
||||
// ConsoleApplication app = new ConsoleTestApplication(
|
||||
// new ConsoleManagerTestImplementation(
|
||||
// new String[] {"test", ConsoleTestApplication.EXIT})); //$NON-NLS-1$
|
||||
// ConsoleRunnable runnable = new ConsoleRunnable(app);
|
||||
// runnable.stop();
|
||||
// Thread th = new Thread(runnable);
|
||||
// th.start();
|
||||
// runnable.stop();
|
||||
// runnable.stop();
|
||||
}
|
||||
|
||||
/** Test method for {@link fr.bigeon.gclc.socket.ConsoleRunnable#stop()}. */
|
||||
@Test
|
||||
public void testRun() {
|
||||
Object lock = new Object();
|
||||
ConsoleApplication app = new ConsoleTestApplication(
|
||||
new ConsoleManagerTestImplementation(
|
||||
new String[] {"test", ConsoleTestApplication.EXIT})); //$NON-NLS-1$
|
||||
ConsoleRunnable runnable = new ConsoleRunnable(app, lock);
|
||||
runnable.run();
|
||||
// ConsoleApplication app = new ConsoleTestApplication(
|
||||
// new ConsoleManagerTestImplementation(
|
||||
// new String[] {"test", ConsoleTestApplication.EXIT})); //$NON-NLS-1$
|
||||
// ConsoleRunnable runnable = new ConsoleRunnable(app);
|
||||
// runnable.run();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -72,7 +72,8 @@ public class ConsoleTestApplication extends ConsoleApplication {
|
||||
try {
|
||||
manager.println("Test command ran fine");
|
||||
} catch (IOException e) {
|
||||
throw new CommandRunException("manager closed", e);
|
||||
throw new CommandRunException("manager closed", e,
|
||||
this);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -89,7 +90,8 @@ public class ConsoleTestApplication extends ConsoleApplication {
|
||||
Thread.sleep(2000);
|
||||
manager.println("Test command ran fine");
|
||||
} catch (IOException | InterruptedException e) {
|
||||
throw new CommandRunException("manager closed", e);
|
||||
throw new CommandRunException("manager closed", e,
|
||||
this);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -38,31 +38,40 @@
|
||||
*/
|
||||
package fr.bigeon.gclc.socket;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PrintWriter;
|
||||
import java.net.Socket;
|
||||
import java.util.Arrays;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.smu.StringEncoder;
|
||||
|
||||
/** Test class for {@link SocketConsoleApplicationShell}
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
@SuppressWarnings({"static-method", "unused", "javadoc", "nls"})
|
||||
public class SocketConsoleApplicationTest {
|
||||
|
||||
private static final StringEncoder ENCODER = new StringEncoder("%",
|
||||
Arrays.asList("\n")); //$NON-NLS-1$
|
||||
private static final Logger LOGGER = Logger
|
||||
.getLogger(SocketConsoleApplicationTest.class.getName());
|
||||
|
||||
@Test
|
||||
public void integrationTest() {
|
||||
Thread server = TestServer.startServer(false);
|
||||
Thread server;
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
server = TestServer.startServer("bye");
|
||||
} catch (IOException e3) {
|
||||
assertNull(e3);
|
||||
fail("unable to start server");
|
||||
}
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
@@ -76,21 +85,84 @@ public class SocketConsoleApplicationTest {
|
||||
new InputStreamReader(kkSocket.getInputStream()));) {
|
||||
|
||||
String fromServer;
|
||||
int i = 0;
|
||||
String[] cmds = {"help", "toto", "test", "close"};
|
||||
int i = -1;
|
||||
String[] cmds = {"help", "toto", "test", "bye"};
|
||||
while ((fromServer = in.readLine()) != null) {
|
||||
System.out.println("Server: \n" + ENCODER.decode(fromServer));
|
||||
if (fromServer.equals("Bye.")) {
|
||||
i++;
|
||||
fromServer = consumeToPrompt(fromServer, in);
|
||||
if (fromServer == null || fromServer.equals("Bye.")) {
|
||||
break;
|
||||
}
|
||||
|
||||
final String fromUser = cmds[i];
|
||||
if (fromUser != null) {
|
||||
System.out.println("Client: " + fromUser);
|
||||
LOGGER.fine("Client: " + fromUser);
|
||||
out.println(fromUser);
|
||||
}
|
||||
}
|
||||
assertEquals(4, i);
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
try (Socket kkSocket = new Socket(hostName, portNumber);
|
||||
PrintWriter out = new PrintWriter(kkSocket.getOutputStream(),
|
||||
true);
|
||||
BufferedReader in = new BufferedReader(
|
||||
new InputStreamReader(kkSocket.getInputStream()));) {
|
||||
|
||||
String fromServer;
|
||||
int i = 0;
|
||||
String[] cmds = {"help", "toto", "test",
|
||||
ConsoleTestApplication.EXIT};
|
||||
while ((fromServer = in.readLine()) != null) {
|
||||
fromServer = consumeToPrompt(fromServer, in);
|
||||
if (fromServer == null || fromServer.equals("Bye.")) {
|
||||
break;
|
||||
}
|
||||
LOGGER.info("Server: \n" + fromServer);
|
||||
|
||||
final String fromUser = cmds[i];
|
||||
if (fromUser != null) {
|
||||
LOGGER.info("Client: " + fromUser);
|
||||
out.println(fromUser);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
assertEquals(4, i);
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
|
||||
try (Socket kkSocket = new Socket(hostName, portNumber);
|
||||
PrintWriter out = new PrintWriter(kkSocket.getOutputStream(),
|
||||
true);
|
||||
BufferedReader in = new BufferedReader(
|
||||
new InputStreamReader(kkSocket.getInputStream()));) {
|
||||
|
||||
String fromServer;
|
||||
int i = 0;
|
||||
String[] cmds = {"help", "toto", "test",
|
||||
ConsoleTestApplication.EXIT};
|
||||
while ((fromServer = in.readLine()) != null) {
|
||||
fromServer = consumeToPrompt(fromServer, in);
|
||||
if (fromServer == null || fromServer.equals("Bye.")) {
|
||||
break;
|
||||
}
|
||||
|
||||
final String fromUser = cmds[i];
|
||||
if (fromUser != null) {
|
||||
LOGGER.fine("Client: " + fromUser);
|
||||
out.println(fromUser);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
assertEquals(4, i);
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@@ -100,7 +172,11 @@ public class SocketConsoleApplicationTest {
|
||||
} catch (InterruptedException e2) {
|
||||
e2.printStackTrace();
|
||||
}
|
||||
try {
|
||||
server = TestServer.startServer(true);
|
||||
} catch (IOException e2) {
|
||||
assertNull(e2);
|
||||
}
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e1) {
|
||||
@@ -117,22 +193,49 @@ public class SocketConsoleApplicationTest {
|
||||
int i = 0;
|
||||
String[] cmds = {"help", "test", "close"};
|
||||
while ((fromServer = in.readLine()) != null) {
|
||||
// System.out.println("Server: \n" + ENCODER.decode(fromServer));
|
||||
if (fromServer.equals("Bye.")) {
|
||||
fromServer = consumeToPrompt(fromServer, in);
|
||||
if (fromServer == null || fromServer.equals("Bye.")) {
|
||||
break;
|
||||
}
|
||||
|
||||
assertTrue(i < 1);
|
||||
final String fromUser = cmds[i];
|
||||
if (fromUser != null) {
|
||||
// System.out.println("Client: " + fromUser);
|
||||
LOGGER.fine("Client: " + fromUser);
|
||||
out.println(fromUser);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
assertEquals(1, i);
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
Thread srv = null;
|
||||
try {
|
||||
srv = TestServer.getServer();
|
||||
} catch (IOException e1) {
|
||||
assertNull(e1);
|
||||
}
|
||||
TestServer.closeServer();
|
||||
try {
|
||||
srv.join();
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/** @param in the input
|
||||
* @return the string
|
||||
* @throws IOException if the input reading failed */
|
||||
private String consumeToPrompt(String server,
|
||||
BufferedReader in) throws IOException {
|
||||
String fromServer = server;
|
||||
LOGGER.fine("Server: \n" + fromServer);
|
||||
while (fromServer != null && !fromServer.equals("Bye.") &&
|
||||
!fromServer.equals("> ")) {
|
||||
fromServer = in.readLine();
|
||||
LOGGER.fine("Server: \n" + fromServer);
|
||||
}
|
||||
return fromServer;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,9 @@
|
||||
*/
|
||||
package fr.bigeon.gclc.socket;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/** A test server
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
@@ -43,8 +46,9 @@ public class TestServer {
|
||||
private static SocketConsoleApplicationShell SHELL;
|
||||
private static Thread server;
|
||||
|
||||
/** @param args no argument */
|
||||
public static void main(String... args) {
|
||||
/** @param args no argument
|
||||
* @throws IOException if the server starting failed */
|
||||
public static void main(String... args) throws IOException {
|
||||
try {
|
||||
startServer(false).join();
|
||||
} catch (final InterruptedException e) {
|
||||
@@ -52,7 +56,7 @@ public class TestServer {
|
||||
}
|
||||
}
|
||||
|
||||
public static Thread getServer() {
|
||||
public static Thread getServer() throws IOException {
|
||||
if (server == null) {
|
||||
server = new Thread(getShell(), "gclcServer");
|
||||
server.start();
|
||||
@@ -60,11 +64,10 @@ public class TestServer {
|
||||
return server;
|
||||
}
|
||||
|
||||
/** @return */
|
||||
private static SocketConsoleApplicationShell getShell() {
|
||||
private static SocketConsoleApplicationShell getShell() throws IOException {
|
||||
if (SHELL == null) {
|
||||
SHELL = new SocketConsoleApplicationShell(3300, "close",
|
||||
ConsoleTestApplication.EXIT);
|
||||
ConsoleTestApplication.EXIT, Charset.forName("UTF-8"));
|
||||
final ConsoleTestApplication app = new ConsoleTestApplication(
|
||||
SHELL.getConsoleManager());
|
||||
SHELL.setApplication(app);
|
||||
@@ -72,10 +75,22 @@ public class TestServer {
|
||||
return SHELL;
|
||||
}
|
||||
|
||||
public static Thread startServer(boolean autoClose) {
|
||||
public static Thread startServer(boolean autoClose) throws IOException {
|
||||
if (SHELL == null) {
|
||||
SHELL = new SocketConsoleApplicationShell(3300, autoClose,
|
||||
ConsoleTestApplication.EXIT);
|
||||
ConsoleTestApplication.EXIT, Charset.forName("UTF-8"));
|
||||
final ConsoleTestApplication app = new ConsoleTestApplication(
|
||||
SHELL.getConsoleManager());
|
||||
SHELL.setApplication(app);
|
||||
server = null;
|
||||
}
|
||||
return getServer();
|
||||
}
|
||||
|
||||
public static Thread startServer(String closeConnection) throws IOException {
|
||||
if (SHELL == null) {
|
||||
SHELL = new SocketConsoleApplicationShell(3300, closeConnection,
|
||||
ConsoleTestApplication.EXIT, Charset.forName("UTF-8"));
|
||||
final ConsoleTestApplication app = new ConsoleTestApplication(
|
||||
SHELL.getConsoleManager());
|
||||
SHELL.setApplication(app);
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>gclc-swt</artifactId>
|
||||
<version>1.0.3-SNAPSHOT</version>
|
||||
<version>1.1.4-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://www.bigeon.fr/emmanuel</url>
|
||||
<properties>
|
||||
@@ -45,23 +45,13 @@
|
||||
<parent>
|
||||
<groupId>fr.bigeon</groupId>
|
||||
<artifactId>ebigeon-config</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<version>1.7.1</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>fr.bigeon</groupId>
|
||||
<artifactId>gclc</artifactId>
|
||||
<version>1.2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.swt</groupId>
|
||||
<artifactId>org.eclipse.swt.gtk.linux.x86_64</artifactId>
|
||||
<version>4.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.swt</groupId>
|
||||
<artifactId>org.eclipse.swt.win32.win32.x86_64</artifactId>
|
||||
<version>4.3</version>
|
||||
<version>1.3.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>fr.bigeon</groupId>
|
||||
@@ -76,4 +66,36 @@
|
||||
<developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection>
|
||||
<tag>HEAD</tag>
|
||||
</scm>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>linux-deps</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>Linux</family>
|
||||
</os>
|
||||
</activation>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.swt</groupId>
|
||||
<artifactId>org.eclipse.swt.gtk.linux.x86_64</artifactId>
|
||||
<version>4.3</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>windows-deps</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>Windows</family>
|
||||
</os>
|
||||
</activation>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.swt</groupId>
|
||||
<artifactId>org.eclipse.swt.win32.win32.x86_64</artifactId>
|
||||
<version>4.3</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Copyright E. Bigeon (2015)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a swt window for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc-swt:fr.bigeon.gclc.swt.ConsoleDelayIO.java
|
||||
* Created on: Nov 19, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.swt;
|
||||
|
||||
/** This class represents an object used to send commands to a console
|
||||
* application.
|
||||
* <p>
|
||||
* The sending of command is done in two phases. Define the input through get
|
||||
* and set, and then validate the input.
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public interface ConsoleDelayIO {
|
||||
/** Actually send the input as the prompt next input. */
|
||||
void validateInput();
|
||||
|
||||
/** @param input the input to set */
|
||||
void setInput(String input);
|
||||
|
||||
/** @return the non validated input */
|
||||
String getInput();
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Copyright E. Bigeon (2015)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a swt window for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc-swt:fr.bigeon.gclc.swt.HistoryTextKeyListener.java
|
||||
* Created on: Jun 9, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.swt;
|
||||
|
||||
import org.eclipse.swt.SWT;
|
||||
import org.eclipse.swt.events.KeyAdapter;
|
||||
import org.eclipse.swt.events.KeyEvent;
|
||||
|
||||
import fr.bigeon.collections.ArrayRibbon;
|
||||
import fr.bigeon.collections.Ribbon;
|
||||
|
||||
/** A key listener to validate commands and manage the history of commands
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public final class HistoryTextKeyListener extends KeyAdapter {
|
||||
|
||||
/** The size of commands history */
|
||||
private static final int DEFAULT_HISTORY_SIZE = 10;
|
||||
/** The empty string constant */
|
||||
private static final String EMPTY = ""; //$NON-NLS-1$
|
||||
/** The history ribbon */
|
||||
private final Ribbon<String> commands;
|
||||
/** The current index in history search */
|
||||
private int currentIndex = 0;
|
||||
/** The console to notify of command validation */
|
||||
private final ConsoleDelayIO console;
|
||||
|
||||
/** @param console the console delayed */
|
||||
public HistoryTextKeyListener(ConsoleDelayIO console) {
|
||||
super();
|
||||
this.console = console;
|
||||
this.commands = new ArrayRibbon<>(DEFAULT_HISTORY_SIZE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void keyPressed(KeyEvent e) {
|
||||
|
||||
pressedKeyCode(e.keyCode);
|
||||
}
|
||||
|
||||
/** @param keyCode the pressed key code */
|
||||
public void pressedKeyCode(int keyCode) {
|
||||
// Enter validates the command if prompting
|
||||
if (keyCode == '\r') {
|
||||
String input = console.getInput();
|
||||
if (!input.isEmpty()) {
|
||||
commands.add(input);
|
||||
}
|
||||
console.validateInput();
|
||||
currentIndex = -1;
|
||||
}
|
||||
|
||||
// Upper arrow retrieves previous commands
|
||||
if (keyCode == SWT.ARROW_UP &&
|
||||
currentIndex < commands.size() - 1) {
|
||||
currentIndex++;
|
||||
String cmd = commands.get(commands.size() - currentIndex - 1);
|
||||
console.setInput(cmd);
|
||||
}
|
||||
|
||||
// Lower arrow retrieves next commands
|
||||
if (keyCode == SWT.ARROW_DOWN) {
|
||||
if (currentIndex == 0) {
|
||||
currentIndex--;
|
||||
console.setInput(EMPTY);
|
||||
} else if (currentIndex > 0) {
|
||||
String cmd = commands
|
||||
.get(commands.size() - (--currentIndex) - 1);
|
||||
console.setInput(cmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,12 +39,10 @@
|
||||
package fr.bigeon.gclc.swt;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.eclipse.swt.SWT;
|
||||
import org.eclipse.swt.events.FocusAdapter;
|
||||
import org.eclipse.swt.events.FocusEvent;
|
||||
import org.eclipse.swt.events.KeyAdapter;
|
||||
import org.eclipse.swt.events.KeyEvent;
|
||||
import org.eclipse.swt.layout.GridData;
|
||||
import org.eclipse.swt.layout.GridLayout;
|
||||
import org.eclipse.swt.widgets.Composite;
|
||||
@@ -52,8 +50,6 @@ import org.eclipse.swt.widgets.Display;
|
||||
import org.eclipse.swt.widgets.Label;
|
||||
import org.eclipse.swt.widgets.Text;
|
||||
|
||||
import fr.bigeon.collections.ArrayRibbon;
|
||||
import fr.bigeon.collections.Ribbon;
|
||||
import fr.bigeon.gclc.ConsoleApplication;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
|
||||
@@ -61,71 +57,19 @@ import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
* <p>
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class SWTConsole extends Composite implements ConsoleManager {
|
||||
/** A key listener to validate commands and manage the history of commands
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public static final class HistoryTextKeyListener extends KeyAdapter {
|
||||
|
||||
/** The size of commands history */
|
||||
private static final int DEFAULT_HISTORY_SIZE = 10;
|
||||
/** The history ribbon */
|
||||
private final Ribbon<String> commands;
|
||||
/** The current index in history search */
|
||||
private int currentIndex = 0;
|
||||
/** The console to write the commands in */
|
||||
private final Text consoleInput;
|
||||
/** The console to notify of command validation */
|
||||
private final SWTConsole console;
|
||||
|
||||
/** @param console the console
|
||||
* @param consoleInput the text to write commands in */
|
||||
public HistoryTextKeyListener(SWTConsole console, Text consoleInput) {
|
||||
super();
|
||||
this.console = console;
|
||||
this.consoleInput = consoleInput;
|
||||
this.commands = new ArrayRibbon<>(DEFAULT_HISTORY_SIZE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void keyPressed(KeyEvent e) {
|
||||
// Enter validates the command if prompting
|
||||
if (e.keyCode == '\r') {
|
||||
commands.add(consoleInput.getText());
|
||||
console.validateInput();
|
||||
currentIndex = -1;
|
||||
}
|
||||
|
||||
// Upper arrow retrieves previous commands
|
||||
if (e.keyCode == SWT.ARROW_UP &&
|
||||
currentIndex < commands.size() - 1) {
|
||||
currentIndex++;
|
||||
String cmd = commands.get(commands.size() - currentIndex - 1);
|
||||
consoleInput.setText(cmd);
|
||||
consoleInput.setSelection(cmd.length());
|
||||
}
|
||||
|
||||
// Lower arrow retrieves next commands
|
||||
if (e.keyCode == SWT.ARROW_DOWN) {
|
||||
if (currentIndex == 0) {
|
||||
currentIndex--;
|
||||
consoleInput.setText(new String());
|
||||
} else if (currentIndex > 0) {
|
||||
String cmd = commands
|
||||
.get(commands.size() - (--currentIndex) - 1);
|
||||
consoleInput.setText(cmd);
|
||||
consoleInput.setSelection(cmd.length());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class SWTConsole extends Composite
|
||||
implements ConsoleDelayIO, ConsoleManager {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final int LAYOUT_NB_COLUMNS = 2;
|
||||
/** The cmd prefix in the output console */
|
||||
private static final String CMD_PREFIX = "[CMD] "; //$NON-NLS-1$
|
||||
/** The class logger */
|
||||
private static final Logger LOGGER = Logger
|
||||
.getLogger(SWTConsole.class.getName());
|
||||
/** The empty string constant */
|
||||
private static final String EMPTY = ""; //$NON-NLS-1$
|
||||
/** The console output text field */
|
||||
private final Text consoleOutput;
|
||||
/** The console input text field */
|
||||
@@ -155,13 +99,6 @@ public class SWTConsole extends Composite implements ConsoleManager {
|
||||
consoleOutput.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true,
|
||||
LAYOUT_NB_COLUMNS, 1));
|
||||
consoleOutput.setRedraw(true);
|
||||
consoleOutput.addFocusListener(new FocusAdapter() {
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void focusGained(FocusEvent e) {
|
||||
consoleInput.setFocus();
|
||||
}
|
||||
});
|
||||
|
||||
lblPromptlabel = new Label(this, SWT.NONE);
|
||||
lblPromptlabel.setText(prompt);
|
||||
@@ -169,25 +106,43 @@ public class SWTConsole extends Composite implements ConsoleManager {
|
||||
consoleInput = new Text(this, SWT.BORDER);
|
||||
consoleInput.setLayoutData(
|
||||
new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
|
||||
consoleInput.addKeyListener(
|
||||
new HistoryTextKeyListener(this, consoleInput));
|
||||
consoleInput.addKeyListener(new HistoryTextKeyListener(this));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
protected void validateInput() {
|
||||
if (prompting) {
|
||||
@Override
|
||||
public void validateInput() {
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
consoleInput.setEnabled(false);
|
||||
}
|
||||
});
|
||||
synchronized (promptLock) {
|
||||
while (!prompting) {
|
||||
try {
|
||||
promptLock.wait();
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE,
|
||||
"Interruption while waiting prompt", e); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
command = consoleInput.getText();
|
||||
prompting = false;
|
||||
consoleInput.setText(new String());
|
||||
consoleInput.setEnabled(false);
|
||||
consoleOutput
|
||||
.append(CMD_PREFIX + command + System.lineSeparator());
|
||||
promptLock.notifyAll();
|
||||
consoleInput.setText(EMPTY);
|
||||
consoleOutput.append(
|
||||
CMD_PREFIX + command + System.lineSeparator());
|
||||
}
|
||||
});
|
||||
promptLock.notifyAll();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,8 +166,10 @@ public class SWTConsole extends Composite implements ConsoleManager {
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
if (!consoleOutput.isDisposed()) {
|
||||
consoleOutput.append(text);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -224,8 +181,10 @@ public class SWTConsole extends Composite implements ConsoleManager {
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
if (!consoleOutput.isDisposed()) {
|
||||
consoleOutput.append(System.lineSeparator());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -237,8 +196,10 @@ public class SWTConsole extends Composite implements ConsoleManager {
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
if (!consoleOutput.isDisposed()) {
|
||||
consoleOutput.append(message + System.lineSeparator());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
@@ -256,16 +217,24 @@ public class SWTConsole extends Composite implements ConsoleManager {
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
if (!consoleInput.isDisposed()) {
|
||||
consoleInput.setEnabled(true);
|
||||
consoleInput.setFocus();
|
||||
}
|
||||
}
|
||||
});
|
||||
prompting = true;
|
||||
promptLock.notifyAll();
|
||||
promptLock.wait();
|
||||
} catch (final InterruptedException e) {
|
||||
LOGGER.log(Level.WARNING,
|
||||
"Error in synchronization of prompting", e); //$NON-NLS-1$
|
||||
command = null;
|
||||
}
|
||||
}
|
||||
if (isDisposed()) {
|
||||
throw new IOException("Input closed"); //$NON-NLS-1$
|
||||
}
|
||||
return command;
|
||||
}
|
||||
|
||||
@@ -282,12 +251,14 @@ public class SWTConsole extends Composite implements ConsoleManager {
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
if (!consoleOutput.isDisposed()) {
|
||||
lblPromptlabel.setText(message);
|
||||
// relayout
|
||||
SWTConsole.this.layout();
|
||||
consoleInput.setEnabled(true);
|
||||
consoleInput.setFocus();
|
||||
}
|
||||
}
|
||||
});
|
||||
prompting = true;
|
||||
promptLock.wait();
|
||||
@@ -295,16 +266,20 @@ public class SWTConsole extends Composite implements ConsoleManager {
|
||||
throw new IOException();
|
||||
}
|
||||
} catch (final InterruptedException e) {
|
||||
LOGGER.log(Level.WARNING,
|
||||
"Error in synchronization of prompting", e); //$NON-NLS-1$
|
||||
command = null;
|
||||
} finally {
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
if (!consoleOutput.isDisposed()) {
|
||||
lblPromptlabel.setText(prompt);
|
||||
// relayout
|
||||
SWTConsole.this.layout();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -327,10 +302,12 @@ public class SWTConsole extends Composite implements ConsoleManager {
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
if (!consoleOutput.isDisposed()) {
|
||||
lblPromptlabel.setText(prompt);
|
||||
// relayout
|
||||
SWTConsole.this.layout();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -355,4 +332,40 @@ public class SWTConsole extends Composite implements ConsoleManager {
|
||||
return isDisposed();
|
||||
}
|
||||
|
||||
/** @param string the text */
|
||||
public void setText(String string) {
|
||||
consoleInput.setText(string);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void validateCommand() {
|
||||
validateInput();
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.swt.ConsoleDelayIO#setInput(java.lang.String) */
|
||||
@Override
|
||||
public void setInput(String input) {
|
||||
consoleInput.setText(input);
|
||||
consoleInput.setSelection(input.length());
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.swt.ConsoleDelayIO#getInput() */
|
||||
@Override
|
||||
public String getInput() {
|
||||
return consoleInput.getText();
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */
|
||||
@Override
|
||||
public void interruptPrompt() {
|
||||
synchronized (promptLock) {
|
||||
promptLock.notify();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
188
gclc-swt/src/main/java/fr/bigeon/gclc/swt/SWTConsoleView.java
Normal file
188
gclc-swt/src/main/java/fr/bigeon/gclc/swt/SWTConsoleView.java
Normal file
@@ -0,0 +1,188 @@
|
||||
/*
|
||||
* Copyright E. Bigeon (2015)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a swt window for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc-swt:fr.bigeon.gclc.swt.SWTConsole.java
|
||||
* Created on: Apr 18, 2015
|
||||
*/
|
||||
package fr.bigeon.gclc.swt;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.eclipse.swt.SWT;
|
||||
import org.eclipse.swt.layout.GridData;
|
||||
import org.eclipse.swt.layout.GridLayout;
|
||||
import org.eclipse.swt.widgets.Composite;
|
||||
import org.eclipse.swt.widgets.Display;
|
||||
import org.eclipse.swt.widgets.Text;
|
||||
|
||||
import fr.bigeon.gclc.ConsoleApplication;
|
||||
import fr.bigeon.gclc.manager.PipedConsoleManager;
|
||||
import fr.bigeon.gclc.tools.AOutputForwardRunnable;
|
||||
|
||||
/** A SWT component to connect to gclc {@link ConsoleApplication}
|
||||
* <p>
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class SWTConsoleView extends Composite implements ConsoleDelayIO {
|
||||
/** The local implementation of the forwarding runnable
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
private final class ToSWTConsoleForwardRunnable
|
||||
extends AOutputForwardRunnable {
|
||||
/** The running status */
|
||||
private boolean running = true;
|
||||
|
||||
/** @param manager the manager */
|
||||
public ToSWTConsoleForwardRunnable(PipedConsoleManager manager) {
|
||||
super(manager);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void forwardLine(String m) {
|
||||
appendConsoleOutput(m);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isRunning() {
|
||||
return running && !isDisposed();
|
||||
}
|
||||
|
||||
/** @param running the running to set */
|
||||
public void setRunning(boolean running) {
|
||||
this.running = running;
|
||||
}
|
||||
}
|
||||
|
||||
/** The class logger */
|
||||
private static final Logger LOGGER = Logger
|
||||
.getLogger(SWTConsoleView.class.getName());
|
||||
/** The console output text field */
|
||||
private final Text consoleOutput;
|
||||
/** The console input text field */
|
||||
private final Text consoleInput;
|
||||
/** The actual manager */
|
||||
private PipedConsoleManager manager;
|
||||
/** The forwarding runnable */
|
||||
private ToSWTConsoleForwardRunnable forward;
|
||||
|
||||
/** Create the composite.
|
||||
*
|
||||
* @param parent the prent composite
|
||||
* @param style the composite style */
|
||||
public SWTConsoleView(Composite parent, int style) {
|
||||
super(parent, style);
|
||||
|
||||
setLayout(new GridLayout(1, false));
|
||||
|
||||
consoleOutput = new Text(this, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP |
|
||||
SWT.V_SCROLL | SWT.MULTI);
|
||||
consoleOutput.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true,
|
||||
1, 1));
|
||||
consoleOutput.setRedraw(true);
|
||||
|
||||
consoleInput = new Text(this, SWT.BORDER);
|
||||
consoleInput.setLayoutData(
|
||||
new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
|
||||
consoleInput.addKeyListener(new HistoryTextKeyListener(this));
|
||||
}
|
||||
|
||||
/** @param manager the manager to set */
|
||||
public void setManager(PipedConsoleManager manager) {
|
||||
this.manager = manager;
|
||||
if (forward != null) {
|
||||
forward.setRunning(false);
|
||||
}
|
||||
forward = new ToSWTConsoleForwardRunnable(manager);
|
||||
Thread th = new Thread(forward, "gclcToSWT"); //$NON-NLS-1$
|
||||
th.start();
|
||||
}
|
||||
|
||||
/** @param next the next message */
|
||||
protected void appendConsoleOutput(final String next) {
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
consoleOutput.append(System.lineSeparator() + next);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@Override
|
||||
public void validateInput() {
|
||||
try {
|
||||
manager.type(getInput());
|
||||
} catch (IOException e) {
|
||||
LOGGER.log(Level.SEVERE, "Unable to input value to console", e); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void checkSubclass() {
|
||||
// Disable the check that prevents subclassing of SWT components
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.eclipse.swt.widgets.Composite#setFocus() */
|
||||
@Override
|
||||
public boolean setFocus() {
|
||||
return consoleInput.setFocus();
|
||||
}
|
||||
|
||||
/** @param string the text */
|
||||
public void setText(String string) {
|
||||
consoleInput.setText(string);
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.swt.ConsoleDelayIO#setInput(java.lang.String) */
|
||||
@Override
|
||||
public void setInput(String input) {
|
||||
consoleInput.setText(input);
|
||||
consoleInput.setSelection(input.length());
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.swt.ConsoleDelayIO#getInput() */
|
||||
@Override
|
||||
public String getInput() {
|
||||
return consoleInput.getText();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Copyright E. Bigeon (2015)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a swt window for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc-swt:fr.bigeon.gclc.swt.HistoryTextKeyListenerTest.java
|
||||
* Created on: Nov 19, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.swt;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.eclipse.swt.SWT;
|
||||
import org.junit.Test;
|
||||
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class HistoryTextKeyListenerTest {
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.swt.HistoryTextKeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)}. */
|
||||
@Test
|
||||
public final void testKeyPressedKeyEvent() {
|
||||
ConsoleDelayIO io = new ConsoleDelayIO() {
|
||||
private String input = "";
|
||||
|
||||
@Override
|
||||
public void validateInput() {
|
||||
input = "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInput(String input) {
|
||||
this.input = input;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getInput() {
|
||||
return input;
|
||||
}
|
||||
};
|
||||
HistoryTextKeyListener listener = new HistoryTextKeyListener(io);
|
||||
|
||||
// no effects
|
||||
assertEquals("", io.getInput());
|
||||
listener.pressedKeyCode(SWT.ARROW_UP);
|
||||
assertEquals("", io.getInput());
|
||||
listener.pressedKeyCode(SWT.ARROW_DOWN);
|
||||
assertEquals("", io.getInput());
|
||||
listener.pressedKeyCode('\r');
|
||||
assertEquals("", io.getInput());
|
||||
|
||||
io.setInput("cmd arg");
|
||||
listener.pressedKeyCode(SWT.ARROW_UP);
|
||||
assertEquals("cmd arg", io.getInput());
|
||||
listener.pressedKeyCode(SWT.ARROW_DOWN);
|
||||
assertEquals("cmd arg", io.getInput());
|
||||
listener.pressedKeyCode('\r');
|
||||
assertEquals("", io.getInput());
|
||||
|
||||
io.setInput("cmd arg2");
|
||||
listener.pressedKeyCode(SWT.ARROW_UP);
|
||||
assertEquals("cmd arg", io.getInput());
|
||||
listener.pressedKeyCode(SWT.ARROW_DOWN);
|
||||
assertEquals("", io.getInput());
|
||||
io.setInput("cmd arg2");
|
||||
listener.pressedKeyCode('\r');
|
||||
assertEquals("", io.getInput());
|
||||
listener.pressedKeyCode(SWT.ARROW_UP);
|
||||
assertEquals("cmd arg2", io.getInput());
|
||||
listener.pressedKeyCode(SWT.ARROW_UP);
|
||||
assertEquals("cmd arg", io.getInput());
|
||||
listener.pressedKeyCode(SWT.ARROW_UP);
|
||||
assertEquals("cmd arg", io.getInput());
|
||||
listener.pressedKeyCode(SWT.ARROW_DOWN);
|
||||
assertEquals("cmd arg2", io.getInput());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -39,35 +39,178 @@
|
||||
package fr.bigeon.gclc.swt;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.eclipse.swt.widgets.Display;
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.ConsoleApplication;
|
||||
import fr.bigeon.gclc.command.Command;
|
||||
import fr.bigeon.gclc.command.ExitCommand;
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.InvalidCommandName;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon
|
||||
*
|
||||
*/
|
||||
* @author Emmanuel Bigeon */
|
||||
@SuppressWarnings({"javadoc", "static-method", "nls", "deprecation"})
|
||||
public class SWTConsoleShellTest {
|
||||
|
||||
protected static final long TWO_SECONDS = 2000;
|
||||
private static final Display DISPLAY = Display.getDefault();
|
||||
|
||||
@Test
|
||||
public void testConsoleClose() {
|
||||
final SWTConsoleShell shell = new SWTConsoleShell(DISPLAY);
|
||||
final SWTConsole swtConsole = (SWTConsole) shell.getManager();
|
||||
swtConsole.close();
|
||||
swtConsole.setPrompt(":");
|
||||
try {
|
||||
final ConsoleApplication appl = new ConsoleApplication(swtConsole,
|
||||
"Hello", "See you");
|
||||
appl.add(new ExitCommand("exit", appl));
|
||||
appl.add(new Command("long") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "a long running command";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) {
|
||||
try {
|
||||
Thread.sleep(TWO_SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
appl.add(new Command("test") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "a prompting running command";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
try {
|
||||
appl.getManager().prompt("Test");
|
||||
} catch (IOException e) {
|
||||
throw new CommandRunException("No input", e, this);
|
||||
}
|
||||
}
|
||||
});
|
||||
// shell.pack();
|
||||
shell.open();
|
||||
Thread applThread = new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
appl.start();
|
||||
}
|
||||
});
|
||||
Thread testThread = new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(TWO_SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
swtConsole.setText("test"); //$NON-NLS-1$
|
||||
swtConsole.validateCommand();
|
||||
}
|
||||
});
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
swtConsole.setText("ok"); //$NON-NLS-1$
|
||||
}
|
||||
});
|
||||
swtConsole.validateCommand();
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
swtConsole.setText("long"); //$NON-NLS-1$
|
||||
}
|
||||
});
|
||||
swtConsole.validateCommand();
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
swtConsole.setText("test"); //$NON-NLS-1$
|
||||
}
|
||||
});
|
||||
swtConsole.validateCommand();
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
swtConsole.setText("test"); //$NON-NLS-1$
|
||||
}
|
||||
});
|
||||
swtConsole.validateCommand();
|
||||
try {
|
||||
Thread.sleep(TWO_SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
shell.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
});
|
||||
applThread.start();
|
||||
testThread.start();
|
||||
while (!shell.isDisposed()) {
|
||||
if (!DISPLAY.readAndDispatch()) {
|
||||
DISPLAY.sleep();
|
||||
}
|
||||
}
|
||||
swtConsole.setPrompt(">");
|
||||
try {
|
||||
swtConsole.prompt();
|
||||
fail("Prompting when closed should fail!");
|
||||
} catch (IOException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
// DISPLAY.dispose();
|
||||
assertTrue(appl.getManager().isClosed());
|
||||
Thread.sleep(TWO_SECONDS);
|
||||
assertFalse(appl.isRunning());
|
||||
} catch (InvalidCommandName e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
Display display = new Display();
|
||||
final SWTConsoleShell shell = new SWTConsoleShell(display);
|
||||
ConsoleManager swtConsole = shell.getManager();
|
||||
final SWTConsoleShell shell = new SWTConsoleShell(DISPLAY);
|
||||
final SWTConsole swtConsole = (SWTConsole) shell.getManager();
|
||||
try {
|
||||
final ConsoleApplication appl = new ConsoleApplication(swtConsole,
|
||||
"exit", "Hello", "See you");
|
||||
"Hello", "See you");
|
||||
appl.add(new ExitCommand("exit", appl));
|
||||
appl.add(new Command("long") {
|
||||
|
||||
@Override
|
||||
@@ -98,6 +241,19 @@ public class SWTConsoleShellTest {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(TWO_SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
swtConsole.setText("test"); //$NON-NLS-1$
|
||||
swtConsole.validateCommand();
|
||||
}
|
||||
});
|
||||
try {
|
||||
Thread.sleep(TWO_SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
@@ -115,11 +271,11 @@ public class SWTConsoleShellTest {
|
||||
applThread.start();
|
||||
testThread.start();
|
||||
while (!shell.isDisposed()) {
|
||||
if (!display.readAndDispatch()) {
|
||||
display.sleep();
|
||||
if (!DISPLAY.readAndDispatch()) {
|
||||
DISPLAY.sleep();
|
||||
}
|
||||
}
|
||||
// display.dispose();
|
||||
// DISPLAY.dispose();
|
||||
assertTrue(appl.getManager().isClosed());
|
||||
Thread.sleep(TWO_SECONDS);
|
||||
assertFalse(appl.isRunning());
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
/*
|
||||
* Copyright E. Bigeon (2015)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a swt window for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc-swt:fr.bigeon.gclc.swt.SWTConsoleShellTest.java
|
||||
* Created on: Jun 8, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.swt;
|
||||
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.eclipse.swt.SWT;
|
||||
import org.eclipse.swt.widgets.Display;
|
||||
import org.eclipse.swt.widgets.Shell;
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.ConsoleApplication;
|
||||
import fr.bigeon.gclc.command.Command;
|
||||
import fr.bigeon.gclc.command.ExitCommand;
|
||||
import fr.bigeon.gclc.exception.InvalidCommandName;
|
||||
import fr.bigeon.gclc.manager.PipedConsoleManager;
|
||||
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
@SuppressWarnings({"javadoc", "static-method", "nls", "deprecation"})
|
||||
public class SWTConsoleViewTest {
|
||||
|
||||
protected static final long TWO_SECONDS = 2000;
|
||||
private static final Display DISPLAY = Display.getDefault();
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
final Shell shell = new Shell(DISPLAY);
|
||||
final SWTConsoleView swtConsole = new SWTConsoleView(shell, SWT.NONE);
|
||||
try (PipedConsoleManager manager = new PipedConsoleManager()) {
|
||||
swtConsole.setManager(manager);
|
||||
} catch (IOException e2) {
|
||||
assertNull(e2);
|
||||
}
|
||||
try (PipedConsoleManager manager = new PipedConsoleManager()) {
|
||||
swtConsole.setManager(manager);
|
||||
final ConsoleApplication appl = new ConsoleApplication(manager,
|
||||
"Hello", "See you");
|
||||
appl.add(new ExitCommand("exit", appl));
|
||||
appl.add(new Command("long") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "a long running command";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) {
|
||||
try {
|
||||
Thread.sleep(TWO_SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
// shell.pack();
|
||||
shell.open();
|
||||
Thread applThread = new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
appl.start();
|
||||
}
|
||||
});
|
||||
Thread testThread = new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(TWO_SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
swtConsole.setText("test"); //$NON-NLS-1$
|
||||
swtConsole.validateInput();
|
||||
}
|
||||
});
|
||||
try {
|
||||
Thread.sleep(TWO_SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
Display.getDefault().syncExec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
shell.dispose();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
applThread.start();
|
||||
testThread.start();
|
||||
while (!shell.isDisposed()) {
|
||||
if (!DISPLAY.readAndDispatch()) {
|
||||
DISPLAY.sleep();
|
||||
}
|
||||
}
|
||||
} catch (InvalidCommandName e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (IOException e1) {
|
||||
// TODO Auto-generated catch block
|
||||
e1.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
4
gclc.system/.gitignore
vendored
Normal file
4
gclc.system/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
/target/
|
||||
/.classpath
|
||||
/.project
|
||||
/.settings/
|
||||
41
gclc.system/pom.xml
Normal file
41
gclc.system/pom.xml
Normal file
@@ -0,0 +1,41 @@
|
||||
<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>
|
||||
<groupId>net.bigeon</groupId>
|
||||
<artifactId>gclc.system</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://www.bigeon.net</url>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.11</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>fr.bigeon</groupId>
|
||||
<artifactId>gclc</artifactId>
|
||||
<version>1.3.1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<name>GCLC system command</name>
|
||||
<description>Provide an exec command to execute system commands</description>
|
||||
<inceptionYear>2016</inceptionYear>
|
||||
<scm>
|
||||
<developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection>
|
||||
<tag>HEAD</tag>
|
||||
</scm>
|
||||
<parent>
|
||||
<groupId>fr.bigeon</groupId>
|
||||
<artifactId>ebigeon-config</artifactId>
|
||||
<version>1.7.1</version>
|
||||
</parent>
|
||||
</project>
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* gclc.system:net.bigeon.gclc.system.ExecSystemCommand.java
|
||||
* Created on: Jun 20, 2016
|
||||
*/
|
||||
package net.bigeon.gclc.system;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import fr.bigeon.gclc.command.Command;
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.CommandRunExceptionType;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
|
||||
/** A command that will execute a system command.
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class ExecSystemCommand extends Command {
|
||||
|
||||
/** The command default name */
|
||||
private static final String COMMAND_DEFAULT_NAME = "exec"; //$NON-NLS-1$
|
||||
/** The end of line separator */
|
||||
private static final String EOL = System.lineSeparator();
|
||||
/** The class logger */
|
||||
private static final Logger LOGGER = Logger
|
||||
.getLogger(ExecSystemCommand.class.getName());
|
||||
/** The manager for the application's user interface */
|
||||
private final ConsoleManager manager;
|
||||
|
||||
/** @param name the name of the command (the input from the manager that
|
||||
* should trigger this command)
|
||||
* @param manager the console manager for input and outputs */
|
||||
public ExecSystemCommand(String name, ConsoleManager manager) {
|
||||
super(name);
|
||||
this.manager = manager;
|
||||
}
|
||||
|
||||
/** @param manager the console manager for input and outputs */
|
||||
public ExecSystemCommand(ConsoleManager manager) {
|
||||
super(COMMAND_DEFAULT_NAME);
|
||||
this.manager = manager;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */
|
||||
@SuppressWarnings("resource")
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
Process proc;
|
||||
try {
|
||||
proc = Runtime.getRuntime().exec(args);
|
||||
} catch (IOException e2) {
|
||||
LOGGER.log(Level.SEVERE, "Unable to run process", e2); //$NON-NLS-1$
|
||||
return;
|
||||
}
|
||||
|
||||
final InputStream is = proc
|
||||
.getInputStream();
|
||||
Thread th = new Thread(new Runnable() {
|
||||
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
readToEnd(is);
|
||||
is.close();
|
||||
} catch (CommandRunException e) {
|
||||
LOGGER.log(Level.WARNING,
|
||||
"Manager was closed in the meantime...", e); //$NON-NLS-1$
|
||||
} catch (IOException e) {
|
||||
LOGGER.log(Level.WARNING, "Input stream was closed...", e); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
});
|
||||
th.start();
|
||||
manager.setPrompt(""); //$NON-NLS-1$
|
||||
final OutputStream os = proc.getOutputStream();
|
||||
try (BufferedWriter writer = new BufferedWriter(
|
||||
new OutputStreamWriter(os))) {
|
||||
while (th.isAlive()) {
|
||||
String user;
|
||||
try {
|
||||
user = manager.prompt();
|
||||
} catch (IOException e) {
|
||||
throw new CommandRunException(
|
||||
CommandRunExceptionType.INTERACTION,
|
||||
"manager was closed", e, this); //$NON-NLS-1$
|
||||
}
|
||||
writer.write(user + EOL);
|
||||
}
|
||||
} catch (IOException e1) {
|
||||
throw new CommandRunException(CommandRunExceptionType.INTERACTION,
|
||||
"manager was closed", e1, this); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
|
||||
/** @param is the input stream
|
||||
* @throws CommandRunException if the manager was closed while writing the
|
||||
* stream */
|
||||
protected void readToEnd(InputStream is) throws CommandRunException {
|
||||
int c;
|
||||
try {
|
||||
while ((c = is.read()) != -1) {
|
||||
try {
|
||||
manager.print(Character.valueOf((char) c).toString());
|
||||
} catch (IOException e) {
|
||||
throw new CommandRunException(
|
||||
CommandRunExceptionType.INTERACTION,
|
||||
"manager was closed", e, this); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOGGER.log(Level.INFO, "input stream reading failed", e); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#usageDetail() */
|
||||
@Override
|
||||
protected String usageDetail() {
|
||||
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() + System.lineSeparator() +
|
||||
" As an example if you give \"cat /etc/hostname\" as argument, on a linux" + //$NON-NLS-1$
|
||||
System.lineSeparator() +
|
||||
"system, you would get the computer name." + //$NON-NLS-1$
|
||||
System.lineSeparator();
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#usagePattern() */
|
||||
@Override
|
||||
protected String usagePattern() {
|
||||
return " CMD <system command>"; //$NON-NLS-1$
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.ICommand#tip() */
|
||||
@Override
|
||||
public String tip() {
|
||||
return "Execute a system command"; //$NON-NLS-1$
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,3 +1,11 @@
|
||||
## Version 1.2.6
|
||||
|
||||
* in script command failure report improved
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* command line reading now succeed to parse last argument if it is a string
|
||||
|
||||
## Version 1.1.0
|
||||
|
||||
* Parsing quoted string as one argument
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>gclc</artifactId>
|
||||
<version>1.2.2-SNAPSHOT</version>
|
||||
<version>1.3.7</version>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://www.bigeon.fr/emmanuel</url>
|
||||
<properties>
|
||||
@@ -53,7 +53,7 @@
|
||||
<parent>
|
||||
<groupId>fr.bigeon</groupId>
|
||||
<artifactId>ebigeon-config</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<version>1.7.1</version>
|
||||
</parent>
|
||||
<build>
|
||||
<plugins>
|
||||
@@ -83,6 +83,6 @@
|
||||
<scm>
|
||||
|
||||
<developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection>
|
||||
<tag>HEAD</tag>
|
||||
<tag>gclc-1.3.7</tag>
|
||||
</scm>
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.ApplicationAttachement.java
|
||||
* Created on: Apr 19, 2017
|
||||
*/
|
||||
package fr.bigeon.gclc;
|
||||
|
||||
import fr.bigeon.gclc.exception.InvalidCommandName;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon
|
||||
*
|
||||
*/
|
||||
public interface ApplicationAttachement {
|
||||
/** Attach this object to a console application.
|
||||
* <p>
|
||||
* The attaching usually consist in the addition of commands in the console
|
||||
* application. The attached command should be specific to the attachement
|
||||
* (typically, the generic help command or the script command should not be
|
||||
* added through this mechanism).
|
||||
*
|
||||
* @param application the application
|
||||
* @throws InvalidCommandName if a command name is invalid for the
|
||||
* application. */
|
||||
void attach(ConsoleApplication application) throws InvalidCommandName;
|
||||
}
|
||||
@@ -37,24 +37,22 @@
|
||||
package fr.bigeon.gclc;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InterruptedIOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import fr.bigeon.gclc.command.ExitCommand;
|
||||
import fr.bigeon.gclc.command.HelpExecutor;
|
||||
import fr.bigeon.gclc.command.ICommand;
|
||||
import fr.bigeon.gclc.command.ICommandProvider;
|
||||
import fr.bigeon.gclc.command.SubedCommand;
|
||||
import fr.bigeon.gclc.command.UnrecognizedCommand;
|
||||
import fr.bigeon.gclc.exception.CommandParsingException;
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.CommandRunExceptionType;
|
||||
import fr.bigeon.gclc.exception.InvalidCommandName;
|
||||
import fr.bigeon.gclc.i18n.Messages;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
import fr.bigeon.gclc.manager.SystemConsoleManager;
|
||||
|
||||
/** <p>
|
||||
* A {@link ConsoleApplication} is an application that require the user to input
|
||||
@@ -63,7 +61,8 @@ import fr.bigeon.gclc.manager.SystemConsoleManager;
|
||||
* A typical use case is the following:
|
||||
*
|
||||
* <pre>
|
||||
* {@link ConsoleApplication} app = new {@link ConsoleApplication#ConsoleApplication(String, String, String) ConsoleApplication("exit", "welcome", "see you latter")};
|
||||
* {@link ConsoleManager} manager = new {@link fr.bigeon.gclc.manager.SystemConsoleManager#SystemConsoleManager()}
|
||||
* {@link ConsoleApplication} app = new {@link ConsoleApplication#ConsoleApplication(ConsoleManager, String, String) ConsoleApplication(manager, "welcome", "see you latter")};
|
||||
* app.{@link ConsoleApplication#add(ICommand) add}("my_command", new {@link ICommand MyCommand()});
|
||||
* app.{@link ConsoleApplication#start start}();
|
||||
* </pre>
|
||||
@@ -74,19 +73,19 @@ import fr.bigeon.gclc.manager.SystemConsoleManager;
|
||||
* start method.
|
||||
*
|
||||
* @author Emmanuel BIGEON */
|
||||
public class ConsoleApplication implements ICommandProvider {
|
||||
public final class ConsoleApplication implements ICommandProvider {
|
||||
|
||||
/** The class logger */
|
||||
private static final Logger LOGGER = Logger
|
||||
.getLogger(ConsoleApplication.class.getName());
|
||||
/** The welcome message */
|
||||
private final String header;
|
||||
public final String header;
|
||||
/** The good bye message */
|
||||
private final String footer;
|
||||
public final String footer;
|
||||
/** The console manager */
|
||||
protected final ConsoleManager manager;
|
||||
public final ConsoleManager manager;
|
||||
/** The container of commands */
|
||||
private final SubedCommand root;
|
||||
public final SubedCommand root;
|
||||
/** The state of this application */
|
||||
private boolean running;
|
||||
/** The listeners */
|
||||
@@ -100,38 +99,7 @@ public class ConsoleApplication implements ICommandProvider {
|
||||
this.header = welcome;
|
||||
this.footer = goodbye;
|
||||
this.manager = manager;
|
||||
root = new SubedCommand(new String(), new UnrecognizedCommand(manager));
|
||||
}
|
||||
|
||||
/** @param manager the manager
|
||||
* @param exit the keyword for the exit command of this application
|
||||
* @param welcome the header message to display on launch of this
|
||||
* application
|
||||
* @param goodbye the message to display on exit
|
||||
* @throws InvalidCommandName if the exit command name is invalid
|
||||
* @deprecated since 1.2.0, use the {@link #add(ICommand)} method to add the
|
||||
* exit command */
|
||||
@Deprecated
|
||||
public ConsoleApplication(ConsoleManager manager, String exit,
|
||||
String welcome, String goodbye) throws InvalidCommandName {
|
||||
this(manager, welcome, goodbye);
|
||||
root.add(new ExitCommand(exit, this));
|
||||
}
|
||||
|
||||
/** @param exit the keyword for the exit command of this application
|
||||
* @param welcome the header message to display on launch of this
|
||||
* application
|
||||
* @param goodbye the message to display on exit
|
||||
* @throws InvalidCommandName if the exit command name is invalid
|
||||
* @deprecated since 1.2.0, use the {@link #add(ICommand)} method to add the
|
||||
* command and create this console using the
|
||||
* {@link #ConsoleApplication(ConsoleManager, String, String)}
|
||||
* method with a {@link SystemConsoleManager} as argument */
|
||||
@Deprecated
|
||||
public ConsoleApplication(String exit, String welcome,
|
||||
String goodbye) throws InvalidCommandName {
|
||||
this(new SystemConsoleManager(), welcome, goodbye);
|
||||
root.add(new ExitCommand(exit, this));
|
||||
root = new SubedCommand(""); //$NON-NLS-1$
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -139,30 +107,13 @@ public class ConsoleApplication implements ICommandProvider {
|
||||
return root.add(cmd);
|
||||
}
|
||||
|
||||
/** Adds help command on the given key
|
||||
*
|
||||
* @param cmd the handle for help
|
||||
* @return if the help command was added
|
||||
* @throws InvalidCommandName if the help command was not valid
|
||||
* @deprecated since 1.2.0 use the {@link #add(ICommand)} with a
|
||||
* {@link HelpExecutor} instead */
|
||||
@Deprecated
|
||||
public final boolean addHelpCommand(String cmd) throws InvalidCommandName {
|
||||
return root.add(new HelpExecutor(cmd, manager, root));
|
||||
}
|
||||
|
||||
/** Add a command request listener.
|
||||
* <p>
|
||||
* A listener can listen several times to the same application.
|
||||
*
|
||||
* @param listener the listener to add. */
|
||||
/** @param listener the command listener */
|
||||
public final void addListener(CommandRequestListener listener) {
|
||||
listeners.add(listener);
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see
|
||||
* fr.bigeon.gclc.command.ICommandProvider#executeSub(java.lang.String,
|
||||
* @see fr.bigeon.gclc.command.ICommandProvider#executeSub(java.lang.String,
|
||||
* java.lang.String[]) */
|
||||
@Override
|
||||
public final void executeSub(String command,
|
||||
@@ -170,10 +121,11 @@ public class ConsoleApplication implements ICommandProvider {
|
||||
root.executeSub(command, args);
|
||||
}
|
||||
|
||||
/** Exit this running application before next command prompt */
|
||||
/** Signify to the application that no command should be inputed anymore */
|
||||
public final void exit() {
|
||||
LOGGER.fine("Request exiting application..."); //$NON-NLS-1$
|
||||
running = false;
|
||||
manager.interruptPrompt();
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
@@ -183,20 +135,15 @@ public class ConsoleApplication implements ICommandProvider {
|
||||
return root.get(command);
|
||||
}
|
||||
|
||||
/** @return the manager */
|
||||
public final ConsoleManager getManager() {
|
||||
return manager;
|
||||
}
|
||||
|
||||
/** @param cmd the command to interpret
|
||||
* @throws IOException if the manager was closed */
|
||||
/** @param cmd the command
|
||||
* @throws IOException if the command could not be parsed */
|
||||
public final void interpretCommand(String cmd) throws IOException {
|
||||
List<String> args;
|
||||
try {
|
||||
args = GCLCConstants.splitCommand(cmd);
|
||||
} catch (CommandParsingException e1) {
|
||||
manager.println("Command line cannot be parsed"); //$NON-NLS-1$
|
||||
LOGGER.log(Level.INFO, "Invalid user command " + cmd, e1); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE, "Invalid user command " + cmd, e1); //$NON-NLS-1$
|
||||
return;
|
||||
}
|
||||
if (!args.isEmpty()) {
|
||||
@@ -204,15 +151,18 @@ public class ConsoleApplication implements ICommandProvider {
|
||||
executeSub(args.get(0), Arrays.copyOfRange(
|
||||
args.toArray(new String[0]), 1, args.size()));
|
||||
} catch (final CommandRunException e) {
|
||||
LOGGER.log(Level.WARNING, "Command failed: " + cmd, e); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE, "Command failed: " + cmd, e); //$NON-NLS-1$
|
||||
manager.println(Messages
|
||||
.getString("ConsoleApplication.cmd.failed", cmd)); //$NON-NLS-1$
|
||||
manager.println(e.getLocalizedMessage());
|
||||
if (e.getType() == CommandRunExceptionType.USAGE) {
|
||||
e.getSource().help(manager);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param listener the listener to remove (once) */
|
||||
/** @param listener the command listener to remove */
|
||||
public final void removeListener(CommandRequestListener listener) {
|
||||
for (int i = 0; i < listeners.size(); i++) {
|
||||
if (listeners.get(i) == listener) {
|
||||
@@ -222,43 +172,74 @@ public class ConsoleApplication implements ICommandProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/** Launches the prompting application */
|
||||
/** Start the application */
|
||||
public final void start() {
|
||||
try {
|
||||
running = true;
|
||||
if (header != null) {
|
||||
manager.println(header);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// The manager was closed
|
||||
running = false;
|
||||
LOGGER.warning(
|
||||
"The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE,
|
||||
"An exception caused the closing of the application", //$NON-NLS-1$
|
||||
e);
|
||||
return;
|
||||
}
|
||||
do {
|
||||
runLoop();
|
||||
} while (running);
|
||||
if (footer != null) {
|
||||
try {
|
||||
manager.println(footer);
|
||||
} catch (IOException e) {
|
||||
// The manager was closed
|
||||
running = false;
|
||||
LOGGER.warning("The console manager was closed."); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE,
|
||||
"An exception occured when trying to print the good by e message... The application will still close.", //$NON-NLS-1$
|
||||
e);
|
||||
}
|
||||
}
|
||||
running = false;
|
||||
LOGGER.fine("Exiting application."); //$NON-NLS-1$
|
||||
}
|
||||
|
||||
/** The running loop content.
|
||||
* <p>
|
||||
* This consisting in getting the command, executing it and exiting
|
||||
* (restarting the loop). */
|
||||
private void runLoop() {
|
||||
try {
|
||||
final String cmd = manager.prompt();
|
||||
if (cmd == null || cmd.isEmpty()) {
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
for (final CommandRequestListener listener : listeners) {
|
||||
listener.commandRequest(cmd);
|
||||
}
|
||||
interpretCommand(cmd);
|
||||
} while (running);
|
||||
if (footer != null) {
|
||||
manager.println(footer);
|
||||
}
|
||||
LOGGER.fine("Exiting application."); //$NON-NLS-1$
|
||||
} catch (InterruptedIOException e) {
|
||||
LOGGER.info(
|
||||
"Prompt interrupted. It is likely the application is closing."); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINER, "Interruption of the prompt.", //$NON-NLS-1$
|
||||
e);
|
||||
} catch (IOException e) {
|
||||
// The manager was closed
|
||||
running = false;
|
||||
LOGGER.log(Level.WARNING,
|
||||
"The console manager was closed. Closing the application as no one can reach it.", //$NON-NLS-1$
|
||||
LOGGER.warning(
|
||||
"The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE,
|
||||
"An exception caused the closing of the application", //$NON-NLS-1$
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return if the application is running */
|
||||
/** @return the running status */
|
||||
public boolean isRunning() {
|
||||
return running;
|
||||
}
|
||||
|
||||
/** @return the root */
|
||||
public SubedCommand getRoot() {
|
||||
return root;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,11 +51,19 @@ import fr.bigeon.gclc.exception.CommandParsingException;
|
||||
* @author Emmanuel Bigeon */
|
||||
public class GCLCConstants {
|
||||
|
||||
/** The escaping character */
|
||||
private static final char ESCAPING_CHAR = getSystemEscapingChar();
|
||||
|
||||
/** Hide utility class constructor */
|
||||
private GCLCConstants() {
|
||||
// utility class
|
||||
}
|
||||
|
||||
/** @return the escaping character */
|
||||
private static char getSystemEscapingChar() {
|
||||
return '\\';
|
||||
}
|
||||
|
||||
/** Splits a command in the diferrent arguments
|
||||
*
|
||||
* @param cmd the command to split in its parts
|
||||
@@ -71,7 +79,7 @@ public class GCLCConstants {
|
||||
while (index < cmd.length()) {
|
||||
char c = cmd.charAt(index);
|
||||
index++;
|
||||
if (escaped || c == '\\') {
|
||||
if (escaped || c == ESCAPING_CHAR) {
|
||||
escaped = !escaped;
|
||||
continue;
|
||||
}
|
||||
@@ -90,8 +98,8 @@ public class GCLCConstants {
|
||||
inString = startIndex == index - 1;
|
||||
}
|
||||
}
|
||||
if (startIndex < cmd.length()) {
|
||||
final String arg = cmd.substring(startIndex, cmd.length());
|
||||
if (!arg.isEmpty()) {
|
||||
args.add(arg);
|
||||
}
|
||||
return args;
|
||||
@@ -102,11 +110,11 @@ public class GCLCConstants {
|
||||
private static String removeEscaped(String arg) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
int index = 0;
|
||||
int endIndex = arg.indexOf('\\');
|
||||
int endIndex = arg.indexOf(ESCAPING_CHAR);
|
||||
while (endIndex != -1) {
|
||||
builder.append(arg.subSequence(index, endIndex));
|
||||
index = endIndex + 1;
|
||||
endIndex = arg.indexOf('\\', index + 1);
|
||||
endIndex = arg.indexOf(ESCAPING_CHAR, index + 1);
|
||||
}
|
||||
builder.append(arg.substring(index));
|
||||
return builder.toString();
|
||||
|
||||
@@ -69,6 +69,8 @@ public abstract class Command implements ICommand {
|
||||
*
|
||||
*/
|
||||
private static final String EOL_LINUX = "\n"; //$NON-NLS-1$
|
||||
/** The empty string constant */
|
||||
private static final String EMPTY = ""; //$NON-NLS-1$
|
||||
/** The name of the command */
|
||||
protected final String name;
|
||||
|
||||
@@ -119,7 +121,7 @@ public abstract class Command implements ICommand {
|
||||
* @return the detailed help (should end with end of line or be empty) */
|
||||
@SuppressWarnings("static-method")
|
||||
protected String usageDetail() {
|
||||
return new String();
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
/** <p>
|
||||
|
||||
@@ -45,6 +45,8 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import fr.bigeon.gclc.exception.CommandParsingException;
|
||||
|
||||
/** <p>
|
||||
* An object representing a collection of parameters. It is used for defaulting
|
||||
* values.
|
||||
@@ -56,9 +58,9 @@ public class CommandParameters {
|
||||
*/
|
||||
private static final int STRINGARG_NUMBER_OF_ELEMENTS = 2;
|
||||
/** Boolean arguments */
|
||||
private final Map<String, Boolean> boolArgs = new HashMap<>();
|
||||
private final Map<String, Boolean> booleanArguments = new HashMap<>();
|
||||
/** String arguments */
|
||||
private final Map<String, String> stringArgs = new HashMap<>();
|
||||
private final Map<String, String> stringArguments = new HashMap<>();
|
||||
/** Arguments restriction on the named ones */
|
||||
private final boolean strict;
|
||||
/** additional (unnamed) parameters */
|
||||
@@ -71,10 +73,10 @@ public class CommandParameters {
|
||||
public CommandParameters(Set<String> bools, Set<String> strings,
|
||||
boolean strict) {
|
||||
for (final String string : bools) {
|
||||
boolArgs.put(string, false);
|
||||
booleanArguments.put(string, false);
|
||||
}
|
||||
for (final String string : strings) {
|
||||
stringArgs.put(string, null);
|
||||
stringArguments.put(string, null);
|
||||
}
|
||||
this.strict = strict;
|
||||
}
|
||||
@@ -82,7 +84,7 @@ public class CommandParameters {
|
||||
/** @param key the key
|
||||
* @return the associated value, null if it was not specified */
|
||||
public String get(String key) {
|
||||
return stringArgs.get(key);
|
||||
return stringArguments.get(key);
|
||||
}
|
||||
|
||||
/** @return additional non parsed parameters */
|
||||
@@ -92,14 +94,14 @@ public class CommandParameters {
|
||||
|
||||
/** @param key the key
|
||||
* @return if the key was specified */
|
||||
@SuppressWarnings("boxing")
|
||||
public boolean getBool(String key) {
|
||||
return boolArgs.get(key);
|
||||
return booleanArguments.containsKey(key) &&
|
||||
booleanArguments.get(key).booleanValue();
|
||||
}
|
||||
|
||||
/** @param args the arguments to parse
|
||||
* @return if the arguments were parsed */
|
||||
public boolean parseArgs(String... args) {
|
||||
* @throws CommandParsingException if the arguments parsing failed */
|
||||
public void parseArgs(String... args) throws CommandParsingException {
|
||||
int i = 0;
|
||||
while (i < args.length) {
|
||||
String next = null;
|
||||
@@ -108,11 +110,11 @@ public class CommandParameters {
|
||||
}
|
||||
int p = parseArg(args[i], next);
|
||||
if (p == 0) {
|
||||
return false;
|
||||
throw new CommandParsingException(
|
||||
"Invalid parameter " + args[i]); //$NON-NLS-1$
|
||||
}
|
||||
i += p;
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
@@ -126,14 +128,14 @@ public class CommandParameters {
|
||||
* @return the number of element read */
|
||||
private int parseArg(String arg, String next) {
|
||||
if (!arg.startsWith("-")) { //$NON-NLS-1$
|
||||
return 1;
|
||||
return strict ? 0 : 1;
|
||||
}
|
||||
String name = arg.substring(1);
|
||||
if (boolArgs.containsKey(name)) {
|
||||
boolArgs.put(name, Boolean.TRUE);
|
||||
if (booleanArguments.containsKey(name)) {
|
||||
booleanArguments.put(name, Boolean.TRUE);
|
||||
return 1;
|
||||
}
|
||||
if (stringArgs.containsKey(name)) {
|
||||
if (stringArguments.containsKey(name)) {
|
||||
return parseStringArg(name, next);
|
||||
}
|
||||
if (strict) {
|
||||
@@ -152,7 +154,7 @@ public class CommandParameters {
|
||||
if (next == null) {
|
||||
return 0;
|
||||
}
|
||||
stringArgs.put(name, next);
|
||||
stringArguments.put(name, next);
|
||||
return STRINGARG_NUMBER_OF_ELEMENTS;
|
||||
}
|
||||
|
||||
@@ -160,16 +162,33 @@ public class CommandParameters {
|
||||
* @param value the value */
|
||||
@SuppressWarnings("boxing")
|
||||
public void set(String string, boolean value) {
|
||||
if (boolArgs.containsKey(string)) {
|
||||
boolArgs.put(string, value);
|
||||
if (booleanArguments.containsKey(string)) {
|
||||
booleanArguments.put(string, value);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param string the key
|
||||
* @param value the value */
|
||||
public void set(String string, String value) {
|
||||
if (stringArgs.containsKey(string)) {
|
||||
stringArgs.put(string, value);
|
||||
if (stringArguments.containsKey(string)) {
|
||||
stringArguments.put(string, value);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return the boolean arguments */
|
||||
public Set<String> getBooleanArgumentKeys() {
|
||||
return booleanArguments.keySet();
|
||||
}
|
||||
|
||||
/** @return the boolean arguments */
|
||||
public Set<String> getStringArgumentKeys() {
|
||||
return stringArguments.keySet();
|
||||
}
|
||||
|
||||
/** @param key the key
|
||||
* @return if the key is present in string arguments or boolean ones. */
|
||||
public boolean hasArgument(String key) {
|
||||
return stringArguments.containsKey(key) ||
|
||||
booleanArguments.containsKey(key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,8 +36,8 @@
|
||||
* Created on: Aug 6, 2014 */
|
||||
package fr.bigeon.gclc.command;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.InvalidCommandName;
|
||||
@@ -53,12 +53,12 @@ public class CommandProvider implements ICommandProvider {
|
||||
/** The space character */
|
||||
private static final String SPACE = " "; //$NON-NLS-1$
|
||||
/** The commands map */
|
||||
protected final Set<ICommand> commands;
|
||||
protected final List<ICommand> commands;
|
||||
|
||||
/** Create a command provider */
|
||||
public CommandProvider() {
|
||||
super();
|
||||
commands = new HashSet<>();
|
||||
commands = new ArrayList<>();
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
@@ -67,12 +67,28 @@ public class CommandProvider implements ICommandProvider {
|
||||
@Override
|
||||
public boolean add(ICommand value) throws InvalidCommandName {
|
||||
final String name = value.getCommandName();
|
||||
if (name == null || name.startsWith(MINUS) || name.contains(SPACE)) {
|
||||
throw new InvalidCommandName();
|
||||
testCommandName(name);
|
||||
if (commands.contains(value)) {
|
||||
return true;
|
||||
}
|
||||
for (ICommand iCommand : commands) {
|
||||
if (iCommand.getCommandName().equals(value.getCommandName())) {
|
||||
throw new InvalidCommandName(
|
||||
"Name already used: " + value.getCommandName()); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
return commands.add(value);
|
||||
}
|
||||
|
||||
/** @param name the command name
|
||||
* @throws InvalidCommandName if the name is invalid */
|
||||
private static void testCommandName(String name) throws InvalidCommandName {
|
||||
if (name == null || name.isEmpty() || name.startsWith(MINUS) ||
|
||||
name.contains(SPACE)) {
|
||||
throw new InvalidCommandName();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void executeSub(String cmd,
|
||||
String... args) throws CommandRunException {
|
||||
@@ -83,7 +99,7 @@ public class CommandProvider implements ICommandProvider {
|
||||
}
|
||||
}
|
||||
throw new CommandRunException(
|
||||
Messages.getString("CommandProvider.unrecognized", cmd)); //$NON-NLS-1$
|
||||
Messages.getString("CommandProvider.unrecognized", cmd), null); //$NON-NLS-1$
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
|
||||
@@ -41,6 +41,7 @@ package fr.bigeon.gclc.command;
|
||||
import java.io.IOException;
|
||||
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.CommandRunExceptionType;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
import fr.bigeon.gclc.prompt.CLIPrompterMessages;
|
||||
|
||||
@@ -77,7 +78,8 @@ public class HelpExecutor extends Command {
|
||||
try {
|
||||
cmd.help(consoleManager, args);
|
||||
} catch (IOException e) {
|
||||
throw new CommandRunException("Console manager closed", e); //$NON-NLS-1$
|
||||
throw new CommandRunException(CommandRunExceptionType.INTERACTION,
|
||||
"Console manager closed", e, this); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,15 +87,21 @@ public class HelpExecutor extends Command {
|
||||
* @see fr.bigeon.gclc.command.Command#brief() */
|
||||
@Override
|
||||
protected String brief() {
|
||||
if (cmd instanceof SubedCommand) {
|
||||
return " A command to get help for other commands"; //$NON-NLS-1$
|
||||
}
|
||||
return " A command to retrieve help for " + cmd.getCommandName(); //$NON-NLS-1$
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#usagePattern() */
|
||||
@Override
|
||||
protected String usagePattern() {
|
||||
if (cmd instanceof SubedCommand) {
|
||||
return getCommandName() + " <otherCommand>"; //$NON-NLS-1$
|
||||
}
|
||||
return getCommandName();
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#tip() */
|
||||
|
||||
@@ -33,8 +33,8 @@
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.UnrecognizedCommand.java
|
||||
* Created on: Dec 23, 2014
|
||||
* gclc:fr.bigeon.gclc.command.MockCommand.java
|
||||
* Created on: Nov 18, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.command;
|
||||
|
||||
@@ -42,59 +42,50 @@ import java.io.IOException;
|
||||
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
import fr.bigeon.gclc.prompt.CLIPrompterMessages;
|
||||
|
||||
/** <p>
|
||||
* The error message for unrecognized commands
|
||||
/** This implement a command that does nothing.
|
||||
* <p>
|
||||
* This class is intended for testing purpose only.
|
||||
*
|
||||
* @author Emmanuel BIGEON */
|
||||
public final class UnrecognizedCommand implements ICommand {
|
||||
/** The unrecognized command key */
|
||||
private static final String UNRECOGNIZED_CMD = "unrecognized.cmd"; //$NON-NLS-1$
|
||||
/** The unrecognized command key */
|
||||
private static final String EXPECTED_CMD = "expected.cmd"; //$NON-NLS-1$
|
||||
/** The manager */
|
||||
private final ConsoleManager manager;
|
||||
* @author Emmanuel Bigeon */
|
||||
public final class MockCommand implements ICommand {
|
||||
|
||||
/** @param manager the console manager to use */
|
||||
public UnrecognizedCommand(ConsoleManager manager) {
|
||||
if (manager == null) {
|
||||
throw new NullPointerException("The argument cannot be null"); //$NON-NLS-1$
|
||||
}
|
||||
this.manager = manager;
|
||||
/** The command name */
|
||||
private final String name;
|
||||
|
||||
/** @param name the command name */
|
||||
public MockCommand(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
//
|
||||
}
|
||||
|
||||
try {
|
||||
if (args.length > 0) {
|
||||
manager.println(CLIPrompterMessages.getString(UNRECOGNIZED_CMD,
|
||||
(Object[]) args));
|
||||
} else {
|
||||
manager.println(CLIPrompterMessages.getString(EXPECTED_CMD));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new CommandRunException("Manager closed", e); //$NON-NLS-1$
|
||||
}
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.ICommand#tip() */
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.ICommand#getCommandName() */
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return ""; //$NON-NLS-1$
|
||||
return name;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.ICommand#help(fr.bigeon.gclc.manager.
|
||||
* ConsoleManager, java.lang.String[]) */
|
||||
@Override
|
||||
public void help(@SuppressWarnings("hiding") ConsoleManager manager,
|
||||
String... args) {
|
||||
// Nothing to do (no help provided as this is not a user command
|
||||
// (usually)
|
||||
public void help(ConsoleManager manager,
|
||||
String... args) throws IOException {
|
||||
//
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -40,11 +40,18 @@ package fr.bigeon.gclc.command;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
import fr.bigeon.gclc.exception.CommandParsingException;
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.CommandRunExceptionType;
|
||||
import fr.bigeon.gclc.exception.InvalidParameterException;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
|
||||
/** <p>
|
||||
@@ -54,20 +61,18 @@ import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
public abstract class ParametrizedCommand extends Command {
|
||||
|
||||
/** If the command may use interactive prompting for required parameters
|
||||
* that
|
||||
* were not provided on execution */
|
||||
* that were not provided on execution */
|
||||
private boolean interactive = true;
|
||||
/** The manager */
|
||||
protected final ConsoleManager manager;
|
||||
/** The boolean parameters mandatory status */
|
||||
private final Map<String, Boolean> boolParams = new HashMap<>();
|
||||
private final Set<String> boolParams = new HashSet<>();
|
||||
/** The string parameters mandatory status */
|
||||
private final Map<String, Boolean> stringParams = new HashMap<>();
|
||||
/** The parameters mandatory status */
|
||||
private final Map<String, Boolean> params = new HashMap<>();
|
||||
/** The restriction of provided parameters on execution to declared
|
||||
* paramters
|
||||
* in the status maps. */
|
||||
* paramters in the status maps. */
|
||||
private final boolean strict;
|
||||
|
||||
/** @param manager the manager
|
||||
@@ -76,6 +81,11 @@ public abstract class ParametrizedCommand extends Command {
|
||||
this(manager, name, true);
|
||||
}
|
||||
|
||||
/** @param name the name */
|
||||
public ParametrizedCommand(String name) {
|
||||
this(null, name, true);
|
||||
}
|
||||
|
||||
/** @param manager the manager
|
||||
* @param name the name
|
||||
* @param strict if the arguments are restricted to the declared ones */
|
||||
@@ -87,50 +97,141 @@ public abstract class ParametrizedCommand extends Command {
|
||||
this.strict = strict;
|
||||
}
|
||||
|
||||
/** @param name the name
|
||||
* @param strict if the arguments are restricted to the declared ones */
|
||||
public ParametrizedCommand(String name, boolean strict) {
|
||||
this(null, name, strict);
|
||||
}
|
||||
|
||||
/** <p>
|
||||
* Add a parameter to the defined parameters
|
||||
*
|
||||
* @param param the parameter identification
|
||||
* @param stringOrBool if the parameter is a parameter with an argument
|
||||
* @param needed if the parameter is required */
|
||||
@SuppressWarnings("boxing")
|
||||
protected void addParameter(String param, boolean stringOrBool,
|
||||
boolean needed) {
|
||||
* @param stringParameter if the parameter is a parameter with an argument
|
||||
* @param needed if the parameter is required
|
||||
* @throws InvalidParameterException if the parameter was invalid
|
||||
* @deprecated since gclc-1.3.3, use the
|
||||
* {@link #addStringParameter(String, boolean)} and
|
||||
* {@link #addBooleanParameter(String)} */
|
||||
@Deprecated
|
||||
protected void addParameter(String param, boolean stringParameter,
|
||||
boolean needed) throws InvalidParameterException {
|
||||
if (params.containsKey(param)) {
|
||||
checkParam(param, stringParameter, needed);
|
||||
return;
|
||||
}
|
||||
params.put(param, needed);
|
||||
if (stringOrBool) {
|
||||
stringParams.put(param, needed);
|
||||
if (stringParameter) {
|
||||
stringParams.put(param, Boolean.valueOf(needed));
|
||||
params.put(param, Boolean.valueOf(needed));
|
||||
} else {
|
||||
if (needed) {
|
||||
// ERROR the boolean parameters cannot be needed
|
||||
throw new InvalidParameterException(
|
||||
"Boolean parameter are present by their very nature. They should not be defined as needed"); //$NON-NLS-1$
|
||||
}
|
||||
boolParams.put(param, needed);
|
||||
boolParams.add(param);
|
||||
params.put(param, Boolean.valueOf(false));
|
||||
}
|
||||
}
|
||||
|
||||
/** @param parameters the command parameters */
|
||||
protected abstract void doExecute(CommandParameters parameters);
|
||||
/** Add a boolean parameter to defined parmaters.
|
||||
*
|
||||
* @param flag the boolean flag
|
||||
* @throws InvalidParameterException if the parameter is already defined as
|
||||
* a string parameter */
|
||||
protected void addBooleanParameter(String flag) throws InvalidParameterException {
|
||||
if (params.containsKey(flag) && stringParams.containsKey(flag)) {
|
||||
throw new InvalidParameterException(
|
||||
"Parameter is already defined as string"); //$NON-NLS-1$
|
||||
}
|
||||
boolParams.add(flag);
|
||||
params.put(flag, Boolean.valueOf(false));
|
||||
}
|
||||
|
||||
/** Add a string parameter to defined parmaters.
|
||||
*
|
||||
* @param flag the parameter flag
|
||||
* @param needed if the parameter's absence should cause an exception
|
||||
* @throws InvalidParameterException if the parameter is already defined as
|
||||
* a boolean parameter */
|
||||
protected void addStringParameter(String flag,
|
||||
boolean needed) throws InvalidParameterException {
|
||||
if (params.containsKey(flag)) {
|
||||
checkParam(flag, needed);
|
||||
return;
|
||||
}
|
||||
stringParams.put(flag, Boolean.valueOf(needed));
|
||||
params.put(flag, Boolean.valueOf(needed));
|
||||
}
|
||||
|
||||
/** @param param the parameter
|
||||
* @param stringParameter the string parameter type
|
||||
* @param needed if the parameter is needed
|
||||
* @throws InvalidParameterException if the new definition is invalid
|
||||
* @deprecated since 1.3.3 */
|
||||
@Deprecated
|
||||
private void checkParam(String param, boolean stringParameter,
|
||||
boolean needed) throws InvalidParameterException {
|
||||
if (stringParameter) {
|
||||
if (stringParams.containsKey(param)) {
|
||||
Boolean need = Boolean.valueOf(
|
||||
needed || stringParams.get(param).booleanValue());
|
||||
stringParams.put(param, need);
|
||||
params.put(param, need);
|
||||
return;
|
||||
}
|
||||
throw new InvalidParameterException(
|
||||
"Parameter is already defined as boolean"); //$NON-NLS-1$
|
||||
}
|
||||
if (stringParams.containsKey(param) || needed) {
|
||||
throw new InvalidParameterException(
|
||||
"Parameter is already defined as string"); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
|
||||
/** @param param the string parameter
|
||||
* @param needed if the parameter is needed
|
||||
* @throws InvalidParameterException if the new definition is invalid */
|
||||
private void checkParam(String param,
|
||||
boolean needed) throws InvalidParameterException {
|
||||
if (stringParams.containsKey(param)) {
|
||||
Boolean need = Boolean
|
||||
.valueOf(needed || stringParams.get(param).booleanValue());
|
||||
stringParams.put(param, need);
|
||||
params.put(param, need);
|
||||
return;
|
||||
}
|
||||
throw new InvalidParameterException(
|
||||
"Parameter is already defined as boolean"); //$NON-NLS-1$
|
||||
}
|
||||
|
||||
/** @param parameters the command parameters
|
||||
* @throws CommandRunException if the command failed */
|
||||
protected abstract void doExecute(CommandParameters parameters) throws CommandRunException;
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#execute(java.lang.String[]) */
|
||||
@SuppressWarnings("boxing")
|
||||
@Override
|
||||
public final void execute(String... args) throws CommandRunException {
|
||||
final CommandParameters parameters = new CommandParameters(
|
||||
boolParams.keySet(), stringParams.keySet(), strict);
|
||||
if (!parameters.parseArgs(args)) {
|
||||
// ERROR the parameters could not be correctly parsed
|
||||
throw new CommandRunException("Unable to read arguments"); //$NON-NLS-1$
|
||||
final CommandParameters parameters = new CommandParameters(boolParams,
|
||||
stringParams.keySet(), strict);
|
||||
try {
|
||||
parameters.parseArgs(args);
|
||||
} catch (CommandParsingException e) {
|
||||
throw new CommandRunException(CommandRunExceptionType.USAGE,
|
||||
"Unable to read arguments", e, this); //$NON-NLS-1$
|
||||
}
|
||||
final List<String> toProvide = new ArrayList<>();
|
||||
for (final String string : params.keySet()) {
|
||||
if (params.get(string) && parameters.get(string) == null) {
|
||||
for (final Entry<String, Boolean> string : params.entrySet()) {
|
||||
if (string.getValue() && parameters.get(string.getKey()) == null) {
|
||||
if (!interactive) {
|
||||
return;
|
||||
throw new CommandRunException(
|
||||
CommandRunExceptionType.INTERACTION,
|
||||
"Missing required parameter " + string.getKey(), //$NON-NLS-1$
|
||||
this);
|
||||
}
|
||||
toProvide.add(string);
|
||||
toProvide.add(string.getKey());
|
||||
}
|
||||
}
|
||||
// for each needed parameters that is missing, prompt the user.
|
||||
@@ -146,15 +247,48 @@ public abstract class ParametrizedCommand extends Command {
|
||||
for (final String string : toProvide) {
|
||||
String value;
|
||||
try {
|
||||
value = manager.prompt(string);
|
||||
value = manager.prompt("value of " + string + "? ");
|
||||
while (value.isEmpty()) {
|
||||
value = manager.prompt(string);
|
||||
value = manager.prompt(
|
||||
"value of " + string + "? (cannot be empty) ");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new CommandRunException(
|
||||
"Interactive command but manager closed...", e); //$NON-NLS-1$
|
||||
CommandRunExceptionType.INTERACTION,
|
||||
"Interactive command but manager closed...", e, this); //$NON-NLS-1$
|
||||
}
|
||||
parameters.set(string, value);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return the set of boolean parameters */
|
||||
public Set<String> getBooleanParameters() {
|
||||
return Collections.unmodifiableSet(boolParams);
|
||||
}
|
||||
|
||||
/** @return the stringParams */
|
||||
public Set<String> getStringParameters() {
|
||||
return stringParams.keySet();
|
||||
}
|
||||
|
||||
/** @return the stringParams */
|
||||
public Set<String> getParameters() {
|
||||
return params.keySet();
|
||||
}
|
||||
|
||||
/** @param param the parameter name
|
||||
* @return if the parameter is needed */
|
||||
public boolean isNeeded(String param) {
|
||||
return params.containsKey(param) && params.get(param).booleanValue();
|
||||
}
|
||||
|
||||
/** @return the strict */
|
||||
public boolean isStrict() {
|
||||
return strict;
|
||||
}
|
||||
|
||||
/** @return the interactive */
|
||||
public boolean isInteractive() {
|
||||
return interactive;
|
||||
}
|
||||
}
|
||||
|
||||
206
gclc/src/main/java/fr/bigeon/gclc/command/ScriptExecution.java
Normal file
206
gclc/src/main/java/fr/bigeon/gclc/command/ScriptExecution.java
Normal file
@@ -0,0 +1,206 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.command.ScriptExecution.java
|
||||
* Created on: Jun 12, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.command;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.Charset;
|
||||
import java.text.MessageFormat;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import fr.bigeon.gclc.ConsoleApplication;
|
||||
import fr.bigeon.gclc.GCLCConstants;
|
||||
import fr.bigeon.gclc.exception.CommandParsingException;
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.CommandRunExceptionType;
|
||||
|
||||
/** A command that will laucnh a series of command from a file
|
||||
* <p>
|
||||
* This command will read a file and execute each non empty non commented line
|
||||
* as a command of the application.
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class ScriptExecution extends Command {
|
||||
|
||||
/** The tab character */
|
||||
private static final String TAB = "\t"; //$NON-NLS-1$
|
||||
/** the space character */
|
||||
private static final String SPACE = " "; //$NON-NLS-1$
|
||||
/** The application */
|
||||
private final ConsoleApplication application;
|
||||
/** The commenting prefix */
|
||||
private final String commentPrefix;
|
||||
/** The charset for files */
|
||||
private final Charset charset;
|
||||
|
||||
/** @param name the name of the command
|
||||
* @param application the application
|
||||
* @param commentPrefix the comment prefix in the script files
|
||||
* @param charset the charset to use for files */
|
||||
public ScriptExecution(String name, ConsoleApplication application,
|
||||
String commentPrefix, Charset charset) {
|
||||
super(name);
|
||||
this.application = application;
|
||||
this.commentPrefix = commentPrefix;
|
||||
this.charset = charset;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
checkArgs(args);
|
||||
String scriptFile = args[0];
|
||||
String[] params = Arrays.copyOfRange(args, 1, args.length);
|
||||
String cmd;
|
||||
int lineNo = -1;
|
||||
try (InputStreamReader fReader = new InputStreamReader(
|
||||
new FileInputStream(scriptFile), charset);
|
||||
BufferedReader reader = new BufferedReader(fReader)) {
|
||||
while ((cmd = reader.readLine()) != null) {
|
||||
lineNo++;
|
||||
String cmdLine = readCommandLine(cmd, params);
|
||||
if (cmdLine == null) {
|
||||
continue;
|
||||
}
|
||||
List<String> ps = GCLCConstants.splitCommand(cmdLine);
|
||||
String command = ps.remove(0);
|
||||
application.executeSub(command, ps.toArray(new String[0]));
|
||||
}
|
||||
} catch (CommandParsingException e) {
|
||||
throw new CommandRunException(MessageFormat.format(
|
||||
"Invalid command in script ({0})", e.getLocalizedMessage()), //$NON-NLS-1$
|
||||
e, this);
|
||||
} catch (IOException e) {
|
||||
throw new CommandRunException("Unable to read script", //$NON-NLS-1$
|
||||
e, this);
|
||||
} catch (CommandRunException e) {
|
||||
throw manageRunException(e, lineNo);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param args the arguments
|
||||
* @throws CommandRunException if the arguments were not the ones
|
||||
* expected */
|
||||
private void checkArgs(String[] args) throws CommandRunException {
|
||||
if (args.length == 0) {
|
||||
throw new CommandRunException(CommandRunExceptionType.USAGE,
|
||||
"Expecting a file", this); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
|
||||
/** This method will create the correct exception. The exception source must
|
||||
* be this command.
|
||||
*
|
||||
* @param e the exception
|
||||
* @param lineNo the line nu;ber
|
||||
* @return the exception to actually throw */
|
||||
private CommandRunException manageRunException(CommandRunException e,
|
||||
int lineNo) {
|
||||
if (e.getSource() == this) {
|
||||
// ensure closing?
|
||||
return e;
|
||||
}
|
||||
return new CommandRunException(CommandRunExceptionType.EXECUTION,
|
||||
MessageFormat.format(
|
||||
"The script could not complete due to command failure at line {0} ({1})", //$NON-NLS-1$
|
||||
Integer.valueOf(lineNo), e.getLocalizedMessage()),
|
||||
e, this);
|
||||
}
|
||||
|
||||
/** @param cmd the line
|
||||
* @param params the formatting parameters
|
||||
* @return the command if it is indeed one, null otherwise
|
||||
* @throws CommandRunException if the line stqrted with a space character */
|
||||
private String readCommandLine(String cmd,
|
||||
Object[] params) throws CommandRunException {
|
||||
if (cmd.startsWith(SPACE) || cmd.startsWith(TAB)) {
|
||||
throw new CommandRunException(
|
||||
"Invalid command in script (line starts with space character)", //$NON-NLS-1$
|
||||
this);
|
||||
}
|
||||
if (cmd.isEmpty() || cmd.startsWith(commentPrefix)) {
|
||||
return null;
|
||||
}
|
||||
return MessageFormat.format(cmd, params);
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#usageDetail() */
|
||||
@SuppressWarnings("nls")
|
||||
@Override
|
||||
protected String usageDetail() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append(
|
||||
" scriptfile: path to the file containing the script to execute.");
|
||||
builder.append(System.lineSeparator());
|
||||
builder.append(System.lineSeparator());
|
||||
builder.append(
|
||||
" The script file must contain one line commands. The lines must never");
|
||||
builder.append(System.lineSeparator());
|
||||
builder.append(
|
||||
"start with whitespace characters. The lines starting with");
|
||||
builder.append(System.lineSeparator());
|
||||
builder.append("\"" + commentPrefix +
|
||||
"\" will be ignored as well as empty lines.");
|
||||
builder.append(System.lineSeparator());
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#usagePattern() */
|
||||
@SuppressWarnings("nls")
|
||||
@Override
|
||||
protected String usagePattern() {
|
||||
return super.usagePattern() + " <scriptfile>";
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.ICommand#tip() */
|
||||
@SuppressWarnings("nls")
|
||||
@Override
|
||||
public String tip() {
|
||||
return "Execute a script";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -40,6 +40,7 @@ import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.CommandRunExceptionType;
|
||||
import fr.bigeon.gclc.exception.InvalidCommandName;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
|
||||
@@ -114,10 +115,19 @@ public class SubedCommand implements ICommandProvider, ICommand {
|
||||
if (noArgCommand != null) {
|
||||
noArgCommand.execute(args);
|
||||
} else {
|
||||
throw new CommandRunException("Unrecognized command"); //$NON-NLS-1$
|
||||
throw new CommandRunException("Unrecognized command", this); //$NON-NLS-1$
|
||||
}
|
||||
} else {
|
||||
|
||||
try {
|
||||
executeSub(args[0], Arrays.copyOfRange(args, 1, args.length));
|
||||
} catch (CommandRunException e) {
|
||||
if (e.getSource() != null) {
|
||||
throw e;
|
||||
}
|
||||
throw new CommandRunException(CommandRunExceptionType.USAGE,
|
||||
e.getLocalizedMessage(), e, this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,8 +44,6 @@
|
||||
* {@link fr.bigeon.gclc.command.SubedCommand} for a command that is declined in
|
||||
* a set of sub commands, the {@link fr.bigeon.gclc.command.HelpExecutor} for
|
||||
* help display of other commands and the
|
||||
* {@link fr.bigeon.gclc.command.UnrecognizedCommand} that should not be
|
||||
* directly accessible to the user, but will be used in case of error in typing.
|
||||
*
|
||||
* @author Emmanuel BIGEON */
|
||||
package fr.bigeon.gclc.command;
|
||||
@@ -38,6 +38,8 @@
|
||||
*/
|
||||
package fr.bigeon.gclc.exception;
|
||||
|
||||
import fr.bigeon.gclc.command.ICommand;
|
||||
|
||||
/** <p>
|
||||
* An exception thrown when a command failed to run correctly.
|
||||
*
|
||||
@@ -49,15 +51,48 @@ public class CommandRunException extends Exception {
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** @param message a message */
|
||||
public CommandRunException(String message) {
|
||||
/** The type of run exception */
|
||||
private final CommandRunExceptionType type;
|
||||
/** The command that caused the error */
|
||||
private final ICommand source;
|
||||
|
||||
/** @param message a message
|
||||
* @param source the source */
|
||||
public CommandRunException(String message, ICommand source) {
|
||||
super(message);
|
||||
type = CommandRunExceptionType.EXECUTION;
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
/** @param message a message
|
||||
* @param cause the cause */
|
||||
public CommandRunException(String message, Throwable cause) {
|
||||
* @param cause the cause
|
||||
* @param source the source */
|
||||
public CommandRunException(String message, Throwable cause,
|
||||
ICommand source) {
|
||||
super(message, cause);
|
||||
type = CommandRunExceptionType.EXECUTION;
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
/** @param type the type of exception
|
||||
* @param message the message
|
||||
* @param source the source */
|
||||
public CommandRunException(CommandRunExceptionType type, String message,
|
||||
ICommand source) {
|
||||
super(message);
|
||||
this.type = type;
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
/** @param type the type of exception
|
||||
* @param message a message
|
||||
* @param cause the cause
|
||||
* @param source the source */
|
||||
public CommandRunException(CommandRunExceptionType type, String message,
|
||||
Throwable cause, ICommand source) {
|
||||
super(message, cause);
|
||||
this.type = type;
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
@@ -71,4 +106,13 @@ public class CommandRunException extends Exception {
|
||||
return super.getLocalizedMessage();
|
||||
}
|
||||
|
||||
/** @return the source */
|
||||
public ICommand getSource() {
|
||||
return source;
|
||||
}
|
||||
|
||||
/** @return the type */
|
||||
public CommandRunExceptionType getType() {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.exception.CommandRunExceptionType.java
|
||||
* Created on: Jun 12, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.exception;
|
||||
|
||||
/** The command run exception possible types
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public enum CommandRunExceptionType {
|
||||
/** Type of exception due to a wrong usage */
|
||||
USAGE,
|
||||
/** Type of exception due to a problem in execution */
|
||||
EXECUTION,
|
||||
/** Type of exception due to the impossibility to interact with user */
|
||||
INTERACTION;
|
||||
}
|
||||
@@ -40,7 +40,7 @@ package fr.bigeon.gclc.exception;
|
||||
|
||||
/** <p>
|
||||
* Exception sent from the application when a command is added but the name of
|
||||
* the command
|
||||
* the command is already used
|
||||
*
|
||||
* @author Emmanuel BIGEON */
|
||||
public class InvalidCommandName extends Exception {
|
||||
@@ -50,4 +50,25 @@ public class InvalidCommandName extends Exception {
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** Default constructor */
|
||||
public InvalidCommandName() {
|
||||
super();
|
||||
}
|
||||
|
||||
/** @param message the message
|
||||
* @param cause the cause */
|
||||
public InvalidCommandName(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
/** @param message the message */
|
||||
public InvalidCommandName(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/** @param cause the cause */
|
||||
public InvalidCommandName(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.exception.InvalidParameterException.java
|
||||
* Created on: Nov 19, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.exception;
|
||||
|
||||
/** This exception is thrown during command definitions to indicate a wrong
|
||||
* parameter definition.
|
||||
* <p>
|
||||
* This class is particularly used by
|
||||
* {@link fr.bigeon.gclc.command.ParametrizedCommand parameterized commands}.
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class InvalidParameterException extends Exception {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** @param message the message
|
||||
* @param cause the cause */
|
||||
public InvalidParameterException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
/** @param message the message */
|
||||
public InvalidParameterException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/** @param cause the cause */
|
||||
public InvalidParameterException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -39,6 +39,7 @@
|
||||
package fr.bigeon.gclc.manager;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InterruptedIOException;
|
||||
|
||||
/** <p>
|
||||
* A console manager is in charge of the basic prompts and prints on a console.
|
||||
@@ -47,7 +48,7 @@ import java.io.IOException;
|
||||
* a message, in that case, the usual behavior is to prompt normally.
|
||||
*
|
||||
* @author Emmanuel BIGEON */
|
||||
public interface ConsoleManager {
|
||||
public interface ConsoleManager extends AutoCloseable {
|
||||
|
||||
/** @return the prompt prefix */
|
||||
String getPrompt();
|
||||
@@ -69,16 +70,29 @@ public interface ConsoleManager {
|
||||
void println(String message) throws IOException;
|
||||
|
||||
/** @return the user inputed string
|
||||
* @throws IOException if the manager is closed or could not read the
|
||||
* prompt */
|
||||
* @throws IOException if the manager is closed or could not read the prompt
|
||||
* @throws InterruptedIOException if the prompt was interrupted */
|
||||
String prompt() throws IOException;
|
||||
|
||||
/** @param timeout the time to wait in milliseconds
|
||||
* @return the user inputed string, null if the timeout was reached
|
||||
* @throws IOException if the manager is closed or could not read the prompt
|
||||
* @throws InterruptedIOException if the prompt was interrupted */
|
||||
String prompt(long timeout) throws IOException;
|
||||
|
||||
/** @param message the message to prompt the user
|
||||
* @return the user inputed string
|
||||
* @throws IOException if the manager is closed or could not read the
|
||||
* prompt */
|
||||
* @throws IOException if the manager is closed or could not read the prompt
|
||||
* @throws InterruptedIOException if the prompt was interrupted */
|
||||
String prompt(String message) throws IOException;
|
||||
|
||||
/** @param timeout the time to wait in milliseconds
|
||||
* @param message the message to prompt the user
|
||||
* @return the user inputed string, null if the timeout was reached
|
||||
* @throws IOException if the manager is closed or could not read the prompt
|
||||
* @throws InterruptedIOException if the prompt was interrupted */
|
||||
String prompt(String message, long timeout) throws IOException;
|
||||
|
||||
/** <p>
|
||||
* Set a prompting prefix.
|
||||
*
|
||||
@@ -88,8 +102,18 @@ public interface ConsoleManager {
|
||||
/** Closes the manager.
|
||||
*
|
||||
* @throws IOException if the close raised an exception */
|
||||
@Override
|
||||
void close() throws IOException;
|
||||
|
||||
/** @return if the manager is closed. */
|
||||
boolean isClosed();
|
||||
|
||||
/** Indicate to the manager that is should interrompt the prompting, if
|
||||
* possible.
|
||||
* <p>
|
||||
* The pending {@link #prompt()} or {@link #prompt(String)} operations
|
||||
* should return immediatly. However the returned value can be anything
|
||||
* (from the partial prompt content to an empty string or even a null
|
||||
* pointer). */
|
||||
void interruptPrompt();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc-test:fr.bigeon.gclc.test.TestConsoleManager.java
|
||||
* Created on: Nov 18, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.manager;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PipedInputStream;
|
||||
import java.io.PipedOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/** This console manager allows to enter commands and retrieve the output as an
|
||||
* input.
|
||||
* <p>
|
||||
* This console manager is used to internally pilot an application. This can be
|
||||
* used to test application behavior.
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public final class PipedConsoleManager
|
||||
implements ConsoleManager {
|
||||
|
||||
/** The encoding between streams */
|
||||
private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
|
||||
/** THe inner manager */
|
||||
private final SystemConsoleManager innerManager;
|
||||
/** The stream to pipe commands into */
|
||||
private final PipedOutputStream commandInput;
|
||||
/** The reader to get application return from */
|
||||
private final BufferedReader commandBuffOutput;
|
||||
/** The stream to get application return from */
|
||||
private final PipedInputStream commandOutput;
|
||||
/** The print writer for application to write return to */
|
||||
private final PrintStream outPrint;
|
||||
/** The stream for the application to read commands from */
|
||||
private final PipedInputStream in;
|
||||
/** The writing thread */
|
||||
private final WritingRunnable writing;
|
||||
/** The reading thread */
|
||||
private final ReadingRunnable reading;
|
||||
|
||||
/** @throws IOException if the piping failed for streams */
|
||||
public PipedConsoleManager() throws IOException {
|
||||
commandInput = new PipedOutputStream();
|
||||
in = new PipedInputStream(commandInput);
|
||||
commandOutput = new PipedInputStream();
|
||||
PipedOutputStream out = new PipedOutputStream(commandOutput);
|
||||
commandBuffOutput = new BufferedReader(
|
||||
new InputStreamReader(commandOutput, Charset.forName(UTF_8)));
|
||||
outPrint = new PrintStream(out, true, UTF_8);
|
||||
innerManager = new SystemConsoleManager(outPrint, in,
|
||||
Charset.forName(UTF_8));
|
||||
writing = new WritingRunnable(commandInput, Charset.forName(UTF_8));
|
||||
reading = new ReadingRunnable(commandBuffOutput);
|
||||
Thread th = new Thread(writing, "write"); //$NON-NLS-1$
|
||||
th.start();
|
||||
th = new Thread(reading, "read"); //$NON-NLS-1$
|
||||
th.setDaemon(true);
|
||||
th.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPrompt() {
|
||||
return innerManager.getPrompt();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void print(String object) throws IOException {
|
||||
innerManager.print(object);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void println() throws IOException {
|
||||
innerManager.println();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void println(String object) throws IOException {
|
||||
innerManager.println(object);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String prompt() throws IOException {
|
||||
return innerManager
|
||||
.prompt(innerManager.getPrompt() + System.lineSeparator());
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */
|
||||
@Override
|
||||
public String prompt(long timeout) throws IOException {
|
||||
return innerManager.prompt(timeout);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String prompt(String message) throws IOException {
|
||||
return innerManager.prompt(message + System.lineSeparator());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String prompt(String message, long timeout) throws IOException {
|
||||
return innerManager.prompt(message + System.lineSeparator(), timeout);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPrompt(String prompt) {
|
||||
innerManager.setPrompt(prompt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
innerManager.close();
|
||||
reading.setRunning(false);
|
||||
writing.setRunning(false);
|
||||
outPrint.close();
|
||||
commandBuffOutput.close();
|
||||
commandOutput.close();
|
||||
in.close();
|
||||
commandInput.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClosed() {
|
||||
return innerManager.isClosed();
|
||||
}
|
||||
|
||||
/** @param content the content to type to the application
|
||||
* @throws IOException if the typing failed */
|
||||
public void type(String content) throws IOException {
|
||||
writing.addMessage(content);
|
||||
}
|
||||
|
||||
/** @return the content of the next line written by the application
|
||||
* @throws IOException if the reading failed */
|
||||
public String readNextLine() throws IOException {
|
||||
return reading.getMessage();
|
||||
}
|
||||
|
||||
/** @return the content of the next line written by the application
|
||||
* @throws IOException if the reading failed */
|
||||
public boolean available() throws IOException {
|
||||
return reading.hasMessage();
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */
|
||||
@Override
|
||||
public void interruptPrompt() {
|
||||
innerManager.interruptPrompt();
|
||||
}
|
||||
|
||||
/** @param message the message
|
||||
* @return the thread to join to wait for message delivery
|
||||
* @see fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String) */
|
||||
public Thread getWaitForDelivery(String message) {
|
||||
return reading.getWaitForDelivery(message);
|
||||
}
|
||||
|
||||
}
|
||||
310
gclc/src/main/java/fr/bigeon/gclc/manager/ReadingRunnable.java
Normal file
310
gclc/src/main/java/fr/bigeon/gclc/manager/ReadingRunnable.java
Normal file
@@ -0,0 +1,310 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.test.utils.WritingRunnable.java
|
||||
* Created on: Nov 29, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.manager;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InterruptedIOException;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/** A runnable to read the piped output.
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class ReadingRunnable implements Runnable {
|
||||
|
||||
/** The runnable to wait for notification on an object
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
private final class ToWaitRunnable implements Runnable {
|
||||
/** The Object */
|
||||
private final Object obj;
|
||||
/** The locking object */
|
||||
private final Object start;
|
||||
/** The message */
|
||||
private final String message;
|
||||
/** The started status */
|
||||
private boolean started = false;
|
||||
|
||||
/** @param obj the object to lock on
|
||||
* @param start the object to notify when ready to wait
|
||||
* @param message the message to wait for */
|
||||
public ToWaitRunnable(Object obj, Object start, String message) {
|
||||
this.obj = obj;
|
||||
this.start = start;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (obj) {
|
||||
synchronized (start) {
|
||||
started = true;
|
||||
start.notify();
|
||||
}
|
||||
while (isRunning()) {
|
||||
try {
|
||||
obj.wait();
|
||||
if (delivering.equals(message)) {
|
||||
return;
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION,
|
||||
e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return the started */
|
||||
public boolean isStarted() {
|
||||
synchronized (start) {
|
||||
return started;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The thread intteruption logging message */
|
||||
private static final String THREAD_INTERRUPTION_EXCEPTION = "Thread interruption exception."; //$NON-NLS-1$
|
||||
/** The closed pipe message */
|
||||
private static final String CLOSED_PIPE = "Closed pipe"; //$NON-NLS-1$
|
||||
/** Wait timeout */
|
||||
private static final long TIMEOUT = 1000;
|
||||
/** Class logger */
|
||||
private static final Logger LOGGER = Logger
|
||||
.getLogger(ReadingRunnable.class.getName());
|
||||
/** Read messages */
|
||||
private final Deque<String> messages = new ArrayDeque<>();
|
||||
/** the reader */
|
||||
private final BufferedReader reader;
|
||||
/** the state of this runnable */
|
||||
private boolean running = true;
|
||||
|
||||
/** Synchro object */
|
||||
private final Object lock = new Object();
|
||||
/** The waiting status for a message */
|
||||
private boolean waiting;
|
||||
/** The blocker for a given message */
|
||||
private final Map<String, Object> messageBlocker = new HashMap<>();
|
||||
/** The lock */
|
||||
private final Object messageBlockerLock = new Object();
|
||||
/** The message being delivered */
|
||||
private String delivering;
|
||||
|
||||
/** @param reader the input to read from */
|
||||
public ReadingRunnable(BufferedReader reader) {
|
||||
super();
|
||||
this.reader = reader;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see java.lang.Runnable#run() */
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
while (running) {
|
||||
try {
|
||||
String line = reader.readLine();
|
||||
if (line == null) {
|
||||
// Buffer end
|
||||
running = false;
|
||||
return;
|
||||
}
|
||||
LOGGER.finer("Read: " + line); //$NON-NLS-1$
|
||||
line = stripNull(line);
|
||||
synchronized (lock) {
|
||||
messages.add(line);
|
||||
lock.notify();
|
||||
}
|
||||
} catch (InterruptedIOException e) {
|
||||
LOGGER.info("Reading interrupted"); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINER,
|
||||
"Read interruption was caused by an exception", e); //$NON-NLS-1$
|
||||
} catch (IOException e) {
|
||||
LOGGER.severe("Unable to read from stream"); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE, "The stream reading threw an exception", //$NON-NLS-1$
|
||||
e);
|
||||
running = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Strip the string from head NULL characters.
|
||||
*
|
||||
* @param line the line to strip the null character from
|
||||
* @return the resulting string */
|
||||
private static String stripNull(String line) {
|
||||
String res = line;
|
||||
while (res.length() > 0 && res.charAt(0) == 0) {
|
||||
LOGGER.severe(
|
||||
"NULL character heading the result of the read. This is a stream problem..."); //$NON-NLS-1$
|
||||
res = res.substring(1);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/** @return the next read message
|
||||
* @throws IOException if the pipe is closed */
|
||||
public String getMessage() throws IOException {
|
||||
synchronized (lock) {
|
||||
if (!running) {
|
||||
throw new IOException(CLOSED_PIPE);
|
||||
}
|
||||
waiting = true;
|
||||
while (messages.isEmpty()) {
|
||||
try {
|
||||
lock.wait(TIMEOUT);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e);
|
||||
}
|
||||
if (messages.isEmpty() && !running) {
|
||||
throw new IOException(CLOSED_PIPE);
|
||||
}
|
||||
}
|
||||
LOGGER.finest("Polled: " + messages.peek()); //$NON-NLS-1$
|
||||
waiting = false;
|
||||
notifyMessage(messages.peek());
|
||||
return messages.poll();
|
||||
}
|
||||
}
|
||||
|
||||
public String getNextMessage(long timeout) throws IOException {
|
||||
synchronized (lock) {
|
||||
if (!running) {
|
||||
throw new IOException(CLOSED_PIPE);
|
||||
}
|
||||
waiting = true;
|
||||
try {
|
||||
lock.wait(timeout);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e);
|
||||
}
|
||||
if (messages.isEmpty() && !running) {
|
||||
throw new IOException(CLOSED_PIPE);
|
||||
}
|
||||
waiting = false;
|
||||
if (messages.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return messages.poll();
|
||||
}
|
||||
}
|
||||
|
||||
/** @param running the running to set */
|
||||
public void setRunning(boolean running) {
|
||||
synchronized (lock) {
|
||||
this.running = running;
|
||||
}
|
||||
}
|
||||
|
||||
/** @return the running */
|
||||
public boolean isRunning() {
|
||||
synchronized (lock) {
|
||||
return running;
|
||||
}
|
||||
}
|
||||
|
||||
/** @return if a message is waiting
|
||||
* @throws IOException if the pipe is closed */
|
||||
public boolean hasMessage() throws IOException {
|
||||
synchronized (lock) {
|
||||
if (!running) {
|
||||
throw new IOException(CLOSED_PIPE);
|
||||
}
|
||||
return !messages.isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
/** Interrupts the wait on the next message by providing an empty message */
|
||||
public void interrupt() {
|
||||
synchronized (lock) {
|
||||
if (waiting) {
|
||||
messages.offer(""); //$NON-NLS-1$
|
||||
lock.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param message the message */
|
||||
private void notifyMessage(String message) {
|
||||
synchronized (messageBlockerLock) {
|
||||
delivering = message;
|
||||
if (messageBlocker.containsKey(message)) {
|
||||
Object mLock = messageBlocker.get(message);
|
||||
synchronized (mLock) {
|
||||
mLock.notify();
|
||||
}
|
||||
messageBlocker.remove(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param message the message
|
||||
* @return the thread to join to wait for message delivery */
|
||||
public Thread getWaitForDelivery(final String message) {
|
||||
synchronized (messageBlockerLock) {
|
||||
if (!messageBlocker.containsKey(message)) {
|
||||
messageBlocker.put(message, new Object());
|
||||
}
|
||||
final Object obj = messageBlocker.get(message);
|
||||
final Object start = new Object();
|
||||
ToWaitRunnable waitRunn = new ToWaitRunnable(obj, start, message);
|
||||
Thread th = new Thread(waitRunn);
|
||||
|
||||
synchronized (start) {
|
||||
th.start();
|
||||
while (!waitRunn.isStarted()) {
|
||||
try {
|
||||
start.wait(TIMEOUT);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION,
|
||||
e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return th;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,22 +43,17 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PrintStream;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/** A console using the input stream and print stream.
|
||||
* <p>
|
||||
* The default constructor will use the system standart input and output.
|
||||
*
|
||||
* @author Emmanuel BIGEON */
|
||||
public class SystemConsoleManager implements ConsoleManager { // NOSONAR
|
||||
public final class SystemConsoleManager implements ConsoleManager { // NOSONAR
|
||||
|
||||
/** The default prompt */
|
||||
public static final String DEFAULT_PROMPT = ">"; //$NON-NLS-1$
|
||||
|
||||
/** The logger */
|
||||
private static final Logger LOGGER = Logger
|
||||
.getLogger(SystemConsoleManager.class.getName());
|
||||
public static final String DEFAULT_PROMPT = "> "; //$NON-NLS-1$
|
||||
|
||||
/** The command prompt. It can be changed. */
|
||||
private String prompt = DEFAULT_PROMPT;
|
||||
@@ -71,18 +66,30 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
|
||||
/** If the manager is closed */
|
||||
private boolean closed = false;
|
||||
|
||||
/** The prompting thread */
|
||||
private final Thread promptThread;
|
||||
|
||||
/** The reading runnable */
|
||||
private final ReadingRunnable reading;
|
||||
|
||||
/** This default constructor relies on the system defined standart output
|
||||
* and input stream. */
|
||||
public SystemConsoleManager() {
|
||||
this(System.out, System.in);
|
||||
this(System.out, System.in, Charset.defaultCharset());
|
||||
}
|
||||
|
||||
/** @param out the output stream
|
||||
* @param in the input stream */
|
||||
public SystemConsoleManager(PrintStream out, InputStream in) {
|
||||
* @param in the input stream
|
||||
* @param charset the charset for the input */
|
||||
public SystemConsoleManager(PrintStream out, InputStream in,
|
||||
Charset charset) {
|
||||
super();
|
||||
this.out = out;
|
||||
this.in = new BufferedReader(new InputStreamReader(in));
|
||||
this.in = new BufferedReader(new InputStreamReader(in, charset));
|
||||
reading = new ReadingRunnable(this.in);
|
||||
promptThread = new Thread(reading, "prompt"); //$NON-NLS-1$
|
||||
promptThread.setDaemon(true);
|
||||
promptThread.start();
|
||||
}
|
||||
|
||||
/** @return the prompt */
|
||||
@@ -95,19 +102,22 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
|
||||
* @see fr.bigeon.gclc.ConsoleManager#print(java.lang.Object) */
|
||||
@Override
|
||||
public void print(String object) throws IOException {
|
||||
checkOpen();
|
||||
out.print(object);
|
||||
}
|
||||
|
||||
/** @throws IOException if the stream was closed */
|
||||
private void checkOpen() throws IOException {
|
||||
if (closed) {
|
||||
throw new IOException();
|
||||
}
|
||||
out.print(object);
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.ConsoleManager#println() */
|
||||
@Override
|
||||
public void println() throws IOException {
|
||||
if (closed) {
|
||||
throw new IOException();
|
||||
}
|
||||
checkOpen();
|
||||
out.println();
|
||||
}
|
||||
|
||||
@@ -115,9 +125,7 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
|
||||
* @see fr.bigeon.gclc.ConsoleManager#println(java.lang.Object) */
|
||||
@Override
|
||||
public void println(String object) throws IOException {
|
||||
if (closed) {
|
||||
throw new IOException();
|
||||
}
|
||||
checkOpen();
|
||||
out.println(object);
|
||||
}
|
||||
|
||||
@@ -125,33 +133,32 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
|
||||
* @see fr.bigeon.gclc.ConsoleManager#prompt() */
|
||||
@Override
|
||||
public String prompt() throws IOException {
|
||||
return prompt(new String() + prompt);
|
||||
return prompt(prompt);
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */
|
||||
@Override
|
||||
public String prompt(long timeout) throws IOException {
|
||||
return prompt(prompt, timeout);
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */
|
||||
@Override
|
||||
public String prompt(String message) throws IOException {
|
||||
if (closed) {
|
||||
throw new IOException();
|
||||
checkOpen();
|
||||
out.print(message);
|
||||
return reading.getMessage();
|
||||
}
|
||||
String result = new String();
|
||||
out.print(message + ' ');
|
||||
char c;
|
||||
try {
|
||||
result = in.readLine();
|
||||
// c = (char) in.read();
|
||||
// while (c != System.lineSeparator().charAt(0)) {
|
||||
// result += c;
|
||||
// c = (char) in.read();
|
||||
// }
|
||||
// while (in.available() != 0) {
|
||||
// in.read();
|
||||
// }
|
||||
} catch (final IOException e) {
|
||||
LOGGER.log(Level.SEVERE, "Unable to read prompt", e); //$NON-NLS-1$
|
||||
}
|
||||
return result;
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */
|
||||
@Override
|
||||
public String prompt(String message, long timeout) throws IOException {
|
||||
checkOpen();
|
||||
out.print(message);
|
||||
return reading.getNextMessage(timeout);
|
||||
}
|
||||
|
||||
/** @param prompt the prompt to set */
|
||||
@@ -165,6 +172,8 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
closed = true;
|
||||
reading.setRunning(false);
|
||||
promptThread.interrupt();
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
@@ -174,4 +183,12 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
|
||||
return closed;
|
||||
}
|
||||
|
||||
/** Beware, in this implementation this is the same as closing the manager.
|
||||
*
|
||||
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */
|
||||
@Override
|
||||
public void interruptPrompt() {
|
||||
reading.interrupt();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
140
gclc/src/main/java/fr/bigeon/gclc/manager/WritingRunnable.java
Normal file
140
gclc/src/main/java/fr/bigeon/gclc/manager/WritingRunnable.java
Normal file
@@ -0,0 +1,140 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.test.utils.WritingRunnable.java
|
||||
* Created on: Nov 29, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.manager;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/** The runnable in charge of writing messages as they are read.
|
||||
* <p>
|
||||
* Messages are queued to be retrieved latter on.
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class WritingRunnable implements Runnable {
|
||||
|
||||
/** Wait timeout */
|
||||
private static final long TIMEOUT = 1000;
|
||||
/** Class logger */
|
||||
private static final Logger LOGGER = Logger
|
||||
.getLogger(WritingRunnable.class.getName());
|
||||
/** Messages to write */
|
||||
private final Deque<String> messages = new ArrayDeque<>();
|
||||
/** Stream to write to */
|
||||
private final OutputStream outPrint;
|
||||
/** The charset */
|
||||
private final Charset charset;
|
||||
/** Runnable state */
|
||||
private boolean running = true;
|
||||
|
||||
/** Synchro object */
|
||||
private final Object lock = new Object();
|
||||
|
||||
/** @param outPrint the output to print to
|
||||
* @param charset the charset of the stream */
|
||||
public WritingRunnable(OutputStream outPrint, Charset charset) {
|
||||
super();
|
||||
this.outPrint = outPrint;
|
||||
this.charset = charset;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see java.lang.Runnable#run() */
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
while (running) {
|
||||
synchronized (lock) {
|
||||
while (messages.isEmpty()) {
|
||||
try {
|
||||
lock.wait(TIMEOUT);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE,
|
||||
"Thread interruption exception.", e); //$NON-NLS-1$
|
||||
}
|
||||
if (!running) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
String message = messages.poll();
|
||||
ByteBuffer buff = charset
|
||||
.encode(message + System.lineSeparator());
|
||||
if (buff.hasArray()) {
|
||||
try {
|
||||
outPrint.write(buff.array());
|
||||
} catch (IOException e) {
|
||||
LOGGER.log(Level.SEVERE, "Unable to write to stream", //$NON-NLS-1$
|
||||
e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param message the message
|
||||
* @throws IOException if the pipe is closed */
|
||||
public void addMessage(String message) throws IOException {
|
||||
synchronized (lock) {
|
||||
if (!running) {
|
||||
throw new IOException("Closed pipe"); //$NON-NLS-1$
|
||||
}
|
||||
messages.offer(message);
|
||||
lock.notify();
|
||||
}
|
||||
}
|
||||
|
||||
/** @param running the running to set */
|
||||
public void setRunning(boolean running) {
|
||||
synchronized (lock) {
|
||||
this.running = running;
|
||||
}
|
||||
}
|
||||
|
||||
/** @return the running */
|
||||
public boolean isRunning() {
|
||||
synchronized (lock) {
|
||||
return running;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,9 +90,9 @@ public class CLIPrompter {
|
||||
manager.println(index++ + ") " + u); //$NON-NLS-1$
|
||||
}
|
||||
if (cancel != null) {
|
||||
manager.println(index + ") " + cancel); //$NON-NLS-1$
|
||||
manager.println(index++ + ") " + cancel); //$NON-NLS-1$
|
||||
}
|
||||
return index;
|
||||
return index - 1;
|
||||
}
|
||||
|
||||
/** @param manager the manager
|
||||
@@ -162,8 +162,11 @@ public class CLIPrompter {
|
||||
public static <U, T> T promptChoice(ConsoleManager manager, List<U> choices,
|
||||
Map<U, T> choicesMap, String message,
|
||||
String cancel) throws IOException {
|
||||
return choicesMap.get(choices.get(
|
||||
promptChoice(manager, choices, message, cancel).intValue()));
|
||||
Integer res = promptChoice(manager, choices, message, cancel);
|
||||
if (res == null) {
|
||||
return null;
|
||||
}
|
||||
return choicesMap.get(choices.get(res.intValue()));
|
||||
}
|
||||
|
||||
/** @param manager the manager
|
||||
@@ -195,6 +198,8 @@ public class CLIPrompter {
|
||||
}
|
||||
|
||||
} catch (final NumberFormatException e) {
|
||||
LOGGER.log(Level.FINER,
|
||||
"Unrecognized number. Prompting user again.", e); //$NON-NLS-1$
|
||||
keepOn = true;
|
||||
manager.println(CLIPrompterMessages
|
||||
.getString(PROMPTCHOICE_FORMATERR, 0, index));
|
||||
@@ -240,8 +245,8 @@ public class CLIPrompter {
|
||||
r = Integer.parseInt(result);
|
||||
still = false;
|
||||
} catch (final NumberFormatException e) {
|
||||
LOGGER.log(Level.INFO,
|
||||
"User input a non parsable integer: " + result, e); //$NON-NLS-1$
|
||||
LOGGER.info("User input a non parsable integer: " + result); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINEST, "Unrecognized integer", e); //$NON-NLS-1$
|
||||
still = true;
|
||||
}
|
||||
}
|
||||
@@ -306,10 +311,10 @@ public class CLIPrompter {
|
||||
String ender) throws IOException {
|
||||
manager.println(message + CLIPrompterMessages
|
||||
.getString("promptlongtext.exit.dispkey", ender)); //$NON-NLS-1$
|
||||
String res = manager.prompt(PROMPT);
|
||||
String res = manager.prompt(CLIPrompterMessages.getString(PROMPT));
|
||||
String line = res;
|
||||
while (!line.equals(ender)) {
|
||||
line = manager.prompt(PROMPT);
|
||||
line = manager.prompt(CLIPrompterMessages.getString(PROMPT));
|
||||
if (!line.equals(ender)) {
|
||||
res += System.lineSeparator() + line;
|
||||
}
|
||||
@@ -351,7 +356,7 @@ public class CLIPrompter {
|
||||
final List<Integer> chs = promptMultiChoice(manager, choices, message);
|
||||
final List<T> userChoices = new ArrayList<>();
|
||||
for (final Integer integer : chs) {
|
||||
userChoices.add(choicesMap.get(integer));
|
||||
userChoices.add(choicesMap.get(choices.get(integer.intValue())));
|
||||
}
|
||||
return userChoices;
|
||||
}
|
||||
@@ -381,6 +386,8 @@ public class CLIPrompter {
|
||||
try {
|
||||
added = addUserChoice(val, chs, index);
|
||||
} catch (final NumberFormatException e) {
|
||||
LOGGER.log(Level.FINER,
|
||||
"Unrecognized number. Prompting user again.", e); //$NON-NLS-1$
|
||||
keepOn = true;
|
||||
manager.println(CLIPrompterMessages
|
||||
.getString(PROMPTCHOICE_FORMATERR, 0, index));
|
||||
@@ -409,7 +416,7 @@ public class CLIPrompter {
|
||||
}
|
||||
final int r;
|
||||
r = Integer.parseInt(val);
|
||||
if (r >= 0 && r < index) {
|
||||
if (r >= 0 && r <= index) {
|
||||
chs.add(Integer.valueOf(r));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -74,7 +74,8 @@ public class CLIPrompterMessages {
|
||||
try {
|
||||
return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args);
|
||||
} catch (final MissingResourceException e) {
|
||||
LOGGER.log(Level.WARNING, "Unrecognized key: " + key, e); //$NON-NLS-1$
|
||||
LOGGER.warning("Unrecognized key: " + key); //$NON-NLS-1$
|
||||
LOGGER.log(Level.FINE, "Missing key in " + BUNDLE_NAME, e); //$NON-NLS-1$
|
||||
return '!' + key + '!';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.tools.AOutputForwardRunnable.java
|
||||
* Created on: Dec 1, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.tools;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import fr.bigeon.gclc.manager.PipedConsoleManager;
|
||||
|
||||
/** An incomplete implematation used to forward messages from a piped console.
|
||||
* <p>
|
||||
* This forwarding can be interrupted without closing the piped manager.
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public abstract class AOutputForwardRunnable implements Runnable {
|
||||
|
||||
/** The class logger */
|
||||
private static final Logger LOGGER = Logger
|
||||
.getLogger(AOutputForwardRunnable.class.getName());
|
||||
/** The default timeout (one tenth of second). */
|
||||
private static final long DEFAULT_TIMEOUT = 100;
|
||||
/** The manager. */
|
||||
private final PipedConsoleManager manager;
|
||||
/** The timeout */
|
||||
private final long timeout;
|
||||
|
||||
/** Create a forward runnable with the given timeout.
|
||||
* <p>
|
||||
* Short timeout will be very responsive to the application actual messages,
|
||||
* but may use computation time if the application is not verbose. Long
|
||||
* timeout will save computation time, but will read batches of messages at
|
||||
* once if the application is verbose. The right length for the timeout is
|
||||
* likely to depend on the application and the use of it.
|
||||
* <p>
|
||||
* If you do not know what timeout length to use, please use the
|
||||
* {@link #AOutputForwardRunnable(PipedConsoleManager)} constructor.
|
||||
*
|
||||
* @param manager the manager
|
||||
* @param timeout the timeout between message requests. */
|
||||
public AOutputForwardRunnable(PipedConsoleManager manager, long timeout) {
|
||||
super();
|
||||
this.manager = manager;
|
||||
this.timeout = timeout;
|
||||
}
|
||||
|
||||
/** Create a forwarding runnable.
|
||||
*
|
||||
* @param manager the manager */
|
||||
public AOutputForwardRunnable(PipedConsoleManager manager) {
|
||||
super();
|
||||
this.manager = manager;
|
||||
timeout = DEFAULT_TIMEOUT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while (isRunning()) {
|
||||
while (isRunning() && !manager.available()) {
|
||||
waitASec();
|
||||
}
|
||||
if (!isRunning()) {
|
||||
return;
|
||||
}
|
||||
String m = manager.readNextLine();
|
||||
forwardLine(m);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOGGER.log(Level.SEVERE, "Unexpected problem in manager", //$NON-NLS-1$
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param m the line to forward */
|
||||
protected abstract void forwardLine(String m);
|
||||
|
||||
/** @return if the thread should keep running */
|
||||
protected abstract boolean isRunning();
|
||||
|
||||
/** a method to wait some time */
|
||||
protected void waitASec() {
|
||||
try {
|
||||
synchronized (this) {
|
||||
wait(timeout);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.log(Level.SEVERE, "Interrupted wait", //$NON-NLS-1$
|
||||
e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -50,6 +50,8 @@ public class PrintUtils {
|
||||
private static final String CONT_DOT = "..."; //$NON-NLS-1$
|
||||
/** The continuation dot string length */
|
||||
private static final int CONT_DOT_LENGTH = CONT_DOT.length();
|
||||
/** The empty string constant */
|
||||
private static final String EMPTY = ""; //$NON-NLS-1$
|
||||
|
||||
/** Utility class */
|
||||
private PrintUtils() {
|
||||
@@ -101,8 +103,9 @@ public class PrintUtils {
|
||||
toCut = toCut.substring(index + 1);
|
||||
}
|
||||
result.add(toCut);
|
||||
result.add(new String());
|
||||
result.add(EMPTY);
|
||||
}
|
||||
result.remove(result.size() - 1);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
exit.tip=Exit the application
|
||||
help.cmd.tip=Display an help tip
|
||||
|
||||
prompt.lineprompt=>
|
||||
prompt.lineprompt=>\
|
||||
|
||||
promptlist.exit.defaultkey=\\q
|
||||
promptlist.exit.dispkey=\ (exit with a new line made of "{0}")
|
||||
promptlist.prompt=>\
|
||||
promptlist.multi.sepkey=\
|
||||
|
||||
promptbool.choices=\ (Y/N)
|
||||
promptbool.choices.invalid=Invalid input. Please input one of {0}.
|
||||
@@ -15,7 +16,8 @@ promptbool.choices.no1=N
|
||||
promptbool.choices.no2=no
|
||||
|
||||
promptchoice.outofbounds=Please choose something between {0} and {1}. The choices were:
|
||||
promptchoice.formaterr=The input seems to be something that is not an integer.\nPlease choose something between {0} and {1}. The choices were:
|
||||
promptchoice.formaterr=The input seems to be something that is not an integer.\
|
||||
Please choose something between {0} and {1}. The choices were:
|
||||
|
||||
promptlongtext.exit.defaultkey=\\q
|
||||
promptlongtext.exit.dispkey=\ (exit with a new line made of "{0}")
|
||||
|
||||
123
gclc/src/test/java/fr/bigeon/gclc/CommandTestingApplication.java
Normal file
123
gclc/src/test/java/fr/bigeon/gclc/CommandTestingApplication.java
Normal file
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.command.CommandTestingApplication.java
|
||||
* Created on: Jun 12, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import fr.bigeon.gclc.command.ICommand;
|
||||
import fr.bigeon.gclc.exception.InvalidCommandName;
|
||||
import fr.bigeon.gclc.manager.PipedConsoleManager;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("javadoc")
|
||||
public class CommandTestingApplication implements AutoCloseable {
|
||||
|
||||
private final ConsoleApplication application;
|
||||
private final Thread th;
|
||||
private final PipedConsoleManager manager;
|
||||
|
||||
/** @throws IOException if the streams cannot be build */
|
||||
public CommandTestingApplication() throws IOException {
|
||||
manager = new PipedConsoleManager();
|
||||
application = new ConsoleApplication(manager, "", "");
|
||||
new ConsoleTestApplication().attach(application);
|
||||
th = new Thread(new Runnable() {
|
||||
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
application.start();
|
||||
}
|
||||
});
|
||||
|
||||
th.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
application.exit();
|
||||
manager.close();
|
||||
}
|
||||
|
||||
public void sendCommand(String cmd) throws IOException {
|
||||
manager.type(cmd);
|
||||
}
|
||||
|
||||
/** @param cmd the command
|
||||
* @return if the command was added
|
||||
* @throws InvalidCommandName if the command name is invalid
|
||||
* @see fr.bigeon.gclc.ConsoleApplication#add(fr.bigeon.gclc.command.ICommand) */
|
||||
public final boolean add(ICommand cmd) throws InvalidCommandName {
|
||||
return application.add(cmd);
|
||||
}
|
||||
|
||||
/** @return the application */
|
||||
public ConsoleApplication getApplication() {
|
||||
return application;
|
||||
}
|
||||
|
||||
/** @throws IOException if the writing failed */
|
||||
public void waitAndStop() throws IOException {
|
||||
manager.type(ConsoleTestApplication.EXIT);
|
||||
try {
|
||||
th.join();
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/** @return the next written line, null if it is the prompt
|
||||
* @throws IOException if the reading failed
|
||||
* @see fr.bigeon.gclc.manager.PipedConsoleManager#readNextLine() */
|
||||
public String readNextLine() throws IOException {
|
||||
String ret = manager.readNextLine();
|
||||
if (ret.equals(manager.getPrompt())) {
|
||||
return null;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -38,47 +38,118 @@
|
||||
*/
|
||||
package fr.bigeon.gclc;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.PipedInputStream;
|
||||
import java.io.PipedOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.manager.SystemConsoleManager;
|
||||
import fr.bigeon.gclc.command.ExitCommand;
|
||||
import fr.bigeon.gclc.command.ICommand;
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.CommandRunExceptionType;
|
||||
import fr.bigeon.gclc.exception.InvalidCommandName;
|
||||
import fr.bigeon.gclc.i18n.Messages;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
import fr.bigeon.gclc.manager.PipedConsoleManager;
|
||||
|
||||
/** Test class for ConsoleApplication
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
@SuppressWarnings("static-method")
|
||||
@SuppressWarnings({"javadoc", "nls", "static-method"})
|
||||
public class ConsoleApplicationTest {
|
||||
|
||||
/** 3 seconds in milliseconds */
|
||||
protected static final long THREE_SECONDS = 3000;
|
||||
|
||||
/** Test the base of a console application */
|
||||
@Test
|
||||
public void test() {
|
||||
ConsoleTestApplication app = new ConsoleTestApplication(
|
||||
new SystemConsoleManager());
|
||||
|
||||
try (PipedConsoleManager manager = new PipedConsoleManager()) {
|
||||
ConsoleApplication app = new ConsoleApplication(manager, "", "");
|
||||
app.exit();
|
||||
} catch (IOException e) {
|
||||
fail("System Console Manager failed");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void executionTest() {
|
||||
try {
|
||||
final PipedOutputStream src = new PipedOutputStream();
|
||||
InputStream in = new PipedInputStream(src);
|
||||
try (CommandTestingApplication application = new CommandTestingApplication()) {
|
||||
|
||||
// remove welcome
|
||||
assertEquals(application.getApplication().header,
|
||||
application.readNextLine());
|
||||
// Remove first prompt
|
||||
assertNull(application.readNextLine());
|
||||
application.sendCommand("");
|
||||
assertNull(application.readNextLine());
|
||||
application.sendCommand("test");
|
||||
assertEquals("Test command ran fine", application.readNextLine());
|
||||
assertNull(application.readNextLine());
|
||||
application.sendCommand("toto");
|
||||
assertEquals(
|
||||
Messages.getString("ConsoleApplication.cmd.failed", "toto"),
|
||||
application.readNextLine());
|
||||
assertEquals(
|
||||
Messages.getString("CommandProvider.unrecognized", "toto"),
|
||||
application.readNextLine());
|
||||
assertNull(application.readNextLine());
|
||||
application.sendCommand("long");
|
||||
assertEquals("Waita minute", application.readNextLine());
|
||||
assertEquals("done!", application.readNextLine());
|
||||
|
||||
CommandRequestListener crl = new CommandRequestListener() {
|
||||
|
||||
@Override
|
||||
public void commandRequest(String command) {
|
||||
//
|
||||
}
|
||||
};
|
||||
CommandRequestListener crl2 = new CommandRequestListener() {
|
||||
|
||||
@Override
|
||||
public void commandRequest(String command) {
|
||||
//
|
||||
}
|
||||
};
|
||||
application.getApplication().addListener(crl);
|
||||
application.getApplication().addListener(crl2);
|
||||
assertNull(application.readNextLine());
|
||||
application.sendCommand("test");
|
||||
assertEquals("Test command ran fine", application.readNextLine());
|
||||
application.getApplication().removeListener(crl2);
|
||||
application.getApplication().removeListener(crl);
|
||||
application.getApplication().removeListener(crl);
|
||||
|
||||
assertTrue(application.getApplication().isRunning());
|
||||
|
||||
assertNull(application.readNextLine());
|
||||
application.sendCommand("exit");
|
||||
assertEquals(application.getApplication().footer,
|
||||
application.readNextLine());
|
||||
assertFalse(application.getApplication().isRunning());
|
||||
} catch (IOException e1) {
|
||||
assertNull(e1);
|
||||
}
|
||||
|
||||
ConsoleApplication appli = null;
|
||||
try (PipedConsoleManager manager = new PipedConsoleManager()) {
|
||||
final ConsoleApplication app = new ConsoleApplication(manager, null,
|
||||
null);
|
||||
appli = app;
|
||||
app.add(new ExitCommand("exit", app));
|
||||
|
||||
final PipedInputStream snk = new PipedInputStream();
|
||||
PrintStream out = new PrintStream(new PipedOutputStream(snk));
|
||||
final ConsoleTestApplication app = new ConsoleTestApplication(
|
||||
new SystemConsoleManager(System.out, in));
|
||||
Thread th = new Thread(new Runnable() {
|
||||
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
app.start();
|
||||
@@ -87,33 +158,70 @@ public class ConsoleApplicationTest {
|
||||
|
||||
th.start();
|
||||
|
||||
Thread test = new Thread(new Runnable() {
|
||||
manager.type("exit");
|
||||
th.join();
|
||||
|
||||
} catch (IOException | InvalidCommandName |
|
||||
|
||||
InterruptedException e) {
|
||||
|
||||
assertNull(e);
|
||||
}
|
||||
|
||||
assertNotNull(appli);
|
||||
appli.start();
|
||||
assertFalse(appli.isRunning());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void interpretCommandTest() {
|
||||
try (PipedConsoleManager test = new PipedConsoleManager()) {
|
||||
ConsoleApplication appl = new ConsoleApplication(test, "", "");
|
||||
|
||||
appl.interpretCommand("invalid cmd \"due to misplaced\"quote");
|
||||
assertEquals("Command line cannot be parsed", test.readNextLine());
|
||||
|
||||
appl.interpretCommand("");
|
||||
|
||||
final String message = "message";
|
||||
try {
|
||||
appl.add(new ICommand() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try (PrintWriter writer = new PrintWriter(src, true)) {
|
||||
writer.println("test");
|
||||
writer.println("toto");
|
||||
writer.println("long");
|
||||
writer.println("exit");
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
throw new CommandRunException(
|
||||
CommandRunExceptionType.USAGE, message, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return "fail";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void help(ConsoleManager manager,
|
||||
String... args) throws IOException {
|
||||
manager.println(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "";
|
||||
}
|
||||
|
||||
});
|
||||
test.start();
|
||||
try {
|
||||
th.join();
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
try {
|
||||
test.join();
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (InvalidCommandName e) {
|
||||
assertNull(e);
|
||||
}
|
||||
appl.interpretCommand("fail");
|
||||
assertEquals(
|
||||
Messages.getString("ConsoleApplication.cmd.failed", "fail"),
|
||||
test.readNextLine());
|
||||
assertEquals(message, test.readNextLine());
|
||||
assertEquals(message, test.readNextLine());
|
||||
|
||||
} catch (IOException e) {
|
||||
fail("pipe creation"); //$NON-NLS-1$
|
||||
assertNull(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,18 +36,16 @@ package fr.bigeon.gclc;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import fr.bigeon.gclc.ConsoleApplication;
|
||||
import fr.bigeon.gclc.command.Command;
|
||||
import fr.bigeon.gclc.command.ExitCommand;
|
||||
import fr.bigeon.gclc.command.HelpExecutor;
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.InvalidCommandName;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
|
||||
/** A test-purpose application
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class ConsoleTestApplication extends ConsoleApplication {
|
||||
public class ConsoleTestApplication implements ApplicationAttachement {
|
||||
|
||||
/** Exit command */
|
||||
public static final String EXIT = "exit"; //$NON-NLS-1$
|
||||
@@ -55,14 +53,14 @@ public class ConsoleTestApplication extends ConsoleApplication {
|
||||
protected static final long TWO_SECONDS = 2000;
|
||||
|
||||
/** @param manager the manager */
|
||||
@Override
|
||||
@SuppressWarnings("nls")
|
||||
public ConsoleTestApplication(final ConsoleManager manager) {
|
||||
super(manager, "Welcome to the test application. Type help or test.",
|
||||
"See you");
|
||||
public void attach(final ConsoleApplication application) {
|
||||
try {
|
||||
add(new ExitCommand(EXIT, this));
|
||||
add(new HelpExecutor("help", manager, this.getRoot()));
|
||||
add(new Command("test") {
|
||||
application.add(new ExitCommand(EXIT, application));
|
||||
application.add(new HelpExecutor("help", application.manager,
|
||||
application.root));
|
||||
application.add(new Command("test") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
@@ -72,13 +70,14 @@ public class ConsoleTestApplication extends ConsoleApplication {
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
try {
|
||||
manager.println("Test command ran fine");
|
||||
application.manager.println("Test command ran fine");
|
||||
} catch (IOException e) {
|
||||
throw new CommandRunException("manager closed", e);
|
||||
throw new CommandRunException("manager closed", e,
|
||||
this);
|
||||
}
|
||||
}
|
||||
});
|
||||
add(new Command("long") {
|
||||
application.add(new Command("long") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
@@ -88,16 +87,30 @@ public class ConsoleTestApplication extends ConsoleApplication {
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
try {
|
||||
manager.println("Waita minute");
|
||||
application.manager.println("Waita minute");
|
||||
Thread.sleep(TWO_SECONDS);
|
||||
manager.println("done!");
|
||||
application.manager.println("done!");
|
||||
} catch (IOException e) {
|
||||
throw new CommandRunException("manager closed", e);
|
||||
throw new CommandRunException("manager closed", e,
|
||||
this);
|
||||
} catch (InterruptedException e) {
|
||||
throw new CommandRunException("wait interrupted", e);
|
||||
throw new CommandRunException("wait interrupted", e,
|
||||
this);
|
||||
}
|
||||
}
|
||||
});
|
||||
application.add(new Command("failingCmd") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "A long execution command";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
throw new CommandRunException("Failing command", this);
|
||||
}
|
||||
});
|
||||
} catch (final InvalidCommandName e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ public class GCLCConstantsTest {
|
||||
try {
|
||||
res = GCLCConstants.splitCommand("aCommand");
|
||||
} catch (CommandParsingException e) {
|
||||
fail("Unable to parse simple command"); //$NON-NLS-1$
|
||||
fail("Unable to parse simple command " + e.getLocalizedMessage()); //$NON-NLS-1$
|
||||
return;
|
||||
}
|
||||
assertTrue(res.size() == 1);
|
||||
@@ -71,7 +71,8 @@ public class GCLCConstantsTest {
|
||||
try {
|
||||
res = GCLCConstants.splitCommand("aCommand with some arguments");
|
||||
} catch (CommandParsingException e) {
|
||||
fail("Unable to parse command with arguments"); //$NON-NLS-1$
|
||||
fail("Unable to parse command with arguments " + //$NON-NLS-1$
|
||||
e.getLocalizedMessage());
|
||||
return;
|
||||
}
|
||||
assertTrue(res.size() == 4);
|
||||
@@ -82,7 +83,8 @@ public class GCLCConstantsTest {
|
||||
try {
|
||||
res = GCLCConstants.splitCommand("aCommand with some arguments");
|
||||
} catch (CommandParsingException e) {
|
||||
fail("Unable to parse command with arguments and double whitspaces"); //$NON-NLS-1$
|
||||
fail("Unable to parse command with arguments and double whitspaces " + //$NON-NLS-1$
|
||||
e.getLocalizedMessage());
|
||||
return;
|
||||
}
|
||||
assertTrue(res.size() == 4);
|
||||
@@ -94,7 +96,8 @@ public class GCLCConstantsTest {
|
||||
res = GCLCConstants
|
||||
.splitCommand("aCommand \"with some\" arguments");
|
||||
} catch (CommandParsingException e) {
|
||||
fail("Unable to parse command with string argument"); //$NON-NLS-1$
|
||||
fail("Unable to parse command with string argument " + //$NON-NLS-1$
|
||||
e.getLocalizedMessage());
|
||||
return;
|
||||
}
|
||||
assertTrue(res.size() == 3);
|
||||
@@ -104,7 +107,8 @@ public class GCLCConstantsTest {
|
||||
try {
|
||||
res = GCLCConstants.splitCommand("aCommand with\\ some arguments");
|
||||
} catch (CommandParsingException e) {
|
||||
fail("Unable to parse command with arguments with escaped whitspaces"); //$NON-NLS-1$
|
||||
fail("Unable to parse command with arguments with escaped whitspaces " + //$NON-NLS-1$
|
||||
e.getLocalizedMessage());
|
||||
return;
|
||||
}
|
||||
assertTrue(res.size() == 3);
|
||||
@@ -115,7 +119,8 @@ public class GCLCConstantsTest {
|
||||
res = GCLCConstants
|
||||
.splitCommand("aCommand wi\\\"th some arguments");
|
||||
} catch (CommandParsingException e) {
|
||||
fail("Unable to parse command with string argument"); //$NON-NLS-1$
|
||||
fail("Unable to parse command with string argument " + //$NON-NLS-1$
|
||||
e.getLocalizedMessage());
|
||||
return;
|
||||
}
|
||||
assertTrue(res.size() == 4);
|
||||
@@ -124,6 +129,19 @@ public class GCLCConstantsTest {
|
||||
assertTrue(res.get(2).equals("some"));
|
||||
assertTrue(res.get(3).equals("arguments"));
|
||||
|
||||
try {
|
||||
res = GCLCConstants
|
||||
.splitCommand("aCommand with \"some arguments\"");
|
||||
} catch (CommandParsingException e) {
|
||||
fail("Unable to parse command ending with string argument " + //$NON-NLS-1$
|
||||
e.getLocalizedMessage());
|
||||
return;
|
||||
}
|
||||
assertTrue(res.size() == 3);
|
||||
assertTrue(res.get(0).equals("aCommand"));
|
||||
assertTrue(res.get(1).equals("with"));
|
||||
assertTrue(res.get(2).equals("some arguments"));
|
||||
|
||||
// Wrong lines?
|
||||
try {
|
||||
res = GCLCConstants
|
||||
@@ -131,6 +149,7 @@ public class GCLCConstantsTest {
|
||||
fail("Parsing argument with string cut");
|
||||
} catch (CommandParsingException e) {
|
||||
// OK
|
||||
assertTrue(e.getLocalizedMessage(), true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.command.CommandParametersTest.java
|
||||
* Created on: Nov 18, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.command;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.exception.CommandParsingException;
|
||||
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
@SuppressWarnings({"static-method", "nls"})
|
||||
public class CommandParametersTest {
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.CommandParameters#CommandParameters(java.util.Set, java.util.Set, boolean)}. */
|
||||
@Test
|
||||
public final void testCommandParameters() {
|
||||
Set<String> strings = new HashSet<>();
|
||||
Set<String> bools = new HashSet<>();
|
||||
CommandParameters parameters = new CommandParameters(bools, strings,
|
||||
true);
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-ungivenFlag");
|
||||
fail("parse of unknown in strict should fail");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
parameters = new CommandParameters(bools, strings, false);
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-ungivenFlag");
|
||||
} catch (CommandParsingException e) {
|
||||
fail("parse of unknown in non strict should suceed");
|
||||
assertNull(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.CommandParameters#get(java.lang.String)}. */
|
||||
@Test
|
||||
public final void testGet() {
|
||||
Set<String> strings = new HashSet<>();
|
||||
Set<String> bools = new HashSet<>();
|
||||
|
||||
bools.add("boolFlag");
|
||||
strings.add("str");
|
||||
|
||||
CommandParameters parameters = new CommandParameters(bools, strings,
|
||||
true);
|
||||
|
||||
assertNull(parameters.get("ungiven"));
|
||||
assertNull(parameters.get("str"));
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-ungiven", "val");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
assertNull(parameters.get("ungiven"));
|
||||
assertNull(parameters.get("str"));
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-str", "val");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
assertNull(parameters.get("ungiven"));
|
||||
assertEquals("val", parameters.get("str"));
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-ungiven");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
assertNull(parameters.get("ungiven"));
|
||||
assertEquals("val", parameters.get("str"));
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.CommandParameters#getAdditionals()}. */
|
||||
@Test
|
||||
public final void testGetAdditionals() {
|
||||
Set<String> strings = new HashSet<>();
|
||||
Set<String> bools = new HashSet<>();
|
||||
|
||||
bools.add("boolFlag");
|
||||
strings.add("str");
|
||||
|
||||
CommandParameters parameters = new CommandParameters(bools, strings,
|
||||
true);
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-boolFlag");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
assertTrue(parameters.getAdditionals().isEmpty());
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-ungiven");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
assertTrue(parameters.getAdditionals().isEmpty());
|
||||
|
||||
parameters = new CommandParameters(bools, strings, false);
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-boolFlag");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
assertTrue(parameters.getAdditionals().isEmpty());
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-ungiven");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
assertTrue(parameters.getAdditionals().contains("ungiven"));
|
||||
assertEquals(1, parameters.getAdditionals().size());
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.CommandParameters#getBool(java.lang.String)}. */
|
||||
@Test
|
||||
public final void testGetBool() {
|
||||
Set<String> strings = new HashSet<>();
|
||||
Set<String> bools = new HashSet<>();
|
||||
|
||||
bools.add("boolFlag");
|
||||
strings.add("str");
|
||||
|
||||
CommandParameters parameters = new CommandParameters(bools, strings,
|
||||
true);
|
||||
|
||||
assertFalse(parameters.getBool("ungiven"));
|
||||
assertFalse(parameters.getBool("boolFlag"));
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-boolFlag");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
assertTrue(parameters.getBool("boolFlag"));
|
||||
assertFalse(parameters.getBool("ungiven"));
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-ungiven");
|
||||
fail("unknown parameter should fail");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
assertFalse(parameters.getBool("ungiven"));
|
||||
assertTrue(parameters.getBool("boolFlag"));
|
||||
|
||||
parameters = new CommandParameters(bools, strings, false);
|
||||
|
||||
assertFalse(parameters.getBool("ungiven"));
|
||||
assertFalse(parameters.getBool("boolFlag"));
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-boolFlag");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
assertTrue(parameters.getBool("boolFlag"));
|
||||
assertFalse(parameters.getBool("ungiven"));
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-ungiven");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
assertFalse(parameters.getBool("ungiven"));
|
||||
assertTrue(parameters.getBool("boolFlag"));
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.CommandParameters#parseArgs(java.lang.String[])}. */
|
||||
@Test
|
||||
public final void testParseArgs() {
|
||||
Set<String> strings = new HashSet<>();
|
||||
Set<String> bools = new HashSet<>();
|
||||
|
||||
bools.add("boolFlag");
|
||||
strings.add("str");
|
||||
|
||||
CommandParameters parameters = new CommandParameters(bools, strings,
|
||||
true);
|
||||
|
||||
try {
|
||||
parameters.parseArgs("-ungivenFlag");
|
||||
fail("unknown argument should fail in strict");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
parameters.parseArgs("-str");
|
||||
fail("missing string argument value should fail");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
parameters.parseArgs("-boolFlag");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
try {
|
||||
parameters.parseArgs("-str", "-boolFlag");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
try {
|
||||
parameters.parseArgs("-boolFlag", "-str", "val");
|
||||
} catch (CommandParsingException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, boolean)}. */
|
||||
@Test
|
||||
public final void testSetStringBoolean() {
|
||||
Set<String> strings = new HashSet<>();
|
||||
Set<String> bools = new HashSet<>();
|
||||
|
||||
bools.add("boolFlag");
|
||||
strings.add("str");
|
||||
|
||||
CommandParameters parameters = new CommandParameters(bools, strings,
|
||||
true);
|
||||
|
||||
assertFalse(parameters.getBool("ungiven"));
|
||||
assertFalse(parameters.getBool("boolFlag"));
|
||||
|
||||
parameters.set("boolFlag", true);
|
||||
assertTrue(parameters.getBool("boolFlag"));
|
||||
assertFalse(parameters.getBool("ungiven"));
|
||||
|
||||
parameters.set("ungiven", true);
|
||||
assertFalse(parameters.getBool("ungiven"));
|
||||
assertTrue(parameters.getBool("boolFlag"));
|
||||
|
||||
parameters = new CommandParameters(bools, strings, false);
|
||||
|
||||
assertFalse(parameters.getBool("ungiven"));
|
||||
assertFalse(parameters.getBool("boolFlag"));
|
||||
|
||||
parameters.set("boolFlag", true);
|
||||
assertTrue(parameters.getBool("boolFlag"));
|
||||
assertFalse(parameters.getBool("ungiven"));
|
||||
|
||||
parameters.set("ungiven", true);
|
||||
assertFalse(parameters.getBool("ungiven"));
|
||||
assertTrue(parameters.getBool("boolFlag"));
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, java.lang.String)}. */
|
||||
@Test
|
||||
public final void testSetStringString() {
|
||||
Set<String> strings = new HashSet<>();
|
||||
Set<String> bools = new HashSet<>();
|
||||
|
||||
bools.add("boolFlag");
|
||||
strings.add("str");
|
||||
|
||||
CommandParameters parameters = new CommandParameters(bools, strings,
|
||||
true);
|
||||
|
||||
assertNull(parameters.get("ungiven"));
|
||||
assertNull(parameters.get("str"));
|
||||
|
||||
parameters.set("ungiven", "val");
|
||||
assertNull(parameters.get("ungiven"));
|
||||
assertNull(parameters.get("str"));
|
||||
|
||||
parameters.set("str", "val");
|
||||
assertNull(parameters.get("ungiven"));
|
||||
assertEquals("val", parameters.get("str"));
|
||||
|
||||
parameters.set("ungiven", "val");
|
||||
assertNull(parameters.get("ungiven"));
|
||||
assertEquals("val", parameters.get("str"));
|
||||
|
||||
parameters = new CommandParameters(bools, strings, false);
|
||||
|
||||
assertNull(parameters.get("ungiven"));
|
||||
assertNull(parameters.get("str"));
|
||||
|
||||
parameters.set("ungiven", "val");
|
||||
assertNull(parameters.get("ungiven"));
|
||||
assertNull(parameters.get("str"));
|
||||
|
||||
parameters.set("str", "val");
|
||||
assertNull(parameters.get("ungiven"));
|
||||
assertEquals("val", parameters.get("str"));
|
||||
|
||||
parameters.set("ungiven", "val");
|
||||
assertNull(parameters.get("ungiven"));
|
||||
assertEquals("val", parameters.get("str"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.command.CommandProviderTest.java
|
||||
* Created on: Nov 19, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.command;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.exception.InvalidCommandName;
|
||||
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class CommandProviderTest {
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.CommandProvider#add(fr.bigeon.gclc.command.ICommand)}. */
|
||||
@Test
|
||||
public final void testAdd() {
|
||||
CommandProvider provider = new CommandProvider();
|
||||
try {
|
||||
provider.add(new MockCommand(null));
|
||||
fail("null name for command should be rejected");
|
||||
} catch (InvalidCommandName e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
provider.add(new MockCommand(""));
|
||||
fail("null name for command should be rejected");
|
||||
} catch (InvalidCommandName e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
provider.add(new MockCommand("-name"));
|
||||
fail("name with minus as starting character for command should be rejected");
|
||||
} catch (InvalidCommandName e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
provider.add(new MockCommand("name command"));
|
||||
fail("name with space for command should be rejected");
|
||||
} catch (InvalidCommandName e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
ICommand mock = new MockCommand("name");
|
||||
try {
|
||||
provider.add(mock);
|
||||
} catch (InvalidCommandName e) {
|
||||
assertNull(e);
|
||||
}
|
||||
|
||||
try {
|
||||
provider.add(new MockCommand(mock.getCommandName()));
|
||||
fail("already existing command name should be rejected");
|
||||
} catch (InvalidCommandName e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
|
||||
try {
|
||||
provider.add(mock);
|
||||
} catch (InvalidCommandName e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
217
gclc/src/test/java/fr/bigeon/gclc/command/CommandTest.java
Normal file
217
gclc/src/test/java/fr/bigeon/gclc/command/CommandTest.java
Normal file
@@ -0,0 +1,217 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.command.CommandTest.java
|
||||
* Created on: Nov 19, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.command;
|
||||
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.manager.PipedConsoleManager;
|
||||
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class CommandTest {
|
||||
|
||||
@Test
|
||||
public final void test() {
|
||||
try (PipedConsoleManager test = new PipedConsoleManager()) {
|
||||
Command cmd;
|
||||
cmd = new Command("name") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
//
|
||||
}
|
||||
};
|
||||
cmd.help(test);
|
||||
|
||||
cmd = new Command("name") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
//
|
||||
}
|
||||
};
|
||||
cmd.help(test);
|
||||
|
||||
cmd = new Command("name") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "tip";
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#brief() */
|
||||
@Override
|
||||
protected String brief() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
//
|
||||
}
|
||||
};
|
||||
cmd.help(test);
|
||||
|
||||
cmd = new Command("name") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "tip";
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#brief() */
|
||||
@Override
|
||||
protected String brief() {
|
||||
return "brief";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
//
|
||||
}
|
||||
};
|
||||
cmd.help(test);
|
||||
|
||||
cmd = new Command("name") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "tip";
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#usageDetail() */
|
||||
@Override
|
||||
protected String usageDetail() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
//
|
||||
}
|
||||
};
|
||||
cmd.help(test);
|
||||
|
||||
cmd = new Command("name") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "tip";
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#usageDetail() */
|
||||
@Override
|
||||
protected String usageDetail() {
|
||||
return "details";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
//
|
||||
}
|
||||
};
|
||||
cmd.help(test);
|
||||
cmd = new Command("name") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "tip";
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#usageDetail() */
|
||||
@Override
|
||||
protected String usageDetail() {
|
||||
return "details" + System.lineSeparator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
//
|
||||
}
|
||||
};
|
||||
cmd.help(test);
|
||||
|
||||
cmd = new Command("name") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "tip";
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see fr.bigeon.gclc.command.Command#usageDetail() */
|
||||
@Override
|
||||
protected String usageDetail() {
|
||||
return "\n";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
//
|
||||
}
|
||||
};
|
||||
cmd.help(test);
|
||||
|
||||
} catch (IOException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
137
gclc/src/test/java/fr/bigeon/gclc/command/HelpExecutorTest.java
Normal file
137
gclc/src/test/java/fr/bigeon/gclc/command/HelpExecutorTest.java
Normal file
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.command.HelpExecutorTest.java
|
||||
* Created on: Nov 19, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.command;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.manager.PipedConsoleManager;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon
|
||||
*
|
||||
*/
|
||||
public class HelpExecutorTest {
|
||||
|
||||
/**
|
||||
* Test method for {@link fr.bigeon.gclc.command.HelpExecutor#HelpExecutor(java.lang.String, fr.bigeon.gclc.manager.ConsoleManager, fr.bigeon.gclc.command.ICommand)}.
|
||||
*/
|
||||
@Test
|
||||
public final void testHelpExecutor(){
|
||||
HelpExecutor help;
|
||||
try {
|
||||
help = new HelpExecutor("?", null, new MockCommand("mock"));
|
||||
fail("help is an interactive command, should need console manager");
|
||||
} catch (Exception e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
try (PipedConsoleManager test = new PipedConsoleManager()) {
|
||||
help = new HelpExecutor("?", test, new MockCommand("mock"));
|
||||
} catch (Exception e) {
|
||||
assertNull(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for {@link fr.bigeon.gclc.command.HelpExecutor#execute(java.lang.String[])}.
|
||||
*/
|
||||
@Test
|
||||
public final void testExecute(){
|
||||
try {
|
||||
PipedConsoleManager test = new PipedConsoleManager();
|
||||
HelpExecutor help = new HelpExecutor("?", test,
|
||||
new Command("mock") {
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
//
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "";
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
help.execute();
|
||||
test.close();
|
||||
|
||||
try {
|
||||
help.execute();
|
||||
fail("manager closed shall provoke failure of help command execution");
|
||||
} catch (Exception e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
assertNull(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for {@link fr.bigeon.gclc.command.HelpExecutor#tip()}.
|
||||
*/
|
||||
@Test
|
||||
public final void testTip(){
|
||||
try (PipedConsoleManager test = new PipedConsoleManager()) {
|
||||
HelpExecutor help = new HelpExecutor("?", test,
|
||||
new MockCommand("mock"));
|
||||
help.tip();
|
||||
help.help(test);
|
||||
} catch (Exception e) {
|
||||
assertNull(e);
|
||||
}
|
||||
try (PipedConsoleManager test = new PipedConsoleManager()) {
|
||||
HelpExecutor help = new HelpExecutor("?", test,
|
||||
new SubedCommand("sub", new MockCommand("mock")));
|
||||
help.tip();
|
||||
help.help(test);
|
||||
} catch (Exception e) {
|
||||
assertNull(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,666 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.command.ParametrizedCommandTest.java
|
||||
* Created on: Nov 18, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.command;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.InvalidParameterException;
|
||||
import fr.bigeon.gclc.manager.PipedConsoleManager;
|
||||
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class ParametrizedCommandTest {
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */
|
||||
@Test
|
||||
public final void testParametrizedCommandConsoleManagerString() {
|
||||
try (PipedConsoleManager test = new PipedConsoleManager()) {
|
||||
ParametrizedCommand cmd = new ParametrizedCommand(test, "name") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
//
|
||||
}
|
||||
};
|
||||
assertTrue(cmd.isStrict());
|
||||
assertTrue(cmd.isInteractive());
|
||||
} catch (IOException e) {
|
||||
fail("Unexpected exception in creation");
|
||||
assertNull(e);
|
||||
}
|
||||
ParametrizedCommand cmd = new ParametrizedCommand(null, "name") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
//
|
||||
}
|
||||
};
|
||||
assertTrue(cmd.isStrict());
|
||||
assertFalse(cmd.isInteractive());
|
||||
cmd = new ParametrizedCommand("name") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
//
|
||||
}
|
||||
};
|
||||
assertTrue(cmd.isStrict());
|
||||
assertFalse(cmd.isInteractive());
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String, boolean)}. */
|
||||
@Test
|
||||
public final void testParametrizedCommandConsoleManagerStringBoolean() {
|
||||
try (PipedConsoleManager test = new PipedConsoleManager()) {
|
||||
ParametrizedCommand cmd = new ParametrizedCommand(test, "name",
|
||||
false) {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
//
|
||||
}
|
||||
};
|
||||
assertFalse(cmd.isStrict());
|
||||
assertTrue(cmd.isInteractive());
|
||||
} catch (IOException e) {
|
||||
fail("Unexpected exception in creation");
|
||||
assertNull(e);
|
||||
}
|
||||
ParametrizedCommand cmd = new ParametrizedCommand(null, "name", false) {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
//
|
||||
}
|
||||
};
|
||||
assertFalse(cmd.isStrict());
|
||||
assertFalse(cmd.isInteractive());
|
||||
cmd = new ParametrizedCommand("name", false) {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
//
|
||||
}
|
||||
};
|
||||
assertFalse(cmd.isStrict());
|
||||
assertFalse(cmd.isInteractive());
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.ParametrizedCommand#addParameter(java.lang.String, boolean, boolean)}. */
|
||||
@Test
|
||||
public final void testAddParameter() {
|
||||
ParametrizedCommand cmd = new ParametrizedCommand(null, "name") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
//
|
||||
}
|
||||
};
|
||||
cmd = new ParametrizedCommand(null, "name", true) {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
//
|
||||
}
|
||||
};
|
||||
// XXX Boolean flag should not be specified mandatory! They are by
|
||||
// nature qualified
|
||||
try {
|
||||
cmd.addParameter("boolFlag", false, true);
|
||||
fail("Boolean parameters should never be needed specified");
|
||||
} catch (InvalidParameterException e) {
|
||||
// OK
|
||||
assertNotNull(e);
|
||||
}
|
||||
String str = "str";
|
||||
try {
|
||||
assertTrue(cmd.getBooleanParameters().isEmpty());
|
||||
assertTrue(cmd.getStringParameters().isEmpty());
|
||||
cmd.addParameter("boolFlag", false, false);
|
||||
assertEquals(1, cmd.getBooleanParameters().size());
|
||||
assertTrue(cmd.getStringParameters().isEmpty());
|
||||
cmd.addParameter(str, true, false);
|
||||
assertEquals(1, cmd.getBooleanParameters().size());
|
||||
assertEquals(1, cmd.getStringParameters().size());
|
||||
assertFalse(cmd.isNeeded(str));
|
||||
cmd.addParameter("boolFlag", false, false);
|
||||
assertEquals(1, cmd.getBooleanParameters().size());
|
||||
assertEquals(1, cmd.getStringParameters().size());
|
||||
cmd.addParameter(str, true, true);
|
||||
assertEquals(1, cmd.getBooleanParameters().size());
|
||||
assertEquals(1, cmd.getStringParameters().size());
|
||||
assertTrue(cmd.isNeeded(str));
|
||||
cmd.addParameter(str, true, false);
|
||||
assertEquals(1, cmd.getBooleanParameters().size());
|
||||
assertEquals(1, cmd.getStringParameters().size());
|
||||
assertTrue(cmd.isNeeded(str));
|
||||
} catch (InvalidParameterException e) {
|
||||
fail("Unexpected error in addition of legitimate parameter");
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.addParameter(str, false, false);
|
||||
fail("parameter type conversion shall fail");
|
||||
} catch (InvalidParameterException e) {
|
||||
// OK
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.addParameter("boolFlag", true, false);
|
||||
fail("parameter type conversion shall fail");
|
||||
} catch (InvalidParameterException e) {
|
||||
// OK
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.addParameter("boolFlag", false, true);
|
||||
fail("parameter type conversion shall fail");
|
||||
} catch (InvalidParameterException e) {
|
||||
// OK
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.addParameter("boolFlag", true, true);
|
||||
fail("parameter type conversion shall fail");
|
||||
} catch (InvalidParameterException e) {
|
||||
// OK
|
||||
assertNotNull(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.ParametrizedCommand#execute(java.lang.String[])}. */
|
||||
@Test
|
||||
public final void testExecute() {
|
||||
final String addParam = "additional";
|
||||
final String str1 = "str1";
|
||||
final String str2 = "str2";
|
||||
final String bool1 = "bool1";
|
||||
final String bool2 = "bool2";
|
||||
|
||||
// Test on command with no needed elements
|
||||
ParametrizedCommand cmd = new ParametrizedCommand("name", false) {
|
||||
private boolean evenCall = true;
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
assertTrue(parameters.getBooleanArgumentKeys().isEmpty());
|
||||
assertTrue(parameters.getStringArgumentKeys().isEmpty());
|
||||
if (evenCall) {
|
||||
assertTrue(parameters.getAdditionals().isEmpty());
|
||||
evenCall = false;
|
||||
} else {
|
||||
assertEquals(1, parameters.getAdditionals().size());
|
||||
assertTrue(parameters.getAdditionals().contains(addParam));
|
||||
evenCall = true;
|
||||
}
|
||||
}
|
||||
};
|
||||
try {
|
||||
cmd.execute();
|
||||
cmd.execute("-" + addParam);
|
||||
cmd.execute(addParam);
|
||||
cmd.execute("-" + addParam, addParam);
|
||||
} catch (CommandRunException e) {
|
||||
assertNull(e);
|
||||
fail("unepected error");
|
||||
}
|
||||
cmd = new ParametrizedCommand("name", false) {
|
||||
private int call = 0;
|
||||
{
|
||||
|
||||
try {
|
||||
addParameter(str1, true, false);
|
||||
addParameter(str2, true, false);
|
||||
addParameter(bool1, false, false);
|
||||
addParameter(bool2, false, false);
|
||||
} catch (InvalidParameterException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
assertEquals(2, parameters.getBooleanArgumentKeys().size());
|
||||
assertEquals(2, parameters.getStringArgumentKeys().size());
|
||||
switch (call) {
|
||||
case 0:
|
||||
case 1:
|
||||
case 2:
|
||||
case 3:
|
||||
assertNull(parameters.get(str1));
|
||||
assertNull(parameters.get(str2));
|
||||
assertFalse(parameters.getBool(bool1));
|
||||
assertFalse(parameters.getBool(bool2));
|
||||
call++;
|
||||
break;
|
||||
case 4:
|
||||
assertEquals(str2, parameters.get(str1));
|
||||
assertNull(parameters.get(str2));
|
||||
assertFalse(parameters.getBool(bool1));
|
||||
assertFalse(parameters.getBool(bool2));
|
||||
call++;
|
||||
break;
|
||||
case 5:
|
||||
assertEquals(str2, parameters.get(str1));
|
||||
assertNull(parameters.get(str2));
|
||||
assertTrue(parameters.getBool(bool1));
|
||||
assertFalse(parameters.getBool(bool2));
|
||||
call = 0;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
try {
|
||||
cmd.execute();
|
||||
cmd.execute("-" + addParam);
|
||||
cmd.execute(addParam);
|
||||
cmd.execute("-" + addParam, addParam);
|
||||
cmd.execute("-" + str1, str2);
|
||||
cmd.execute("-" + str1, str2, "-" + bool1);
|
||||
} catch (CommandRunException e) {
|
||||
assertNull(e);
|
||||
fail("unepected error");
|
||||
}
|
||||
cmd = new ParametrizedCommand("name", true) {
|
||||
private int call = 0;
|
||||
{
|
||||
|
||||
try {
|
||||
addParameter(str1, true, false);
|
||||
addParameter(str2, true, false);
|
||||
addParameter(bool1, false, false);
|
||||
addParameter(bool2, false, false);
|
||||
} catch (InvalidParameterException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
assertEquals(2, parameters.getBooleanArgumentKeys().size());
|
||||
assertEquals(2, parameters.getStringArgumentKeys().size());
|
||||
switch (call) {
|
||||
case 0:
|
||||
assertNull(parameters.get(str1));
|
||||
assertNull(parameters.get(str2));
|
||||
assertFalse(parameters.getBool(bool1));
|
||||
assertFalse(parameters.getBool(bool2));
|
||||
call++;
|
||||
break;
|
||||
case 1:
|
||||
assertEquals(str2, parameters.get(str1));
|
||||
assertNull(parameters.get(str2));
|
||||
assertFalse(parameters.getBool(bool1));
|
||||
assertFalse(parameters.getBool(bool2));
|
||||
call++;
|
||||
break;
|
||||
case 2:
|
||||
assertEquals(str2, parameters.get(str1));
|
||||
assertNull(parameters.get(str2));
|
||||
assertTrue(parameters.getBool(bool1));
|
||||
assertFalse(parameters.getBool(bool2));
|
||||
call = 0;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
try {
|
||||
cmd.execute();
|
||||
cmd.execute("-" + str1, str2);
|
||||
cmd.execute("-" + str1, str2, "-" + bool1);
|
||||
} catch (CommandRunException e) {
|
||||
assertNull(e);
|
||||
fail("unexpected error");
|
||||
}
|
||||
try {
|
||||
cmd.execute(addParam);
|
||||
fail("Strict should fail with unexpected argument");
|
||||
} catch (CommandRunException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.execute("-" + addParam);
|
||||
fail("Strict should fail with unexpected argument");
|
||||
} catch (CommandRunException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
// Test on command with missing needed elements
|
||||
cmd = new ParametrizedCommand("name", false) {
|
||||
private final int call = 0;
|
||||
{
|
||||
|
||||
try {
|
||||
addParameter(str1, true, true);
|
||||
addParameter(str2, true, false);
|
||||
addParameter(bool1, false, false);
|
||||
addParameter(bool2, false, false);
|
||||
} catch (InvalidParameterException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
assertEquals(str2, parameters.get(str1));
|
||||
}
|
||||
};
|
||||
try {
|
||||
cmd.execute("-" + str1, str2);
|
||||
cmd.execute("-" + str1, str2, "-" + bool1);
|
||||
cmd.execute("-" + str1, str2, "-" + addParam);
|
||||
cmd.execute("-" + str1, str2, addParam);
|
||||
cmd.execute("-" + str1, str2, "-" + addParam, addParam);
|
||||
} catch (CommandRunException e) {
|
||||
assertNull(e);
|
||||
fail("unepected error");
|
||||
}
|
||||
try {
|
||||
cmd.execute();
|
||||
fail("needed " + str1 + " not provided shall fail");
|
||||
} catch (CommandRunException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
cmd = new ParametrizedCommand("name", true) {
|
||||
private final int call = 0;
|
||||
{
|
||||
|
||||
try {
|
||||
addParameter(str1, true, true);
|
||||
addParameter(str2, true, false);
|
||||
addParameter(bool1, false, false);
|
||||
addParameter(bool2, false, false);
|
||||
} catch (InvalidParameterException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
//
|
||||
assertEquals(str2, parameters.get(str1));
|
||||
}
|
||||
};
|
||||
try {
|
||||
cmd.execute("-" + str1, str2);
|
||||
cmd.execute("-" + str1, str2, "-" + bool1);
|
||||
} catch (CommandRunException e) {
|
||||
assertNull(e);
|
||||
fail("unepected error");
|
||||
}
|
||||
try {
|
||||
cmd.execute("-" + str1, str2, addParam);
|
||||
fail("Additional parameter should cause failure");
|
||||
} catch (CommandRunException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.execute();
|
||||
fail("needed " + str1 + " not provided shall fail");
|
||||
} catch (CommandRunException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.execute("-" + str1, str2, "-" + addParam);
|
||||
fail("unepected error");
|
||||
} catch (CommandRunException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.execute("-" + str1, str2, "-" + addParam, addParam);
|
||||
fail("unepected error");
|
||||
} catch (CommandRunException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
// TODO Test of interactive not providing and providing all needed
|
||||
try (PipedConsoleManager test = new PipedConsoleManager()) {
|
||||
cmd = new ParametrizedCommand(test, "name", false) {
|
||||
{
|
||||
try {
|
||||
addParameter(str1, true, true);
|
||||
addParameter(str2, true, false);
|
||||
addParameter(bool1, false, false);
|
||||
addParameter(bool2, false, false);
|
||||
} catch (InvalidParameterException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
assertEquals(str2, parameters.get(str1));
|
||||
}
|
||||
};
|
||||
try {
|
||||
cmd.execute("-" + str1, str2);
|
||||
cmd.execute("-" + str1, str2, "-" + bool1);
|
||||
cmd.execute("-" + str1, str2, addParam);
|
||||
cmd.execute("-" + str1, str2, "-" + addParam);
|
||||
cmd.execute("-" + str1, str2, "-" + addParam, addParam);
|
||||
} catch (CommandRunException e) {
|
||||
assertNull(e);
|
||||
fail("unepected error");
|
||||
}
|
||||
try {
|
||||
|
||||
Thread th = new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
assertEquals("value of " + str1 + "? ",
|
||||
test.readNextLine());
|
||||
test.type("");
|
||||
assertEquals(
|
||||
"value of " + str1 + "? (cannot be empty) ",
|
||||
test.readNextLine());
|
||||
test.type("");
|
||||
assertEquals(
|
||||
"value of " + str1 + "? (cannot be empty) ",
|
||||
test.readNextLine());
|
||||
test.type(str2);
|
||||
} catch (IOException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
th.start();
|
||||
|
||||
cmd.execute();
|
||||
|
||||
th.join();
|
||||
|
||||
th = new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
assertEquals("value of " + str1 + "? ",
|
||||
test.readNextLine());
|
||||
test.type(str2);
|
||||
} catch (IOException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
th.start();
|
||||
|
||||
cmd.execute("-" + addParam);
|
||||
|
||||
th.join();
|
||||
} catch (CommandRunException | InterruptedException e) {
|
||||
assertNull(e);
|
||||
fail("unepected error");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
assertNull(e);
|
||||
fail("unepected error");
|
||||
}
|
||||
try {
|
||||
PipedConsoleManager test = new PipedConsoleManager();
|
||||
cmd = new ParametrizedCommand(test, "name") {
|
||||
{
|
||||
try {
|
||||
addParameter(str1, true, true);
|
||||
addParameter(str2, true, false);
|
||||
addParameter(bool1, false, false);
|
||||
addParameter(bool2, false, false);
|
||||
} catch (InvalidParameterException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doExecute(CommandParameters parameters) {
|
||||
assertEquals(str2, parameters.get(str1));
|
||||
}
|
||||
};
|
||||
test.close();
|
||||
cmd.execute("-" + str1, str2);
|
||||
cmd.execute("-" + addParam);
|
||||
fail("Closed manager shall cause error");
|
||||
} catch (IOException e) {
|
||||
assertNull(e);
|
||||
} catch (CommandRunException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.command.ScriptExecutionTest.java
|
||||
* Created on: Jun 12, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.command;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.ConsoleApplication;
|
||||
import fr.bigeon.gclc.ConsoleTestApplication;
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.CommandRunExceptionType;
|
||||
import fr.bigeon.gclc.manager.PipedConsoleManager;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("static-method")
|
||||
public class ScriptExecutionTest {
|
||||
|
||||
/**
|
||||
* Test method for {@link fr.bigeon.gclc.command.ScriptExecution#execute(java.lang.String[])}.
|
||||
*/
|
||||
@Test
|
||||
public void testExecute() {
|
||||
PipedConsoleManager test;
|
||||
try {
|
||||
test = new PipedConsoleManager();
|
||||
} catch (IOException e2) {
|
||||
fail("creation of console manager failed"); //$NON-NLS-1$
|
||||
assertNotNull(e2);
|
||||
return;
|
||||
}
|
||||
ConsoleApplication app = new ConsoleApplication(
|
||||
test, "", "");
|
||||
new ConsoleTestApplication().attach(app);
|
||||
ScriptExecution exec = new ScriptExecution("script", app, "#", //$NON-NLS-1$ //$NON-NLS-2$
|
||||
Charset.forName("UTF-8"));
|
||||
try {
|
||||
exec.execute();
|
||||
fail("execution of script command with no file should fail"); //$NON-NLS-1$
|
||||
} catch (CommandRunException e1) {
|
||||
// ok
|
||||
assertEquals(exec, e1.getSource());
|
||||
assertEquals(CommandRunExceptionType.USAGE, e1.getType());
|
||||
}
|
||||
|
||||
try {
|
||||
exec.execute("src/test/resources/scripts/withprependSpace.txt"); //$NON-NLS-1$
|
||||
fail("execution of script with lines begining with space should fail"); //$NON-NLS-1$
|
||||
} catch (CommandRunException e1) {
|
||||
// ok
|
||||
assertEquals(exec, e1.getSource());
|
||||
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
|
||||
}
|
||||
|
||||
try {
|
||||
exec.execute("src/test/resources/scripts/invalidCmdParse.txt"); //$NON-NLS-1$
|
||||
fail("execution of script with invalid command line should fail"); //$NON-NLS-1$
|
||||
} catch (CommandRunException e1) {
|
||||
// ok
|
||||
assertEquals(exec, e1.getSource());
|
||||
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
|
||||
}
|
||||
|
||||
try {
|
||||
exec.execute("src/test/resources/scripts/invalidCmd.txt"); //$NON-NLS-1$
|
||||
fail("execution of script with invalid command should fail"); //$NON-NLS-1$
|
||||
} catch (CommandRunException e1) {
|
||||
// ok
|
||||
assertEquals(exec, e1.getSource());
|
||||
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
|
||||
}
|
||||
|
||||
try {
|
||||
exec.execute("src/test/resources/scripts/failingCmdInvoc.txt"); //$NON-NLS-1$
|
||||
fail("execution of script with failing command should fail"); //$NON-NLS-1$
|
||||
} catch (CommandRunException e1) {
|
||||
// ok
|
||||
assertEquals(exec, e1.getSource());
|
||||
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
|
||||
}
|
||||
|
||||
try {
|
||||
exec.execute("src/test/resources/scripts/someNonExisting.file"); //$NON-NLS-1$
|
||||
fail("execution of script with unexisting file should fail"); //$NON-NLS-1$
|
||||
} catch (CommandRunException e1) {
|
||||
// ok
|
||||
assertEquals(exec, e1.getSource());
|
||||
assertEquals(CommandRunExceptionType.EXECUTION, e1.getType());
|
||||
}
|
||||
|
||||
try {
|
||||
exec.execute("src/test/resources/script1.txt"); //$NON-NLS-1$
|
||||
exec.execute("src/test/resources/script2.txt"); //$NON-NLS-1$
|
||||
exec.execute("src/test/resources/script3.txt"); //$NON-NLS-1$
|
||||
exec.execute("src/test/resources/script4.txt"); //$NON-NLS-1$
|
||||
exec.execute("src/test/resources/script5.txt", "test"); //$NON-NLS-1$ //$NON-NLS-2$
|
||||
} catch (CommandRunException e) {
|
||||
e.printStackTrace();
|
||||
fail("execution of wellformed script should not fail"); //$NON-NLS-1$
|
||||
}
|
||||
try {
|
||||
test.close();
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/** Test method for {@link fr.bigeon.gclc.command.ScriptExecution#tip()}. */
|
||||
@Test
|
||||
public void testTip() {
|
||||
ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$
|
||||
Charset.forName("UTF-8"));
|
||||
exec.tip();
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.ScriptExecution#help(fr.bigeon.gclc.manager.ConsoleManager, String...)}. */
|
||||
@Test
|
||||
public void testHelp() {
|
||||
ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$
|
||||
Charset.forName("UTF-8"));
|
||||
try (PipedConsoleManager test = new PipedConsoleManager()) {
|
||||
exec.help(test);
|
||||
exec.help(test, "ignored element");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
fail("unexpected error in help invocation"); //$NON-NLS-1$
|
||||
}
|
||||
}
|
||||
}
|
||||
390
gclc/src/test/java/fr/bigeon/gclc/command/SubedCommandTest.java
Normal file
390
gclc/src/test/java/fr/bigeon/gclc/command/SubedCommandTest.java
Normal file
@@ -0,0 +1,390 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.command.SubedCommandTest.java
|
||||
* Created on: Nov 18, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.command;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.exception.CommandRunException;
|
||||
import fr.bigeon.gclc.exception.InvalidCommandName;
|
||||
import fr.bigeon.gclc.manager.ConsoleManager;
|
||||
import fr.bigeon.gclc.manager.PipedConsoleManager;
|
||||
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
@SuppressWarnings("all")
|
||||
public class SubedCommandTest {
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String)}. */
|
||||
@Test
|
||||
public final void testSubedCommandString() {
|
||||
SubedCommand cmd = new SubedCommand("name");
|
||||
assertEquals("name", cmd.getCommandName());
|
||||
cmd = new SubedCommand("name with spaces");
|
||||
assertNull(cmd.tip());
|
||||
assertEquals("name with spaces", cmd.getCommandName());
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String, fr.bigeon.gclc.command.ICommand)}. */
|
||||
@Test
|
||||
public final void testSubedCommandStringICommand() {
|
||||
SubedCommand cmd = new SubedCommand("name", new MockCommand(""));
|
||||
assertEquals("name", cmd.getCommandName());
|
||||
cmd = new SubedCommand("name with spaces", new MockCommand(""));
|
||||
assertNull(cmd.tip());
|
||||
assertEquals("name with spaces", cmd.getCommandName());
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String, fr.bigeon.gclc.command.ICommand, java.lang.String)}. */
|
||||
@Test
|
||||
public final void testSubedCommandStringICommandString() {
|
||||
SubedCommand cmd = new SubedCommand("name", new MockCommand(""), "tip");
|
||||
assertEquals("name", cmd.getCommandName());
|
||||
cmd = new SubedCommand("name with spaces", new MockCommand(""), "tip");
|
||||
assertEquals("name with spaces", cmd.getCommandName());
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String, java.lang.String)}. */
|
||||
@Test
|
||||
public final void testSubedCommandStringString() {
|
||||
SubedCommand cmd = new SubedCommand("name", "tip");
|
||||
assertEquals("name", cmd.getCommandName());
|
||||
cmd = new SubedCommand("name with spaces", "tip");
|
||||
assertEquals("name with spaces", cmd.getCommandName());
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.SubedCommand#add(fr.bigeon.gclc.command.ICommand)}. */
|
||||
@Test
|
||||
public final void testAdd() {
|
||||
SubedCommand cmd = new SubedCommand("name");
|
||||
|
||||
try {
|
||||
cmd.add(new MockCommand("id"));
|
||||
} catch (InvalidCommandName e) {
|
||||
fail("addition of command with valid id failed");
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.add(new MockCommand("id"));
|
||||
fail("addition of command with already used id succeeded");
|
||||
} catch (InvalidCommandName e) {
|
||||
//
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.add(new MockCommand(""));
|
||||
fail("addition of command with invalid id succeeded");
|
||||
} catch (InvalidCommandName e) {
|
||||
//
|
||||
assertNotNull(e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.SubedCommand#execute(java.lang.String[])}. */
|
||||
@Test
|
||||
public final void testExecute() {
|
||||
SubedCommand cmd = new SubedCommand("name");
|
||||
|
||||
MockCommand mock = new MockCommand("id");
|
||||
try {
|
||||
cmd.add(mock);
|
||||
cmd.add(new Command("fail") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
throw new CommandRunException("Failing command", null);
|
||||
}
|
||||
});
|
||||
} catch (InvalidCommandName e) {
|
||||
fail("addition of command with valid id failed");
|
||||
assertNotNull(e);
|
||||
}
|
||||
|
||||
try {
|
||||
cmd.execute("id");
|
||||
} catch (CommandRunException e) {
|
||||
fail("Unexpected exception when running mock command");
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.execute("fail");
|
||||
fail("Fail command error should be re thrown");
|
||||
} catch (CommandRunException e) {
|
||||
assertNotNull(e);
|
||||
assertEquals(cmd, e.getSource());
|
||||
}
|
||||
try {
|
||||
cmd.execute();
|
||||
fail("Request for inexistent default command should fail");
|
||||
} catch (CommandRunException e) {
|
||||
assertNotNull(e);
|
||||
assertEquals(cmd, e.getSource());
|
||||
}
|
||||
cmd = new SubedCommand("name", mock);
|
||||
|
||||
try {
|
||||
cmd.add(mock);
|
||||
cmd.add(new Command("fail") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
throw new CommandRunException("Failing command", this);
|
||||
}
|
||||
});
|
||||
} catch (InvalidCommandName e) {
|
||||
fail("addition of command with valid id failed");
|
||||
assertNotNull(e);
|
||||
}
|
||||
|
||||
try {
|
||||
cmd.execute("id");
|
||||
} catch (CommandRunException e) {
|
||||
fail("Unexpected exception when running mock command");
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.execute("fail");
|
||||
fail("Fail command error should be re thrown");
|
||||
} catch (CommandRunException e) {
|
||||
assertNotNull(e);
|
||||
assertEquals(cmd.get("fail"), e.getSource());
|
||||
}
|
||||
try {
|
||||
cmd.execute();
|
||||
} catch (CommandRunException e) {
|
||||
fail("Request for default command should execute default command");
|
||||
assertNotNull(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.SubedCommand#executeSub(java.lang.String, java.lang.String[])}. */
|
||||
@Test
|
||||
public final void testExecuteSub() {
|
||||
SubedCommand cmd = new SubedCommand("name");
|
||||
|
||||
MockCommand mock = new MockCommand("id");
|
||||
try {
|
||||
cmd.add(mock);
|
||||
cmd.add(new Command("fail") {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
throw new CommandRunException("Failing command", this);
|
||||
}
|
||||
});
|
||||
} catch (InvalidCommandName e) {
|
||||
fail("addition of command with valid id failed");
|
||||
assertNotNull(e);
|
||||
}
|
||||
|
||||
try {
|
||||
cmd.executeSub("id");
|
||||
} catch (CommandRunException e) {
|
||||
fail("Unexpected exception when running mock command");
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
cmd.executeSub("fail");
|
||||
fail("Fail command error should be re thrown");
|
||||
} catch (CommandRunException e) {
|
||||
assertNotNull(e);
|
||||
assertEquals(cmd.get("fail"), e.getSource());
|
||||
}
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.SubedCommand#get(java.lang.String)}. */
|
||||
@Test
|
||||
public final void testGet() {
|
||||
SubedCommand cmd = new SubedCommand("name");
|
||||
|
||||
assertNull(cmd.get("id"));
|
||||
|
||||
MockCommand mock = new MockCommand("id");
|
||||
try {
|
||||
cmd.add(mock);
|
||||
} catch (InvalidCommandName e) {
|
||||
fail("addition of command with valid id failed");
|
||||
assertNotNull(e);
|
||||
}
|
||||
assertEquals(mock, cmd.get("id"));
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.SubedCommand#getCommandName()}. */
|
||||
@Test
|
||||
public final void testGetCommandName() {
|
||||
SubedCommand cmd = new SubedCommand("name");
|
||||
assertEquals("name", cmd.getCommandName());
|
||||
cmd = new SubedCommand("name with spaces");
|
||||
assertEquals("name with spaces", cmd.getCommandName());
|
||||
cmd = new SubedCommand("name", "some tip");
|
||||
assertEquals("name", cmd.getCommandName());
|
||||
cmd = new SubedCommand("name", new MockCommand(""));
|
||||
assertEquals("name", cmd.getCommandName());
|
||||
cmd = new SubedCommand("name", new MockCommand(""), "some tip");
|
||||
assertEquals("name", cmd.getCommandName());
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.command.SubedCommand#help(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String[])}. */
|
||||
@Test
|
||||
public final void testHelp() {
|
||||
SubedCommand cmd = new SubedCommand("name");
|
||||
|
||||
ICommand mock = new MockCommand("id");
|
||||
try {
|
||||
cmd.add(mock);
|
||||
} catch (InvalidCommandName e) {
|
||||
fail("addition of command with valid id failed");
|
||||
assertNotNull(e);
|
||||
}
|
||||
|
||||
try (PipedConsoleManager manager = new PipedConsoleManager();
|
||||
PipedConsoleManager manager2 = new PipedConsoleManager()) {
|
||||
cmd.help(manager);
|
||||
assertEquals("\tid", manager.readNextLine());
|
||||
cmd.help(manager, "id");
|
||||
cmd.help(manager, "inexistent");
|
||||
} catch (IOException e) {
|
||||
fail("Unexpected exception when running help");
|
||||
assertNotNull(e);
|
||||
}
|
||||
|
||||
cmd = new SubedCommand("name", mock);
|
||||
|
||||
try {
|
||||
cmd.add(mock);
|
||||
} catch (InvalidCommandName e) {
|
||||
fail("addition of command with valid id failed");
|
||||
assertNotNull(e);
|
||||
}
|
||||
|
||||
try (PipedConsoleManager manager = new PipedConsoleManager();
|
||||
PipedConsoleManager manager2 = new PipedConsoleManager()) {
|
||||
cmd.help(manager);
|
||||
assertEquals("\tid", manager.readNextLine());
|
||||
} catch (IOException e) {
|
||||
fail("Unexpected exception when running help");
|
||||
assertNotNull(e);
|
||||
}
|
||||
|
||||
mock = new ICommand() {
|
||||
|
||||
@Override
|
||||
public String tip() {
|
||||
return "tip";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void help(ConsoleManager manager,
|
||||
String... args) throws IOException {
|
||||
//
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return "id";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String... args) throws CommandRunException {
|
||||
//
|
||||
}
|
||||
};
|
||||
cmd = new SubedCommand("name", mock);
|
||||
|
||||
try {
|
||||
cmd.add(mock);
|
||||
} catch (InvalidCommandName e) {
|
||||
fail("addition of command with valid id failed");
|
||||
assertNotNull(e);
|
||||
}
|
||||
|
||||
try (PipedConsoleManager manager = new PipedConsoleManager();
|
||||
PipedConsoleManager manager2 = new PipedConsoleManager()) {
|
||||
cmd.help(manager);
|
||||
assertEquals("\ttip", manager.readNextLine());
|
||||
assertEquals("\tid: tip", manager.readNextLine());
|
||||
} catch (IOException e) {
|
||||
fail("Unexpected exception when running help");
|
||||
assertNotNull(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Test method for {@link fr.bigeon.gclc.command.SubedCommand#tip()}. */
|
||||
@Test
|
||||
public final void testTip() {
|
||||
SubedCommand cmd = new SubedCommand("name");
|
||||
assertNull(cmd.tip());
|
||||
cmd = new SubedCommand("name with spaces", new MockCommand(""), "tip");
|
||||
assertEquals("tip", cmd.tip());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.exception.CommandRunExceptionTest.java
|
||||
* Created on: Nov 19, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.exception;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.command.ICommand;
|
||||
import fr.bigeon.gclc.command.MockCommand;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon
|
||||
*
|
||||
*/
|
||||
public class CommandRunExceptionTest {
|
||||
|
||||
/**
|
||||
* Test method for {@link fr.bigeon.gclc.exception.CommandRunException#getLocalizedMessage()}.
|
||||
*/
|
||||
@Test
|
||||
public final void testGetLocalizedMessage() {
|
||||
CommandRunException e;
|
||||
ICommand cmd = new MockCommand("name");
|
||||
String messageInner = "inner";
|
||||
String message = "message";
|
||||
e = new CommandRunException(message,
|
||||
new CommandRunException(messageInner, new MockCommand("name")), //$NON-NLS-1$
|
||||
cmd);
|
||||
|
||||
assertEquals(message + ": " + messageInner, e.getLocalizedMessage());
|
||||
e = new CommandRunException(message, cmd);
|
||||
assertEquals(message, e.getLocalizedMessage());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.manager.ReadingRunnableTest.java
|
||||
* Created on: Dec 6, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.manager;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PipedInputStream;
|
||||
import java.io.PipedOutputStream;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class ReadingRunnableTest {
|
||||
|
||||
/**
|
||||
*/
|
||||
@Before
|
||||
public void setUp() {}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.manager.ReadingRunnable#getMessage()}. */
|
||||
@Test
|
||||
public final void testGetMessage() {
|
||||
BufferedReader reader = null;
|
||||
ReadingRunnable runnable = new ReadingRunnable(reader);
|
||||
runnable.setRunning(false);
|
||||
|
||||
try {
|
||||
runnable.getMessage();
|
||||
fail("reading from closed runnable");
|
||||
} catch (IOException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.manager.ReadingRunnable#hasMessage()}. */
|
||||
@Test
|
||||
public final void testHasMessage() {
|
||||
|
||||
BufferedReader reader = null;
|
||||
ReadingRunnable runnable = new ReadingRunnable(reader);
|
||||
runnable.setRunning(false);
|
||||
|
||||
try {
|
||||
runnable.getMessage();
|
||||
fail("reading from closed runnable");
|
||||
} catch (IOException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String)}.
|
||||
*
|
||||
* @throws InterruptedException */
|
||||
@Test
|
||||
public final void testGetWaitForDelivery() throws InterruptedException {
|
||||
try (PipedOutputStream out = new PipedOutputStream();
|
||||
InputStream piped = new PipedInputStream(out);
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(piped, "UTF-8"))) {
|
||||
final ReadingRunnable runnable = new ReadingRunnable(reader);
|
||||
Thread th0 = new Thread(runnable, "read");
|
||||
th0.start();
|
||||
Thread th = runnable.getWaitForDelivery("msg");
|
||||
|
||||
out.write(Charset.forName("UTF-8")
|
||||
.encode("msg" + System.lineSeparator()).array());
|
||||
|
||||
Thread th2 = new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
runnable.getMessage();
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}, "get");
|
||||
th2.start();
|
||||
try {
|
||||
th.join();
|
||||
} catch (InterruptedException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
runnable.setRunning(false);
|
||||
out.close();
|
||||
} catch (IOException e1) {
|
||||
assertNull(e1);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.manager.SystemConsoleManagerTest.java
|
||||
* Created on: Nov 19, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.manager;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.PipedInputStream;
|
||||
import java.io.PipedOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class SystemConsoleManagerTest {
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.manager.SystemConsoleManager#prompt()}. */
|
||||
@Test
|
||||
public final void testPrompt() {
|
||||
|
||||
final String test = "test";
|
||||
try (PipedOutputStream outStream = new PipedOutputStream();
|
||||
InputStream in = new PipedInputStream(outStream);
|
||||
final PrintStream out = new PrintStream(outStream);
|
||||
SystemConsoleManager manager = new SystemConsoleManager(System.out,
|
||||
in, Charset.forName("UTF-8"))) {
|
||||
|
||||
Thread th = new Thread(new Runnable() {
|
||||
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
out.println(test);
|
||||
}
|
||||
});
|
||||
|
||||
th.start();
|
||||
assertEquals(test, manager.prompt());
|
||||
|
||||
th.join();
|
||||
} catch (IOException | InterruptedException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.manager.SystemConsoleManager#setPrompt(java.lang.String)}. */
|
||||
@Test
|
||||
public final void testSetPrompt() {
|
||||
try (PipedOutputStream outStream = new PipedOutputStream();
|
||||
InputStream in = new PipedInputStream(outStream);
|
||||
final PrintStream out = new PrintStream(outStream);
|
||||
SystemConsoleManager manager = new SystemConsoleManager(System.out,
|
||||
in, Charset.forName("UTF-8"))) {
|
||||
|
||||
String prt = "++";
|
||||
manager.setPrompt(prt);
|
||||
assertEquals(prt, manager.getPrompt());
|
||||
} catch (IOException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.manager.SystemConsoleManager#isClosed()}. */
|
||||
@Test
|
||||
public final void testIsClosed() {
|
||||
try {
|
||||
PipedOutputStream outStream = new PipedOutputStream();
|
||||
InputStream in = new PipedInputStream(outStream);
|
||||
final PrintStream out = new PrintStream(outStream);
|
||||
final String test = "test";
|
||||
SystemConsoleManager manager = new SystemConsoleManager(System.out,
|
||||
in, Charset.forName("UTF-8"));
|
||||
|
||||
Thread th = new Thread(new Runnable() {
|
||||
|
||||
@SuppressWarnings("synthetic-access")
|
||||
@Override
|
||||
public void run() {
|
||||
out.println(test);
|
||||
}
|
||||
});
|
||||
|
||||
th.start();
|
||||
assertEquals(test, manager.prompt());
|
||||
assertFalse(manager.isClosed());
|
||||
manager.close();
|
||||
assertTrue(manager.isClosed());
|
||||
try {
|
||||
manager.prompt();
|
||||
fail("prompt on closed manager");
|
||||
} catch (IOException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
manager.println(test);
|
||||
fail("prompt on closed manager");
|
||||
} catch (IOException e) {
|
||||
assertNotNull(e);
|
||||
}
|
||||
th.join();
|
||||
} catch (IOException | InterruptedException e) {
|
||||
assertNull(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.prompt.CLIPrompterMessagesTest.java
|
||||
* Created on: Nov 19, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.prompt;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon
|
||||
*
|
||||
*/
|
||||
public class CLIPrompterMessagesTest {
|
||||
|
||||
/**
|
||||
* Test method for {@link fr.bigeon.gclc.prompt.CLIPrompterMessages#getString(java.lang.String, java.lang.Object[])}.
|
||||
*/
|
||||
@Test
|
||||
public final void testGetString() {
|
||||
String key = "bad.key";
|
||||
assertEquals('!' + key + '!', CLIPrompterMessages.getString(key));
|
||||
assertEquals('!' + key + '!',
|
||||
CLIPrompterMessages.getString(key, "some arg"));
|
||||
assertEquals('!' + key + '!',
|
||||
CLIPrompterMessages.getString(key, new Object[] {}));
|
||||
}
|
||||
|
||||
}
|
||||
1080
gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterTest.java
Normal file
1080
gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterTest.java
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.tools.AOutputForwardRunnableTest.java
|
||||
* Created on: Dec 3, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.tools;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fr.bigeon.gclc.manager.PipedConsoleManager;
|
||||
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class AOutputForwardRunnableTest {
|
||||
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
private final class AOutputForwardTestRunnable
|
||||
extends AOutputForwardRunnable {
|
||||
private int count = 2;
|
||||
private String message;
|
||||
|
||||
/** @param manager */
|
||||
private AOutputForwardTestRunnable(PipedConsoleManager manager) {
|
||||
super(manager);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isRunning() {
|
||||
return count != 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void forwardLine(String m) {
|
||||
// Do nothing
|
||||
message = m;
|
||||
synchronized (this) {
|
||||
notify();
|
||||
try {
|
||||
wait();
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return the message */
|
||||
public String getMessage() {
|
||||
if (message == null) {
|
||||
synchronized (this) {
|
||||
try {
|
||||
wait();
|
||||
} catch (InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
String m = message;
|
||||
count--;
|
||||
message = null;
|
||||
synchronized (this) {
|
||||
notify();
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.tools.AOutputForwardRunnable#run()}. */
|
||||
@Test
|
||||
public final void testRun() {
|
||||
try (PipedConsoleManager manager = new PipedConsoleManager()) {
|
||||
AOutputForwardTestRunnable runnable = new AOutputForwardTestRunnable(
|
||||
manager);
|
||||
|
||||
Thread th = new Thread(runnable, "forward");
|
||||
manager.println("before");
|
||||
th.start();
|
||||
|
||||
assertEquals("before", runnable.getMessage());
|
||||
|
||||
synchronized (this) {
|
||||
wait(3000);
|
||||
}
|
||||
manager.println("after");
|
||||
assertEquals("after", runnable.getMessage());
|
||||
synchronized (this) {
|
||||
wait(3000);
|
||||
}
|
||||
|
||||
th.join();
|
||||
|
||||
} catch (IOException | InterruptedException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
94
gclc/src/test/java/fr/bigeon/gclc/tools/PrintUtilsTest.java
Normal file
94
gclc/src/test/java/fr/bigeon/gclc/tools/PrintUtilsTest.java
Normal file
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* Copyright Bigeon Emmanuel (2014)
|
||||
*
|
||||
* emmanuel@bigeon.fr
|
||||
*
|
||||
* This software is a computer program whose purpose is to
|
||||
* provide a generic framework for console applications.
|
||||
*
|
||||
* This software is governed by the CeCILL license under French law and
|
||||
* abiding by the rules of distribution of free software. You can use,
|
||||
* modify and/or redistribute the software under the terms of the CeCILL
|
||||
* license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
* "http://www.cecill.info".
|
||||
*
|
||||
* As a counterpart to the access to the source code and rights to copy,
|
||||
* modify and redistribute granted by the license, users are provided only
|
||||
* with a limited warranty and the software's author, the holder of the
|
||||
* economic rights, and the successive licensors have only limited
|
||||
* liability.
|
||||
*
|
||||
* In this respect, the user's attention is drawn to the risks associated
|
||||
* with loading, using, modifying and/or developing or reproducing the
|
||||
* software by the user in light of its specific status of free software,
|
||||
* that may mean that it is complicated to manipulate, and that also
|
||||
* therefore means that it is reserved for developers and experienced
|
||||
* professionals having in-depth computer knowledge. Users are therefore
|
||||
* encouraged to load and test the software's suitability as regards their
|
||||
* requirements in conditions enabling the security of their systems and/or
|
||||
* data to be ensured and, more generally, to use and operate it in the
|
||||
* same conditions as regards security.
|
||||
*
|
||||
* The fact that you are presently reading this means that you have had
|
||||
* knowledge of the CeCILL license and that you accept its terms.
|
||||
*/
|
||||
/**
|
||||
* gclc:fr.bigeon.gclc.tools.PrintUtilsTest.java
|
||||
* Created on: Nov 19, 2016
|
||||
*/
|
||||
package fr.bigeon.gclc.tools;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/** <p>
|
||||
* TODO
|
||||
*
|
||||
* @author Emmanuel Bigeon */
|
||||
public class PrintUtilsTest {
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.tools.PrintUtils#print(java.lang.String, int, boolean)}. */
|
||||
@Test
|
||||
public final void testPrint() {
|
||||
String text = "Some text";
|
||||
String longText = text + " that may be abbreviated";
|
||||
assertEquals(text, PrintUtils.print(text, text.length(), true));
|
||||
assertEquals(text, PrintUtils.print(text, text.length(), false));
|
||||
assertEquals(text + " ",
|
||||
PrintUtils.print(text, text.length() + 3, false));
|
||||
assertEquals(text + " ",
|
||||
PrintUtils.print(text, text.length() + 3, true));
|
||||
assertEquals(text, PrintUtils.print(longText, text.length(), false));
|
||||
assertEquals(text + "...",
|
||||
PrintUtils.print(longText, text.length() + 3, true));
|
||||
}
|
||||
|
||||
/** Test method for
|
||||
* {@link fr.bigeon.gclc.tools.PrintUtils#wrap(java.lang.String, int)}. */
|
||||
@Test
|
||||
public final void testWrap() {
|
||||
String[] line = {"A text separated", "on several lines", "with cuts at",
|
||||
"whitespace", "characters"};
|
||||
String text = line[0] + " " + line[1] + " " + line[2] + " " + line[3] +
|
||||
" " + line[4];
|
||||
assertEquals(Arrays.asList(line),
|
||||
PrintUtils.wrap(text, line[0].length() + 1));
|
||||
assertEquals(Arrays.asList(line),
|
||||
PrintUtils.wrap(text, line[0].length()));
|
||||
|
||||
// test with split word
|
||||
line = new String[] {"A text separated", "on several lines", "",
|
||||
"with cuts at", "whitespacecharac", "ters"};
|
||||
text = line[0] + " " + line[1] + System.lineSeparator() + line[3] +
|
||||
" " + line[4] + line[5];
|
||||
assertEquals(Arrays.asList(line),
|
||||
PrintUtils.wrap(text, line[0].length()));
|
||||
assertEquals(Arrays.asList(""),
|
||||
PrintUtils.wrap("", line[0].length()));
|
||||
}
|
||||
|
||||
}
|
||||
0
gclc/src/test/resources/script1.txt
Normal file
0
gclc/src/test/resources/script1.txt
Normal file
1
gclc/src/test/resources/script2.txt
Normal file
1
gclc/src/test/resources/script2.txt
Normal file
@@ -0,0 +1 @@
|
||||
# test only comment
|
||||
1
gclc/src/test/resources/script3.txt
Normal file
1
gclc/src/test/resources/script3.txt
Normal file
@@ -0,0 +1 @@
|
||||
test
|
||||
7
gclc/src/test/resources/script4.txt
Normal file
7
gclc/src/test/resources/script4.txt
Normal file
@@ -0,0 +1,7 @@
|
||||
# Test file with commands
|
||||
test
|
||||
# and comments
|
||||
long
|
||||
# interwined
|
||||
|
||||
# with empty line too
|
||||
2
gclc/src/test/resources/script5.txt
Normal file
2
gclc/src/test/resources/script5.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
# A script with arguments
|
||||
{0}
|
||||
2
gclc/src/test/resources/scripts/failingCmdInvoc.txt
Normal file
2
gclc/src/test/resources/scripts/failingCmdInvoc.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
# a script invoking a failing command
|
||||
failingCmd
|
||||
2
gclc/src/test/resources/scripts/invalidCmd.txt
Normal file
2
gclc/src/test/resources/scripts/invalidCmd.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
# a script with invalid commands
|
||||
invalid
|
||||
2
gclc/src/test/resources/scripts/invalidCmdParse.txt
Normal file
2
gclc/src/test/resources/scripts/invalidCmdParse.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
# a script with invalid commands
|
||||
test "po"m
|
||||
3
gclc/src/test/resources/scripts/withprependSpace.txt
Normal file
3
gclc/src/test/resources/scripts/withprependSpace.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
# a script with space in begining
|
||||
test
|
||||
should never be reached
|
||||
Reference in New Issue
Block a user