Compare commits

..

48 Commits

Author SHA1 Message Date
7de2dadbe0 [maven-release-plugin] prepare release gclc-socket-1.1.6 2016-12-06 10:58:46 -05:00
50395ba852 upgrade dependencies on gclc
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-06 10:57:58 -05:00
248c82cf50 Systematic end of communication phase by sending 'Bye.'. modify tests.
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-06 10:38:16 -05:00
6289ca1db9 [maven-release-plugin] prepare for next development iteration 2016-12-06 00:14:51 -05:00
5b6634eaf0 [maven-release-plugin] prepare release gclc-socket-1.1.5 2016-12-06 00:14:47 -05:00
4737a16874 [maven-release-plugin] prepare for next development iteration 2016-12-05 23:57:46 -05:00
bf0a3b30e5 [maven-release-plugin] prepare release gclc-1.3.3 2016-12-05 23:57:38 -05:00
5d25971b56 Fix the non delivery of Bye message
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-05 23:51:50 -05:00
c27872de94 Added parameters parsing exception rather than boolean
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-05 19:21:39 -05:00
a12484a72a [maven-release-plugin] prepare for next development iteration 2016-12-04 13:06:39 -05:00
ee0d91e455 [maven-release-plugin] prepare release gclc-socket-1.1.4 2016-12-04 13:06:30 -05:00
719d7ada3f Communication loop now interrupts after clearing the output of appli
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-04 12:41:05 -05:00
c877450b2b [maven-release-plugin] prepare for next development iteration 2016-12-04 10:10:30 -05:00
f3a8aafce1 [maven-release-plugin] prepare release gclc-swt-1.1.2 2016-12-04 10:10:25 -05:00
d2bc86fffc Removed duplicate method. Added test on swt console view
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-04 09:55:51 -05:00
3b6ba337f1 [maven-release-plugin] prepare for next development iteration 2016-12-04 09:54:32 -05:00
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
32 changed files with 1397 additions and 562 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"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>gclc-socket</artifactId> <artifactId>gclc-socket</artifactId>
<version>1.0.7-SNAPSHOT</version> <version>1.1.6</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<url>http://www.bigeon.fr/emmanuel</url> <url>http://www.bigeon.fr/emmanuel</url>
<properties> <properties>
@@ -78,16 +78,10 @@ of Emmanuel Bigeon. -->
<project.scm.id>git.bigeon.net</project.scm.id> <project.scm.id>git.bigeon.net</project.scm.id>
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>
<artifactId>gclc</artifactId> <artifactId>gclc</artifactId>
<version>1.2.6</version> <version>1.3.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>
@@ -104,6 +98,6 @@ of Emmanuel Bigeon. -->
<description>Socket implementation of GCLC</description> <description>Socket implementation of GCLC</description>
<scm> <scm>
<developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection> <developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection>
<tag>HEAD</tag> <tag>gclc-socket-1.1.6</tag>
</scm> </scm>
</project> </project>

View File

