Compare commits

...

21 Commits

Author SHA1 Message Date
2bf1fa7c80 [maven-release-plugin] prepare release gclc-1.2.4 2016-06-12 22:39:36 -04:00
32e5f777fe licensing 2016-06-12 22:38:53 -04:00
f8aeef14e3 Corrected ScriptExecution and added tests 2016-06-12 22:36:09 -04:00
763b7361ec Update gclc-swt and -socket for gclc-1.2.3 2016-06-12 16:11:44 -04:00
c151107207 [maven-release-plugin] prepare for next development iteration 2016-06-12 16:08:19 -04:00
f95d2f114a [maven-release-plugin] prepare release gclc-1.2.3 2016-06-12 16:08:17 -04:00
e04e7ceaa5 Code compliance 2016-06-12 16:07:14 -04:00
3c1c8e85c8 Adding simple script command. Improving run exception.
Adding a simple script command implementation in ScriptExecution
The CommandRunException now embeds a type for usage, interaction or
running and the source
2016-06-12 15:59:50 -04:00
095a363520 [maven-release-plugin] prepare for next development iteration 2016-06-12 12:47:08 -04:00
932780e9d9 [maven-release-plugin] prepare release gclc-socket-1.0.6 2016-06-12 12:47:06 -04:00
d404d0ab69 Set parent to update release-plugin version 2016-06-12 12:43:59 -04:00
8038db26f3 release-prepare 2016-06-12 12:19:38 -04:00
a29fe4b458 pom 2016-06-12 12:17:54 -04:00
4ddce780e0 Escape character prepare for platform dependent... 2016-06-12 12:15:11 -04:00
12326b7cba Prepare for next development 2016-06-11 18:10:27 -04:00
04fcb5bedd Update dependencies to match platform by profiles 2016-06-11 18:10:03 -04:00
fef08dd29a Released gclc-swt-1.0.3 2016-06-11 16:38:26 -04:00
801189fdeb GCLC swt code compliance 2016-06-11 16:35:34 -04:00
04ca80f1b5 Update POM 2016-06-09 20:10:15 -04:00
2dbdf55694 Update l10n for message format 2016-06-09 19:20:15 -04:00
3ac978bdc1 Correction of message key test long run command 2016-06-09 19:09:17 -04:00
32 changed files with 990 additions and 265 deletions

View File

@@ -67,15 +67,15 @@ of Emmanuel Bigeon. -->
<!-- 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-socket</artifactId> <artifactId>gclc-socket</artifactId>
<version>1.0.4-SNAPSHOT</version> <version>1.0.7-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<url>http://www.bigeon.fr/emmanuel</url> <url>http://www.bigeon.fr/emmanuel</url>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.scm.id>git.bigeon.net</project.scm.id>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
@@ -87,7 +87,7 @@ of Emmanuel Bigeon. -->
<dependency> <dependency>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>
<artifactId>gclc</artifactId> <artifactId>gclc</artifactId>
<version>1.2.0</version> <version>1.2.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>
@@ -98,8 +98,12 @@ of Emmanuel Bigeon. -->
<parent> <parent>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>
<artifactId>ebigeon-config</artifactId> <artifactId>ebigeon-config</artifactId>
<version>1.6.0</version> <version>1.7.0</version>
</parent> </parent>
<name>GCLC Socket</name> <name>GCLC Socket</name>
<description>Socket implementation of GCLC</description> <description>Socket implementation of GCLC</description>
<scm>
<developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection>
<tag>HEAD</tag>
</scm>
</project> </project>

View File

