Compare commits

...

58 Commits

Author SHA1 Message Date
2e28e269e1 [maven-release-plugin] prepare release gclc-1.5.0 2017-08-19 15:48:07 -04:00
e11d90378f Removed deprecation, comments. Update major version
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2017-08-19 15:25:31 -04:00
6a0e68d312 [maven-release-plugin] prepare for next development iteration 2017-08-19 14:48:21 -04:00
3534e817e2 [maven-release-plugin] prepare release gclc-socket-1.1.8 2017-08-19 14:48:15 -04:00
20193dd1e4 Added comment 2017-08-19 14:38:04 -04:00
5df8321dee [maven-release-plugin] prepare for next development iteration 2017-05-10 18:15:03 -04:00
629d07bc32 [maven-release-plugin] prepare release gclc-1.4.0 2017-05-10 18:14:56 -04:00
e32e2428e5 Add task mechanism for the console
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2017-05-10 18:03:34 -04:00
db9f81c6a8 [maven-release-plugin] prepare for next development iteration 2017-04-23 09:41:23 -04:00
0a995394f9 [maven-release-plugin] prepare release gclc-1.3.7 2017-04-23 09:41:08 -04:00
0ca055db8e Licensing 2017-04-23 09:38:46 -04:00
b93c2b5220 Add prompt with timeout
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2017-04-20 13:23:28 -04:00
8322454f72 Adapted applications to make only attachement to the framework
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2017-04-19 13:14:04 -04:00
ab47d6573b Added a wait for application closing before closing of manager
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-21 16:37:24 -05:00
6d496d701d NLS fixes in script command definition
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-18 12:21:31 -05:00
b4df39491e Added pattern to script execution help
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-18 12:18:21 -05:00
775a71b2ec [maven-release-plugin] prepare for next development iteration 2016-12-16 11:54:30 -05:00
c9eb221d31 [maven-release-plugin] prepare release gclc-swt-1.1.3 2016-12-16 11:54:25 -05:00
340a0317af Removing focus forwarder from output field to input.
It seems to trouble the Ctrl-C mechanism in the output.

Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-16 11:32:32 -05:00
35959a8d8a [maven-release-plugin] prepare for next development iteration 2016-12-06 14:47:02 -05:00
07645d7c0c [maven-release-plugin] prepare release gclc-socket-1.1.7 2016-12-06 14:47:00 -05:00
99c0c9008b Upgrade gclc-socket dependency on gclc 2016-12-06 14:34:40 -05:00
26265ad7e6 [maven-release-plugin] prepare for next development iteration 2016-12-06 14:27:22 -05:00
092883f4c3 [maven-release-plugin] prepare release gclc-1.3.6 2016-12-06 14:27:15 -05:00
25904c907d upgrade test to avoid memory leaks 2016-12-06 14:23:31 -05:00
ae55ebea29 Upgrade the gclc pom
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-06 13:05:11 -05:00
e989aff2f4 [maven-release-plugin] rollback the release of gclc-1.3.4 2016-12-06 13:03:29 -05:00
2f0c03a73b [maven-release-plugin] prepare release gclc-1.3.4 2016-12-06 12:59:04 -05:00
ff9ace1033 Fix test for getWaitRunnable 2016-12-06 12:56:42 -05:00
ffa54af3be [maven-release-plugin] rollback the release of gclc-1.3.4 2016-12-06 12:56:22 -05:00
269704f5a2 [maven-release-plugin] prepare for next development iteration 2016-12-06 12:51:25 -05:00
aecc18cc83 [maven-release-plugin] prepare release gclc-1.3.4 2016-12-06 12:51:15 -05:00
063cad61cd Upgrade dependency on gclc, fixed test. 2016-12-06 12:27:50 -05:00
201b6ad366 Added test on reading runnable 2016-12-06 11:39:36 -05:00
bf8d76750f Cleanup for release stage
Signed-off-by: Emmanuel Bigeon <emmanuel@bigeon.fr>
2016-12-06 11:35:38 -05:00
17ac47f15e [maven-release-plugin] prepare for next development iteration 2016-12-06 10:58:48 -05:00
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
34 changed files with 1311 additions and 382 deletions

View File

@@ -70,7 +70,7 @@ of Emmanuel Bigeon. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>gclc-socket</artifactId>
<version>1.1.2-SNAPSHOT</version>
<version>1.1.9-SNAPSHOT</version>
<packaging>jar</packaging>
<url>http://www.bigeon.fr/emmanuel</url>
<properties>
@@ -78,16 +78,10 @@ of Emmanuel Bigeon. -->
<project.scm.id>git.bigeon.net</project.scm.id>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>fr.bigeon</groupId>
<artifactId>gclc</artifactId>
<version>1.3.1</version>
<version>1.3.6</version>
</dependency>
<dependency>
<groupId>fr.bigeon</groupId>

View File