@@ -38,6 +38,9 @@
*/ */
package fr.bigeon.gclc.socket; package fr.bigeon.gclc.socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import fr.bigeon.gclc.ConsoleApplication; import fr.bigeon.gclc.ConsoleApplication;
/** A runnable class that will actually have the application running. /** A runnable class that will actually have the application running.
@@ -45,27 +48,49 @@ import fr.bigeon.gclc.ConsoleApplication;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class ConsoleRunnable implements Runnable { 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 */ /** The actual application */
private final ConsoleApplication app; private final ConsoleApplication app;
/** The synchronization object */ /** The synchro object */
private final Object promptingLock; 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 app the application */
* @param promptingLock the synchronization object */ public ConsoleRunnable(ConsoleApplication app) {
public ConsoleRunnable(ConsoleApplication app, Object promptingLock) {
super(); super();
this.app = app; this.app = app;
this.promptingLock = promptingLock;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see java.lang.Runnable#run() */ * @see java.lang.Runnable#run() */
@Override @Override
public void run() { public void run() {
app.start(); while (running) {
synchronized (promptingLock) { synchronized (lock) {
// release all waiting elements before ending while (running && !startReq) {
promptingLock.notifyAll(); 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();
} }
} }
@@ -75,8 +100,34 @@ public class ConsoleRunnable implements Runnable {
} }
/** @return if the application is running */ /** @return if the application is running */
public boolean isRunning() { public boolean isApplicationRunning() {
return app.isRunning(); 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; package fr.bigeon.gclc.socket;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.Socket; import java.net.Socket;
import java.net.SocketException; import java.net.SocketException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import fr.bigeon.gclc.ConsoleApplication; import fr.bigeon.gclc.ConsoleApplication;
import fr.bigeon.gclc.manager.ConsoleManager; 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 /** This is a socket communicating console consoleManager
* <p> * <p>
@@ -72,36 +69,69 @@ import fr.bigeon.smu.StringEncoder;
* end of the execution. * end of the execution.
* *
* @author Emmanuel Bigeon */ * @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 final PrintWriter writer;
/**
*
*/
private final Socket socket;
/** @param writer the writer
* @param socket the socket */
protected OutputForwardRunnable(PrintWriter writer, Socket socket) {
this.writer = writer;
this.socket = socket;
}
@SuppressWarnings("synthetic-access")
@Override
public void run() {
try {
while (!socket.isClosed()) {
while (!socket.isClosed() &&
!consoleManager.available()) {
waitASec();
}
if (socket.isClosed()) {
return;
}
String m = consoleManager.readNextLine();
writer.println(m);
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Unexpected problem in manager", //$NON-NLS-1$
e);
}
}
}
/**
*
*/
private static final String INTERRUPTION_WHILE_WORKING = "Interruption while application was working"; //$NON-NLS-1$
/** The end of line character */ /** The end of line character */
protected static final String EOL = "\n"; //$NON-NLS-1$ 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 */ /** The class logger */
private static final Logger LOGGER = Logger private static final Logger LOGGER = Logger
.getLogger(SocketConsoleApplicationShell.class.getName()); .getLogger(SocketConsoleApplicationShell.class.getName());
/** Time of wait */
protected static final long ONE_TENTH_OF_SECOND = 100;
/** The listening port */ /** The listening port */
private final int port; private final int port;
/** The input */
private final PipedInputStream consoleInput = new PipedInputStream();
/** The application */ /** The application */
private ConsoleApplication app; private ConsoleApplication app;
/** The session closing command */ /** The session closing command */
private final String close; private final String close;
/** The running status */ /** The running status */
private boolean running; private boolean running;
/** An object to lock on for prompt */
private final Object promptingLock = new Object();
/** The console manager implementation */ /** The console manager implementation */
private final ThreadedServerConsoleManager consoleManager = new ThreadedServerConsoleManager( private final PipedConsoleManager consoleManager;
ENCODER, promptingLock);
/** The auto close flag. if this is true, every request closes the session /** The auto close flag. if this is true, every request closes the session
* after its call */ * after its call */
private final boolean autoClose; private final boolean autoClose;
@@ -118,14 +148,17 @@ public class SocketConsoleApplicationShell implements Runnable {
* @param port the port to listen to * @param port the port to listen to
* @param close the session closing command * @param close the session closing command
* @param applicationShutdown the appication shut down command * @param applicationShutdown the appication shut down command
* @param charset the charset for communication */ * @param charset the charset for communication
* @throws IOException if the manager could not be created */
public SocketConsoleApplicationShell(int port, String close, public SocketConsoleApplicationShell(int port, String close,
String applicationShutdown, Charset charset) { String applicationShutdown, Charset charset) throws IOException {
this.port = port; this.port = port;
this.close = close; this.close = close;
this.applicationShutdown = applicationShutdown; this.applicationShutdown = applicationShutdown;
this.autoClose = false; this.autoClose = false;
this.charset = charset; this.charset = charset;
//
consoleManager = new PipedConsoleManager();
} }
/** Create a socket application shell which will listen on the given port /** 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 * @param autoClose if the session must be closed once the request has been
* sent * sent
* @param applicationShutdown the appication shut down 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, boolean autoClose, public SocketConsoleApplicationShell(int port, boolean autoClose,
String applicationShutdown, Charset charset) { String applicationShutdown, Charset charset) throws IOException {
this.port = port; this.port = port;
this.autoClose = autoClose; this.autoClose = autoClose;
this.applicationShutdown = applicationShutdown; this.applicationShutdown = applicationShutdown;
this.close = autoClose ? null : "close"; //$NON-NLS-1$ this.close = autoClose ? null : "close"; //$NON-NLS-1$
this.charset = charset; this.charset = charset;
//
consoleManager = new PipedConsoleManager();
} }
/* (non-Javadoc) /* (non-Javadoc)
@@ -154,39 +190,20 @@ public class SocketConsoleApplicationShell implements Runnable {
this.serverSocket = actualServerSocket; this.serverSocket = actualServerSocket;
running = true; running = true;
// Create the streams // Create the streams
try (PipedOutputStream outStream = new PipedOutputStream(); runSokectServer();
BufferedWriter writer = new BufferedWriter( } catch (final IOException e) {
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) {
LOGGER.log(Level.SEVERE, LOGGER.log(Level.SEVERE,
"Communication error between client and server", e); //$NON-NLS-1$ "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 */
* @throws IOException if the communication with the client failed */ private void runSokectServer() throws IOException {
private void runSokectServer(BufferedWriter writer) throws IOException { final ConsoleRunnable runnable = new ConsoleRunnable(app);
final ConsoleRunnable runnable = new ConsoleRunnable(app, Thread appThNext = new Thread(runnable, "gclc-ctrl"); //$NON-NLS-1$
promptingLock); appThNext.start();
Thread appThOld = null;
Thread appThNext = new Thread(runnable);
while (running) { while (running) {
LOGGER.info("Opening client"); //$NON-NLS-1$ LOGGER.info("Waiting client"); //$NON-NLS-1$
try (Socket clientSocket = serverSocket.accept(); try (Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(new OutputStreamWriter( PrintWriter out = new PrintWriter(new OutputStreamWriter(
clientSocket.getOutputStream(), charset), true); clientSocket.getOutputStream(), charset), true);
@@ -195,19 +212,18 @@ public class SocketConsoleApplicationShell implements Runnable {
BufferedReader in = new BufferedReader(isr);) { BufferedReader in = new BufferedReader(isr);) {
// this is not threaded to avoid several clients at the same // this is not threaded to avoid several clients at the same
// time // time
consoleManager.setOutput(out); LOGGER.info("Opening client"); //$NON-NLS-1$
// Initiate application
if (appThOld == null || !appThOld.isAlive() || // Initiate application
!runnable.isRunning()) { if (!runnable.isApplicationRunning()) {
appThNext.start(); LOGGER.info("Start application"); //$NON-NLS-1$
// Prepare next start startApplication(runnable);
appThOld = appThNext;
appThNext = new Thread(runnable, "gclc-ctrl"); //$NON-NLS-1$
} else { } else {
LOGGER.info("Reconnect to application"); //$NON-NLS-1$
out.println("Reconnected"); //$NON-NLS-1$ out.println("Reconnected"); //$NON-NLS-1$
out.println(consoleManager.getPrompt());
} }
communicate(writer, in); communicate(clientSocket, out, in);
} catch (SocketException e) { } catch (SocketException e) {
LOGGER.log(Level.INFO, "Socket closed"); //$NON-NLS-1$ LOGGER.log(Level.INFO, "Socket closed"); //$NON-NLS-1$
LOGGER.log(Level.FINE, LOGGER.log(Level.FINE,
@@ -216,77 +232,108 @@ public class SocketConsoleApplicationShell implements Runnable {
} }
LOGGER.info("Closing client"); //$NON-NLS-1$ LOGGER.info("Closing client"); //$NON-NLS-1$
} }
LOGGER.info("Out 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 /** active communication between server and client
* *
* @param socket the socket
* @param writer the writer to the application * @param writer the writer to the application
* @param in the input from the client * @param in the input from the client
* @throws IOException if the communication failed */ * @throws IOException if the communication failed */
private void communicate(BufferedWriter writer, private void communicate(final Socket socket, final PrintWriter writer,
BufferedReader in) throws IOException { BufferedReader in) throws IOException {
synchronized (promptingLock) { OutputForwardRunnable cc = new OutputForwardRunnable(writer, socket);
if (!consoleManager.isPrompting()) { Thread th = new Thread(cc, "ClientComm"); //$NON-NLS-1$
try { th.start();
// wait for application to finish its operation if (autoClose) {
promptingLock.wait(); communicateOnce(socket, in);
} catch (final InterruptedException e) { } else {
LOGGER.log(Level.SEVERE, INTERRUPTION_WHILE_WORKING, e); communicateLoop(socket, in);
}
}
/** @param socket the socket
* @param in the input from the client
* @throws IOException if the communication failed */
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);
doEndCommunication(reading);
}
/** @param reading the reading runnable
* @throws IOException if the end of communication failed */
private void doEndCommunication(ReadingRunnable reading) throws IOException {
reading.setRunning(false);
Thread wait = consoleManager.getWaitForDelivery("Bye."); //$NON-NLS-1$
consoleManager.println("Bye."); //$NON-NLS-1$
try {
wait.join();
} catch (InterruptedException e) {
LOGGER.warning("The Bye wait was interrupted."); //$NON-NLS-1$
LOGGER.log(Level.FINE, "An interruption occured", e); //$NON-NLS-1$
}
}
/** @param socket the socket
* @param in the input from the client
* @throws IOException if the communication failed */
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
}
doEndCommunication(reading);
}
/** @param reading the reading
* @return if the communication should be stopped.
* @throws IOException if the reading failed */
private boolean communicationContent(ReadingRunnable reading) throws IOException {
try {
while (app.isRunning() && !reading.hasMessage()) {
synchronized (this) {
waitASec();
} }
} }
if (autoClose) { } catch (IOException e) {
communicateOnce(in, writer); LOGGER.warning("Client seems dead. Closing communication"); //$NON-NLS-1$
} else { LOGGER.log(Level.FINE, "Wait on message from client failed", e); //$NON-NLS-1$
communicateLoop(in, writer); return false;
}
} }
} if (!app.isRunning()) {
return false;
/** @param in the input from the client
* @param writer the output to the client
* @throws IOException if the communication failed */
private void communicateOnce(BufferedReader in,
BufferedWriter writer) throws IOException {
String ln;
if ((ln = in.readLine()) != null) {
if (ln.equals(close)) {
return;
}
// 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);
}
} }
} String ln = reading.getMessage();
if (ln.equals(close)) {
/** @param in the input from the client return false;
* @param writer the output to the client
* @throws IOException if the communication failed */
private void communicateLoop(BufferedReader in,
BufferedWriter writer) throws IOException {
String ln;
while (app.isRunning() && (ln = in.readLine()) != null) {
if (ln.equals(close)) {
break;
}
// 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);
}
} }
// Pass command to application
consoleManager.type(ln);
return true;
} }
/** @return the consoleManager */ /** @return the consoleManager */
@@ -310,10 +357,26 @@ public class SocketConsoleApplicationShell implements Runnable {
} catch (IOException e) { } catch (IOException e) {
LOGGER.log(Level.SEVERE, "Exception in closing socket server", e); //$NON-NLS-1$ LOGGER.log(Level.SEVERE, "Exception in closing socket server", e); //$NON-NLS-1$
} }
synchronized (promptingLock) {
promptingLock.notifyAll();
}
app.exit(); 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 org.junit.Test;
import fr.bigeon.gclc.ConsoleApplication;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
import fr.bigeon.gclc.manager.SystemConsoleManager;
/** Test class for {@link ConsoleRunnable} /** Test class for {@link ConsoleRunnable}
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
@SuppressWarnings({"static-method", "unused", "javadoc"}) @SuppressWarnings({"unused", "javadoc"})
public class ConsoleRunnableTest { public class ConsoleRunnableTest {
/** <p> /** <p>
@@ -123,59 +121,62 @@ public class ConsoleRunnableTest {
public boolean isClosed() { public boolean isClosed() {
return i == cmds.length; return i == cmds.length;
} }
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */
@Override
public void interruptPrompt() {
//
}
} }
/** Test method for /** 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 @Test
public void testConsoleRunnable() { public void testConsoleRunnable() {
Object lock = new Object(); // ConsoleApplication app = new ConsoleTestApplication(
ConsoleApplication app = new ConsoleTestApplication( // new SystemConsoleManager());
new SystemConsoleManager()); // ConsoleRunnable runnable = new ConsoleRunnable(app);
ConsoleRunnable runnable = new ConsoleRunnable(app, lock);
} }
/** Test method for {@link fr.bigeon.gclc.socket.ConsoleRunnable#run()}. */ /** Test method for {@link fr.bigeon.gclc.socket.ConsoleRunnable#run()}. */
@Test @Test
public void testRunFlow() { public void testRunFlow() {
Object lock = new Object(); // ConsoleApplication app = new ConsoleTestApplication(
ConsoleApplication app = new ConsoleTestApplication( // new ConsoleManagerTestImplementation(
new ConsoleManagerTestImplementation( // new String[] {"test", ConsoleTestApplication.EXIT})); //$NON-NLS-1$
new String[] {"test", ConsoleTestApplication.EXIT})); //$NON-NLS-1$ // ConsoleRunnable runnable = new ConsoleRunnable(app);
ConsoleRunnable runnable = new ConsoleRunnable(app, lock); //
// Thread th = new Thread(runnable);
Thread th = new Thread(runnable); // th.start();
th.start(); //
// runnable.stop();
runnable.stop();
} }
/** Test method for {@link fr.bigeon.gclc.socket.ConsoleRunnable#stop()}. */ /** Test method for {@link fr.bigeon.gclc.socket.ConsoleRunnable#stop()}. */
@Test @Test
public void testStop() { public void testStop() {
Object lock = new Object(); // ConsoleApplication app = new ConsoleTestApplication(
ConsoleApplication app = new ConsoleTestApplication( // new ConsoleManagerTestImplementation(
new ConsoleManagerTestImplementation( // new String[] {"test", ConsoleTestApplication.EXIT})); //$NON-NLS-1$
new String[] {"test", ConsoleTestApplication.EXIT})); //$NON-NLS-1$ // ConsoleRunnable runnable = new ConsoleRunnable(app);
ConsoleRunnable runnable = new ConsoleRunnable(app, lock); // runnable.stop();
runnable.stop(); // Thread th = new Thread(runnable);
Thread th = new Thread(runnable); // th.start();
th.start(); // runnable.stop();
runnable.stop(); // runnable.stop();
runnable.stop();
} }
/** Test method for {@link fr.bigeon.gclc.socket.ConsoleRunnable#stop()}. */ /** Test method for {@link fr.bigeon.gclc.socket.ConsoleRunnable#stop()}. */
@Test @Test
public void testRun() { public void testRun() {
Object lock = new Object(); // ConsoleApplication app = new ConsoleTestApplication(
ConsoleApplication app = new ConsoleTestApplication( // new ConsoleManagerTestImplementation(
new ConsoleManagerTestImplementation( // new String[] {"test", ConsoleTestApplication.EXIT})); //$NON-NLS-1$
new String[] {"test", ConsoleTestApplication.EXIT})); //$NON-NLS-1$ // ConsoleRunnable runnable = new ConsoleRunnable(app);
ConsoleRunnable runnable = new ConsoleRunnable(app, lock); // runnable.run();
runnable.run();
} }
} }