@@ -142,50 +142,57 @@ public class SocketConsoleApplicationShell implements Runnable {
* @see java.lang.Runnable#run() */ * @see java.lang.Runnable#run() */
@Override @Override
public void run() { public void run() {
// Create the server
try (ServerSocket actualServerSocket = new ServerSocket(port)) { try (ServerSocket actualServerSocket = new ServerSocket(port)) {
this.serverSocket = actualServerSocket; this.serverSocket = actualServerSocket;
final ConsoleRunnable runnable = new ConsoleRunnable(app,
promptingLock);
final Thread appTh = new Thread(runnable);
running = true; running = true;
// Create the streams
try (PipedOutputStream outStream = new PipedOutputStream(); try (PipedOutputStream outStream = new PipedOutputStream();
BufferedWriter writer = new BufferedWriter( BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(outStream))) { new OutputStreamWriter(outStream));
InputStreamReader isr = new InputStreamReader(consoleInput);
BufferedReader inBuf = new BufferedReader(isr)) {
consoleInput.connect(outStream); consoleInput.connect(outStream);
try (InputStreamReader isr = new InputStreamReader(
consoleInput);
BufferedReader inBuf = new BufferedReader(isr);) {
consoleManager.setInput(inBuf); consoleManager.setInput(inBuf);
runSokectServer(appTh, writer); runSokectServer(writer);
// Close the application // Close the application
// Pass command to application // Pass command to application
if (app.isRunning()) {
writer.write(applicationShutdown + EOL); writer.write(applicationShutdown + EOL);
writer.flush(); writer.flush();
} }
} }
} catch (final IOException e) { } 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 appTh the application thread /** @param writer the writer to the application
* @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(Thread appTh, private void runSokectServer(BufferedWriter writer) throws IOException {
BufferedWriter writer) throws IOException { final ConsoleRunnable runnable = new ConsoleRunnable(app,
promptingLock);
Thread appThOld = null;
Thread appThNext = new Thread(runnable);
while (running) { while (running) {
try (Socket clientSocket = serverSocket.accept(); try (Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter( PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true); clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader( InputStreamReader isr = new InputStreamReader(
clientSocket.getInputStream()));) { clientSocket.getInputStream());
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); consoleManager.setOutput(out);
// Initiate application // Initiate application
if (!appTh.isAlive()) { if (appThOld == null || !appThOld.isAlive()) {
appTh.start(); appThNext.start();
// Prepare next start
appThOld = appThNext;
appThNext = new Thread(runnable);
} else { } else {
out.println("Reconnected"); //$NON-NLS-1$ out.println("Reconnected"); //$NON-NLS-1$
} }
@@ -249,7 +256,7 @@ public class SocketConsoleApplicationShell implements Runnable {
private void communicateLoop(BufferedReader in, private void communicateLoop(BufferedReader in,
BufferedWriter writer) throws IOException { BufferedWriter writer) throws IOException {
String ln; String ln;
while (running && (ln = in.readLine()) != null) { while (app.isRunning() && (ln = in.readLine()) != null) {
if (ln.equals(close)) { if (ln.equals(close)) {
break; break;
} }

View File

@@ -72,7 +72,26 @@ public class ConsoleTestApplication extends ConsoleApplication {
try { try {
manager.println("Test command ran fine"); manager.println("Test command ran fine");
} catch (IOException e) { } catch (IOException e) {
throw new CommandRunException("manager closed", e); throw new CommandRunException("manager closed", e,
this);
}
}
});
add(new Command("long") {
@Override
public String tip() {
return "A long run test command";
}
@Override
public void execute(String... args) throws CommandRunException {
try {
Thread.sleep(2000);
manager.println("Test command ran fine");
} catch (IOException | InterruptedException e) {
throw new CommandRunException("manager closed", e,
this);
} }
} }
}); });

View File

@@ -77,7 +77,7 @@ public class SocketConsoleApplicationTest {
String fromServer; String fromServer;
int i = 0; int i = 0;
String[] cmds = {"help", "test", "close"}; String[] cmds = {"help", "toto", "test", "close"};
while ((fromServer = in.readLine()) != null) { while ((fromServer = in.readLine()) != null) {
System.out.println("Server: \n" + ENCODER.decode(fromServer)); System.out.println("Server: \n" + ENCODER.decode(fromServer));
if (fromServer.equals("Bye.")) { if (fromServer.equals("Bye.")) {

View File

@@ -37,7 +37,7 @@
> >
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>gclc-swt</artifactId> <artifactId>gclc-swt</artifactId>
<version>1.0.2-SNAPSHOT</version> <version>1.0.5-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<url>http://www.bigeon.fr/emmanuel</url> <url>http://www.bigeon.fr/emmanuel</url>
<properties> <properties>
@@ -47,23 +47,13 @@
<parent> <parent>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>
<artifactId>ebigeon-config</artifactId> <artifactId>ebigeon-config</artifactId>
<version>1.6.0</version> <version>1.7.0</version>
</parent> </parent>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>
<artifactId>gclc</artifactId> <artifactId>gclc</artifactId>
<version>1.2.0</version> <version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.swt</groupId>
<artifactId>org.eclipse.swt.gtk.linux.x86_64</artifactId>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.swt</groupId>
<artifactId>org.eclipse.swt.win32.win32.x86_64</artifactId>
<version>4.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>
@@ -78,4 +68,36 @@
<developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection> <developerConnection>scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git</developerConnection>
<tag>HEAD</tag> <tag>HEAD</tag>
</scm> </scm>
<profiles>
<profile>
<id>linux-deps</id>
<activation>
<os>
<family>Linux</family>
</os>
</activation>
<dependencies>
<dependency>
<groupId>org.eclipse.swt</groupId>
<artifactId>org.eclipse.swt.gtk.linux.x86_64</artifactId>
<version>4.3</version>
</dependency>
</dependencies>
</profile>
<profile>
<id>windows-deps</id>
<activation>
<os>
<family>Windows</family>
</os>
</activation>
<dependencies>
<dependency>
<groupId>org.eclipse.swt</groupId>
<artifactId>org.eclipse.swt.win32.win32.x86_64</artifactId>
<version>4.3</version>
</dependency>
</dependencies>
</profile>
</profiles>
</project> </project>

View File

@@ -0,0 +1,111 @@
/*
* Copyright E. Bigeon (2015)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a swt window for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
/**
* gclc-swt:fr.bigeon.gclc.swt.HistoryTextKeyListener.java
* Created on: Jun 9, 2016
*/
package fr.bigeon.gclc.swt;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Text;
import fr.bigeon.collections.ArrayRibbon;
import fr.bigeon.collections.Ribbon;
/** A key listener to validate commands and manage the history of commands
*
* @author Emmanuel Bigeon */
public final class HistoryTextKeyListener extends KeyAdapter {
/** The size of commands history */
private static final int DEFAULT_HISTORY_SIZE = 10;
/** The history ribbon */
private final Ribbon<String> commands;
/** The current index in history search */
private int currentIndex = 0;
/** The console to write the commands in */
private final Text consoleInput;
/** The console to notify of command validation */
private final SWTConsole console;
/** @param console the console
* @param consoleInput the text to write commands in */
public HistoryTextKeyListener(SWTConsole console, Text consoleInput) {
super();
this.console = console;
this.consoleInput = consoleInput;
this.commands = new ArrayRibbon<>(DEFAULT_HISTORY_SIZE);
}
@Override
public void keyPressed(KeyEvent e) {
pressedKeyCode(e.keyCode);
}
/** @param keyCode */
public void pressedKeyCode(int keyCode) {
// Enter validates the command if prompting
if (keyCode == '\r') {
commands.add(consoleInput.getText());
console.validateInput();
currentIndex = -1;
}
// Upper arrow retrieves previous commands
if (keyCode == SWT.ARROW_UP &&
currentIndex < commands.size() - 1) {
currentIndex++;
String cmd = commands.get(commands.size() - currentIndex - 1);
consoleInput.setText(cmd);
consoleInput.setSelection(cmd.length());
}
// Lower arrow retrieves next commands
if (keyCode == SWT.ARROW_DOWN) {
if (currentIndex == 0) {
currentIndex--;
consoleInput.setText(new String());
} else if (currentIndex > 0) {
String cmd = commands
.get(commands.size() - (--currentIndex) - 1);
consoleInput.setText(cmd);
consoleInput.setSelection(cmd.length());
}
}
}
}

View File

@@ -39,12 +39,12 @@
package fr.bigeon.gclc.swt; package fr.bigeon.gclc.swt;
import java.io.IOException; import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.swt.SWT; import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Composite;
@@ -52,8 +52,6 @@ import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Text;
import fr.bigeon.collections.ArrayRibbon;
import fr.bigeon.collections.Ribbon;
import fr.bigeon.gclc.ConsoleApplication; import fr.bigeon.gclc.ConsoleApplication;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
@@ -62,70 +60,15 @@ import fr.bigeon.gclc.manager.ConsoleManager;
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class SWTConsole extends Composite implements ConsoleManager { public class SWTConsole extends Composite implements ConsoleManager {
/** A key listener to validate commands and manage the history of commands
*
* @author Emmanuel Bigeon */
public static final class HistoryTextKeyListener extends KeyAdapter {
/** The size of commands history */
private static final int DEFAULT_HISTORY_SIZE = 10;
/** The history ribbon */
private final Ribbon<String> commands;
/** The current index in history search */
private int currentIndex = 0;
/** The console to write the commands in */
private final Text consoleInput;
/** The console to notify of command validation */
private final SWTConsole console;
/** @param console the console
* @param consoleInput the text to write commands in */
public HistoryTextKeyListener(SWTConsole console, Text consoleInput) {
super();
this.console = console;
this.consoleInput = consoleInput;
this.commands = new ArrayRibbon<>(DEFAULT_HISTORY_SIZE);
}
@Override
public void keyPressed(KeyEvent e) {
// Enter validates the command if prompting
if (e.keyCode == '\r') {
commands.add(consoleInput.getText());
console.validateInput();
currentIndex = -1;
}
// Upper arrow retrieves previous commands
if (e.keyCode == SWT.ARROW_UP &&
currentIndex < commands.size() - 1) {
currentIndex++;
String cmd = commands.get(commands.size() - currentIndex - 1);
consoleInput.setText(cmd);
consoleInput.setSelection(cmd.length());
}
// Lower arrow retrieves next commands
if (e.keyCode == SWT.ARROW_DOWN) {
if (currentIndex == 0) {
currentIndex--;
consoleInput.setText(new String());
} else if (currentIndex > 0) {
String cmd = commands
.get(commands.size() - (--currentIndex) - 1);
consoleInput.setText(cmd);
consoleInput.setSelection(cmd.length());
}
}
}
}
/** /**
* *
*/ */
private static final int LAYOUT_NB_COLUMNS = 2; private static final int LAYOUT_NB_COLUMNS = 2;
/** The cmd prefix in the output console */ /** The cmd prefix in the output console */
private static final String CMD_PREFIX = "[CMD] "; //$NON-NLS-1$ private static final String CMD_PREFIX = "[CMD] "; //$NON-NLS-1$
/** The class logger */
private static final Logger LOGGER = Logger
.getLogger(SWTConsole.class.getName());
/** The console output text field */ /** The console output text field */
private final Text consoleOutput; private final Text consoleOutput;
/** The console input text field */ /** The console input text field */
@@ -169,8 +112,8 @@ public class SWTConsole extends Composite implements ConsoleManager {
consoleInput = new Text(this, SWT.BORDER); consoleInput = new Text(this, SWT.BORDER);
consoleInput.setLayoutData( consoleInput.setLayoutData(
new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
consoleInput.addKeyListener( consoleInput
new HistoryTextKeyListener(this, consoleInput)); .addKeyListener(new HistoryTextKeyListener(this, consoleInput));
} }
@@ -178,16 +121,34 @@ public class SWTConsole extends Composite implements ConsoleManager {
* *
*/ */
protected void validateInput() { protected void validateInput() {
if (prompting) { Display.getDefault().syncExec(new Runnable() {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
consoleInput.setEnabled(false);
}
});
synchronized (promptLock) { synchronized (promptLock) {
while (!prompting) {
try {
promptLock.wait();
} catch (InterruptedException e) {
LOGGER.log(Level.SEVERE,
"Interruption while waiting prompt", e); //$NON-NLS-1$
}
}
Display.getDefault().syncExec(new Runnable() {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
command = consoleInput.getText(); command = consoleInput.getText();
prompting = false; prompting = false;
consoleInput.setText(new String()); consoleInput.setText(new String());
consoleInput.setEnabled(false); consoleOutput.append(
consoleOutput CMD_PREFIX + command + System.lineSeparator());
.append(CMD_PREFIX + command + System.lineSeparator());
promptLock.notifyAll();
} }
});
promptLock.notifyAll();
} }
} }
@@ -261,11 +222,15 @@ public class SWTConsole extends Composite implements ConsoleManager {
} }
}); });
prompting = true; prompting = true;
promptLock.notifyAll();
promptLock.wait(); promptLock.wait();
} catch (final InterruptedException e) { } catch (final InterruptedException e) {
command = null; command = null;
} }
} }
if (isDisposed()) {
throw new IOException("Input closed"); //$NON-NLS-1$
}
return command; return command;
} }
@@ -355,4 +320,16 @@ public class SWTConsole extends Composite implements ConsoleManager {
return isDisposed(); return isDisposed();
} }
/** @param string the text */
public void setText(String string) {
consoleInput.setText(string);
}
/**
*
*/
public void validateCommand() {
validateInput();
}
} }

