Compare commits

..

38 Commits

Author SHA1 Message Date
6a117afcb3 [maven-release-plugin] prepare release gclc-socket-1.1.3 2016-12-04 09:54:25 -05:00
7d41a9f4c6 Closing of socket application throw only an IOException, no generic one
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-04 09:44:29 -05:00
90579d79a9 [maven-release-plugin] prepare for next development iteration 2016-12-04 09:38:27 -05:00
b2c98ae940 [maven-release-plugin] prepare release gclc-socket-1.1.2 2016-12-04 09:38:18 -05:00
1d6569cf69 Upgrade dependency to gclc-1.3.2
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-04 09:27:19 -05:00
072653c944 [maven-release-plugin] prepare for next development iteration 2016-12-03 22:24:04 -05:00
ad17c7d5d7 [maven-release-plugin] prepare release gclc-1.3.2 2016-12-03 22:23:52 -05:00
e469313baf minor warn fix
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-03 20:19:22 -05:00
543b1ef605 Fixed thread surviving the application lifespan.
+tests in swt.

Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-03 20:18:20 -05:00
24f1fba97e [maven-release-plugin] prepare for next development iteration 2016-12-03 16:53:44 -05:00
88fe564e24 [maven-release-plugin] prepare release gclc-socket-1.1.1 2016-12-03 16:53:29 -05:00
efa492570e Corrections on the socket closing.
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-03 16:47:26 -05:00
d07795cb6a Removed unreachable code, set test output in fine grain logging
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-03 11:12:02 -05:00
f3c3580855 [maven-release-plugin] prepare for next development iteration 2016-12-02 15:39:53 -05:00
62f59722a6 [maven-release-plugin] prepare release gclc-swt-1.1.1 2016-12-02 15:39:51 -05:00
3e31a38eb9 Skip version 1.1.0
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-02 15:39:03 -05:00
549ddc3e6f [maven-release-plugin] prepare release gclc-swt-1.1.0 2016-12-02 15:37:01 -05:00
d300e896e8 Synchronized swt widgets
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-02 15:35:19 -05:00
16514f9c25 [maven-release-plugin] rollback the release of gclc-swt-1.1.0 2016-12-02 15:34:09 -05:00
bb9f9c515b [maven-release-plugin] prepare for next development iteration 2016-12-02 15:27:42 -05:00
77c5ae64dd [maven-release-plugin] prepare release gclc-swt-1.1.0 2016-12-02 15:27:33 -05:00
18c7f89564 Made gclc-swt and -system compatible with gclc-1.3.1
Added an abstract runnable for output forwarding from piped output

Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-01 13:48:20 -05:00
5f185b52e9 [maven-release-plugin] prepare for next development iteration 2016-11-30 21:46:33 -05:00
2f5ea369b7 [maven-release-plugin] prepare release gclc-socket-1.1.0 2016-11-30 21:46:17 -05:00
ef708c3291 Code compliance
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-11-30 20:46:14 -05:00
9e040d80c4 Temp remove of test for console runnable as it does not fit new version
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-11-30 20:24:25 -05:00
e3ced7b961 Set version of gclc to stable
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-11-30 20:18:46 -05:00
c9b2270786 [maven-release-plugin] prepare for next development iteration 2016-11-30 20:10:00 -05:00
99ebb23138 [maven-release-plugin] prepare release gclc-1.3.1 2016-11-30 20:09:49 -05:00
d4f428d311 Factor constant string and comments added to ReadingRunnable
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-11-30 20:07:28 -05:00
e602a269f8 Made socket comply with new version of gclc. Fixed piped console manager
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-11-30 20:00:36 -05:00
d432914828 [maven-release-plugin] prepare for next development iteration 2016-11-30 09:55:45 -05:00
0cf54c4837 [maven-release-plugin] prepare release gclc-1.3.0 2016-11-30 09:55:33 -05:00
c1692019a6 Commentings and minors
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-11-30 09:53:20 -05:00
72362936be Added piped stream manager
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-11-30 09:49:16 -05:00
65b6be8283 Added prompting interruption, add exception in parameterized commands
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-11-29 16:37:20 -05:00
fd8dde32f1 Removed deprecated code
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-11-19 19:50:36 -05:00
fff9f4ea74 [maven-release-plugin] prepare for next development iteration 2016-11-19 17:40:22 -05:00
35 changed files with 1639 additions and 629 deletions

View File