View File

@@ -39,34 +39,39 @@
package fr.bigeon.gclc.socket; package fr.bigeon.gclc.socket;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.net.Socket; import java.net.Socket;
import java.util.Arrays; import java.util.logging.Logger;
import org.junit.Test; import org.junit.Test;
import fr.bigeon.smu.StringEncoder;
/** Test class for {@link SocketConsoleApplicationShell} /** Test class for {@link SocketConsoleApplicationShell}
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
@SuppressWarnings({"static-method", "unused", "javadoc", "nls"}) @SuppressWarnings({"static-method", "unused", "javadoc", "nls"})
public class SocketConsoleApplicationTest { public class SocketConsoleApplicationTest {
private static final StringEncoder ENCODER = new StringEncoder("%", private static final Logger LOGGER = Logger
Arrays.asList("\n")); //$NON-NLS-1$ .getLogger(SocketConsoleApplicationTest.class.getName());
@Test @Test
public void integrationTest() { public void integrationTest() {
Thread server; Thread server;
server = TestServer.startServer("bye");
try { 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) { } catch (InterruptedException e1) {
e1.printStackTrace(); e1.printStackTrace();
} }
@@ -80,20 +85,20 @@ public class SocketConsoleApplicationTest {
new InputStreamReader(kkSocket.getInputStream()));) { new InputStreamReader(kkSocket.getInputStream()));) {
String fromServer; String fromServer;
int i = 0; int i = -1;
String[] cmds = {"help", "toto", "test", "bye"}; String[] cmds = {"help", "toto", "test", "bye"};
while ((fromServer = in.readLine()) != null) { while ((fromServer = in.readLine()) != null) {
// System.out.println("Server: \n" + ENCODER.decode(fromServer)); i++;
if (fromServer.equals("Bye.")) { fromServer = consumeToPrompt(fromServer, in);
if (fromServer == null || fromServer.equals("Bye.")) {
break; break;
} }
final String fromUser = cmds[i]; final String fromUser = cmds[i];
if (fromUser != null) { if (fromUser != null) {
// System.out.println("Client: " + fromUser); LOGGER.fine("Client: " + fromUser);
out.println(fromUser); out.println(fromUser);
} }
i++;
} }
assertEquals(4, i); assertEquals(4, i);
} catch (final IOException e) { } catch (final IOException e) {
@@ -111,14 +116,15 @@ public class SocketConsoleApplicationTest {
String[] cmds = {"help", "toto", "test", String[] cmds = {"help", "toto", "test",
ConsoleTestApplication.EXIT}; ConsoleTestApplication.EXIT};
while ((fromServer = in.readLine()) != null) { while ((fromServer = in.readLine()) != null) {
// System.out.println("Server: \n" + ENCODER.decode(fromServer)); fromServer = consumeToPrompt(fromServer, in);
if (fromServer.equals("Bye.")) { if (fromServer == null || fromServer.equals("Bye.")) {
break; break;
} }
LOGGER.info("Server: \n" + fromServer);
final String fromUser = cmds[i]; final String fromUser = cmds[i];
if (fromUser != null) { if (fromUser != null) {
// System.out.println("Client: " + fromUser); LOGGER.info("Client: " + fromUser);
out.println(fromUser); out.println(fromUser);
} }
i++; i++;
@@ -144,14 +150,14 @@ public class SocketConsoleApplicationTest {
String[] cmds = {"help", "toto", "test", String[] cmds = {"help", "toto", "test",
ConsoleTestApplication.EXIT}; ConsoleTestApplication.EXIT};
while ((fromServer = in.readLine()) != null) { while ((fromServer = in.readLine()) != null) {
// System.out.println("Server: \n" + ENCODER.decode(fromServer)); fromServer = consumeToPrompt(fromServer, in);
if (fromServer.equals("Bye.")) { if (fromServer == null || fromServer.equals("Bye.")) {
break; break;
} }
final String fromUser = cmds[i]; final String fromUser = cmds[i];
if (fromUser != null) { if (fromUser != null) {
// System.out.println("Client: " + fromUser); LOGGER.fine("Client: " + fromUser);
out.println(fromUser); out.println(fromUser);
} }
i++; i++;
@@ -166,7 +172,11 @@ public class SocketConsoleApplicationTest {
} catch (InterruptedException e2) { } catch (InterruptedException e2) {
e2.printStackTrace(); e2.printStackTrace();
} }
server = TestServer.startServer(true); try {
server = TestServer.startServer(true);
} catch (IOException e2) {
assertNull(e2);
}
try { try {
Thread.sleep(100); Thread.sleep(100);
} catch (InterruptedException e1) { } catch (InterruptedException e1) {
@@ -183,24 +193,28 @@ public class SocketConsoleApplicationTest {
int i = 0; int i = 0;
String[] cmds = {"help", "test", "close"}; String[] cmds = {"help", "test", "close"};
while ((fromServer = in.readLine()) != null) { while ((fromServer = in.readLine()) != null) {
assertTrue(i < 2); fromServer = consumeToPrompt(fromServer, in);
System.out.println("Server: \n" + ENCODER.decode(fromServer)); if (fromServer == null || fromServer.equals("Bye.")) {
if (fromServer.equals("Bye.")) {
break; break;
} }
assertTrue(i < 1);
final String fromUser = cmds[i]; final String fromUser = cmds[i];
if (fromUser != null) { if (fromUser != null) {
System.out.println("Client: " + fromUser); LOGGER.fine("Client: " + fromUser);
out.println(fromUser); out.println(fromUser);
} }
i++; i++;
} }
assertEquals(2, i); assertEquals(1, i);
} catch (final IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
Thread srv = TestServer.getServer(); Thread srv = null;
try {
srv = TestServer.getServer();
} catch (IOException e1) {
assertNull(e1);
}
TestServer.closeServer(); TestServer.closeServer();
try { try {
srv.join(); srv.join();
@@ -209,4 +223,19 @@ public class SocketConsoleApplicationTest {
e.printStackTrace(); e.printStackTrace();
} }
} }
/** @param in the input
* @return the string
* @throws IOException if the input reading failed */
private String consumeToPrompt(String server,
BufferedReader in) throws IOException {
String fromServer = server;
LOGGER.fine("Server: \n" + fromServer);
while (fromServer != null && !fromServer.equals("Bye.") &&
!fromServer.equals("> ")) {
fromServer = in.readLine();
LOGGER.fine("Server: \n" + fromServer);
}
return fromServer;
}
} }

View File