@@ -95,12 +95,11 @@ public class SocketConsoleApplicationShell implements Runnable, AutoCloseable {
@Override
public void run() {
try {
while (!socket.isOutputShutdown()) {
while (!socket.isOutputShutdown() &&
!consoleManager.available()) {
while (!socket.isClosed()) {
while (!socket.isClosed() && !consoleManager.available()) {
waitASec();
}
if (socket.isOutputShutdown()) {
if (socket.isClosed()) {
return;
}
String m = consoleManager.readNextLine();
@@ -192,7 +191,8 @@ public class SocketConsoleApplicationShell implements Runnable, AutoCloseable {
// Create the streams
runSokectServer();
} catch (final IOException e) {
LOGGER.log(Level.SEVERE,
LOGGER.severe("Communication error between client and server"); //$NON-NLS-1$
LOGGER.log(Level.FINE,
"Communication error between client and server", e); //$NON-NLS-1$
}
}
@@ -229,12 +229,28 @@ public class SocketConsoleApplicationShell implements Runnable, AutoCloseable {
LOGGER.log(Level.FINE,
"Socket closed with exception (probably due to server interruption)", //$NON-NLS-1$
e);
} catch (IOException e) {
throw e;
}
LOGGER.info("Closing client"); //$NON-NLS-1$
}
runnable.setRunning(false);
consoleManager.type(applicationShutdown);
consoleManager.close();
try {
consoleManager.type(applicationShutdown);
try {
appThNext.join(ONE_TENTH_OF_SECOND);
} catch (InterruptedException e) {
LOGGER.warning("Application thread was interrupted!"); //$NON-NLS-1$
LOGGER.log(Level.FINE,
"Application thread was interrupted while closing", //$NON-NLS-1$
e);
}
consoleManager.close();
} catch (IOException e) {
LOGGER.warning("Unable to close application correctly"); //$NON-NLS-1$
LOGGER.log(Level.FINE, "Application closing caused an exception", //$NON-NLS-1$
e);
}
LOGGER.info("Closing Server"); //$NON-NLS-1$
}
@@ -259,44 +275,50 @@ public class SocketConsoleApplicationShell implements Runnable, AutoCloseable {
* @throws IOException if the communication failed */
private void communicate(final Socket socket, final PrintWriter writer,
BufferedReader in) throws IOException {
Thread th = new Thread(new OutputForwardRunnable(writer, socket),
"ClientComm"); //$NON-NLS-1$
OutputForwardRunnable cc = new OutputForwardRunnable(writer, socket);
Thread th = new Thread(cc, "ClientComm"); //$NON-NLS-1$
th.start();
if (autoClose) {
communicateOnce(socket, in);
communicateOnce(in);
} else {
communicateLoop(socket, in);
communicateLoop(in);
}
}
/** @param socket the socket
* @param in the input from the client
/** @param in the input from the client
* @throws IOException if the communication failed */
private void communicateOnce(Socket socket,
BufferedReader in) throws IOException {
private void communicateOnce(BufferedReader in) throws IOException {
ReadingRunnable reading = new ReadingRunnable(in);
Thread th = new Thread(reading, "gclcToApp"); //$NON-NLS-1$
th.start();
communicationContent(reading);
reading.setRunning(false);
socket.shutdownOutput();
doEndCommunication(reading);
}
/** @param socket the socket
* @param in the input from the client
/** @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 in the input from the client
* @throws IOException if the communication failed */
private void communicateLoop(Socket socket,
BufferedReader in) throws IOException {
private void communicateLoop(BufferedReader in) throws IOException {
ReadingRunnable reading = new ReadingRunnable(in);
Thread th = new Thread(reading, "gclcToApp"); //$NON-NLS-1$
th.start();
while (app.isRunning() && communicationContent(reading)) {
// keep on going
}
reading.setRunning(false);
socket.shutdownOutput();
doEndCommunication(reading);
}
/** @param reading the reading
@@ -319,7 +341,6 @@ public class SocketConsoleApplicationShell implements Runnable, AutoCloseable {
}
String ln = reading.getMessage();
if (ln.equals(close)) {
consoleManager.println("Bye."); //$NON-NLS-1$
return false;
}
// Pass command to application
@@ -367,7 +388,7 @@ public class SocketConsoleApplicationShell implements Runnable, AutoCloseable {
/* (non-Javadoc)
* @see java.lang.AutoCloseable#close() */
@Override
public void close() throws Exception {
public void close() throws IOException {
consoleManager.close();
}
}

View File

@@ -85,27 +85,20 @@ public class SocketConsoleApplicationTest {
new InputStreamReader(kkSocket.getInputStream()));) {
String fromServer;
int i = 0;
int i = -1;
String[] cmds = {"help", "toto", "test", "bye"};
while ((fromServer = in.readLine()) != null) {
LOGGER.fine("Server: \n" + fromServer);
if (fromServer.equals("Bye.")) {
i++;
fromServer = consumeToPrompt(fromServer, in);
if (fromServer == null || fromServer.equals("Bye.")) {
break;
}
while (fromServer != null && !fromServer.equals("> ")) {
fromServer = in.readLine();
LOGGER.fine("Server: \n" + fromServer);
}
if (fromServer == null) {
fail("Null pointer");
}
final String fromUser = cmds[i];
if (fromUser != null) {
LOGGER.fine("Client: " + fromUser);
out.println(fromUser);
}
i++;
}
assertEquals(4, i);
} catch (final IOException e) {
@@ -123,19 +116,15 @@ public class SocketConsoleApplicationTest {
String[] cmds = {"help", "toto", "test",
ConsoleTestApplication.EXIT};
while ((fromServer = in.readLine()) != null) {
LOGGER.fine("Server: \n" + fromServer);
while (fromServer != null && !fromServer.equals("> ")) {
LOGGER.fine("Server: \n" + fromServer);
fromServer = in.readLine();
}
if (fromServer == null) {
fromServer = consumeToPrompt(fromServer, in);
if (fromServer == null || fromServer.equals("Bye.")) {
break;
}
LOGGER.fine("Server: \n" + fromServer);
LOGGER.info("Server: \n" + fromServer);
final String fromUser = cmds[i];
if (fromUser != null) {
LOGGER.fine("Client: " + fromUser);
LOGGER.info("Client: " + fromUser);
out.println(fromUser);
}
i++;
@@ -161,11 +150,8 @@ public class SocketConsoleApplicationTest {
String[] cmds = {"help", "toto", "test",
ConsoleTestApplication.EXIT};
while ((fromServer = in.readLine()) != null) {
while (fromServer != null && !fromServer.equals("> ")) {
fromServer = in.readLine();
LOGGER.fine("Server: \n" + fromServer);
}
if (fromServer == null) {
fromServer = consumeToPrompt(fromServer, in);
if (fromServer == null || fromServer.equals("Bye.")) {
break;
}
@@ -207,17 +193,11 @@ public class SocketConsoleApplicationTest {
int i = 0;
String[] cmds = {"help", "test", "close"};
while ((fromServer = in.readLine()) != null) {
assertTrue(i < 1);
while (fromServer != null && !fromServer.equals("> ") &&
!fromServer.equals("See you")) {
fromServer = in.readLine();
LOGGER.fine("Server: \n" + fromServer);
}
if (fromServer == null || fromServer.equals("Bye.") ||
fromServer.equals("See you")) {
fromServer = consumeToPrompt(fromServer, in);
if (fromServer == null || fromServer.equals("Bye.")) {
break;
}
assertTrue(i < 1);
final String fromUser = cmds[i];
if (fromUser != null) {
LOGGER.fine("Client: " + fromUser);
@@ -243,4 +223,19 @@ public class SocketConsoleApplicationTest {
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

@@ -35,7 +35,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>gclc-swt</artifactId>
<version>1.1.2-SNAPSHOT</version>
<version>1.1.4-SNAPSHOT</version>
<packaging>jar</packaging>
<url>http://www.bigeon.fr/emmanuel</url>
<properties>
@@ -51,7 +51,7 @@
<dependency>
<groupId>fr.bigeon</groupId>
<artifactId>gclc</artifactId>
<version>1.3.2-SNAPSHOT</version>
<version>1.3.6</version>
</dependency>
<dependency>
<groupId>fr.bigeon</groupId>

View File

@@ -43,8 +43,6 @@ 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;
@@ -101,13 +99,6 @@ public class SWTConsole extends Composite
consoleOutput.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true,
LAYOUT_NB_COLUMNS, 1));
consoleOutput.setRedraw(true);
consoleOutput.addFocusListener(new FocusAdapter() {
@SuppressWarnings("synthetic-access")
@Override
public void focusGained(FocusEvent e) {
consoleInput.setFocus();
}
});
lblPromptlabel = new Label(this, SWT.NONE);
lblPromptlabel.setText(prompt);

View File

@@ -43,8 +43,6 @@ 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;
@@ -115,13 +113,6 @@ public class SWTConsoleView extends Composite implements ConsoleDelayIO {
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(
@@ -180,13 +171,6 @@ public class SWTConsoleView extends Composite implements ConsoleDelayIO {
consoleInput.setText(string);
}
/**
*
*/
public void validateCommand() {
validateInput();
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.swt.ConsoleDelayIO#setInput(java.lang.String) */
@Override

View File

@@ -38,6 +38,8 @@
*/
package fr.bigeon.gclc.swt;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import org.eclipse.swt.SWT;
@@ -65,6 +67,11 @@ public class SWTConsoleViewTest {
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,
@@ -110,7 +117,7 @@ public class SWTConsoleViewTest {
@Override
public void run() {
swtConsole.setText("test"); //$NON-NLS-1$
swtConsole.validateCommand();
swtConsole.validateInput();
}
});
try {

View File

@@ -35,7 +35,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>gclc</artifactId>
<version>1.3.2</version>
<version>1.5.0</version>
<packaging>jar</packaging>
<url>http://www.bigeon.fr/emmanuel</url>
<properties>
@@ -53,7 +53,7 @@
<parent>
<groupId>fr.bigeon</groupId>
<artifactId>ebigeon-config</artifactId>
<version>1.7.0</version>
<version>1.7.1</version>
</parent>
<build>
<plugins>
@@ -83,6 +83,6 @@
<scm>
<developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection>
<tag>gclc-1.3.2</tag>
<tag>gclc-1.5.0</tag>
</scm>
</project>

View File

@@ -0,0 +1,62 @@
/*
* Copyright Bigeon Emmanuel (2014)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a generic framework for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
/**
* gclc:fr.bigeon.gclc.ApplicationAttachement.java
* Created on: Apr 19, 2017
*/
package fr.bigeon.gclc;
import fr.bigeon.gclc.exception.InvalidCommandName;
/**
* <p>
* TODO
*
* @author Emmanuel Bigeon
*
*/
public interface ApplicationAttachement {
/** Attach this object to a console application.
* <p>
* The attaching usually consist in the addition of commands in the console
* application. The attached command should be specific to the attachement
* (typically, the generic help command or the script command should not be
* added through this mechanism).
*
* @param application the application
* @throws InvalidCommandName if a command name is invalid for the
* application. */
void attach(ConsoleApplication application) throws InvalidCommandName;
}

View File

@@ -73,19 +73,19 @@ import fr.bigeon.gclc.manager.ConsoleManager;
* start method.
*
* @author Emmanuel BIGEON */
public class ConsoleApplication implements ICommandProvider {
public final class ConsoleApplication implements ICommandProvider {
/** The class logger */
private static final Logger LOGGER = Logger
.getLogger(ConsoleApplication.class.getName());
/** The welcome message */
private final String header;
public final String header;
/** The good bye message */
private final String footer;
public final String footer;
/** The console manager */
protected final ConsoleManager manager;
public final ConsoleManager manager;
/** The container of commands */
private final SubedCommand root;
public final SubedCommand root;
/** The state of this application */
private boolean running;
/** The listeners */
@@ -135,11 +135,6 @@ public class ConsoleApplication implements ICommandProvider {
return root.get(command);
}
/** @return the manager */
public final ConsoleManager getManager() {
return manager;
}
/** @param cmd the command
* @throws IOException if the command could not be parsed */
public final void interpretCommand(String cmd) throws IOException {
@@ -148,7 +143,7 @@ public class ConsoleApplication implements ICommandProvider {
args = GCLCConstants.splitCommand(cmd);
} catch (CommandParsingException e1) {
manager.println("Command line cannot be parsed"); //$NON-NLS-1$
LOGGER.log(Level.INFO, "Invalid user command " + cmd, e1); //$NON-NLS-1$
LOGGER.log(Level.FINE, "Invalid user command " + cmd, e1); //$NON-NLS-1$
return;
}
if (!args.isEmpty()) {
@@ -156,12 +151,12 @@ public class ConsoleApplication implements ICommandProvider {
executeSub(args.get(0), Arrays.copyOfRange(
args.toArray(new String[0]), 1, args.size()));
} catch (final CommandRunException e) {
LOGGER.log(Level.WARNING, "Command failed: " + cmd, e); //$NON-NLS-1$
LOGGER.log(Level.FINE, "Command failed: " + cmd, e); //$NON-NLS-1$
manager.println(Messages
.getString("ConsoleApplication.cmd.failed", cmd)); //$NON-NLS-1$
manager.println(e.getLocalizedMessage());
if (e.getType() == CommandRunExceptionType.USAGE) {
e.getSource().help(getManager());
e.getSource().help(manager);
}
}
}
@@ -187,8 +182,10 @@ public class ConsoleApplication implements ICommandProvider {
} catch (IOException e) {
// The manager was closed
running = false;
LOGGER.log(Level.WARNING,
"The console manager was closed. Closing the application as no one can reach it.", //$NON-NLS-1$
LOGGER.warning(
"The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$
LOGGER.log(Level.FINE,
"An exception caused the closing of the application", //$NON-NLS-1$
e);
return;
}
@@ -201,8 +198,9 @@ public class ConsoleApplication implements ICommandProvider {
} catch (IOException e) {
// The manager was closed
running = false;
LOGGER.log(Level.WARNING,
"The console manager was closed.", //$NON-NLS-1$
LOGGER.warning("The console manager was closed."); //$NON-NLS-1$
LOGGER.log(Level.FINE,
"An exception occured when trying to print the good by e message... The application will still close.", //$NON-NLS-1$
e);
}
}
@@ -225,14 +223,17 @@ public class ConsoleApplication implements ICommandProvider {
}
interpretCommand(cmd);
} catch (InterruptedIOException e) {
LOGGER.log(Level.INFO,
"Prompt interrupted. It is likely the application is closing.", //$NON-NLS-1$
LOGGER.info(
"Prompt interrupted. It is likely the application is closing."); //$NON-NLS-1$
LOGGER.log(Level.FINER, "Interruption of the prompt.", //$NON-NLS-1$
e);
} catch (IOException e) {
// The manager was closed
running = false;
LOGGER.log(Level.WARNING,
"The console manager was closed. Closing the application as no one can reach it.", //$NON-NLS-1$
LOGGER.warning(
"The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$
LOGGER.log(Level.FINE,
"An exception caused the closing of the application", //$NON-NLS-1$
e);
}
}
@@ -241,19 +242,4 @@ public class ConsoleApplication implements ICommandProvider {
public boolean isRunning() {
return running;
}
/** @return the root */
public SubedCommand getRoot() {
return root;
}
/** @return the header */
public String getHeader() {
return header;
}
/** @return the footer */
public String getFooter() {
return footer;
}
}

View File

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

View File

@@ -39,6 +39,7 @@
package fr.bigeon.gclc.command;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@@ -48,6 +49,7 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import fr.bigeon.gclc.exception.CommandParsingException;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.exception.InvalidParameterException;
@@ -60,8 +62,7 @@ import fr.bigeon.gclc.manager.ConsoleManager;
public abstract class ParametrizedCommand extends Command {
/** If the command may use interactive prompting for required parameters
* that
* were not provided on execution */
* that were not provided on execution */
private boolean interactive = true;
/** The manager */
protected final ConsoleManager manager;
@@ -72,8 +73,7 @@ public abstract class ParametrizedCommand extends Command {
/** The parameters mandatory status */
private final Map<String, Boolean> params = new HashMap<>();
/** The restriction of provided parameters on execution to declared
* paramters
* in the status maps. */
* paramters in the status maps. */
private final boolean strict;
/** @param manager the manager
@@ -104,54 +104,50 @@ public abstract class ParametrizedCommand extends Command {
this(null, name, strict);
}
/** <p>
* Add a parameter to the defined parameters
*
* @param param the parameter identification
* @param stringParameter if the parameter is a parameter with an argument
* @param needed if the parameter is required
* @throws InvalidParameterException if the parameter was invalid */
protected void addParameter(String param, boolean stringParameter,
boolean needed) throws InvalidParameterException {
if (params.containsKey(param)) {
checkParam(param, stringParameter, needed);
return;
}
if (stringParameter) {
stringParams.put(param, Boolean.valueOf(needed));
params.put(param, Boolean.valueOf(needed));
} else {
if (needed) {
// ERROR the boolean parameters cannot be needed
throw new InvalidParameterException(
"Boolean parameter are present by their very nature. They should not be defined as needed"); //$NON-NLS-1$
}
boolParams.add(param);
params.put(param, Boolean.valueOf(false));
}
}
/** @param param the parameter
* @param stringParameter the string parameter type
* @param needed if the parameter is needed
* @throws InvalidParameterException if the new definition is invalid */
private void checkParam(String param, boolean stringParameter,
boolean needed) throws InvalidParameterException {
if (stringParameter) {
if (stringParams.containsKey(param)) {
Boolean need = Boolean.valueOf(
needed || stringParams.get(param).booleanValue());
stringParams.put(param, need);
params.put(param, need);
return;
}
throw new InvalidParameterException(
"Parameter is already defined as boolean"); //$NON-NLS-1$
}
if (stringParams.containsKey(param) || needed) {
/** 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 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
@@ -163,12 +159,13 @@ public abstract class ParametrizedCommand extends Command {
@SuppressWarnings("boxing")
@Override
public final void execute(String... args) throws CommandRunException {
final CommandParameters parameters = new CommandParameters(
boolParams, stringParams.keySet(), strict);
if (!parameters.parseArgs(args)) {
// the parameters could not be correctly parsed
final CommandParameters parameters = new CommandParameters(boolParams,
stringParams.keySet(), strict);
try {
parameters.parseArgs(args);
} catch (CommandParsingException e) {
throw new CommandRunException(CommandRunExceptionType.USAGE,
"Unable to read arguments", this); //$NON-NLS-1$
"Unable to read arguments", e, this); //$NON-NLS-1$
}
final List<String> toProvide = new ArrayList<>();
for (final Entry<String, Boolean> string : params.entrySet()) {
@@ -195,9 +192,13 @@ public abstract class ParametrizedCommand extends Command {
for (final String string : toProvide) {
String value;
try {
value = manager.prompt(string);
value = manager
.prompt(MessageFormat.format("value of {0}? ", string)); //$NON-NLS-1$
while (value.isEmpty()) {
value = manager.prompt(string);
value = manager.prompt(
MessageFormat.format(
"value of {0}? (cannot be empty) ", //$NON-NLS-1$
string));
}
} catch (IOException e) {
throw new CommandRunException(

View File

@@ -107,8 +107,8 @@ public class ScriptExecution extends Command {
application.executeSub(command, ps.toArray(new String[0]));
}
} catch (CommandParsingException e) {
throw new CommandRunException("Invalid command in script (" + //$NON-NLS-1$
e.getLocalizedMessage() + ")", //$NON-NLS-1$
throw new CommandRunException(MessageFormat.format(
"Invalid command in script ({0})", e.getLocalizedMessage()), //$NON-NLS-1$
e, this);
} catch (IOException e) {
throw new CommandRunException("Unable to read script", //$NON-NLS-1$
@@ -166,31 +166,41 @@ public class ScriptExecution extends Command {
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail() */
@SuppressWarnings("nls")
@Override
protected String usageDetail() {
StringBuilder builder = new StringBuilder();
builder.append(
" scriptfile: path to the file containing the script to execute."); //$NON-NLS-1$
" scriptfile: path to the file containing the script to execute.");
builder.append(System.lineSeparator());
builder.append(System.lineSeparator());
builder.append(
" The script file must contain one line commands. The lines must never"); //$NON-NLS-1$
" The script file must contain one line commands. The lines must never");
builder.append(System.lineSeparator());
builder.append(
"start with whitespace characters. The lines starting with"); //$NON-NLS-1$
"start with whitespace characters. The lines starting with");
builder.append(System.lineSeparator());
builder.append("\"" + commentPrefix + //$NON-NLS-1$
"\" will be ignored as well as empty lines."); //$NON-NLS-1$
builder.append("\"" + commentPrefix +
"\" will be ignored as well as empty lines.");
builder.append(System.lineSeparator());
return builder.toString();
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usagePattern() */
@SuppressWarnings("nls")
@Override
protected String usagePattern() {
return super.usagePattern() + " <scriptfile>";
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#tip() */
@SuppressWarnings("nls")
@Override
public String tip() {
return "Execute a script"; //$NON-NLS-1$
return "Execute a script";
}
}

View File

@@ -74,12 +74,25 @@ public interface ConsoleManager extends AutoCloseable {
* @throws InterruptedIOException if the prompt was interrupted */
String prompt() throws IOException;
/** @param timeout the time to wait in milliseconds
* @return the user inputed string, null if the timeout was reached
* @throws IOException if the manager is closed or could not read the prompt
* @throws InterruptedIOException if the prompt was interrupted */
String prompt(long timeout) throws IOException;
/** @param message the message to prompt the user
* @return the user inputed string
* @throws IOException if the manager is closed or could not read the prompt
* @throws InterruptedIOException if the prompt was interrupted */
String prompt(String message) throws IOException;
/** @param timeout the time to wait in milliseconds
* @param message the message to prompt the user
* @return the user inputed string, null if the timeout was reached
* @throws IOException if the manager is closed or could not read the prompt
* @throws InterruptedIOException if the prompt was interrupted */
String prompt(String message, long timeout) throws IOException;
/** <p>
* Set a prompting prefix.
*

View File

@@ -121,11 +121,23 @@ public final class PipedConsoleManager
.prompt(innerManager.getPrompt() + System.lineSeparator());
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */
@Override
public String prompt(long timeout) throws IOException {
return innerManager.prompt(timeout);
}
@Override
public String prompt(String message) throws IOException {
return innerManager.prompt(message + System.lineSeparator());
}
@Override
public String prompt(String message, long timeout) throws IOException {
return innerManager.prompt(message + System.lineSeparator(), timeout);
}
@Override
public void setPrompt(String prompt) {
innerManager.setPrompt(prompt);
@@ -172,4 +184,12 @@ public final class PipedConsoleManager
public void interruptPrompt() {
innerManager.interruptPrompt();
}
/** @param message the message
* @return the thread to join to wait for message delivery
* @see fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String) */
public Thread getWaitForDelivery(String message) {
return reading.getWaitForDelivery(message);
}
}

View File

@@ -43,6 +43,8 @@ import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -51,6 +53,60 @@ import java.util.logging.Logger;
* @author Emmanuel Bigeon */
public class ReadingRunnable implements Runnable {
/** The runnable to wait for notification on an object
*
* @author Emmanuel Bigeon */
private final class ToWaitRunnable implements Runnable {
/** The Object */
private final Object obj;
/** The locking object */
private final Object start;
/** The message */
private final String message;
/** The started status */
private boolean started = false;
/** @param obj the object to lock on
* @param start the object to notify when ready to wait
* @param message the message to wait for */
public ToWaitRunnable(Object obj, Object start, String message) {
this.obj = obj;
this.start = start;
this.message = message;
}
@SuppressWarnings("synthetic-access")
@Override
public void run() {
synchronized (obj) {
synchronized (start) {
started = true;
start.notify();
}
while (isRunning()) {
try {
obj.wait();
if (delivering.equals(message)) {
return;
}
} catch (InterruptedException e) {
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION,
e);
}
}
}
}
/** @return the started */
public boolean isStarted() {
synchronized (start) {
return started;
}
}
}
/** The thread intteruption logging message */
private static final String THREAD_INTERRUPTION_EXCEPTION = "Thread interruption exception."; //$NON-NLS-1$
/** The closed pipe message */
private static final String CLOSED_PIPE = "Closed pipe"; //$NON-NLS-1$
/** Wait timeout */
@@ -69,6 +125,12 @@ public class ReadingRunnable implements Runnable {
private final Object lock = new Object();
/** The waiting status for a message */
private boolean waiting;
/** The blocker for a given message */
private final Map<String, Object> messageBlocker = new HashMap<>();
/** The lock */
private final Object messageBlockerLock = new Object();
/** The message being delivered */
private String delivering;
/** @param reader the input to read from */
public ReadingRunnable(BufferedReader reader) {
@@ -96,10 +158,13 @@ public class ReadingRunnable implements Runnable {
lock.notify();
}
} 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) {
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;
return;
}
@@ -125,22 +190,47 @@ public class ReadingRunnable implements Runnable {
public String getMessage() throws IOException {
synchronized (lock) {
if (!running) {
throw new IOException(CLOSED_PIPE);
throw new IOException(CLOSED_PIPE);
}
waiting = true;
while (messages.isEmpty()) {
try {
lock.wait(TIMEOUT);
} catch (InterruptedException e) {
LOGGER.log(Level.SEVERE, "Thread interruption exception.", //$NON-NLS-1$
e);
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e);
}
if (messages.isEmpty() && !running) {
throw new IOException(CLOSED_PIPE);
throw new IOException(CLOSED_PIPE);
}
}
LOGGER.finest("Polled: " + messages.peek()); //$NON-NLS-1$
waiting = false;
notifyMessage(messages.peek());
return messages.poll();
}
}
/** @param timeout the read time out
* @return The next message that was in the input
* @throws IOException if the input was closed */
public String getNextMessage(long timeout) throws IOException {
synchronized (lock) {
if (!running) {
throw new IOException(CLOSED_PIPE);
}
waiting = true;
try {
lock.wait(timeout);
} catch (InterruptedException e) {
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e);
}
if (messages.isEmpty() && !running) {
throw new IOException(CLOSED_PIPE);
}
waiting = false;
if (messages.isEmpty()) {
return null;
}
return messages.poll();
}
}
@@ -164,7 +254,7 @@ public class ReadingRunnable implements Runnable {
public boolean hasMessage() throws IOException {
synchronized (lock) {
if (!running) {
throw new IOException(CLOSED_PIPE);
throw new IOException(CLOSED_PIPE);
}
return !messages.isEmpty();
}
@@ -179,4 +269,45 @@ public class ReadingRunnable implements Runnable {
}
}
}
/** @param message the message */
private void notifyMessage(String message) {
synchronized (messageBlockerLock) {
delivering = message;
if (messageBlocker.containsKey(message)) {
Object mLock = messageBlocker.get(message);
synchronized (mLock) {
mLock.notify();
}
messageBlocker.remove(message);
}
}
}
/** @param message the message
* @return the thread to join to wait for message delivery */
public Thread getWaitForDelivery(final String message) {
synchronized (messageBlockerLock) {
if (!messageBlocker.containsKey(message)) {
messageBlocker.put(message, new Object());
}
final Object obj = messageBlocker.get(message);
final Object start = new Object();
ToWaitRunnable waitRunn = new ToWaitRunnable(obj, start, message);
Thread th = new Thread(waitRunn);
synchronized (start) {
th.start();
while (!waitRunn.isStarted()) {
try {
start.wait(TIMEOUT);
} catch (InterruptedException e) {
LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION,
e);
}
}
}
return th;
}
}
}

View File

@@ -136,6 +136,13 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR
return prompt(prompt);
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */
@Override
public String prompt(long timeout) throws IOException {
return prompt(prompt, timeout);
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */
@Override
@@ -145,6 +152,15 @@ public final class SystemConsoleManager implements ConsoleManager { // NOSONAR
return reading.getMessage();
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */
@Override
public String prompt(String message, long timeout) throws IOException {
checkOpen();
out.print(message);
return reading.getNextMessage(timeout);
}
/** @param prompt the prompt to set */
@Override
public void setPrompt(String prompt) {

View File

@@ -0,0 +1,47 @@
/*
* 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.proc.InterruptionListener.java
* Created on: May 10, 2017
*/
package fr.bigeon.gclc.proc;
/** A listener for interruption
*
* @author Emmanuel Bigeon */
public interface InterruptionListener {
/** Notification of an interuption of a listened object */
void interrupted();
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright Bigeon Emmanuel (2014)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a generic framework for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
/**
* gclc:fr.bigeon.gclc.proc.ProcessList.java
* Created on: May 10, 2017
*/
package fr.bigeon.gclc.proc;
import fr.bigeon.gclc.command.Command;
import fr.bigeon.gclc.exception.CommandRunException;
/** A command that will flag a task to stop
*
* @author Emmanuel Bigeon */
public class ProcessKill extends Command {
/** The taskpool */
private final TaskPool pool;
/** @param name the command name
* @param pool the pool */
public ProcessKill(String name, TaskPool pool) {
super(name);
this.pool = pool;
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[])
*/
@Override
public void execute(String... args) throws CommandRunException {
pool.get(args[0]).setRunning(false);
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#tip()
*/
@SuppressWarnings("nls")
@Override
public String tip() {
return "Request a process to stop (softly)";
}
}

View File

@@ -0,0 +1,101 @@
/*
* 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.proc.ProcessList.java
* Created on: May 10, 2017
*/
package fr.bigeon.gclc.proc;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import fr.bigeon.gclc.command.Command;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.manager.ConsoleManager;
/** A command to list current processes
*
* @author Emmanuel Bigeon */
public class ProcessList extends Command {
/** The process pool */
private final TaskPool pool;
/** the interaction object */
private final ConsoleManager manager;
/** @param name the command name
* @param pool the pool
* @param manager the console manager */
public ProcessList(String name, TaskPool pool,
ConsoleManager manager) {
super(name);
this.pool = pool;
this.manager = manager;
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[])
*/
@Override
public void execute(String... args) throws CommandRunException {
ArrayList<String> pids = new ArrayList<>(pool.getPIDs());
Collections.sort(pids);
for (String string : pids) {
try {
manager.println(
MessageFormat.format("{0}\t{1}", string, //$NON-NLS-1$
pool.get(string).getName()));
} catch (IOException e) {
throw new CommandRunException(
CommandRunExceptionType.INTERACTION,
"Unable to communicate with user", e, this); //$NON-NLS-1$
}
}
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#tip()
*/
@SuppressWarnings("nls")
@Override
public String tip() {
return "List all processes";
}
}

View File

@@ -0,0 +1,77 @@
/*
* 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.proc.ThreadCommand.java
* Created on: May 10, 2017
*/
package fr.bigeon.gclc.proc;
/** Tasks are named runnable that can be interrupted.
* <p>
* Good practice for those objects include an absence of interaction with the
* user (otherwise the user may not know from which running command comes
* information and requests) and unicity of the object to have a coherent
* control through the {@link #setRunning(boolean)} method.
* <p>
* Typical cases where such command can be useful is for an application that
* does long computations.
*
* @author Emmanuel Bigeon */
public interface Task extends Runnable {
/** @return the task name */
public String getName();
/** @return if the command is supposed to be running */
boolean isRunning();
/** Set the running state.
* <p>
* This method should be only called by external objects with the false
* argument. Calling this method with true has unspecified behavior and
* could do nothing as well as restart the command for example.
*
* @param running the running state */
void setRunning(boolean running);
/** Add a listener for this command end of execution
*
* @param listener the listener */
void addInterruptionListener(InterruptionListener listener);
/** Remove a listener of this command end of execution
*
* @param listener the listener */
void rmInterruptionListener(InterruptionListener listener);
}

View File

@@ -0,0 +1,104 @@
/*
* 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.proc.TaskPool.java
* Created on: May 10, 2017
*/
package fr.bigeon.gclc.proc;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/** A process pool
*
* @author Emmanuel Bigeon */
public class TaskPool {
/** The running processes */
private final Map<String, Task> running = new HashMap<>();
/** The count for process id */
private int count = 0;
/** The lock for pid attribution synchronization */
private final Object lock = new Object();
/** Add a process in the pool
*
* @param cmd the process */
public void add(final Task cmd) {
final String pid = getPID();
synchronized (lock) {
running.put(pid, cmd);
}
cmd.addInterruptionListener(new InterruptionListener() {
@SuppressWarnings("synthetic-access")
@Override
public void interrupted() {
synchronized (lock) {
running.remove(pid);
count = Math.min(count, Integer.parseInt(pid));
}
cmd.rmInterruptionListener(this);
}
});
}
/** @return the process id */
private String getPID() {
synchronized (lock) {
String pid;
do {
pid = Integer.toString(count++);
} while (running.containsKey(pid));
return pid;
}
}
/** Get a process by it associated identifier
*
* @param pid the task id
* @return the task, if any, associated to this id */
public Task get(String pid) {
synchronized (lock) {
return running.get(pid);
}
}
/** @return the pids */
public Collection<String> getPIDs() {
return new HashSet<>(running.keySet());
}
}

View File

@@ -0,0 +1,72 @@
/*
* 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.proc.ProcessList.java
* Created on: May 10, 2017
*/
package fr.bigeon.gclc.proc;
import fr.bigeon.gclc.command.Command;
import fr.bigeon.gclc.exception.CommandRunException;
/** An abstract command to generate a task and return the control to the user
*
* @author Emmanuel Bigeon */
public abstract class TaskSpawner extends Command {
/** The process pool */
private final TaskPool pool;
/** @param name the command name
* @param pool the pool */
public TaskSpawner(String name, TaskPool pool) {
super(name);
this.pool = pool;
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[])
*/
@Override
public final void execute(String... args) throws CommandRunException {
Task task = createTask(args);
Thread th = new Thread(task);
th.start();
pool.add(task);
}
/** @param args the arguments
* @return the process to start and add to the pool */
protected abstract Task createTask(String... args);
}

View File

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

View File

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

View File

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

View File

@@ -54,14 +54,15 @@ import fr.bigeon.gclc.manager.PipedConsoleManager;
@SuppressWarnings("javadoc")
public class CommandTestingApplication implements AutoCloseable {
private final ConsoleTestApplication application;
private final ConsoleApplication application;
private final Thread th;
private final PipedConsoleManager manager;
/** @throws IOException if the streams cannot be build */
public CommandTestingApplication() throws IOException {
manager = new PipedConsoleManager();
application = new ConsoleTestApplication(manager);
application = new ConsoleApplication(manager, "", "");
new ConsoleTestApplication().attach(application);
th = new Thread(new Runnable() {
@SuppressWarnings("synthetic-access")
@@ -93,7 +94,7 @@ public class CommandTestingApplication implements AutoCloseable {
}
/** @return the application */
public ConsoleTestApplication getApplication() {
public ConsoleApplication getApplication() {
return application;
}

View File

@@ -43,6 +43,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
@@ -55,7 +56,6 @@ import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.i18n.Messages;
import fr.bigeon.gclc.manager.ConsoleManager;
import fr.bigeon.gclc.manager.SystemConsoleManager;
import fr.bigeon.gclc.manager.PipedConsoleManager;
/** Test class for ConsoleApplication
@@ -70,9 +70,14 @@ public class ConsoleApplicationTest {
/** Test the base of a console application */
@Test
public void test() {
ConsoleTestApplication app = new ConsoleTestApplication(
new SystemConsoleManager());
app.exit();
try (PipedConsoleManager manager = new PipedConsoleManager()) {
ConsoleApplication app = new ConsoleApplication(manager, "", "");
app.exit();
} catch (IOException e) {
fail("System Console Manager failed");
}
}
@Test
@@ -80,7 +85,7 @@ public class ConsoleApplicationTest {
try (CommandTestingApplication application = new CommandTestingApplication()) {
// remove welcome
assertEquals(application.getApplication().getHeader(),
assertEquals(application.getApplication().header,
application.readNextLine());
// Remove first prompt
assertNull(application.readNextLine());
@@ -128,7 +133,7 @@ public class ConsoleApplicationTest {
assertNull(application.readNextLine());
application.sendCommand("exit");
assertEquals(application.getApplication().getFooter(),
assertEquals(application.getApplication().footer,
application.readNextLine());
assertFalse(application.getApplication().isRunning());
} catch (IOException e1) {
@@ -156,7 +161,10 @@ public class ConsoleApplicationTest {
manager.type("exit");
th.join();
} catch (IOException | InvalidCommandName | InterruptedException e) {
} catch (IOException | InvalidCommandName |
InterruptedException e) {
assertNull(e);
}

View File

@@ -41,12 +41,11 @@ import fr.bigeon.gclc.command.ExitCommand;
import fr.bigeon.gclc.command.HelpExecutor;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.ConsoleManager;
/** A test-purpose application
*
* @author Emmanuel Bigeon */
public class ConsoleTestApplication extends ConsoleApplication {
public class ConsoleTestApplication implements ApplicationAttachement {
/** Exit command */
public static final String EXIT = "exit"; //$NON-NLS-1$
@@ -54,14 +53,14 @@ public class ConsoleTestApplication extends ConsoleApplication {
protected static final long TWO_SECONDS = 2000;
/** @param manager the manager */
@Override
@SuppressWarnings("nls")
public ConsoleTestApplication(final ConsoleManager manager) {
super(manager, "Welcome to the test application. Type help or test.",
"See you");
public void attach(final ConsoleApplication application) {
try {
add(new ExitCommand(EXIT, this));
add(new HelpExecutor("help", manager, this.getRoot()));
add(new Command("test") {
application.add(new ExitCommand(EXIT, application));
application.add(new HelpExecutor("help", application.manager,
application.root));
application.add(new Command("test") {
@Override
public String tip() {
@@ -71,14 +70,14 @@ public class ConsoleTestApplication extends ConsoleApplication {
@Override
public void execute(String... args) throws CommandRunException {
try {
manager.println("Test command ran fine");
application.manager.println("Test command ran fine");
} catch (IOException e) {
throw new CommandRunException("manager closed", e,
this);
}
}
});
add(new Command("long") {
application.add(new Command("long") {
@Override
public String tip() {
@@ -88,9 +87,9 @@ public class ConsoleTestApplication extends ConsoleApplication {
@Override
public void execute(String... args) throws CommandRunException {
try {
manager.println("Waita minute");
application.manager.println("Waita minute");
Thread.sleep(TWO_SECONDS);
manager.println("done!");
application.manager.println("done!");
} catch (IOException e) {
throw new CommandRunException("manager closed", e,
this);
@@ -100,7 +99,7 @@ public class ConsoleTestApplication extends ConsoleApplication {
}
}
});
add(new Command("failingCmd") {
application.add(new Command("failingCmd") {
@Override
public String tip() {

View File

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

View File

@@ -196,32 +196,25 @@ public class ParametrizedCommandTest {
};
// XXX Boolean flag should not be specified mandatory! They are by
// nature qualified
try {
cmd.addParameter("boolFlag", false, true);
fail("Boolean parameters should never be needed specified");
} catch (InvalidParameterException e) {
// OK
assertNotNull(e);
}
String str = "str";
try {
assertTrue(cmd.getBooleanParameters().isEmpty());
assertTrue(cmd.getStringParameters().isEmpty());
cmd.addParameter("boolFlag", false, false);
cmd.addBooleanParameter("boolFlag");
assertEquals(1, cmd.getBooleanParameters().size());
assertTrue(cmd.getStringParameters().isEmpty());
cmd.addParameter(str, true, false);
cmd.addStringParameter(str, false);
assertEquals(1, cmd.getBooleanParameters().size());
assertEquals(1, cmd.getStringParameters().size());
assertFalse(cmd.isNeeded(str));
cmd.addParameter("boolFlag", false, false);
cmd.addBooleanParameter("boolFlag");
assertEquals(1, cmd.getBooleanParameters().size());
assertEquals(1, cmd.getStringParameters().size());
cmd.addParameter(str, true, true);
cmd.addStringParameter(str, true);
assertEquals(1, cmd.getBooleanParameters().size());
assertEquals(1, cmd.getStringParameters().size());
assertTrue(cmd.isNeeded(str));
cmd.addParameter(str, true, false);
cmd.addStringParameter(str, false);
assertEquals(1, cmd.getBooleanParameters().size());
assertEquals(1, cmd.getStringParameters().size());
assertTrue(cmd.isNeeded(str));
@@ -229,34 +222,6 @@ public class ParametrizedCommandTest {
fail("Unexpected error in addition of legitimate parameter");
assertNotNull(e);
}
try {
cmd.addParameter(str, false, false);
fail("parameter type conversion shall fail");
} catch (InvalidParameterException e) {
// OK
assertNotNull(e);
}
try {
cmd.addParameter("boolFlag", true, false);
fail("parameter type conversion shall fail");
} catch (InvalidParameterException e) {
// OK
assertNotNull(e);
}
try {
cmd.addParameter("boolFlag", false, true);
fail("parameter type conversion shall fail");
} catch (InvalidParameterException e) {
// OK
assertNotNull(e);
}
try {
cmd.addParameter("boolFlag", true, true);
fail("parameter type conversion shall fail");
} catch (InvalidParameterException e) {
// OK
assertNotNull(e);
}
}
/** Test method for
@@ -306,10 +271,10 @@ public class ParametrizedCommandTest {
{
try {
addParameter(str1, true, false);
addParameter(str2, true, false);
addParameter(bool1, false, false);
addParameter(bool2, false, false);
addStringParameter(str1, false);
addStringParameter(str2, false);
addBooleanParameter(bool1);
addBooleanParameter(bool2);
} catch (InvalidParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@@ -371,10 +336,10 @@ public class ParametrizedCommandTest {
{
try {
addParameter(str1, true, false);
addParameter(str2, true, false);
addParameter(bool1, false, false);
addParameter(bool2, false, false);
addStringParameter(str1, false);
addStringParameter(str2, false);
addBooleanParameter(bool1);
addBooleanParameter(bool2);
} catch (InvalidParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@@ -392,21 +357,20 @@ public class ParametrizedCommandTest {
assertEquals(2, parameters.getStringArgumentKeys().size());
switch (call) {
case 0:
case 1:
assertNull(parameters.get(str1));
assertNull(parameters.get(str2));
assertFalse(parameters.getBool(bool1));
assertFalse(parameters.getBool(bool2));
call++;
break;
case 2:
case 1:
assertEquals(str2, parameters.get(str1));
assertNull(parameters.get(str2));
assertFalse(parameters.getBool(bool1));
assertFalse(parameters.getBool(bool2));
call++;
break;
case 3:
case 2:
assertEquals(str2, parameters.get(str1));
assertNull(parameters.get(str2));
assertTrue(parameters.getBool(bool1));
@@ -420,12 +384,17 @@ public class ParametrizedCommandTest {
};
try {
cmd.execute();
cmd.execute(addParam);
cmd.execute("-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1);
} catch (CommandRunException 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 {
cmd.execute("-" + addParam);
@@ -439,10 +408,10 @@ public class ParametrizedCommandTest {
{
try {
addParameter(str1, true, true);
addParameter(str2, true, false);
addParameter(bool1, false, false);
addParameter(bool2, false, false);
addStringParameter(str1, true);
addStringParameter(str2, false);
addBooleanParameter(bool1);
addBooleanParameter(bool2);
} catch (InvalidParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@@ -480,10 +449,10 @@ public class ParametrizedCommandTest {
{
try {
addParameter(str1, true, true);
addParameter(str2, true, false);
addParameter(bool1, false, false);
addParameter(bool2, false, false);
addStringParameter(str1, true);
addStringParameter(str2, false);
addBooleanParameter(bool1);
addBooleanParameter(bool2);
} catch (InvalidParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@@ -504,11 +473,16 @@ public class ParametrizedCommandTest {
try {
cmd.execute("-" + str1, str2);
cmd.execute("-" + str1, str2, "-" + bool1);
cmd.execute("-" + str1, str2, addParam);
} catch (CommandRunException e) {
assertNull(e);
fail("unepected error");
}
try {
cmd.execute("-" + str1, str2, addParam);
fail("Additional parameter should cause failure");
} catch (CommandRunException e) {
assertNotNull(e);
}
try {
cmd.execute();
fail("needed " + str1 + " not provided shall fail");
@@ -532,10 +506,10 @@ public class ParametrizedCommandTest {
cmd = new ParametrizedCommand(test, "name", false) {
{
try {
addParameter(str1, true, true);
addParameter(str2, true, false);
addParameter(bool1, false, false);
addParameter(bool2, false, false);
addStringParameter(str1, true);
addStringParameter(str2, false);
addBooleanParameter(bool1);
addBooleanParameter(bool2);
} catch (InvalidParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@@ -569,9 +543,16 @@ public class ParametrizedCommandTest {
@Override
public void run() {
try {
assertEquals(str1, test.readNextLine());
assertEquals("value of " + str1 + "? ",
test.readNextLine());
test.type("");
assertEquals(str1, test.readNextLine());
assertEquals(
"value of " + str1 + "? (cannot be empty) ",
test.readNextLine());
test.type("");
assertEquals(
"value of " + str1 + "? (cannot be empty) ",
test.readNextLine());
test.type(str2);
} catch (IOException e) {
assertNull(e);
@@ -589,7 +570,8 @@ public class ParametrizedCommandTest {
@Override
public void run() {
try {
assertEquals(str1, test.readNextLine());
assertEquals("value of " + str1 + "? ",
test.readNextLine());
test.type(str2);
} catch (IOException e) {
assertNull(e);
@@ -614,10 +596,10 @@ public class ParametrizedCommandTest {
cmd = new ParametrizedCommand(test, "name") {
{
try {
addParameter(str1, true, true);
addParameter(str2, true, false);
addParameter(bool1, false, false);
addParameter(bool2, false, false);
addStringParameter(str1, true);
addStringParameter(str2, false);
addBooleanParameter(bool1);
addBooleanParameter(bool2);
} catch (InvalidParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();

View File

@@ -47,18 +47,16 @@ import java.nio.charset.Charset;
import org.junit.Test;
import fr.bigeon.gclc.ConsoleApplication;
import fr.bigeon.gclc.ConsoleTestApplication;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.manager.PipedConsoleManager;
/**
* <p>
* TODO
/** <p>
* Test class for {@link ScriptExecution}
*
* @author Emmanuel Bigeon
*
*/
* @author Emmanuel Bigeon */
@SuppressWarnings("static-method")
public class ScriptExecutionTest {
@@ -75,8 +73,9 @@ public class ScriptExecutionTest {
assertNotNull(e2);
return;
}
ConsoleTestApplication app = new ConsoleTestApplication(
test);
ConsoleApplication app = new ConsoleApplication(
test, "", "");
new ConsoleTestApplication().attach(app);
ScriptExecution exec = new ScriptExecution("script", app, "#", //$NON-NLS-1$ //$NON-NLS-2$
Charset.forName("UTF-8"));
try {

View File

@@ -0,0 +1,144 @@
/*
* Copyright Bigeon Emmanuel (2014)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a generic framework for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
/**
* gclc:fr.bigeon.gclc.manager.ReadingRunnableTest.java
* Created on: Dec 6, 2016
*/
package fr.bigeon.gclc.manager;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.Charset;
import org.junit.Before;
import org.junit.Test;
/** <p>
* TODO
*
* @author Emmanuel Bigeon */
public class ReadingRunnableTest {
/**
*/
@Before
public void setUp() {}
/** Test method for
* {@link fr.bigeon.gclc.manager.ReadingRunnable#getMessage()}. */
@Test
public final void testGetMessage() {
BufferedReader reader = null;
ReadingRunnable runnable = new ReadingRunnable(reader);
runnable.setRunning(false);
try {
runnable.getMessage();
fail("reading from closed runnable");
} catch (IOException e) {
assertNotNull(e);
}
}
/** Test method for
* {@link fr.bigeon.gclc.manager.ReadingRunnable#hasMessage()}. */
@Test
public final void testHasMessage() {
BufferedReader reader = null;
ReadingRunnable runnable = new ReadingRunnable(reader);
runnable.setRunning(false);
try {
runnable.getMessage();
fail("reading from closed runnable");
} catch (IOException e) {
assertNotNull(e);
}
}
/** Test method for
* {@link fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String)}.
*
* @throws InterruptedException */
@Test
public final void testGetWaitForDelivery() throws InterruptedException {
try (PipedOutputStream out = new PipedOutputStream();
InputStream piped = new PipedInputStream(out);
BufferedReader reader = new BufferedReader(
new InputStreamReader(piped, "UTF-8"))) {
final ReadingRunnable runnable = new ReadingRunnable(reader);
Thread th0 = new Thread(runnable, "read");
th0.start();
Thread th = runnable.getWaitForDelivery("msg");
out.write(Charset.forName("UTF-8")
.encode("msg" + System.lineSeparator()).array());
Thread th2 = new Thread(new Runnable() {
@Override
public void run() {
try {
runnable.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, "get");
th2.start();
try {
th.join();
} catch (InterruptedException e) {
assertNull(e);
}
runnable.setRunning(false);
out.close();
} catch (IOException e1) {
assertNull(e1);
}
}
}

View File

@@ -65,13 +65,12 @@ public class SystemConsoleManagerTest {
@Test
public final void testPrompt() {
try {
PipedOutputStream outStream = new PipedOutputStream();
InputStream in = new PipedInputStream(outStream);
final PrintStream out = new PrintStream(outStream);
final String test = "test";
SystemConsoleManager manager = new SystemConsoleManager(System.out,
in, Charset.forName("UTF-8"));
final String test = "test";
try (PipedOutputStream outStream = new PipedOutputStream();
InputStream in = new PipedInputStream(outStream);
final PrintStream out = new PrintStream(outStream);
SystemConsoleManager manager = new SystemConsoleManager(System.out,
in, Charset.forName("UTF-8"))) {
Thread th = new Thread(new Runnable() {
@@ -95,10 +94,18 @@ public class SystemConsoleManagerTest {
* {@link fr.bigeon.gclc.manager.SystemConsoleManager#setPrompt(java.lang.String)}. */
@Test
public final void testSetPrompt() {
SystemConsoleManager manager = new SystemConsoleManager();
String prt = "++";
manager.setPrompt(prt);
assertEquals(prt, manager.getPrompt());
try (PipedOutputStream outStream = new PipedOutputStream();
InputStream in = new PipedInputStream(outStream);
final PrintStream out = new PrintStream(outStream);
SystemConsoleManager manager = new SystemConsoleManager(System.out,
in, Charset.forName("UTF-8"))) {
String prt = "++";
manager.setPrompt(prt);
assertEquals(prt, manager.getPrompt());
} catch (IOException e) {
assertNull(e);
}
}
/** Test method for