@@ -70,7 +70,7 @@ of Emmanuel Bigeon. -->
<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.7-SNAPSHOT</version>
<version>1.1.3</version>
<packaging>jar</packaging>
<url>http://www.bigeon.fr/emmanuel</url>
<properties>
@@ -87,7 +87,7 @@ of Emmanuel Bigeon. -->
<dependency>
<groupId>fr.bigeon</groupId>
<artifactId>gclc</artifactId>
<version>1.2.5</version>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>fr.bigeon</groupId>
@@ -104,6 +104,6 @@ of Emmanuel Bigeon. -->
<description>Socket implementation of GCLC</description>
<scm>
<developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection>
<tag>HEAD</tag>
<tag>gclc-socket-1.1.3</tag>
</scm>
</project>

View File

@@ -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$
}
}
}
}

View File

@@ -35,24 +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.nio.charset.Charset;
import java.util.Arrays;
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>
@@ -72,36 +69,69 @@ 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.isOutputShutdown()) {
while (!socket.isOutputShutdown() &&
!consoleManager.available()) {
waitASec();
}
if (socket.isOutputShutdown()) {
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;
@@ -110,7 +140,7 @@ public class SocketConsoleApplicationShell implements Runnable {
/** The application shutdown string */
private final String applicationShutdown;
/** The charset for the communication. */
private Charset charset;
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
@@ -118,14 +148,17 @@ public class SocketConsoleApplicationShell implements Runnable {
* @param port the port to listen to
* @param close the session closing command
* @param applicationShutdown the appication shut down command
* @param charset the charset for communication */
* @param charset the charset for communication
* @throws IOException if the manager could not be created */
public SocketConsoleApplicationShell(int port, String close,
String applicationShutdown, Charset charset) {
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
@@ -135,14 +168,17 @@ public class SocketConsoleApplicationShell implements Runnable {
* @param autoClose if the session must be closed once the request has been
* sent
* @param applicationShutdown the appication shut down command
* @param charset the charset for communication */
* @param charset the charset for communication
* @throws IOException if the manager could not be created */
public SocketConsoleApplicationShell(int port, boolean autoClose,
String applicationShutdown, Charset charset) {
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)
@@ -154,138 +190,141 @@ public class SocketConsoleApplicationShell implements Runnable {
this.serverSocket = actualServerSocket;
running = true;
// Create the streams
try (PipedOutputStream outStream = new PipedOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(outStream,
charset));
InputStreamReader isr = new InputStreamReader(consoleInput,
charset);
BufferedReader inBuf = new BufferedReader(isr)) {
consoleInput.connect(outStream);
consoleManager.setInput(inBuf);
runSokectServer(writer);
// Close the application
// Pass command to application
if (app.isRunning()) {
writer.write(applicationShutdown + EOL);
writer.flush();
}
}
} catch (
final IOException e) {
runSokectServer();
} catch (final IOException e) {
LOGGER.log(Level.SEVERE,
"Communication error between client and server", e); //$NON-NLS-1$
}
}
/** @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(
new OutputStreamWriter(clientSocket.getOutputStream(),
charset),
true);
PrintWriter out = new PrintWriter(new OutputStreamWriter(
clientSocket.getOutputStream(), charset), true);
InputStreamReader isr = new InputStreamReader(
clientSocket.getInputStream(),
charset);
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"); //$NON-NLS-1$
LOGGER.log(Level.FINE,
"Socket closed with exception (probably due to server interruption)", //$NON-NLS-1$
e);
}
LOGGER.info("Closing client"); //$NON-NLS-1$
}
runnable.setRunning(false);
consoleManager.type(applicationShutdown);
consoleManager.close();
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);
}
}
Thread th = new Thread(new OutputForwardRunnable(writer, socket),
"ClientComm"); //$NON-NLS-1$
th.start();
if (autoClose) {
communicateOnce(in, writer);
communicateOnce(socket, in);
} else {
communicateLoop(in, writer);
}
communicateLoop(socket, in);
}
}
/** @param in the input from the client
* @param writer the output to the client
/** @param socket the socket
* @param in the input from 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;
}
// 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);
}
}
private void communicateOnce(Socket socket,
BufferedReader in) throws IOException {
ReadingRunnable reading = new ReadingRunnable(in);
Thread th = new Thread(reading, "gclcToApp"); //$NON-NLS-1$
th.start();
communicationContent(reading);
reading.setRunning(false);
socket.shutdownOutput();
}
/** @param in the input from the client
* @param writer the output to the client
/** @param socket the socket
* @param in the input from 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(Socket socket,
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
}
reading.setRunning(false);
socket.shutdownOutput();
}
/** @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;
consoleManager.println("Bye."); //$NON-NLS-1$
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 */
@@ -309,10 +348,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();
}
}

View File

@@ -1,178 +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 empty string constant */
private static final String EMPTY = ""; //$NON-NLS-1$
/** The prompting sequence */
private String prompt = EMPTY;
/** 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 = EMPTY;
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;
}
}

View File

@@ -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>
@@ -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();
}
}

View File

@@ -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();
}
@@ -77,20 +86,97 @@ public class SocketConsoleApplicationTest {
String fromServer;
int i = 0;
String[] cmds = {"help", "toto", "test", "close"};
String[] cmds = {"help", "toto", "test", "bye"};
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: \n" + ENCODER.decode(fromServer));
LOGGER.fine("Server: \n" + fromServer);
if (fromServer.equals("Bye.")) {
break;
}
while (fromServer != null && !fromServer.equals("> ")) {
fromServer = in.readLine();
LOGGER.fine("Server: \n" + fromServer);
}
if (fromServer == null) {
fail("Null pointer");
}
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();
}
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) {
LOGGER.fine("Server: \n" + fromServer);
while (fromServer != null && !fromServer.equals("> ")) {
LOGGER.fine("Server: \n" + fromServer);
fromServer = in.readLine();
}
if (fromServer == null) {
break;
}
LOGGER.fine("Server: \n" + fromServer);
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();
}
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) {
while (fromServer != null && !fromServer.equals("> ")) {
fromServer = in.readLine();
LOGGER.fine("Server: \n" + fromServer);
}
if (fromServer == null) {
break;
}
final String fromUser = cmds[i];
if (fromUser != null) {
System.out.println("Client: " + fromUser);
LOGGER.fine("Client: " + fromUser);
out.println(fromUser);
}
i++;
}
assertEquals(4, i);
} catch (final IOException e) {
e.printStackTrace();
}
@@ -100,7 +186,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 +207,40 @@ 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.")) {
assertTrue(i < 1);
while (fromServer != null && !fromServer.equals("> ") &&
!fromServer.equals("See you")) {
fromServer = in.readLine();
LOGGER.fine("Server: \n" + fromServer);
}
if (fromServer == null || fromServer.equals("Bye.") ||
fromServer.equals("See you")) {
break;
}
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();
}
}
}

View File

@@ -34,6 +34,7 @@
*/
package fr.bigeon.gclc.socket;
import java.io.IOException;
import java.nio.charset.Charset;
/** A test server
@@ -45,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) {
@@ -54,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();
@@ -62,7 +64,7 @@ public class TestServer {
return server;
}
private static SocketConsoleApplicationShell getShell() {
private static SocketConsoleApplicationShell getShell() throws IOException {
if (SHELL == null) {
SHELL = new SocketConsoleApplicationShell(3300, "close",
ConsoleTestApplication.EXIT, Charset.forName("UTF-8"));
@@ -73,7 +75,7 @@ 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, Charset.forName("UTF-8"));
@@ -85,6 +87,18 @@ public class TestServer {
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);
server = null;
}
return getServer();
}
public static void closeServer() {
SHELL.stop();
SHELL = null;

View File

@@ -32,12 +32,10 @@
<!-- 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-swt</artifactId>
<version>1.0.5-SNAPSHOT</version>
<version>1.1.2-SNAPSHOT</version>
<packaging>jar</packaging>
<url>http://www.bigeon.fr/emmanuel</url>
<properties>
@@ -53,7 +51,7 @@
<dependency>
<groupId>fr.bigeon</groupId>
<artifactId>gclc</artifactId>
<version>1.2.3</version>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>fr.bigeon</groupId>

View File

@@ -38,16 +38,14 @@
*/
package fr.bigeon.gclc.swt;
import fr.bigeon.gclc.manager.ConsoleManager;
/**
/** This class represents an object used to send commands to a console
* application.
* <p>
* TODO
* 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 extends ConsoleManager {
* @author Emmanuel Bigeon */
public interface ConsoleDelayIO {
/** Actually send the input as the prompt next input. */
void validateInput();

View File

@@ -53,12 +53,14 @@ import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import fr.bigeon.gclc.ConsoleApplication;
import fr.bigeon.gclc.manager.ConsoleManager;
/** A SWT component to connect to gclc {@link ConsoleApplication}
* <p>
*
* @author Emmanuel Bigeon */
public class SWTConsole extends Composite implements ConsoleDelayIO {
public class SWTConsole extends Composite
implements ConsoleDelayIO, ConsoleManager {
/**
*
*/
@@ -173,8 +175,10 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
if (!consoleOutput.isDisposed()) {
consoleOutput.append(text);
}
}
});
}
@@ -186,8 +190,10 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
if (!consoleOutput.isDisposed()) {
consoleOutput.append(System.lineSeparator());
}
}
});
}
@@ -199,8 +205,10 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
if (!consoleOutput.isDisposed()) {
consoleOutput.append(message + System.lineSeparator());
}
}
});
}
@@ -218,9 +226,11 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
if (!consoleInput.isDisposed()) {
consoleInput.setEnabled(true);
consoleInput.setFocus();
}
}
});
prompting = true;
promptLock.notifyAll();
@@ -250,12 +260,14 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@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();
@@ -271,10 +283,12 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
if (!consoleOutput.isDisposed()) {
lblPromptlabel.setText(prompt);
// relayout
SWTConsole.this.layout();
}
}
});
}
}
@@ -297,10 +311,12 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
if (!consoleOutput.isDisposed()) {
lblPromptlabel.setText(prompt);
// relayout
SWTConsole.this.layout();
}
}
});
}
@@ -352,4 +368,13 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
return consoleInput.getText();
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */
@Override
public void interruptPrompt() {
synchronized (promptLock) {
promptLock.notify();
}
}
}