@@ -34,6 +34,7 @@
*/ */
package fr.bigeon.gclc.socket; package fr.bigeon.gclc.socket;
import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
/** A test server /** A test server
@@ -45,8 +46,9 @@ public class TestServer {
private static SocketConsoleApplicationShell SHELL; private static SocketConsoleApplicationShell SHELL;
private static Thread server; private static Thread server;
/** @param args no argument */ /** @param args no argument
public static void main(String... args) { * @throws IOException if the server starting failed */
public static void main(String... args) throws IOException {
try { try {
startServer(false).join(); startServer(false).join();
} catch (final InterruptedException e) { } catch (final InterruptedException e) {
@@ -54,7 +56,7 @@ public class TestServer {
} }
} }
public static Thread getServer() { public static Thread getServer() throws IOException {
if (server == null) { if (server == null) {
server = new Thread(getShell(), "gclcServer"); server = new Thread(getShell(), "gclcServer");
server.start(); server.start();
@@ -62,7 +64,7 @@ public class TestServer {
return server; return server;
} }
private static SocketConsoleApplicationShell getShell() { private static SocketConsoleApplicationShell getShell() throws IOException {
if (SHELL == null) { if (SHELL == null) {
SHELL = new SocketConsoleApplicationShell(3300, "close", SHELL = new SocketConsoleApplicationShell(3300, "close",
ConsoleTestApplication.EXIT, Charset.forName("UTF-8")); ConsoleTestApplication.EXIT, Charset.forName("UTF-8"));
@@ -73,7 +75,7 @@ public class TestServer {
return SHELL; return SHELL;
} }
public static Thread startServer(boolean autoClose) { public static Thread startServer(boolean autoClose) throws IOException {
if (SHELL == null) { if (SHELL == null) {
SHELL = new SocketConsoleApplicationShell(3300, autoClose, SHELL = new SocketConsoleApplicationShell(3300, autoClose,
ConsoleTestApplication.EXIT, Charset.forName("UTF-8")); ConsoleTestApplication.EXIT, Charset.forName("UTF-8"));
@@ -85,7 +87,7 @@ public class TestServer {
return getServer(); return getServer();
} }
public static Thread startServer(String closeConnection) { public static Thread startServer(String closeConnection) throws IOException {
if (SHELL == null) { if (SHELL == null) {
SHELL = new SocketConsoleApplicationShell(3300, closeConnection, SHELL = new SocketConsoleApplicationShell(3300, closeConnection,
ConsoleTestApplication.EXIT, Charset.forName("UTF-8")); ConsoleTestApplication.EXIT, Charset.forName("UTF-8"));

View File

@@ -32,12 +32,10 @@
<!-- The fact that you are presently reading this means that you have had --> <!-- The fact that you are presently reading this means that you have had -->
<!-- knowledge of the CeCILL license and that you accept its terms. --> <!-- 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" <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">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>gclc-swt</artifactId> <artifactId>gclc-swt</artifactId>
<version>1.0.5-SNAPSHOT</version> <version>1.1.3-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<url>http://www.bigeon.fr/emmanuel</url> <url>http://www.bigeon.fr/emmanuel</url>
<properties> <properties>
@@ -53,7 +51,7 @@
<dependency> <dependency>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>
<artifactId>gclc</artifactId> <artifactId>gclc</artifactId>
<version>1.2.6</version> <version>1.3.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>

View File

@@ -38,8 +38,6 @@
*/ */
package fr.bigeon.gclc.swt; package fr.bigeon.gclc.swt;
import fr.bigeon.gclc.manager.ConsoleManager;
/** This class represents an object used to send commands to a console /** This class represents an object used to send commands to a console
* application. * application.
* <p> * <p>
@@ -47,7 +45,7 @@ import fr.bigeon.gclc.manager.ConsoleManager;
* and set, and then validate the input. * and set, and then validate the input.
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public interface ConsoleDelayIO extends ConsoleManager { public interface ConsoleDelayIO {
/** Actually send the input as the prompt next input. */ /** Actually send the input as the prompt next input. */
void validateInput(); void validateInput();

View File

@@ -53,12 +53,14 @@ import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Text;
import fr.bigeon.gclc.ConsoleApplication; import fr.bigeon.gclc.ConsoleApplication;
import fr.bigeon.gclc.manager.ConsoleManager;
/** A SWT component to connect to gclc {@link ConsoleApplication} /** A SWT component to connect to gclc {@link ConsoleApplication}
* <p> * <p>
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class SWTConsole extends Composite implements ConsoleDelayIO { public class SWTConsole extends Composite
implements ConsoleDelayIO, ConsoleManager {
/** /**
* *
*/ */
@@ -173,7 +175,9 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access") @SuppressWarnings("synthetic-access")
@Override @Override
public void run() { public void run() {
consoleOutput.append(text); if (!consoleOutput.isDisposed()) {
consoleOutput.append(text);
}
} }
}); });
} }
@@ -186,7 +190,9 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access") @SuppressWarnings("synthetic-access")
@Override @Override
public void run() { public void run() {
consoleOutput.append(System.lineSeparator()); if (!consoleOutput.isDisposed()) {
consoleOutput.append(System.lineSeparator());
}
} }
}); });
} }
@@ -199,7 +205,9 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access") @SuppressWarnings("synthetic-access")
@Override @Override
public void run() { public void run() {
consoleOutput.append(message + System.lineSeparator()); if (!consoleOutput.isDisposed()) {
consoleOutput.append(message + System.lineSeparator());
}
} }
}); });
@@ -218,8 +226,10 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access") @SuppressWarnings("synthetic-access")
@Override @Override
public void run() { public void run() {
consoleInput.setEnabled(true); if (!consoleInput.isDisposed()) {
consoleInput.setFocus(); consoleInput.setEnabled(true);
consoleInput.setFocus();
}
} }
}); });
prompting = true; prompting = true;
@@ -250,11 +260,13 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access") @SuppressWarnings("synthetic-access")
@Override @Override
public void run() { public void run() {
lblPromptlabel.setText(message); if (!consoleOutput.isDisposed()) {
// relayout lblPromptlabel.setText(message);
SWTConsole.this.layout(); // relayout
consoleInput.setEnabled(true); SWTConsole.this.layout();
consoleInput.setFocus(); consoleInput.setEnabled(true);
consoleInput.setFocus();
}
} }
}); });
prompting = true; prompting = true;
@@ -271,9 +283,11 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access") @SuppressWarnings("synthetic-access")
@Override @Override
public void run() { public void run() {
lblPromptlabel.setText(prompt); if (!consoleOutput.isDisposed()) {
// relayout lblPromptlabel.setText(prompt);
SWTConsole.this.layout(); // relayout
SWTConsole.this.layout();
}
} }
}); });
} }
@@ -297,9 +311,11 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
@SuppressWarnings("synthetic-access") @SuppressWarnings("synthetic-access")
@Override @Override
public void run() { public void run() {
lblPromptlabel.setText(prompt); if (!consoleOutput.isDisposed()) {
// relayout lblPromptlabel.setText(prompt);
SWTConsole.this.layout(); // relayout
SWTConsole.this.layout();
}
} }
}); });
} }
@@ -352,4 +368,13 @@ public class SWTConsole extends Composite implements ConsoleDelayIO {
return consoleInput.getText(); 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,197 @@
/*
* 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);
}
/* (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 static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.eclipse.swt.SWT; import org.eclipse.swt.SWT;
import org.junit.Test; import org.junit.Test;
@@ -58,51 +56,6 @@ public class HistoryTextKeyListenerTest {
ConsoleDelayIO io = new ConsoleDelayIO() { ConsoleDelayIO io = new ConsoleDelayIO() {
private String input = ""; 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 @Override
public void validateInput() { public void validateInput() {
input = ""; input = "";

View File

@@ -39,7 +39,9 @@
package fr.bigeon.gclc.swt; package fr.bigeon.gclc.swt;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException; import java.io.IOException;
@@ -48,6 +50,7 @@ import org.junit.Test;
import fr.bigeon.gclc.ConsoleApplication; import fr.bigeon.gclc.ConsoleApplication;
import fr.bigeon.gclc.command.Command; import fr.bigeon.gclc.command.Command;
import fr.bigeon.gclc.command.ExitCommand;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.InvalidCommandName; import fr.bigeon.gclc.exception.InvalidCommandName;
@@ -59,7 +62,7 @@ import fr.bigeon.gclc.exception.InvalidCommandName;
public class SWTConsoleShellTest { public class SWTConsoleShellTest {
protected static final long TWO_SECONDS = 2000; protected static final long TWO_SECONDS = 2000;
private static final Display DISPLAY = new Display(); private static final Display DISPLAY = Display.getDefault();
@Test @Test
public void testConsoleClose() { public void testConsoleClose() {
@@ -69,7 +72,8 @@ public class SWTConsoleShellTest {
swtConsole.setPrompt(":"); swtConsole.setPrompt(":");
try { try {
final ConsoleApplication appl = new ConsoleApplication(swtConsole, final ConsoleApplication appl = new ConsoleApplication(swtConsole,
"exit", "Hello", "See you"); "Hello", "See you");
appl.add(new ExitCommand("exit", appl));
appl.add(new Command("long") { appl.add(new Command("long") {
@Override @Override
@@ -169,6 +173,7 @@ public class SWTConsoleShellTest {
shell.dispose(); shell.dispose();
} }
}); });
} }
}); });
applThread.start(); applThread.start();
@@ -178,6 +183,13 @@ public class SWTConsoleShellTest {
DISPLAY.sleep(); DISPLAY.sleep();
} }
} }
swtConsole.setPrompt(">");
try {
swtConsole.prompt();
fail("Prompting when closed should fail!");
} catch (IOException e) {
assertNotNull(e);
}
// DISPLAY.dispose(); // DISPLAY.dispose();
assertTrue(appl.getManager().isClosed()); assertTrue(appl.getManager().isClosed());
Thread.sleep(TWO_SECONDS); Thread.sleep(TWO_SECONDS);
@@ -197,7 +209,8 @@ public class SWTConsoleShellTest {
final SWTConsole swtConsole = (SWTConsole) shell.getManager(); final SWTConsole swtConsole = (SWTConsole) shell.getManager();
try { try {
final ConsoleApplication appl = new ConsoleApplication(swtConsole, final ConsoleApplication appl = new ConsoleApplication(swtConsole,
"exit", "Hello", "See you"); "Hello", "See you");
appl.add(new ExitCommand("exit", appl));
appl.add(new Command("long") { appl.add(new Command("long") {
@Override @Override

View File

@@ -0,0 +1,152 @@
/*
* Copyright E. Bigeon (2015)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a swt window for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
/**
* gclc-swt:fr.bigeon.gclc.swt.SWTConsoleShellTest.java
* Created on: Jun 8, 2016
*/
package fr.bigeon.gclc.swt;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.junit.Test;
import fr.bigeon.gclc.ConsoleApplication;
import fr.bigeon.gclc.command.Command;
import fr.bigeon.gclc.command.ExitCommand;
import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.PipedConsoleManager;
/** <p>
* TODO
*
* @author Emmanuel Bigeon */
@SuppressWarnings({"javadoc", "static-method", "nls", "deprecation"})
public class SWTConsoleViewTest {
protected static final long TWO_SECONDS = 2000;
private static final Display DISPLAY = Display.getDefault();
@Test
public void test() {
final Shell shell = new Shell(DISPLAY);
final SWTConsoleView swtConsole = new SWTConsoleView(shell, SWT.NONE);
try (PipedConsoleManager manager = new PipedConsoleManager()) {
swtConsole.setManager(manager);
} catch (IOException e2) {
assertNull(e2);
}
try (PipedConsoleManager manager = new PipedConsoleManager()) {
swtConsole.setManager(manager);
final ConsoleApplication appl = new ConsoleApplication(manager,
"Hello", "See you");
appl.add(new ExitCommand("exit", appl));
appl.add(new Command("long") {
@Override
public String tip() {
return "a long running command";
}
@Override
public void execute(String... args) {
try {
Thread.sleep(TWO_SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// shell.pack();
shell.open();
Thread applThread = new Thread(new Runnable() {
@Override
public void run() {
appl.start();
}
});
Thread testThread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(TWO_SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
swtConsole.setText("test"); //$NON-NLS-1$
swtConsole.validateInput();
}
});
try {
Thread.sleep(TWO_SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
shell.dispose();
}
});
}
});
applThread.start();
testThread.start();
while (!shell.isDisposed()) {
if (!DISPLAY.readAndDispatch()) {
DISPLAY.sleep();
}
}
} catch (InvalidCommandName e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

View File

@@ -23,7 +23,7 @@
<dependency> <dependency>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>
<artifactId>gclc</artifactId> <artifactId>gclc</artifactId>
<version>1.2.6</version> <version>1.3.1</version>
</dependency> </dependency>
</dependencies> </dependencies>
<name>GCLC system command</name> <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.exception.CommandRunExceptionType;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
/** <p> /** A command that will execute a system command.
* TODO
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class ExecSystemCommand extends Command { public class ExecSystemCommand extends Command {
@@ -79,7 +78,7 @@ public class ExecSystemCommand extends Command {
} }
}); });
th.start(); th.start();
manager.setPrompt(""); manager.setPrompt(""); //$NON-NLS-1$
final OutputStream os = proc.getOutputStream(); final OutputStream os = proc.getOutputStream();
try (BufferedWriter writer = new BufferedWriter( try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os))) { new OutputStreamWriter(os))) {

View File

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

View File

@@ -148,7 +148,7 @@ public class ConsoleApplication implements ICommandProvider {
args = GCLCConstants.splitCommand(cmd); args = GCLCConstants.splitCommand(cmd);
} catch (CommandParsingException e1) { } catch (CommandParsingException e1) {
manager.println("Command line cannot be parsed"); //$NON-NLS-1$ manager.println("Command line cannot be parsed"); //$NON-NLS-1$
LOGGER.log(Level.INFO, "Invalid user command " + cmd, e1); //$NON-NLS-1$ LOGGER.log(Level.FINE, "Invalid user command " + cmd, e1); //$NON-NLS-1$
return; return;
} }
if (!args.isEmpty()) { if (!args.isEmpty()) {
@@ -156,7 +156,7 @@ public class ConsoleApplication implements ICommandProvider {
executeSub(args.get(0), Arrays.copyOfRange( executeSub(args.get(0), Arrays.copyOfRange(
args.toArray(new String[0]), 1, args.size())); args.toArray(new String[0]), 1, args.size()));
} catch (final CommandRunException e) { } catch (final CommandRunException e) {
LOGGER.log(Level.WARNING, "Command failed: " + cmd, e); //$NON-NLS-1$ LOGGER.log(Level.FINE, "Command failed: " + cmd, e); //$NON-NLS-1$
manager.println(Messages manager.println(Messages
.getString("ConsoleApplication.cmd.failed", cmd)); //$NON-NLS-1$ .getString("ConsoleApplication.cmd.failed", cmd)); //$NON-NLS-1$
manager.println(e.getLocalizedMessage()); manager.println(e.getLocalizedMessage());
@@ -187,8 +187,10 @@ public class ConsoleApplication implements ICommandProvider {
} catch (IOException e) { } catch (IOException e) {
// The manager was closed // The manager was closed
running = false; running = false;
LOGGER.log(Level.WARNING, LOGGER.warning(
"The console manager was closed. Closing the application as no one can reach it.", //$NON-NLS-1$ "The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$
LOGGER.log(Level.FINE,
"An exception caused the closing of the application", //$NON-NLS-1$
e); e);
return; return;
} }
@@ -201,8 +203,9 @@ public class ConsoleApplication implements ICommandProvider {
} catch (IOException e) { } catch (IOException e) {
// The manager was closed // The manager was closed
running = false; running = false;
LOGGER.log(Level.WARNING, LOGGER.warning("The console manager was closed."); //$NON-NLS-1$
"The console manager was closed.", //$NON-NLS-1$ LOGGER.log(Level.FINE,
"An exception occured when trying to print the good by e message... The application will still close.", //$NON-NLS-1$
e); e);
} }
} }
@@ -225,14 +228,17 @@ public class ConsoleApplication implements ICommandProvider {
} }
interpretCommand(cmd); interpretCommand(cmd);
} catch (InterruptedIOException e) { } catch (InterruptedIOException e) {
LOGGER.log(Level.INFO, LOGGER.info(
"Prompt interrupted. It is likely the application is closing.", //$NON-NLS-1$ "Prompt interrupted. It is likely the application is closing."); //$NON-NLS-1$
LOGGER.log(Level.FINER, "Interruption of the prompt.", //$NON-NLS-1$
e); e);
} catch (IOException e) { } catch (IOException e) {
// The manager was closed // The manager was closed
running = false; running = false;
LOGGER.log(Level.WARNING, LOGGER.warning(
"The console manager was closed. Closing the application as no one can reach it.", //$NON-NLS-1$ "The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$
LOGGER.log(Level.FINE,
"An exception caused the closing of the application", //$NON-NLS-1$
e); e);
} }
} }

View File

@@ -45,6 +45,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import fr.bigeon.gclc.exception.CommandParsingException;
/** <p> /** <p>
* An object representing a collection of parameters. It is used for defaulting * An object representing a collection of parameters. It is used for defaulting
* values. * values.
@@ -98,8 +100,8 @@ public class CommandParameters {
} }
/** @param args the arguments to parse /** @param args the arguments to parse
* @return if the arguments were parsed */ * @throws CommandParsingException if the arguments parsing failed */
public boolean parseArgs(String... args) { public void parseArgs(String... args) throws CommandParsingException {
int i = 0; int i = 0;
while (i < args.length) { while (i < args.length) {
String next = null; String next = null;
@@ -108,11 +110,11 @@ public class CommandParameters {
} }
int p = parseArg(args[i], next); int p = parseArg(args[i], next);
if (p == 0) { if (p == 0) {
return false; throw new CommandParsingException(
"Invalid parameter " + args[i]); //$NON-NLS-1$
} }
i += p; i += p;
} }
return true;
} }
@@ -126,7 +128,7 @@ public class CommandParameters {
* @return the number of element read */ * @return the number of element read */
private int parseArg(String arg, String next) { private int parseArg(String arg, String next) {
if (!arg.startsWith("-")) { //$NON-NLS-1$ if (!arg.startsWith("-")) { //$NON-NLS-1$
return 1; return strict ? 0 : 1;
} }
String name = arg.substring(1); String name = arg.substring(1);
if (booleanArguments.containsKey(name)) { if (booleanArguments.containsKey(name)) {

View File

@@ -48,6 +48,7 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import fr.bigeon.gclc.exception.CommandParsingException;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType; import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.exception.InvalidParameterException; import fr.bigeon.gclc.exception.InvalidParameterException;
@@ -60,8 +61,7 @@ import fr.bigeon.gclc.manager.ConsoleManager;
public abstract class ParametrizedCommand extends Command { public abstract class ParametrizedCommand extends Command {
/** If the command may use interactive prompting for required parameters /** If the command may use interactive prompting for required parameters
* that * that were not provided on execution */
* were not provided on execution */
private boolean interactive = true; private boolean interactive = true;
/** The manager */ /** The manager */
protected final ConsoleManager manager; protected final ConsoleManager manager;
@@ -72,8 +72,7 @@ public abstract class ParametrizedCommand extends Command {
/** The parameters mandatory status */ /** The parameters mandatory status */
private final Map<String, Boolean> params = new HashMap<>(); private final Map<String, Boolean> params = new HashMap<>();
/** The restriction of provided parameters on execution to declared /** The restriction of provided parameters on execution to declared
* paramters * paramters in the status maps. */
* in the status maps. */
private final boolean strict; private final boolean strict;
/** @param manager the manager /** @param manager the manager
@@ -110,7 +109,11 @@ public abstract class ParametrizedCommand extends Command {
* @param param the parameter identification * @param param the parameter identification
* @param stringParameter if the parameter is a parameter with an argument * @param stringParameter if the parameter is a parameter with an argument
* @param needed if the parameter is required * @param needed if the parameter is required
* @throws InvalidParameterException if the parameter was invalid */ * @throws InvalidParameterException if the parameter was invalid
* @deprecated since gclc-1.3.3, use the
* {@link #addStringParameter(String, boolean)} and
* {@link #addBooleanParameter(String)} */
@Deprecated
protected void addParameter(String param, boolean stringParameter, protected void addParameter(String param, boolean stringParameter,
boolean needed) throws InvalidParameterException { boolean needed) throws InvalidParameterException {
if (params.containsKey(param)) { if (params.containsKey(param)) {
@@ -131,10 +134,41 @@ public abstract class ParametrizedCommand extends Command {
} }
} }
/** Add a boolean parameter to defined parmaters.
*
* @param flag the boolean flag
* @throws InvalidParameterException if the parameter is already defined as
* a string parameter */
protected void addBooleanParameter(String flag) throws InvalidParameterException {
if (params.containsKey(flag) && stringParams.containsKey(flag)) {
throw new InvalidParameterException(
"Parameter is already defined as string"); //$NON-NLS-1$
}
boolParams.add(flag);
params.put(flag, Boolean.valueOf(false));
}
/** Add a string parameter to defined parmaters.
*
* @param flag the parameter flag
* @param needed if the parameter's absence should cause an exception
* @throws InvalidParameterException if the parameter is already defined as
* a boolean parameter */
protected void addStringParameter(String flag,
boolean needed) throws InvalidParameterException {
if (params.containsKey(flag)) {
checkParam(flag, needed);
return;
}
stringParams.put(flag, Boolean.valueOf(needed));
params.put(flag, Boolean.valueOf(needed));
}
/** @param param the parameter /** @param param the parameter
* @param stringParameter the string parameter type * @param stringParameter the string parameter type
* @param needed if the parameter is needed * @param needed if the parameter is needed
* @throws InvalidParameterException if the new definition is invalid */ * @throws InvalidParameterException if the new definition is invalid */
@Deprecated
private void checkParam(String param, boolean stringParameter, private void checkParam(String param, boolean stringParameter,
boolean needed) throws InvalidParameterException { boolean needed) throws InvalidParameterException {
if (stringParameter) { if (stringParameter) {
@@ -154,6 +188,22 @@ public abstract class ParametrizedCommand extends Command {
} }
} }
/** @param param the string parameter
* @param needed if the parameter is needed
* @throws InvalidParameterException if the new definition is invalid */
private void checkParam(String param,
boolean needed) throws InvalidParameterException {
if (stringParams.containsKey(param)) {
Boolean need = Boolean
.valueOf(needed || stringParams.get(param).booleanValue());
stringParams.put(param, need);
params.put(param, need);
return;
}
throw new InvalidParameterException(
"Parameter is already defined as boolean"); //$NON-NLS-1$
}
/** @param parameters the command parameters /** @param parameters the command parameters
* @throws CommandRunException if the command failed */ * @throws CommandRunException if the command failed */
protected abstract void doExecute(CommandParameters parameters) throws CommandRunException; protected abstract void doExecute(CommandParameters parameters) throws CommandRunException;
@@ -163,12 +213,13 @@ public abstract class ParametrizedCommand extends Command {
@SuppressWarnings("boxing") @SuppressWarnings("boxing")
@Override @Override
public final void execute(String... args) throws CommandRunException { public final void execute(String... args) throws CommandRunException {
final CommandParameters parameters = new CommandParameters( final CommandParameters parameters = new CommandParameters(boolParams,
boolParams, stringParams.keySet(), strict); stringParams.keySet(), strict);
if (!parameters.parseArgs(args)) { try {
// the parameters could not be correctly parsed parameters.parseArgs(args);
} catch (CommandParsingException e) {
throw new CommandRunException(CommandRunExceptionType.USAGE, throw new CommandRunException(CommandRunExceptionType.USAGE,
"Unable to read arguments", this); //$NON-NLS-1$ "Unable to read arguments", e, this); //$NON-NLS-1$
} }
final List<String> toProvide = new ArrayList<>(); final List<String> toProvide = new ArrayList<>();
for (final Entry<String, Boolean> string : params.entrySet()) { for (final Entry<String, Boolean> string : params.entrySet()) {

View File

@@ -48,7 +48,7 @@ import java.io.InterruptedIOException;
* a message, in that case, the usual behavior is to prompt normally. * a message, in that case, the usual behavior is to prompt normally.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
public interface ConsoleManager { public interface ConsoleManager extends AutoCloseable {
/** @return the prompt prefix */ /** @return the prompt prefix */
String getPrompt(); String getPrompt();
@@ -89,12 +89,18 @@ public interface ConsoleManager {
/** Closes the manager. /** Closes the manager.
* *
* @throws IOException if the close raised an exception */ * @throws IOException if the close raised an exception */
@Override
void close() throws IOException; void close() throws IOException;
/** @return if the manager is closed. */ /** @return if the manager is closed. */
boolean isClosed(); boolean isClosed();
/** Indicate to the manager that is should interrompt the prompting, if /** Indicate to the manager that is should interrompt the prompting, if
* possible. */ * 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(); void interruptPrompt();
} }

View File

@@ -54,7 +54,7 @@ import java.nio.charset.Charset;
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public final class PipedConsoleManager public final class PipedConsoleManager
implements ConsoleManager, AutoCloseable { implements ConsoleManager {
/** The encoding between streams */ /** The encoding between streams */
private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$ private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
@@ -91,6 +91,7 @@ public final class PipedConsoleManager
Thread th = new Thread(writing, "write"); //$NON-NLS-1$ Thread th = new Thread(writing, "write"); //$NON-NLS-1$
th.start(); th.start();
th = new Thread(reading, "read"); //$NON-NLS-1$ th = new Thread(reading, "read"); //$NON-NLS-1$
th.setDaemon(true);
th.start(); th.start();
} }
@@ -159,10 +160,24 @@ public final class PipedConsoleManager
return reading.getMessage(); 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) /* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */ * @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */
@Override @Override
public void interruptPrompt() { public void interruptPrompt() {
innerManager.interruptPrompt(); innerManager.interruptPrompt();
} }
/** @param message the message
* @return the thread to join to wait for message delivery
* @see fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String) */
public Thread getWaitForDelivery(String message) {
return reading.getWaitForDelivery(message);
}
} }

View File

@@ -43,6 +43,8 @@ import java.io.IOException;
import java.io.InterruptedIOException; import java.io.InterruptedIOException;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.Deque; import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -51,6 +53,8 @@ import java.util.logging.Logger;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class ReadingRunnable implements Runnable { public class ReadingRunnable implements Runnable {
/** The closed pipe message */
private static final String CLOSED_PIPE = "Closed pipe"; //$NON-NLS-1$
/** Wait timeout */ /** Wait timeout */
private static final long TIMEOUT = 1000; private static final long TIMEOUT = 1000;
/** Class logger */ /** Class logger */
@@ -65,6 +69,17 @@ public class ReadingRunnable implements Runnable {
/** Synchro object */ /** Synchro object */
private final Object lock = new Object(); private final Object lock = new Object();
/** The waiting status for a message */
private boolean waiting;
/**
* The blocker for a given message
*/
private final Map<String, Object> messageBlocker = new HashMap<>();
/**
* The lock
*/
private final Object messageBlockerLock = new Object();
private String delivering;
/** @param reader the input to read from */ /** @param reader the input to read from */
public ReadingRunnable(BufferedReader reader) { public ReadingRunnable(BufferedReader reader) {
@@ -92,9 +107,13 @@ public class ReadingRunnable implements Runnable {
lock.notify(); lock.notify();
} }
} catch (InterruptedIOException e) { } catch (InterruptedIOException e) {
LOGGER.log(Level.INFO, "Reading interrupted", e); //$NON-NLS-1$ LOGGER.info("Reading interrupted"); //$NON-NLS-1$
LOGGER.log(Level.FINER,
"Read interruption was caused by an exception", e); //$NON-NLS-1$
} catch (IOException e) { } catch (IOException e) {
LOGGER.log(Level.SEVERE, "Unable to read from stream", e); //$NON-NLS-1$ LOGGER.severe("Unable to read from stream"); //$NON-NLS-1$
LOGGER.log(Level.FINE, "The stream reading threw an exception", //$NON-NLS-1$
e);
running = false; running = false;
return; return;
} }
@@ -120,8 +139,9 @@ public class ReadingRunnable implements Runnable {
public String getMessage() throws IOException { public String getMessage() throws IOException {
synchronized (lock) { synchronized (lock) {
if (!running) { if (!running) {
throw new IOException("Closed pipe"); //$NON-NLS-1$ throw new IOException(CLOSED_PIPE);
} }
waiting = true;
while (messages.isEmpty()) { while (messages.isEmpty()) {
try { try {
lock.wait(TIMEOUT); lock.wait(TIMEOUT);
@@ -130,10 +150,12 @@ public class ReadingRunnable implements Runnable {
e); e);
} }
if (messages.isEmpty() && !running) { if (messages.isEmpty() && !running) {
throw new IOException("Closed pipe"); //$NON-NLS-1$ throw new IOException(CLOSED_PIPE);
} }
} }
LOGGER.finest("Polled: " + messages.peek()); //$NON-NLS-1$ LOGGER.finest("Polled: " + messages.peek()); //$NON-NLS-1$
waiting = false;
notifyMessage(messages.peek());
return messages.poll(); return messages.poll();
} }
} }
@@ -151,4 +173,84 @@ public class ReadingRunnable implements Runnable {
return running; return running;
} }
} }
/** @return if a message is waiting
* @throws IOException if the pipe is closed */
public boolean hasMessage() throws IOException {
synchronized (lock) {
if (!running) {
throw new IOException(CLOSED_PIPE);
}
return !messages.isEmpty();
}
}
/** Interrupts the wait on the next message by providing an empty message */
public void interrupt() {
synchronized (lock) {
if (waiting) {
messages.offer(""); //$NON-NLS-1$
lock.notify();
}
}
}
/** @param message the message */
private void notifyMessage(String message) {
synchronized (messageBlockerLock) {
delivering = message;
if (messageBlocker.containsKey(message)) {
Object mLock = messageBlocker.get(message);
synchronized (mLock) {
mLock.notify();
}
messageBlocker.remove(message);
}
}
}
/** @param message the message
* @return the thread to join to wait for message delivery */
public Thread getWaitForDelivery(final String message) {
synchronized (messageBlockerLock) {
if (!messageBlocker.containsKey(message)) {
messageBlocker.put(message, new Object());
}
final Object obj = messageBlocker.get(message);
final Object start = new Object();
Thread th = new Thread(new Runnable() {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
synchronized (obj) {
synchronized (start) {
start.notify();
}
while (isRunning()) {
try {
obj.wait();
if (delivering.equals(message)) {
return;
}
} catch (InterruptedException e) {
LOGGER.log(Level.SEVERE,
"Thread interruption exception.", e); //$NON-NLS-1$
}
}
}
}
});
synchronized (start) {
th.start();
try {
start.wait();
} catch (InterruptedException e) {
LOGGER.log(Level.SEVERE, "Thread interruption exception.", //$NON-NLS-1$
e);
}
}
return th;
}
}
} }

View File

@@ -88,6 +88,7 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR
this.in = new BufferedReader(new InputStreamReader(in, charset)); this.in = new BufferedReader(new InputStreamReader(in, charset));
reading = new ReadingRunnable(this.in); reading = new ReadingRunnable(this.in);
promptThread = new Thread(reading, "prompt"); //$NON-NLS-1$ promptThread = new Thread(reading, "prompt"); //$NON-NLS-1$
promptThread.setDaemon(true);
promptThread.start(); promptThread.start();
} }
@@ -156,6 +157,7 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR
public void close() throws IOException { public void close() throws IOException {
closed = true; closed = true;
reading.setRunning(false); reading.setRunning(false);
promptThread.interrupt();
} }
/* (non-Javadoc) /* (non-Javadoc)
@@ -170,7 +172,7 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR
* @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */ * @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */
@Override @Override
public void interruptPrompt() { public void interruptPrompt() {
promptThread.interrupt(); reading.interrupt();
} }
} }

View File

@@ -39,7 +39,7 @@
package fr.bigeon.gclc.manager; package fr.bigeon.gclc.manager;
import java.io.IOException; import java.io.IOException;
import java.io.PipedOutputStream; import java.io.OutputStream;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.ArrayDeque; import java.util.ArrayDeque;
@@ -62,7 +62,7 @@ public class WritingRunnable implements Runnable {
/** Messages to write */ /** Messages to write */
private final Deque<String> messages = new ArrayDeque<>(); private final Deque<String> messages = new ArrayDeque<>();
/** Stream to write to */ /** Stream to write to */
private final PipedOutputStream outPrint; private final OutputStream outPrint;
/** The charset */ /** The charset */
private final Charset charset; private final Charset charset;
/** Runnable state */ /** Runnable state */
@@ -73,7 +73,7 @@ public class WritingRunnable implements Runnable {
/** @param outPrint the output to print to /** @param outPrint the output to print to
* @param charset the charset of the stream */ * @param charset the charset of the stream */
public WritingRunnable(PipedOutputStream outPrint, Charset charset) { public WritingRunnable(OutputStream outPrint, Charset charset) {
super(); super();
this.outPrint = outPrint; this.outPrint = outPrint;
this.charset = charset; this.charset = charset;

View File

@@ -245,8 +245,8 @@ public class CLIPrompter {
r = Integer.parseInt(result); r = Integer.parseInt(result);
still = false; still = false;
} catch (final NumberFormatException e) { } catch (final NumberFormatException e) {
LOGGER.log(Level.INFO, LOGGER.info("User input a non parsable integer: " + result); //$NON-NLS-1$
"User input a non parsable integer: " + result, e); //$NON-NLS-1$ LOGGER.log(Level.FINEST, "Unrecognized integer", e); //$NON-NLS-1$
still = true; still = true;
} }
} }

View File

@@ -74,7 +74,8 @@ public class CLIPrompterMessages {
try { try {
return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args); return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args);
} catch (final MissingResourceException e) { } catch (final MissingResourceException e) {
LOGGER.log(Level.WARNING, "Unrecognized key: " + key, e); //$NON-NLS-1$ LOGGER.warning("Unrecognized key: " + key); //$NON-NLS-1$
LOGGER.log(Level.FINE, "Missing key in " + BUNDLE_NAME, e); //$NON-NLS-1$
return '!' + key + '!'; return '!' + key + '!';
} }
} }

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

@@ -16,7 +16,8 @@ promptbool.choices.no1=N
promptbool.choices.no2=no promptbool.choices.no2=no
promptchoice.outofbounds=Please choose something between {0} and {1}. The choices were: promptchoice.outofbounds=Please choose something between {0} and {1}. The choices were:
promptchoice.formaterr=The input seems to be something that is not an integer.\nPlease choose something between {0} and {1}. The choices were: promptchoice.formaterr=The input seems to be something that is not an integer.\
Please choose something between {0} and {1}. The choices were:
promptlongtext.exit.defaultkey=\\q promptlongtext.exit.defaultkey=\\q
promptlongtext.exit.dispkey=\ (exit with a new line made of "{0}") promptlongtext.exit.dispkey=\ (exit with a new line made of "{0}")

View File

@@ -40,44 +40,54 @@ package fr.bigeon.gclc.command;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.junit.Test; import org.junit.Test;
/** import fr.bigeon.gclc.exception.CommandParsingException;
* <p>
/** <p>
* TODO * TODO
* *
* @author Emmanuel Bigeon * @author Emmanuel Bigeon */
* @SuppressWarnings({"static-method", "nls"})
*/
public class CommandParametersTest { public class CommandParametersTest {
/** /** Test method for
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#CommandParameters(java.util.Set, java.util.Set, boolean)}. * {@link fr.bigeon.gclc.command.CommandParameters#CommandParameters(java.util.Set, java.util.Set, boolean)}. */
*/
@Test @Test
public final void testCommandParameters(){ public final void testCommandParameters() {
Set<String> strings = new HashSet<>(); Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); Set<String> bools = new HashSet<>();
CommandParameters parameters = new CommandParameters(bools, strings, CommandParameters parameters = new CommandParameters(bools, strings,
true); true);
assertFalse(parameters.parseArgs("-ungivenFlag")); try {
parameters.parseArgs("-ungivenFlag");
fail("parse of unknown in strict should fail");
} catch (CommandParsingException e) {
assertNotNull(e);
}
parameters = new CommandParameters(bools, strings, false); parameters = new CommandParameters(bools, strings, false);
assertTrue(parameters.parseArgs("-ungivenFlag")); try {
parameters.parseArgs("-ungivenFlag");
} catch (CommandParsingException e) {
fail("parse of unknown in non strict should suceed");
assertNull(e);
}
} }
/** /** Test method for
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#get(java.lang.String)}. * {@link fr.bigeon.gclc.command.CommandParameters#get(java.lang.String)}. */
*/
@Test @Test
public final void testGet(){ public final void testGet() {
Set<String> strings = new HashSet<>(); Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); Set<String> bools = new HashSet<>();
@@ -90,24 +100,35 @@ public class CommandParametersTest {
assertNull(parameters.get("ungiven")); assertNull(parameters.get("ungiven"));
assertNull(parameters.get("str")); assertNull(parameters.get("str"));
parameters.parseArgs("-ungiven", "val"); try {
parameters.parseArgs("-ungiven", "val");
} catch (CommandParsingException e) {
assertNotNull(e);
}
assertNull(parameters.get("ungiven")); assertNull(parameters.get("ungiven"));
assertNull(parameters.get("str")); assertNull(parameters.get("str"));
parameters.parseArgs("-str", "val"); try {
parameters.parseArgs("-str", "val");
} catch (CommandParsingException e) {
assertNull(e);
}
assertNull(parameters.get("ungiven")); assertNull(parameters.get("ungiven"));
assertEquals("val", parameters.get("str")); assertEquals("val", parameters.get("str"));
parameters.parseArgs("-ungiven"); try {
parameters.parseArgs("-ungiven");
} catch (CommandParsingException e) {
assertNotNull(e);
}
assertNull(parameters.get("ungiven")); assertNull(parameters.get("ungiven"));
assertEquals("val", parameters.get("str")); assertEquals("val", parameters.get("str"));
} }
/** /** Test method for
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#getAdditionals()}. * {@link fr.bigeon.gclc.command.CommandParameters#getAdditionals()}. */
*/
@Test @Test
public final void testGetAdditionals(){ public final void testGetAdditionals() {
Set<String> strings = new HashSet<>(); Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); Set<String> bools = new HashSet<>();
@@ -117,27 +138,42 @@ public class CommandParametersTest {
CommandParameters parameters = new CommandParameters(bools, strings, CommandParameters parameters = new CommandParameters(bools, strings,
true); true);
parameters.parseArgs("-boolFlag"); try {
parameters.parseArgs("-boolFlag");
} catch (CommandParsingException e) {
assertNull(e);
}
assertTrue(parameters.getAdditionals().isEmpty()); assertTrue(parameters.getAdditionals().isEmpty());
parameters.parseArgs("-ungiven"); try {
parameters.parseArgs("-ungiven");
} catch (CommandParsingException e) {
assertNotNull(e);
}
assertTrue(parameters.getAdditionals().isEmpty()); assertTrue(parameters.getAdditionals().isEmpty());
parameters = new CommandParameters(bools, strings, false); parameters = new CommandParameters(bools, strings, false);
parameters.parseArgs("-boolFlag"); try {
parameters.parseArgs("-boolFlag");
} catch (CommandParsingException e) {
assertNull(e);
}
assertTrue(parameters.getAdditionals().isEmpty()); assertTrue(parameters.getAdditionals().isEmpty());
parameters.parseArgs("-ungiven"); try {
parameters.parseArgs("-ungiven");
} catch (CommandParsingException e) {
assertNotNull(e);
}
assertTrue(parameters.getAdditionals().contains("ungiven")); assertTrue(parameters.getAdditionals().contains("ungiven"));
assertEquals(1, parameters.getAdditionals().size()); assertEquals(1, parameters.getAdditionals().size());
} }
/** /** Test method for
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#getBool(java.lang.String)}. * {@link fr.bigeon.gclc.command.CommandParameters#getBool(java.lang.String)}. */
*/
@Test @Test
public final void testGetBool(){ public final void testGetBool() {
Set<String> strings = new HashSet<>(); Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); Set<String> bools = new HashSet<>();
@@ -150,11 +186,20 @@ public class CommandParametersTest {
assertFalse(parameters.getBool("ungiven")); assertFalse(parameters.getBool("ungiven"));
assertFalse(parameters.getBool("boolFlag")); assertFalse(parameters.getBool("boolFlag"));
parameters.parseArgs("-boolFlag"); try {
parameters.parseArgs("-boolFlag");
} catch (CommandParsingException e) {
assertNull(e);
}
assertTrue(parameters.getBool("boolFlag")); assertTrue(parameters.getBool("boolFlag"));
assertFalse(parameters.getBool("ungiven")); assertFalse(parameters.getBool("ungiven"));
parameters.parseArgs("-ungiven"); try {
parameters.parseArgs("-ungiven");
fail("unknown parameter should fail");
} catch (CommandParsingException e) {
assertNotNull(e);
}
assertFalse(parameters.getBool("ungiven")); assertFalse(parameters.getBool("ungiven"));
assertTrue(parameters.getBool("boolFlag")); assertTrue(parameters.getBool("boolFlag"));
@@ -163,20 +208,27 @@ public class CommandParametersTest {
assertFalse(parameters.getBool("ungiven")); assertFalse(parameters.getBool("ungiven"));
assertFalse(parameters.getBool("boolFlag")); assertFalse(parameters.getBool("boolFlag"));
parameters.parseArgs("-boolFlag"); try {
parameters.parseArgs("-boolFlag");
} catch (CommandParsingException e) {
assertNull(e);
}
assertTrue(parameters.getBool("boolFlag")); assertTrue(parameters.getBool("boolFlag"));
assertFalse(parameters.getBool("ungiven")); assertFalse(parameters.getBool("ungiven"));
parameters.parseArgs("-ungiven"); try {
parameters.parseArgs("-ungiven");
} catch (CommandParsingException e) {
assertNull(e);
}
assertFalse(parameters.getBool("ungiven")); assertFalse(parameters.getBool("ungiven"));
assertTrue(parameters.getBool("boolFlag")); assertTrue(parameters.getBool("boolFlag"));
} }
/** /** Test method for
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#parseArgs(java.lang.String[])}. * {@link fr.bigeon.gclc.command.CommandParameters#parseArgs(java.lang.String[])}. */
*/
@Test @Test
public final void testParseArgs(){ public final void testParseArgs() {
Set<String> strings = new HashSet<>(); Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); Set<String> bools = new HashSet<>();
@@ -186,19 +238,40 @@ public class CommandParametersTest {
CommandParameters parameters = new CommandParameters(bools, strings, CommandParameters parameters = new CommandParameters(bools, strings,
true); true);
assertFalse(parameters.parseArgs("-ungivenFlag")); try {
assertFalse(parameters.parseArgs("-str")); parameters.parseArgs("-ungivenFlag");
assertTrue(parameters.parseArgs("-boolFlag")); fail("unknown argument should fail in strict");
assertTrue(parameters.parseArgs("-str", "-boolFlag")); } catch (CommandParsingException e) {
assertTrue(parameters.parseArgs("-boolFlag", "-str", "val")); assertNotNull(e);
}
try {
parameters.parseArgs("-str");
fail("missing string argument value should fail");
} catch (CommandParsingException e) {
assertNotNull(e);
}
try {
parameters.parseArgs("-boolFlag");
} catch (CommandParsingException e) {
assertNull(e);
}
try {
parameters.parseArgs("-str", "-boolFlag");
} catch (CommandParsingException e) {
assertNull(e);
}
try {
parameters.parseArgs("-boolFlag", "-str", "val");
} catch (CommandParsingException e) {
assertNull(e);
}
} }
/** /** Test method for
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, boolean)}. * {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, boolean)}. */
*/
@Test @Test
public final void testSetStringBoolean(){ public final void testSetStringBoolean() {
Set<String> strings = new HashSet<>(); Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); Set<String> bools = new HashSet<>();
@@ -233,11 +306,10 @@ public class CommandParametersTest {
assertTrue(parameters.getBool("boolFlag")); assertTrue(parameters.getBool("boolFlag"));
} }
/** /** Test method for
* Test method for {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, java.lang.String)}. * {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, java.lang.String)}. */
*/
@Test @Test
public final void testSetStringString(){ public final void testSetStringString() {
Set<String> strings = new HashSet<>(); Set<String> strings = new HashSet<>();
Set<String> bools = new HashSet<>(); Set<String> bools = new HashSet<>();

View File

@@ -392,21 +392,20 @@ public class ParametrizedCommandTest {
assertEquals(2, parameters.getStringArgumentKeys().size()); assertEquals(2, parameters.getStringArgumentKeys().size());
switch (call) { switch (call) {
case 0: case 0:
case 1:
assertNull(parameters.get(str1)); assertNull(parameters.get(str1));
assertNull(parameters.get(str2)); assertNull(parameters.get(str2));
assertFalse(parameters.getBool(bool1)); assertFalse(parameters.getBool(bool1));
assertFalse(parameters.getBool(bool2)); assertFalse(parameters.getBool(bool2));
call++; call++;
break; break;
case 2: case 1:
assertEquals(str2, parameters.get(str1)); assertEquals(str2, parameters.get(str1));
assertNull(parameters.get(str2)); assertNull(parameters.get(str2));
assertFalse(parameters.getBool(bool1)); assertFalse(parameters.getBool(bool1));
assertFalse(parameters.getBool(bool2)); assertFalse(parameters.getBool(bool2));
call++; call++;
break; break;
case 3: case 2:
assertEquals(str2, parameters.get(str1)); assertEquals(str2, parameters.get(str1));
assertNull(parameters.get(str2)); assertNull(parameters.get(str2));
assertTrue(parameters.getBool(bool1)); assertTrue(parameters.getBool(bool1));
@@ -420,12 +419,17 @@ public class ParametrizedCommandTest {
}; };
try { try {
cmd.execute(); cmd.execute();
cmd.execute(addParam);
cmd.execute("-" + str1, str2); cmd.execute("-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1); cmd.execute("-" + str1, str2, "-" + bool1);
} catch (CommandRunException e) { } catch (CommandRunException e) {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unexpected error");
}
try {
cmd.execute(addParam);
fail("Strict should fail with unexpected argument");
} catch (CommandRunException e) {
assertNotNull(e);
} }
try { try {
cmd.execute("-" + addParam); cmd.execute("-" + addParam);
@@ -504,11 +508,16 @@ public class ParametrizedCommandTest {
try { try {
cmd.execute("-" + str1, str2); cmd.execute("-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1); cmd.execute("-" + str1, str2, "-" + bool1);
cmd.execute("-" + str1, str2, addParam);
} catch (CommandRunException e) { } catch (CommandRunException e) {
assertNull(e); assertNull(e);
fail("unepected error"); fail("unepected error");
} }
try {
cmd.execute("-" + str1, str2, addParam);
fail("Additional parameter should cause failure");
} catch (CommandRunException e) {
assertNotNull(e);
}
try { try {
cmd.execute(); cmd.execute();
fail("needed " + str1 + " not provided shall fail"); fail("needed " + str1 + " not provided shall fail");

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