View File

@@ -0,0 +1,57 @@
/*
* Copyright E. Bigeon (2015)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a swt window for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
/**
* gclc-swt:fr.bigeon.gclc.swt.HistoryTextKeyListenerTest.java
* Created on: Jun 9, 2016
*/
package fr.bigeon.gclc.swt;
import org.junit.Test;
/**
* <p>
* TODO
*
* @author Emmanuel Bigeon
*
*/
public class HistoryTextKeyListenerTest {
@Test
public void test() {
}
}

View File

@@ -41,30 +41,159 @@ package fr.bigeon.gclc.swt;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Display;
import org.junit.Test; 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.exception.CommandRunException;
import fr.bigeon.gclc.exception.InvalidCommandName; import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.ConsoleManager;
/** /** <p>
* <p>
* TODO * TODO
* *
* @author Emmanuel Bigeon * @author Emmanuel Bigeon */
*
*/
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();
@Test
public void testConsoleClose() {
final SWTConsoleShell shell = new SWTConsoleShell(DISPLAY);
final SWTConsole swtConsole = (SWTConsole) shell.getManager();
swtConsole.close();
swtConsole.setPrompt(":");
try {
final ConsoleApplication appl = new ConsoleApplication(swtConsole,
"exit", "Hello", "See you");
appl.add(new Command("long") {
@Override
public String tip() {
return "a long running command";
}
@Override
public void execute(String... args) {
try {
Thread.sleep(TWO_SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
appl.add(new Command("test") {
@Override
public String tip() {
return "a prompting running command";
}
@Override
public void execute(String... args) throws CommandRunException {
try {
appl.getManager().prompt("Test");
} catch (IOException e) {
throw new CommandRunException("No input", e, this);
}
}
});
// shell.pack();
shell.open();
Thread applThread = new Thread(new Runnable() {
@Override
public void run() {
appl.start();
}
});
Thread testThread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(TWO_SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
swtConsole.setText("test"); //$NON-NLS-1$
swtConsole.validateCommand();
}
});
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
swtConsole.setText("ok"); //$NON-NLS-1$
}
});
swtConsole.validateCommand();
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
swtConsole.setText("long"); //$NON-NLS-1$
}
});
swtConsole.validateCommand();
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
swtConsole.setText("test"); //$NON-NLS-1$
}
});
swtConsole.validateCommand();
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
swtConsole.setText("test"); //$NON-NLS-1$
}
});
swtConsole.validateCommand();
try {
Thread.sleep(TWO_SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
shell.dispose();
}
});
}
});
applThread.start();
testThread.start();
while (!shell.isDisposed()) {
if (!DISPLAY.readAndDispatch()) {
DISPLAY.sleep();
}
}
// DISPLAY.dispose();
assertTrue(appl.getManager().isClosed());
Thread.sleep(TWO_SECONDS);
assertFalse(appl.isRunning());
} catch (InvalidCommandName e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test @Test
public void test() { public void test() {
Display display = new Display(); final SWTConsoleShell shell = new SWTConsoleShell(DISPLAY);
final SWTConsoleShell shell = new SWTConsoleShell(display); final SWTConsole swtConsole = (SWTConsole) shell.getManager();
ConsoleManager swtConsole = shell.getManager();
try { try {
final ConsoleApplication appl = new ConsoleApplication(swtConsole, final ConsoleApplication appl = new ConsoleApplication(swtConsole,
"exit", "Hello", "See you"); "exit", "Hello", "See you");
@@ -98,6 +227,19 @@ public class SWTConsoleShellTest {
@Override @Override
public void run() { public void run() {
try {
Thread.sleep(TWO_SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
swtConsole.setText("test"); //$NON-NLS-1$
swtConsole.validateCommand();
}
});
try { try {
Thread.sleep(TWO_SECONDS); Thread.sleep(TWO_SECONDS);
} catch (InterruptedException e) { } catch (InterruptedException e) {
@@ -115,11 +257,11 @@ public class SWTConsoleShellTest {
applThread.start(); applThread.start();
testThread.start(); testThread.start();
while (!shell.isDisposed()) { while (!shell.isDisposed()) {
if (!display.readAndDispatch()) { if (!DISPLAY.readAndDispatch()) {
display.sleep(); DISPLAY.sleep();
} }
} }
// display.dispose(); // DISPLAY.dispose();
assertTrue(appl.getManager().isClosed()); assertTrue(appl.getManager().isClosed());
Thread.sleep(TWO_SECONDS); Thread.sleep(TWO_SECONDS);
assertFalse(appl.isRunning()); assertFalse(appl.isRunning());

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.2.1-SNAPSHOT</version> <version>1.2.4</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 +53,7 @@
<parent> <parent>
<groupId>fr.bigeon</groupId> <groupId>fr.bigeon</groupId>
<artifactId>ebigeon-config</artifactId> <artifactId>ebigeon-config</artifactId>
<version>1.6.0</version> <version>1.7.0</version>
</parent> </parent>
<build> <build>
<plugins> <plugins>
@@ -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>HEAD</tag> <tag>gclc-1.2.4</tag>
</scm> </scm>
</project> </project>

View File

@@ -48,9 +48,9 @@ import fr.bigeon.gclc.command.HelpExecutor;
import fr.bigeon.gclc.command.ICommand; import fr.bigeon.gclc.command.ICommand;
import fr.bigeon.gclc.command.ICommandProvider; import fr.bigeon.gclc.command.ICommandProvider;
import fr.bigeon.gclc.command.SubedCommand; import fr.bigeon.gclc.command.SubedCommand;
import fr.bigeon.gclc.command.UnrecognizedCommand;
import fr.bigeon.gclc.exception.CommandParsingException; 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.InvalidCommandName; import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.i18n.Messages; import fr.bigeon.gclc.i18n.Messages;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
@@ -100,7 +100,7 @@ public class ConsoleApplication implements ICommandProvider {
this.header = welcome; this.header = welcome;
this.footer = goodbye; this.footer = goodbye;
this.manager = manager; this.manager = manager;
root = new SubedCommand(new String(), new UnrecognizedCommand(manager)); root = new SubedCommand(new String());
} }
/** @param manager the manager /** @param manager the manager
@@ -208,6 +208,9 @@ public class ConsoleApplication implements ICommandProvider {
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());
if (e.getType() == CommandRunExceptionType.USAGE) {
e.getSource().help(getManager());
}
} }
} }
} }

View File

@@ -51,11 +51,19 @@ import fr.bigeon.gclc.exception.CommandParsingException;
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
public class GCLCConstants { public class GCLCConstants {
/** The escaping character */
private static final char ESCAPING_CHAR = getSystemEscapingChar();
/** Hide utility class constructor */ /** Hide utility class constructor */
private GCLCConstants() { private GCLCConstants() {
// utility class // utility class
} }
/** @return the escaping character */
private static char getSystemEscapingChar() {
return '\\';
}
/** Splits a command in the diferrent arguments /** Splits a command in the diferrent arguments
* *
* @param cmd the command to split in its parts * @param cmd the command to split in its parts
@@ -71,7 +79,7 @@ public class GCLCConstants {
while (index < cmd.length()) { while (index < cmd.length()) {
char c = cmd.charAt(index); char c = cmd.charAt(index);
index++; index++;
if (escaped || c == '\\') { if (escaped || c == ESCAPING_CHAR) {
escaped = !escaped; escaped = !escaped;
continue; continue;
} }
@@ -102,11 +110,11 @@ public class GCLCConstants {
private static String removeEscaped(String arg) { private static String removeEscaped(String arg) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
int index = 0; int index = 0;
int endIndex = arg.indexOf('\\'); int endIndex = arg.indexOf(ESCAPING_CHAR);
while (endIndex != -1) { while (endIndex != -1) {
builder.append(arg.subSequence(index, endIndex)); builder.append(arg.subSequence(index, endIndex));
index = endIndex + 1; index = endIndex + 1;
endIndex = arg.indexOf('\\', index + 1); endIndex = arg.indexOf(ESCAPING_CHAR, index + 1);
} }
builder.append(arg.substring(index)); builder.append(arg.substring(index));
return builder.toString(); return builder.toString();

View File

@@ -83,7 +83,7 @@ public class CommandProvider implements ICommandProvider {
} }
} }
throw new CommandRunException( throw new CommandRunException(
Messages.getString("CommandProvider.unrecognized0", cmd)); //$NON-NLS-1$ Messages.getString("CommandProvider.unrecognized", cmd), null); //$NON-NLS-1$
} }
/* (non-Javadoc) /* (non-Javadoc)

View File

@@ -41,6 +41,7 @@ package fr.bigeon.gclc.command;
import java.io.IOException; import java.io.IOException;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
import fr.bigeon.gclc.prompt.CLIPrompterMessages; import fr.bigeon.gclc.prompt.CLIPrompterMessages;
@@ -77,7 +78,8 @@ public class HelpExecutor extends Command {
try { try {
cmd.help(consoleManager, args); cmd.help(consoleManager, args);
} catch (IOException e) { } catch (IOException e) {
throw new CommandRunException("Console manager closed", e); //$NON-NLS-1$ throw new CommandRunException(CommandRunExceptionType.INTERACTION,
"Console manager closed", e, this); //$NON-NLS-1$
} }
} }

View File

@@ -45,6 +45,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
/** <p> /** <p>
@@ -122,7 +123,8 @@ public abstract class ParametrizedCommand extends Command {
boolParams.keySet(), stringParams.keySet(), strict); boolParams.keySet(), stringParams.keySet(), strict);
if (!parameters.parseArgs(args)) { if (!parameters.parseArgs(args)) {
// ERROR the parameters could not be correctly parsed // ERROR the parameters could not be correctly parsed
throw new CommandRunException("Unable to read arguments"); //$NON-NLS-1$ throw new CommandRunException(CommandRunExceptionType.USAGE,
"Unable to read arguments", this); //$NON-NLS-1$
} }
final List<String> toProvide = new ArrayList<>(); final List<String> toProvide = new ArrayList<>();
for (final String string : params.keySet()) { for (final String string : params.keySet()) {
@@ -152,7 +154,8 @@ public abstract class ParametrizedCommand extends Command {
} }
} catch (IOException e) { } catch (IOException e) {
throw new CommandRunException( throw new CommandRunException(
"Interactive command but manager closed...", e); //$NON-NLS-1$ CommandRunExceptionType.INTERACTION,
"Interactive command but manager closed...", e, this); //$NON-NLS-1$
} }
parameters.set(string, value); parameters.set(string, value);
} }

View File

@@ -0,0 +1,151 @@
/*
* Copyright Bigeon Emmanuel (2014)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a generic framework for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
/**
* gclc:fr.bigeon.gclc.command.ScriptExecution.java
* Created on: Jun 12, 2016
*/
package fr.bigeon.gclc.command;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import fr.bigeon.gclc.ConsoleApplication;
import fr.bigeon.gclc.GCLCConstants;
import fr.bigeon.gclc.exception.CommandParsingException;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType;
/** A command that will laucnh a series of command from a file
* <p>
* This command will read a file and execute each non empty non commented line
* as a command of the application.
*
* @author Emmanuel Bigeon */
public class ScriptExecution extends Command {
/** The application */
private final ConsoleApplication application;
/** The commenting prefix */
private final String commentPrefix;
/** @param name the name of the command
* @param application the application
* @param commentPrefix the comment prefix in the script files */
public ScriptExecution(String name, ConsoleApplication application,
String commentPrefix) {
super(name);
this.application = application;
this.commentPrefix = commentPrefix;
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */
@SuppressWarnings("resource")
@Override
public void execute(String... args) throws CommandRunException {
if (args.length == 0) {
throw new CommandRunException(CommandRunExceptionType.USAGE,
"Expecting a file", this); //$NON-NLS-1$
}
String scriptFile = args[0];
Object[] params = Arrays.copyOfRange(args, 1, args.length);
try (FileReader fReader = new FileReader(new File(scriptFile));
BufferedReader reader = new BufferedReader(fReader)) {
String cmd;
for (int i = 1; i < args.length; i++) {
params[i - 1] = args[i];
}
while ((cmd = reader.readLine()) != null) {
if (cmd.startsWith(" ") || cmd.startsWith("\t")) { //$NON-NLS-1$ //$NON-NLS-2$
reader.close();
fReader.close();
throw new CommandRunException(
"Invalid command in script (line starts with space character)", //$NON-NLS-1$
this);
}
if (cmd.isEmpty() || cmd.startsWith(commentPrefix)) {
continue;
}
String cmdLine = MessageFormat.format(cmd, params);
List<String> ps = GCLCConstants.splitCommand(cmdLine);
String command = ps.remove(0);
application.executeSub(command, ps.toArray(new String[0]));
}
} catch (CommandParsingException e) {
throw new CommandRunException("Invalid command in script (" + //$NON-NLS-1$
e.getLocalizedMessage() + ")", //$NON-NLS-1$
e, this);
} catch (IOException e) {
throw new CommandRunException(
"Unable to read script (" + e.getLocalizedMessage() + ")", //$NON-NLS-1$ //$NON-NLS-2$
e, this);
}
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.Command#usageDetail() */
@Override
protected String usageDetail() {
StringBuilder builder = new StringBuilder();
builder.append(
" scriptfile: path to the file containing the script to execute."); //$NON-NLS-1$
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$
builder.append(System.lineSeparator());
builder.append(
"start with whitespace characters. The lines starting with"); //$NON-NLS-1$
builder.append(System.lineSeparator());
builder.append("\"" + commentPrefix + //$NON-NLS-1$
"\" will be ignored as well as empty lines."); //$NON-NLS-1$
builder.append(System.lineSeparator());
return builder.toString();
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#tip() */
@Override
public String tip() {
return "Execute a script"; //$NON-NLS-1$
}
}

View File

@@ -40,6 +40,7 @@ import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import fr.bigeon.gclc.exception.CommandRunException; import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.exception.CommandRunExceptionType;
import fr.bigeon.gclc.exception.InvalidCommandName; import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.ConsoleManager; import fr.bigeon.gclc.manager.ConsoleManager;
@@ -114,10 +115,16 @@ public class SubedCommand implements ICommandProvider, ICommand {
if (noArgCommand != null) { if (noArgCommand != null) {
noArgCommand.execute(args); noArgCommand.execute(args);
} else { } else {
throw new CommandRunException("Unrecognized command"); //$NON-NLS-1$ throw new CommandRunException("Unrecognized command", this); //$NON-NLS-1$
} }
} else { } else {
try {
executeSub(args[0], Arrays.copyOfRange(args, 1, args.length)); executeSub(args[0], Arrays.copyOfRange(args, 1, args.length));
} catch (CommandRunException e) {
throw new CommandRunException(CommandRunExceptionType.USAGE,
e.getLocalizedMessage(), e, this);
}
} }
} }

View File

@@ -1,100 +0,0 @@
/*
* Copyright Bigeon Emmanuel (2014)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a generic framework for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
/**
* gclc:fr.bigeon.gclc.UnrecognizedCommand.java
* Created on: Dec 23, 2014
*/
package fr.bigeon.gclc.command;
import java.io.IOException;
import fr.bigeon.gclc.exception.CommandRunException;
import fr.bigeon.gclc.manager.ConsoleManager;
import fr.bigeon.gclc.prompt.CLIPrompterMessages;
/** <p>
* The error message for unrecognized commands
*
* @author Emmanuel BIGEON */
public final class UnrecognizedCommand implements ICommand {
/** The unrecognized command key */
private static final String UNRECOGNIZED_CMD = "unrecognized.cmd"; //$NON-NLS-1$
/** The unrecognized command key */
private static final String EXPECTED_CMD = "expected.cmd"; //$NON-NLS-1$
/** The manager */
private final ConsoleManager manager;
/** @param manager the console manager to use */
public UnrecognizedCommand(ConsoleManager manager) {
if (manager == null) {
throw new NullPointerException("The argument cannot be null"); //$NON-NLS-1$
}
this.manager = manager;
}
@Override
public void execute(String... args) throws CommandRunException {
try {
if (args.length > 0) {
manager.println(CLIPrompterMessages.getString(UNRECOGNIZED_CMD,
(Object[]) args));
} else {
manager.println(CLIPrompterMessages.getString(EXPECTED_CMD));
}
} catch (IOException e) {
throw new CommandRunException("Manager closed", e); //$NON-NLS-1$
}
}
/* (non-Javadoc)
* @see fr.bigeon.gclc.command.ICommand#getCommandName() */
@Override
public String getCommandName() {
return ""; //$NON-NLS-1$
}
@Override
public void help(@SuppressWarnings("hiding") ConsoleManager manager,
String... args) {
// Nothing to do (no help provided as this is not a user command
// (usually)
}
@Override
public String tip() {
return null;
}
}

View File

@@ -44,8 +44,6 @@
* {@link fr.bigeon.gclc.command.SubedCommand} for a command that is declined in * {@link fr.bigeon.gclc.command.SubedCommand} for a command that is declined in
* a set of sub commands, the {@link fr.bigeon.gclc.command.HelpExecutor} for * a set of sub commands, the {@link fr.bigeon.gclc.command.HelpExecutor} for
* help display of other commands and the * help display of other commands and the
* {@link fr.bigeon.gclc.command.UnrecognizedCommand} that should not be
* directly accessible to the user, but will be used in case of error in typing.
* *
* @author Emmanuel BIGEON */ * @author Emmanuel BIGEON */
package fr.bigeon.gclc.command; package fr.bigeon.gclc.command;

View File

@@ -38,6 +38,8 @@
*/ */
package fr.bigeon.gclc.exception; package fr.bigeon.gclc.exception;
import fr.bigeon.gclc.command.ICommand;
/** <p> /** <p>
* An exception thrown when a command failed to run correctly. * An exception thrown when a command failed to run correctly.
* *
@@ -49,15 +51,48 @@ public class CommandRunException extends Exception {
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** @param message a message */ /** The type of run exception */
public CommandRunException(String message) { private final CommandRunExceptionType type;
/** The command that caused the error */
private final ICommand source;
/** @param message a message
* @param source the source */
public CommandRunException(String message, ICommand source) {
super(message); super(message);
type = CommandRunExceptionType.EXECUTION;
this.source = source;
} }
/** @param message a message /** @param message a message
* @param cause the cause */ * @param cause the cause
public CommandRunException(String message, Throwable cause) { * @param source the source */
public CommandRunException(String message, Throwable cause,
ICommand source) {
super(message, cause); super(message, cause);
type = CommandRunExceptionType.EXECUTION;
this.source = source;
}
/** @param type the type of exception
* @param message the message
* @param source the source */
public CommandRunException(CommandRunExceptionType type, String message,
ICommand source) {
super(message);
this.type = type;
this.source = source;
}
/** @param type the type of exception
* @param message a message
* @param cause the cause
* @param source the source */
public CommandRunException(CommandRunExceptionType type, String message,
Throwable cause, ICommand source) {
super(message, cause);
this.type = type;
this.source = source;
} }
/* (non-Javadoc) /* (non-Javadoc)
@@ -71,4 +106,13 @@ public class CommandRunException extends Exception {
return super.getLocalizedMessage(); return super.getLocalizedMessage();
} }
/** @return the source */
public ICommand getSource() {
return source;
}
/** @return the type */
public CommandRunExceptionType getType() {
return type;
}
} }

View File

@@ -0,0 +1,55 @@
/*
* Copyright Bigeon Emmanuel (2014)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a generic framework for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
/**
* gclc:fr.bigeon.gclc.exception.CommandRunExceptionType.java
* Created on: Jun 12, 2016
*/
package fr.bigeon.gclc.exception;
/**
* <p>
* TODO
*
* @author Emmanuel Bigeon
*
*/
public enum CommandRunExceptionType {
/** Type of exception due to a wrong usage */
USAGE,
/** Type of exception due to a problem in execution */
EXECUTION,
/** Type of exception due to the impossibility to interact with user */
INTERACTION;
}

View File

@@ -137,17 +137,8 @@ public class SystemConsoleManager implements ConsoleManager { // NOSONAR
} }
String result = new String(); String result = new String();
out.print(message + ' '); out.print(message + ' ');
char c;
try { try {
result = in.readLine(); result = in.readLine();
// c = (char) in.read();
// while (c != System.lineSeparator().charAt(0)) {
// result += c;
// c = (char) in.read();
// }
// while (in.available() != 0) {
// in.read();
// }
} catch (final IOException e) { } catch (final IOException e) {
LOGGER.log(Level.SEVERE, "Unable to read prompt", e); //$NON-NLS-1$ LOGGER.log(Level.SEVERE, "Unable to read prompt", e); //$NON-NLS-1$
} }

View File

@@ -1,2 +1,2 @@
CommandProvider.unrecognized=Unrecognized command '{0}' CommandProvider.unrecognized=Unrecognized command "{0}"
ConsoleApplication.cmd.failed=The command '{0}' failed due to : ConsoleApplication.cmd.failed=The command "{0}" failed due to :

View File

@@ -0,0 +1,117 @@
/*
* Copyright Bigeon Emmanuel (2014)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a generic framework for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
/**
* gclc:fr.bigeon.gclc.command.CommandTestingApplication.java
* Created on: Jun 12, 2016
*/
package fr.bigeon.gclc;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter;
import fr.bigeon.gclc.command.ICommand;
import fr.bigeon.gclc.exception.InvalidCommandName;
import fr.bigeon.gclc.manager.SystemConsoleManager;
/**
* <p>
* TODO
*
* @author Emmanuel Bigeon
*
*/
public class CommandTestingApplication {
private final PrintWriter writer;
private final ConsoleTestApplication application;
private final Thread th;
/** @throws IOException if the streams cannot be build */
public CommandTestingApplication() throws IOException {
final PipedOutputStream src = new PipedOutputStream();
InputStream in = new PipedInputStream(src);
application = new ConsoleTestApplication(
new SystemConsoleManager(System.out, in));
th = new Thread(new Runnable() {
@Override
public void run() {
application.start();
}
});
th.start();
writer = new PrintWriter(src, true);
}
public void stop() {
application.exit();
writer.println();
}
public void sendCommand(String cmd) {
writer.println(cmd);
}
/** @param cmd the command
* @return if the command was added
* @throws InvalidCommandName if the command name is invalid
* @see fr.bigeon.gclc.ConsoleApplication#add(fr.bigeon.gclc.command.ICommand) */
public final boolean add(ICommand cmd) throws InvalidCommandName {
return application.add(cmd);
}
/** @return the application */
public ConsoleTestApplication getApplication() {
return application;
}
/**
*
*/
public void waitAndStop() {
writer.println(ConsoleTestApplication.EXIT);
try {
th.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@@ -44,7 +44,6 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.PipedInputStream; import java.io.PipedInputStream;
import java.io.PipedOutputStream; import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import org.junit.Test; import org.junit.Test;
@@ -54,9 +53,10 @@ import fr.bigeon.gclc.manager.SystemConsoleManager;
/** Test class for ConsoleApplication /** Test class for ConsoleApplication
* *
* @author Emmanuel Bigeon */ * @author Emmanuel Bigeon */
@SuppressWarnings("static-method") @SuppressWarnings({"resource", "javadoc", "nls", "static-method"})
public class ConsoleApplicationTest { public class ConsoleApplicationTest {
/** 3 seconds in milliseconds */
protected static final long THREE_SECONDS = 3000; protected static final long THREE_SECONDS = 3000;
/** Test the base of a console application */ /** Test the base of a console application */
@@ -69,14 +69,25 @@ public class ConsoleApplicationTest {
@Test @Test
public void executionTest() { public void executionTest() {
try {
CommandTestingApplication application = new CommandTestingApplication();
application.sendCommand("test");
application.sendCommand("toto");
application.sendCommand("long");
application.sendCommand("exit");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try { try {
final PipedOutputStream src = new PipedOutputStream(); final PipedOutputStream src = new PipedOutputStream();
InputStream in = new PipedInputStream(src); InputStream in = new PipedInputStream(src);
final PipedInputStream snk = new PipedInputStream();
PrintStream out = new PrintStream(new PipedOutputStream(snk));
final ConsoleTestApplication app = new ConsoleTestApplication( final ConsoleTestApplication app = new ConsoleTestApplication(
new SystemConsoleManager(out, in)); new SystemConsoleManager(System.out, in));
Thread th = new Thread(new Runnable() { Thread th = new Thread(new Runnable() {
@Override @Override
@@ -93,6 +104,7 @@ public class ConsoleApplicationTest {
public void run() { public void run() {
try (PrintWriter writer = new PrintWriter(src, true)) { try (PrintWriter writer = new PrintWriter(src, true)) {
writer.println("test"); writer.println("test");
writer.println("toto");
writer.println("long"); writer.println("long");
writer.println("exit"); writer.println("exit");
} }

View File

@@ -36,7 +36,6 @@ package fr.bigeon.gclc;
import java.io.IOException; import java.io.IOException;
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.command.ExitCommand;
import fr.bigeon.gclc.command.HelpExecutor; import fr.bigeon.gclc.command.HelpExecutor;
@@ -74,7 +73,8 @@ public class ConsoleTestApplication extends ConsoleApplication {
try { try {
manager.println("Test command ran fine"); manager.println("Test command ran fine");
} catch (IOException e) { } catch (IOException e) {
throw new CommandRunException("manager closed", e); throw new CommandRunException("manager closed", e,
this);
} }
} }
}); });
@@ -92,9 +92,11 @@ public class ConsoleTestApplication extends ConsoleApplication {
Thread.sleep(TWO_SECONDS); Thread.sleep(TWO_SECONDS);
manager.println("done!"); manager.println("done!");
} catch (IOException e) { } catch (IOException e) {
throw new CommandRunException("manager closed", e); throw new CommandRunException("manager closed", e,
this);
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new CommandRunException("wait interrupted", e); throw new CommandRunException("wait interrupted", e,
this);
} }
} }
}); });

View File

@@ -0,0 +1,84 @@
/*
* Copyright Bigeon Emmanuel (2014)
*
* emmanuel@bigeon.fr
*
* This software is a computer program whose purpose is to
* provide a generic framework for console applications.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
/**
* gclc:fr.bigeon.gclc.command.ScriptExecutionTest.java
* Created on: Jun 12, 2016
*/
package fr.bigeon.gclc.command;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.junit.Test;
import fr.bigeon.gclc.CommandTestingApplication;
import fr.bigeon.gclc.exception.InvalidCommandName;
/**
* <p>
* TODO
*
* @author Emmanuel Bigeon
*
*/
public class ScriptExecutionTest {
/**
* Test method for {@link fr.bigeon.gclc.command.ScriptExecution#execute(java.lang.String[])}.
*/
@Test
public void testExecute() {
try {
CommandTestingApplication application = new CommandTestingApplication();
application.add(new ScriptExecution("script",
application.getApplication(), "#"));
application.sendCommand("script src/test/resources/script1.txt");
application.sendCommand("script src/test/resources/script2.txt");
application.sendCommand("script src/test/resources/script3.txt");
application.sendCommand("script src/test/resources/script4.txt");
application
.sendCommand("script src/test/resources/script5.txt test");
application.waitAndStop();
} catch (IOException | InvalidCommandName e) {
fail("Unexpected exception");
}
}
}

View File

View File

@@ -0,0 +1 @@
# test only comment

View File

@@ -0,0 +1 @@
test

View File

@@ -0,0 +1,5 @@
# Test file with commands
test
# and comments
long
# interwined

View File

@@ -0,0 +1,2 @@
# A script with arguments
{0}