View File

@@ -0,0 +1,204 @@
/*
* 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.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
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);
consoleOutput.addFocusListener(new FocusAdapter() {
@SuppressWarnings("synthetic-access")
@Override
public void focusGained(FocusEvent e) {
consoleInput.setFocus();
}
});
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);
}
/**
*
*/
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();
}
}

View File

@@ -40,8 +40,6 @@ package fr.bigeon.gclc.swt;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.eclipse.swt.SWT;
import org.junit.Test;
@@ -58,51 +56,6 @@ public class HistoryTextKeyListenerTest {
ConsoleDelayIO io = new ConsoleDelayIO() {
private String input = "";
@Override
public void setPrompt(String prompt) {
//
}
@Override
public String prompt(String message) throws IOException {
return null;
}
@Override
public String prompt() throws IOException {
return null;
}
@Override
public void println(String message) throws IOException {
//
}
@Override
public void println() throws IOException {
//
}
@Override
public void print(String text) throws IOException {
//
}
@Override
public boolean isClosed() {
return false;
}
@Override
public String getPrompt() {
return null;
}
@Override
public void close() throws IOException {
//
}
@Override
public void validateInput() {
input = "";

View File

@@ -39,7 +39,9 @@
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;
@@ -48,6 +50,7 @@ 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;
@@ -59,7 +62,7 @@ import fr.bigeon.gclc.exception.InvalidCommandName;
public class SWTConsoleShellTest {
protected static final long TWO_SECONDS = 2000;
private static final Display DISPLAY = new Display();
private static final Display DISPLAY = Display.getDefault();
@Test
public void testConsoleClose() {
@@ -69,7 +72,8 @@ public class SWTConsoleShellTest {
swtConsole.setPrompt(":");
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
@@ -169,6 +173,7 @@ public class SWTConsoleShellTest {
shell.dispose();
}
});
}
});
applThread.start();
@@ -178,6 +183,13 @@ public class SWTConsoleShellTest {
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);
@@ -197,7 +209,8 @@ public class SWTConsoleShellTest {
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

View File

@@ -0,0 +1,145 @@
/*
* 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 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);
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.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();
}
}
} catch (InvalidCommandName e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

View File

@@ -23,7 +23,7 @@
<dependency>
<groupId>fr.bigeon</groupId>
<artifactId>gclc</artifactId>
<version>1.2.5</version>
<version>1.3.1</version>
</dependency>
</dependencies>
<name>GCLC system command</name>

View File

@@ -17,8 +17,7 @@ import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.manager.ConsoleManager;
/** <p>
* TODO
/** A command that will execute a system command.
*
* @author Emmanuel Bigeon */
public class ExecSystemCommand extends Command {
@@ -79,7 +78,7 @@ public class ExecSystemCommand extends Command {
}
});
th.start();
manager.setPrompt("");
manager.setPrompt(""); //$NON-NLS-1$
final OutputStream os = proc.getOutputStream();
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os))) {

View File

@@ -35,7 +35,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>gclc</artifactId>
<version>1.2.6</version>
<version>1.3.3-SNAPSHOT</version>
<packaging>jar</packaging>
<url>http://www.bigeon.fr/emmanuel</url>
<properties>
@@ -83,6 +83,6 @@
<scm>
<developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection>
<tag>gclc-1.2.6</tag>
<tag>HEAD</tag>
</scm>
</project>

View File

@@ -37,14 +37,13 @@
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;
@@ -54,7 +53,6 @@ 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>
@@ -103,66 +102,18 @@ public class ConsoleApplication implements ICommandProvider {
root = new SubedCommand(""); //$NON-NLS-1$
}
/** @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));
}
@Override
public final boolean add(ICommand cmd) throws InvalidCommandName {
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)
@@ -188,8 +140,8 @@ public class ConsoleApplication implements ICommandProvider {
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 {
@@ -215,7 +167,7 @@ public class ConsoleApplication implements ICommandProvider {
}
}
/** @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) {
@@ -225,28 +177,57 @@ 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.log(Level.WARNING,
"The console manager was closed. Closing the application as no one can reach it.", //$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.log(Level.WARNING,
"The console manager was closed.", //$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);
}
running = false;
LOGGER.fine("Exiting application."); //$NON-NLS-1$
} catch (InterruptedIOException e) {
LOGGER.log(Level.INFO,
"Prompt interrupted. It is likely the application is closing.", //$NON-NLS-1$
e);
} catch (IOException e) {
// The manager was closed
running = false;
@@ -256,7 +237,7 @@ public class ConsoleApplication implements ICommandProvider {
}
}
/** @return if the application is running */
/** @return the running status */
public boolean isRunning() {
return running;
}

View File

@@ -154,8 +154,9 @@ public abstract class ParametrizedCommand extends Command {
}
}
/** @param parameters the command parameters */
protected abstract void doExecute(CommandParameters parameters);
/** @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[]) */

View File

@@ -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,14 +70,14 @@ 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 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;
/** <p>
@@ -88,8 +89,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();
}

View File

@@ -36,7 +36,7 @@
* gclc-test:fr.bigeon.gclc.test.TestConsoleManager.java
* Created on: Nov 18, 2016
*/
package fr.bigeon.gclc.test.utils;
package fr.bigeon.gclc.manager;
import java.io.BufferedReader;
import java.io.IOException;
@@ -44,12 +44,8 @@ import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import fr.bigeon.gclc.manager.ConsoleManager;
import fr.bigeon.gclc.manager.SystemConsoleManager;
/** This console manager allows to enter commands and retrieve the output as an
* input.
* <p>
@@ -57,26 +53,46 @@ import fr.bigeon.gclc.manager.SystemConsoleManager;
* used to test application behavior.
*
* @author Emmanuel Bigeon */
public class TestConsoleManager implements ConsoleManager, AutoCloseable {
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 TestConsoleManager() throws IOException {
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.defaultCharset()));
outPrint = new PrintStream(out);
new InputStreamReader(commandOutput, Charset.forName(UTF_8)));
outPrint = new PrintStream(out, true, UTF_8);
innerManager = new SystemConsoleManager(outPrint, in,
Charset.forName("UTF-8"));
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
@@ -118,6 +134,8 @@ public class TestConsoleManager implements ConsoleManager, AutoCloseable {
@Override
public void close() throws IOException {
innerManager.close();
reading.setRunning(false);
writing.setRunning(false);
outPrint.close();
commandBuffOutput.close();
commandOutput.close();
@@ -130,15 +148,28 @@ public class TestConsoleManager implements ConsoleManager, AutoCloseable {
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 {
ByteBuffer buff = Charset.defaultCharset()
.encode(content + System.lineSeparator());
if (buff.hasArray()) {
commandInput.write(buff.array());
}
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 commandBuffOutput.readLine();
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();
}
}

View File

@@ -0,0 +1,182 @@
/*
* 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.logging.Level;
import java.util.logging.Logger;
/** A runnable to read the piped output.
*
* @author Emmanuel Bigeon */
public class ReadingRunnable implements Runnable {
/** 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;
/** @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.log(Level.INFO, "Reading interrupted", e); //$NON-NLS-1$
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Unable to read from stream", e); //$NON-NLS-1$
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.", //$NON-NLS-1$
e);
}
if (messages.isEmpty() && !running) {
throw new IOException(CLOSED_PIPE);
}
}
LOGGER.finest("Polled: " + messages.peek()); //$NON-NLS-1$
waiting = false;
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();
}
}
}
}

View File

@@ -44,26 +44,17 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
/** 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());
/** The empty string constant */
private static final String EMPTY = ""; //$NON-NLS-1$
/** The command prompt. It can be changed. */
private String prompt = DEFAULT_PROMPT;
@@ -75,6 +66,12 @@ 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() {
@@ -89,6 +86,10 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
super();
this.out = out;
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 */
@@ -140,18 +141,8 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
@Override
public String prompt(String message) throws IOException {
checkOpen();
String result = EMPTY;
out.print(message);
try {
result = in.readLine();
while (result != null && result.length() > 0 &&
result.charAt(0) == 0) {
result = result.substring(1);
}
} catch (final IOException e) {
LOGGER.log(Level.SEVERE, "Unable to read prompt", e); //$NON-NLS-1$
}
return result;
return reading.getMessage();
}
/** @param prompt the prompt to set */
@@ -165,6 +156,8 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
@Override
public void close() throws IOException {
closed = true;
reading.setRunning(false);
promptThread.interrupt();
}
/* (non-Javadoc)
@@ -174,4 +167,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();
}
}

View 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;
}
}
}

View File

@@ -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;
}
}
}

View File

@@ -42,7 +42,7 @@ import java.io.IOException;
import fr.bigeon.gclc.command.ICommand;
import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
import fr.bigeon.gclc.manager.PipedConsoleManager;
/**
* <p>
@@ -56,11 +56,11 @@ public class CommandTestingApplication implements AutoCloseable {
private final ConsoleTestApplication application;
private final Thread th;
private final TestConsoleManager manager;
private final PipedConsoleManager manager;
/** @throws IOException if the streams cannot be build */
public CommandTestingApplication() throws IOException {
manager = new TestConsoleManager();
manager = new PipedConsoleManager();
application = new ConsoleTestApplication(manager);
th = new Thread(new Runnable() {
@@ -110,7 +110,7 @@ public class CommandTestingApplication implements AutoCloseable {
/** @return the next written line, null if it is the prompt
* @throws IOException if the reading failed
* @see fr.bigeon.gclc.test.utils.TestConsoleManager#readNextLine() */
* @see fr.bigeon.gclc.manager.PipedConsoleManager#readNextLine() */
public String readNextLine() throws IOException {
String ret = manager.readNextLine();
if (ret.equals(manager.getPrompt())) {

View File

@@ -56,7 +56,7 @@ import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.i18n.Messages;
import fr.bigeon.gclc.manager.ConsoleManager;
import fr.bigeon.gclc.manager.SystemConsoleManager;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
import fr.bigeon.gclc.manager.PipedConsoleManager;
/** Test class for ConsoleApplication
*
@@ -136,7 +136,7 @@ public class ConsoleApplicationTest {
}
ConsoleApplication appli = null;
try (TestConsoleManager manager = new TestConsoleManager()) {
try (PipedConsoleManager manager = new PipedConsoleManager()) {
final ConsoleApplication app = new ConsoleApplication(manager, null,
null);
appli = app;
@@ -167,7 +167,7 @@ public class ConsoleApplicationTest {
@Test
public void interpretCommandTest() {
try (TestConsoleManager test = new TestConsoleManager()) {
try (PipedConsoleManager test = new PipedConsoleManager()) {
ConsoleApplication appl = new ConsoleApplication(test, "", "");
appl.interpretCommand("invalid cmd \"due to misplaced\"quote");

View File

@@ -55,6 +55,7 @@ import org.junit.Test;
* @author Emmanuel Bigeon
*
*/
@SuppressWarnings({"static-method", "nls"})
public class CommandParametersTest {
/**

View File

@@ -45,7 +45,7 @@ import java.io.IOException;
import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
import fr.bigeon.gclc.manager.PipedConsoleManager;
/** <p>
* TODO
@@ -55,7 +55,7 @@ public class CommandTest {
@Test
public final void test() {
try (TestConsoleManager test = new TestConsoleManager()) {
try (PipedConsoleManager test = new PipedConsoleManager()) {
Command cmd;
cmd = new Command("name") {

View File

@@ -45,7 +45,7 @@ import static org.junit.Assert.fail;
import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
import fr.bigeon.gclc.manager.PipedConsoleManager;
/**
* <p>
@@ -68,7 +68,7 @@ public class HelpExecutorTest {
} catch (Exception e) {
assertNotNull(e);
}
try (TestConsoleManager test = new TestConsoleManager()) {
try (PipedConsoleManager test = new PipedConsoleManager()) {
help = new HelpExecutor("?", test, new MockCommand("mock"));
} catch (Exception e) {
assertNull(e);
@@ -81,7 +81,7 @@ public class HelpExecutorTest {
@Test
public final void testExecute(){
try {
TestConsoleManager test = new TestConsoleManager();
PipedConsoleManager test = new PipedConsoleManager();
HelpExecutor help = new HelpExecutor("?", test,
new Command("mock") {
@@ -116,7 +116,7 @@ public class HelpExecutorTest {
*/
@Test
public final void testTip(){
try (TestConsoleManager test = new TestConsoleManager()) {
try (PipedConsoleManager test = new PipedConsoleManager()) {
HelpExecutor help = new HelpExecutor("?", test,
new MockCommand("mock"));
help.tip();
@@ -124,7 +124,7 @@ public class HelpExecutorTest {
} catch (Exception e) {
assertNull(e);
}
try (TestConsoleManager test = new TestConsoleManager()) {
try (PipedConsoleManager test = new PipedConsoleManager()) {
HelpExecutor help = new HelpExecutor("?", test,
new SubedCommand("sub", new MockCommand("mock")));
help.tip();

View File

@@ -51,7 +51,7 @@ import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.InvalidParameterException;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
import fr.bigeon.gclc.manager.PipedConsoleManager;
/** <p>
* TODO
@@ -63,7 +63,7 @@ public class ParametrizedCommandTest {
* {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */
@Test
public final void testParametrizedCommandConsoleManagerString() {
try (TestConsoleManager test = new TestConsoleManager()) {
try (PipedConsoleManager test = new PipedConsoleManager()) {
ParametrizedCommand cmd = new ParametrizedCommand(test, "name") {
@Override
@@ -116,7 +116,7 @@ public class ParametrizedCommandTest {
* {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String, boolean)}. */
@Test
public final void testParametrizedCommandConsoleManagerStringBoolean() {
try (TestConsoleManager test = new TestConsoleManager()) {
try (PipedConsoleManager test = new PipedConsoleManager()) {
ParametrizedCommand cmd = new ParametrizedCommand(test, "name",
false) {
@@ -528,7 +528,7 @@ public class ParametrizedCommandTest {
assertNotNull(e);
}
// TODO Test of interactive not providing and providing all needed
try (TestConsoleManager test = new TestConsoleManager()) {
try (PipedConsoleManager test = new PipedConsoleManager()) {
cmd = new ParametrizedCommand(test, "name", false) {
{
try {
@@ -610,7 +610,7 @@ public class ParametrizedCommandTest {
fail("unepected error");
}
try {
TestConsoleManager test = new TestConsoleManager();
PipedConsoleManager test = new PipedConsoleManager();
cmd = new ParametrizedCommand(test, "name") {
{
try {

View File

@@ -50,7 +50,7 @@ import org.junit.Test;
import fr.bigeon.gclc.ConsoleTestApplication;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
import fr.bigeon.gclc.manager.PipedConsoleManager;
/**
* <p>
@@ -67,9 +67,9 @@ public class ScriptExecutionTest {
*/
@Test
public void testExecute() {
TestConsoleManager test;
PipedConsoleManager test;
try {
test = new TestConsoleManager();
test = new PipedConsoleManager();
} catch (IOException e2) {
fail("creation of console manager failed"); //$NON-NLS-1$
assertNotNull(e2);
@@ -165,7 +165,7 @@ public class ScriptExecutionTest {
public void testHelp() {
ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$
Charset.forName("UTF-8"));
try (TestConsoleManager test = new TestConsoleManager()) {
try (PipedConsoleManager test = new PipedConsoleManager()) {
exec.help(test);
exec.help(test, "ignored element");
} catch (IOException e) {

View File

@@ -50,7 +50,7 @@ import org.junit.Test;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.ConsoleManager;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
import fr.bigeon.gclc.manager.PipedConsoleManager;
/** <p>
* TODO
@@ -307,8 +307,8 @@ public class SubedCommandTest {
assertNotNull(e);
}
try (TestConsoleManager manager = new TestConsoleManager();
TestConsoleManager manager2 = new TestConsoleManager()) {
try (PipedConsoleManager manager = new PipedConsoleManager();
PipedConsoleManager manager2 = new PipedConsoleManager()) {
cmd.help(manager);
assertEquals("\tid", manager.readNextLine());
cmd.help(manager, "id");
@@ -327,8 +327,8 @@ public class SubedCommandTest {
assertNotNull(e);
}
try (TestConsoleManager manager = new TestConsoleManager();
TestConsoleManager manager2 = new TestConsoleManager()) {
try (PipedConsoleManager manager = new PipedConsoleManager();
PipedConsoleManager manager2 = new PipedConsoleManager()) {
cmd.help(manager);
assertEquals("\tid", manager.readNextLine());
} catch (IOException e) {
@@ -368,8 +368,8 @@ public class SubedCommandTest {
assertNotNull(e);
}
try (TestConsoleManager manager = new TestConsoleManager();
TestConsoleManager manager2 = new TestConsoleManager()) {
try (PipedConsoleManager manager = new PipedConsoleManager();
PipedConsoleManager manager2 = new PipedConsoleManager()) {
cmd.help(manager);
assertEquals("\ttip", manager.readNextLine());
assertEquals("\tid: tip", manager.readNextLine());

View File

@@ -53,7 +53,7 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import fr.bigeon.gclc.test.utils.TestConsoleManager;
import fr.bigeon.gclc.manager.PipedConsoleManager;
/** <p>
* TODO
@@ -77,7 +77,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptBoolean(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */
@Test
public final void testPromptBoolean() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
Thread th = new Thread(new Runnable() {
@Override
@@ -121,7 +121,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptChoice(fr.bigeon.gclc.manager.ConsoleManager, java.util.List, java.util.List, java.lang.String, java.lang.String)}. */
@Test
public final void testPromptChoiceConsoleManagerListOfStringListOfUStringString() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final List<String> keys = new ArrayList<>();
final List<Object> choices = new ArrayList<>();
keys.add("A choice"); //$NON-NLS-1$
@@ -201,7 +201,7 @@ public class CLIPrompterTest {
@Test
public final void testPromptChoiceConsoleManagerListOfUStringString() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final List<Object> keys = new ArrayList<>();
keys.add("A choice"); //$NON-NLS-1$
keys.add("An other"); //$NON-NLS-1$
@@ -289,7 +289,7 @@ public class CLIPrompterTest {
@Test
public final void testPromptChoiceConsoleManagerListOfUMapOfUTStringString() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final List<Object> keys = new ArrayList<>();
final Map<Object, Object> choices = new HashMap<>();
keys.add("A choice"); //$NON-NLS-1$
@@ -373,7 +373,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptChoice(fr.bigeon.gclc.manager.ConsoleManager, java.util.Map, java.lang.String, java.lang.String)}. */
@Test
public final void testPromptChoiceConsoleManagerMapOfUTStringString() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final List<Object> keys = new ArrayList<>();
final Map<Object, Object> choices = new HashMap<>();
keys.add("A choice"); //$NON-NLS-1$
@@ -455,7 +455,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptInteger(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */
@Test
public final void testPromptInteger() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
Thread th = new Thread(new Runnable() {
@Override
@@ -492,7 +492,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptList(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */
@Test
public final void testPromptListConsoleManagerString() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final List<String> keys = new ArrayList<>();
keys.add("A choice"); //$NON-NLS-1$
keys.add("An other"); //$NON-NLS-1$
@@ -549,7 +549,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptList(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String, java.lang.String)}. */
@Test
public final void testPromptListConsoleManagerStringString() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final List<String> keys = new ArrayList<>();
keys.add("A choice"); //$NON-NLS-1$
keys.add("An other"); //$NON-NLS-1$
@@ -603,7 +603,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptLongText(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String)}. */
@Test
public final void testPromptLongTextConsoleManagerString() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final String message = "My message";
final String longText = "Some text with" + System.lineSeparator() +
"line feeds and other" + System.lineSeparator() +
@@ -663,7 +663,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptLongText(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String, java.lang.String)}. */
@Test
public final void testPromptLongTextConsoleManagerStringString() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final String message = "My message";
final String ender = "\\quit";
final String[] text = new String[]{"Some text with" ,
@@ -676,7 +676,7 @@ public class CLIPrompterTest {
@Override
public void run() {
try {
assertEquals("",
assertEquals("", //$NON-NLS-1$
CLIPrompter.promptLongText(test, message, ender));
assertEquals(longText,
CLIPrompter.promptLongText(test, message, ender));
@@ -720,7 +720,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(fr.bigeon.gclc.manager.ConsoleManager, java.util.List, java.util.List, java.lang.String)}. */
@Test
public final void testPromptMultiChoiceConsoleManagerListOfStringListOfUString() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final List<String> keys = new ArrayList<>();
final List<Object> choices = new ArrayList<>();
keys.add("A choice"); //$NON-NLS-1$
@@ -803,7 +803,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(fr.bigeon.gclc.manager.ConsoleManager, java.util.List, java.util.Map, java.lang.String)}. */
@Test
public final void testPromptMultiChoiceConsoleManagerListOfUMapOfUTString() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final List<Object> keys = new ArrayList<>();
final Map<Object, Object> choices = new HashMap<>();
keys.add("A choice"); //$NON-NLS-1$
@@ -886,7 +886,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(fr.bigeon.gclc.manager.ConsoleManager, java.util.List, java.lang.String)}. */
@Test
public final void testPromptMultiChoiceConsoleManagerListOfUString() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final List<Object> keys = new ArrayList<>();
keys.add("A choice"); //$NON-NLS-1$
keys.add("An other"); //$NON-NLS-1$
@@ -966,7 +966,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(fr.bigeon.gclc.manager.ConsoleManager, java.util.Map, java.lang.String)}. */
@Test
public final void testPromptMultiChoiceConsoleManagerMapOfUTString() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final List<Object> keys = new ArrayList<>();
final Map<Object, Object> choices = new HashMap<>();
keys.add("A choice"); //$NON-NLS-1$
@@ -1049,7 +1049,7 @@ public class CLIPrompterTest {
* {@link fr.bigeon.gclc.prompt.CLIPrompter#promptNonEmpty(fr.bigeon.gclc.manager.ConsoleManager, java.lang.String, java.lang.String)}. */
@Test
public final void testPromptNonEmpty() {
try (final TestConsoleManager test = new TestConsoleManager()) {
try (final PipedConsoleManager test = new PipedConsoleManager()) {
final String res = "some content"; //$NON-NLS-1$
Thread th = new Thread(new Runnable() {

View File

@@ -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();
}
}
}