From 953cc3621c8dc7897646c930b565cd8ce4c96078 Mon Sep 17 00:00:00 2001 From: dblouin <dominique.blouin@telecom-paristech.fr> Date: Thu, 2 Feb 2017 17:33:14 +0100 Subject: [PATCH] Issue #18:Improve exceptions handling for DIPLODOCUS simulator --- src/launcher/ExecutionThread.java | 310 ++++++--- src/launcher/LauncherException.java | 19 +- src/launcher/RemoteExecutionThread.java | 2 +- src/launcher/RshClient.java | 736 +++++++++++--------- src/launcher/RshServer.java | 623 +++++++++++------ src/ui/window/JDialogSystemCGeneration.java | 567 ++++++++------- 6 files changed, 1335 insertions(+), 922 deletions(-) diff --git a/src/launcher/ExecutionThread.java b/src/launcher/ExecutionThread.java index 8ab24d2b33..bce47aa21d 100755 --- a/src/launcher/ExecutionThread.java +++ b/src/launcher/ExecutionThread.java @@ -53,38 +53,65 @@ import java.net.*; class ExecutionThread extends Thread { - private String cmd; - private int port; - private RshServer rsh; - private ServerSocket server = null; + private final String cmd; + private final int port; + private final RshServer rsh; + private ServerSocket server;// = null; private boolean go; - BufferedReader proc_in, proc_err; + private BufferedReader proc_in; + private BufferedReader proc_err; private Process proc; - private boolean piped; - private ExecutionThread et; + //private boolean piped; + private ExecutionThread parentExecThread; private boolean mustWaitForPiped; private OutputStream pipe; private boolean isStarted = false; + private boolean sendReturnCode; - public ExecutionThread(String _cmd, int _port, RshServer _rsh) { + private Integer returnCode; + + public ExecutionThread( final String _cmd, + final int startPortnumber, + final RshServer _rsh ) { cmd = _cmd; + //port = _port; rsh = _rsh; - port = _port; - findPortNumber(); + server = null; go = true; + returnCode = null; + mustWaitForPiped = false; + parentExecThread = null; + pipe = null; + proc = null; + proc_in = null; + proc_err = null; + + port = findPortNumber( startPortnumber ); } + + public Integer getReturnCode() { + return returnCode; + } + + public boolean isSendReturnCode() { + return sendReturnCode; + } + + public void setSendReturnCode(boolean sendReturnCode) { + this.sendReturnCode = sendReturnCode; + } public boolean isStarted() { return isStarted; } public void setPiped(ExecutionThread _et) { - et = _et; - piped = true; + parentExecThread = _et; + //piped = true; } public void setWaitForPipe() { @@ -102,7 +129,7 @@ class ExecutionThread extends Thread { } } - public synchronized void setMyPipe(OutputStream os) { + public synchronized void setMyPipe( final OutputStream os ) { pipe = os; notifyAll(); } @@ -112,157 +139,220 @@ class ExecutionThread extends Thread { return port; } - private void findPortNumber() { - for(int i=port + 1; i<port + 1000; i++) { + private int findPortNumber( final int startPortnumber ) { + for( int i = startPortnumber + 1; i < startPortnumber + 1000; i++ ) { try { server = new ServerSocket(i); server.setSoTimeout(60000); - port = i; - return; - } catch (Exception e) { + + return i; + //return; + } + catch (Exception e) { } } + + return startPortnumber; } private Socket waitForClient() { - Socket s = null; - TraceManager.addDev("process " + port + " is waiting for client"); + TraceManager.addDev( "process # " + port + " is waiting for client..." ); + try { - s = server.accept(); - } catch (Exception e) { + final Socket socket = server.accept(); + + TraceManager.addDev( "Processe # " + port + " got client." ); + + return socket; + } + catch (Exception e) { + TraceManager.addError( e ); + return null; } - TraceManager.addDev("processe " + port + " got client"); - return s; } public void closeConnect(Socket s) { try { s.close(); - } catch (IOException io) { + } + catch (IOException io) { + TraceManager.addError( io ); } } public void stopProcess() { go = false; - proc.destroy(); - proc_in = null; - //TraceManager.addDev("Stop process"); + + // Issue #18: It may happen that the process is requested to be stopped before it had time to start + // in which case it will be null + if ( proc != null && proc.isAlive() ) { + proc.destroy(); + } + + if ( proc_in != null ) { + try { + proc_in.close(); + } + catch (IOException e) { + e.printStackTrace(); + } + + proc_in = null; + } + + if ( proc_err != null ) { + try { + proc_err.close(); + } + catch (IOException e) { + e.printStackTrace(); + } + + proc_err = null; + } } - private void respond(PrintStream out, String s) { - try { - out.println(s); - out.flush(); - } catch (Exception e) { - } + private void respond( final PrintStream out, + final ResponseCode code, + final String message ) { + SocketComHelper.send( out, code, message); + //try { + //out.println( co de.name() + message ); + //out.flush(); +// } catch ( IOException e) { +// } } + private void handleReturnCode( PrintStream out ) + throws InterruptedException { + if ( sendReturnCode ) { + returnCode = proc.waitFor(); + final String message = "Ended command " + cmd + " with return code " + returnCode + "."; + TraceManager.addDev( message ); + respond( out, ResponseCode.PROCESS_OUTPUT, message ); + } + else { + returnCode = null; + respond( out, ResponseCode.PROCESS_END, null );//"5"); + } + } + @Override public void run() { isStarted = true; - TraceManager.addDev("Starting process for command " + cmd); + TraceManager.addDev( "Starting process for command " + cmd ); proc = null; - BufferedReader in = null; - String str; + // BufferedReader in = null; + //String str; + try { // print output in pipe - if (mustWaitForPiped) { - try { - proc = Runtime.getRuntime().exec(cmd); - if (piped) { - TraceManager.addDev("Giving my pipe to the other"); - et.setMyPipe(proc.getOutputStream()); + if ( mustWaitForPiped ) { + //try { + proc = Runtime.getRuntime().exec( cmd ); + + if ( parentExecThread != null ) { + TraceManager.addDev( "Giving my pipe to the other..." ); + parentExecThread.setMyPipe( proc.getOutputStream() ); } - TraceManager.addDev("Waiting for pipe"); + + TraceManager.addDev( "Waiting for pipe..." ); + waitingForPipe(); - TraceManager.addDev("Got pipe"); - proc_in = new BufferedReader(new InputStreamReader(proc.getInputStream())); - proc_err = new BufferedReader(new InputStreamReader(proc.getErrorStream())); - + + TraceManager.addDev( "Got pipe." ); + + proc_in = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); + proc_err = new BufferedReader( new InputStreamReader( proc.getErrorStream() ) ); + String str; + try { - while (((str = proc_in.readLine()) != null) && (go == true)){ - pipe.write((str + "\n").getBytes()); - } - while (((str = proc_err.readLine()) != null) && (go == true)){ - pipe.write((str + "\n").getBytes()); + while ( go && ( str = proc_in.readLine() ) != null ) { + TraceManager.addDev( "Writing " + str + " to pipe..." ); + pipe.write( ( str + "\n" ).getBytes() ); } - } catch (IOException e) { - } - } catch (Exception e) { - TraceManager.addDev("Exception [" + e.getMessage() + "] occured when executing " + cmd); - } - try { - pipe.flush(); - pipe.close(); - } catch (Exception e) { - TraceManager.addDev("Exception [" + e.getMessage() + "] occured when executing " + cmd); - } - TraceManager.addDev("Ending command " + cmd); + while ( go && ( str = proc_err.readLine() ) != null ) { + TraceManager.addError( "Writing " + str + " to pipe..." ); + pipe.write( (str + "\n").getBytes() ); + } +// } +// catch (IOException e) { +// TraceManager.addError( e ); +// } +// } +// catch (Exception e) { +// TraceManager.addError("Exception [" + e.getMessage() + "] occured when executing " + cmd, e ); +// } +// try { + } + catch (IOException e) { + TraceManager.addError("Exception [" + e.getMessage() + "] occured when executing " + cmd + "!", e ); + } + finally { + pipe.flush(); + pipe.close(); + } - // print output on socket - } else { - Socket s = waitForClient(); - if (s == null) { - TraceManager.addDev("Client did not connect on time"); - rsh.removeProcess(this); - return; - } + TraceManager.addDev( "Ending piped command " + cmd + "..." ); + } + else { + // print output on socket + Socket s = waitForClient(); - PrintStream out = null; + if (s == null) { + TraceManager.addDev("Client did not connect on time!"); + rsh.removeProcess( this ); + + return; + } - try { - TraceManager.addDev("Going to start command " + cmd); - out = new PrintStream(s.getOutputStream(), true); + TraceManager.addDev("Going to start command " + cmd + "..." ); + final PrintStream out = new PrintStream( s.getOutputStream(), true ); proc = Runtime.getRuntime().exec(cmd); - if (piped) { - TraceManager.addDev("Giving my pipe to the other"); - et.setMyPipe(proc.getOutputStream()); + if ( parentExecThread != null ) { + TraceManager.addDev( "Giving my pipe to the other..." ); + parentExecThread.setMyPipe( proc.getOutputStream() ); } - in = new BufferedReader(new InputStreamReader(s.getInputStream())); - - proc_in = new BufferedReader(new InputStreamReader(proc.getInputStream())); + proc_in = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); + String str; //TraceManager.addDev("Reading the output stream of the process " + cmd); - while (((str = proc_in.readLine()) != null) && (go == true)){ - //System.out.println("out:" + str); - TraceManager.addDev("out " + str); - respond(out, "4" + str); + while ( go && ( str = proc_in.readLine() ) != null ) { + TraceManager.addDev( "Sending " + str + " from " + port + " to client..." ); + respond( out, ResponseCode.PROCESS_OUTPUT, str ); } proc_err = new BufferedReader(new InputStreamReader(proc.getErrorStream())); - while (((str = proc_err.readLine()) != null) && (go == true)){ - //System.out.println("error out:" + str); - TraceManager.addDev("error out " + str); - respond(out, "4" + str); + while ( go && ( str = proc_err.readLine() ) != null ) { + TraceManager.addError( str ); + respond( out, ResponseCode.PROCESS_OUTPUT_ERROR, str ); } - /*int c; - while (((c = proc_in.read()) > 0) && (go == true)){ - System.out.println("char:" + (char)c); - TraceManager.addDev("out " + (char)c); - respond(out, "4" + c); - }*/ - } catch (Exception e) { - TraceManager.addDev("Exception [" + e.getMessage() + "] occured when executing " + cmd); - } - TraceManager.addDev("Ending command " + cmd); - respond(out, "5"); - if (s != null) { - closeConnect(s); - } + handleReturnCode( out ); + + if ( s != null ) { + closeConnect( s ); + } + } } - - if (proc != null) { - proc.destroy(); + catch ( Throwable ex ) { + TraceManager.addError( "Exception occured when executing " + cmd, ex ); + } + finally { + if ( proc != null ) { + proc.destroy(); + } + + if ( !sendReturnCode ) { + rsh.removeProcess(this); + } } - - rsh.removeProcess(this); } } diff --git a/src/launcher/LauncherException.java b/src/launcher/LauncherException.java index 532ab7477c..dad9b6b6af 100755 --- a/src/launcher/LauncherException.java +++ b/src/launcher/LauncherException.java @@ -48,8 +48,21 @@ package launcher; public class LauncherException extends Exception { - public LauncherException(String s) { - super(s); + /** + * + */ + private static final long serialVersionUID = 490922511550027307L; + + public LauncherException( String message ) { + super( message ); + } + + public LauncherException( Throwable cause ) { + super( cause ); + } + + public LauncherException( String message, + Throwable cause ) { + super ( message, cause ); } - } \ No newline at end of file diff --git a/src/launcher/RemoteExecutionThread.java b/src/launcher/RemoteExecutionThread.java index 7b3e040e8d..fd031b25cb 100755 --- a/src/launcher/RemoteExecutionThread.java +++ b/src/launcher/RemoteExecutionThread.java @@ -67,7 +67,7 @@ public class RemoteExecutionThread extends Thread { rshc.sendFileData(fileName, data); } rshc.setCmd(cmd); - rshc.sendProcessRequest(); + rshc.sendExecuteCommandRequest(); rshc.getDataFromProcess(); } catch (Exception e) { } diff --git a/src/launcher/RshClient.java b/src/launcher/RshClient.java index 3e2efe33fa..5204c7077a 100755 --- a/src/launcher/RshClient.java +++ b/src/launcher/RshClient.java @@ -48,21 +48,20 @@ package launcher; import java.io.*; import java.net.*; -import javax.swing.*; import myutil.*; - public class RshClient { public static String sk; //Secret key for communicating with the launcher - private static String NO_HOST = "Application has no execution host"; + private static String NO_HOST = "Application has no execution host"; private static String INET = "Bad internet address for host "; private static String SERV_NOT_RESP = "Server not responding on "; private static String IO_ERROR = "Communication pb with server "; private static String PROC_FAILED = "Process could not be launched"; private static String FILE_FAILED = "File creation failed"; + public static String FAILED = "Request failed"; private static String ID_FAILED = "Wrong id"; private static int BUFSIZE = 511; @@ -74,13 +73,13 @@ public class RshClient { private int portString = -1; private int portString2 = -1; private Socket clientSocket = null; - private BufferedReader in; + private BufferedReader inReader; //private DataInputStream in2; private PrintStream out; //private int offset = 0; - private boolean go; - + // private boolean go; + public RshClient(String _cmd, String _host) { //System.out.println("Using port: " + port); cmd = _cmd; @@ -100,467 +99,536 @@ public class RshClient { cmd = _cmd; } - public void stopFillJTA() throws LauncherException { + public void stopCommand() + throws LauncherException { sendKillProcessRequest(); - go = false; - closeConnect(); + + // Issue #18: Socket is already closed by kiss process method + //go = false; + //closeConnect(); } public int getId() throws LauncherException { - connect(port); - send("00"); + connect(); + send( RequestCode.GET_SESSION_ID ); int id = readId(); closeConnect(); + return id; } public int freeId(int id) throws LauncherException { - connect(port); - send("0" + id); + connect(); + send( RequestCode.FREE_SESSION_ID, Integer.toString( id ) ); int idret = readId(); + if (idret != id) { throw new LauncherException(ID_FAILED); } + return idret; } - public void sendProcessRequest() throws LauncherException { - connect(port); - send("1" + cmd); - readPortString(); + public void sendExecuteCommandRequest() + throws LauncherException { + sendExecuteCommandRequest( false ); + } + + public void sendExecuteCommandRequest( final boolean checkReturnCode ) + throws LauncherException { + connect(); + + if ( checkReturnCode ) { + send( RequestCode.PROCESS_CREATE, cmd ); + readPortString(); + closeConnect(); + + final String procIdStr = Integer.toString( portString ); + connect(); + send( RequestCode.PROCESS_CHECK_RETURN_CODE, procIdStr ); + readServerResponse(); + closeConnect(); + + connect(); + send( RequestCode.PROCESS_START, procIdStr ); + readServerResponse(); + } + else { + send( RequestCode.PROCESS_CREATE_START, cmd ); + readPortString(); + } + closeConnect(); } - public void sendProcessRequest(String cmd1, String cmd2) throws LauncherException { - connect(port); - send("3" + cmd1); - int id1 = readPortString(); + public void sendExecutePipedCommandsRequest( String cmd1, + String cmd2 ) + throws LauncherException { + connect(); + send( RequestCode.PROCESS_CREATE, cmd1 ); + readPortString(); + final int id1 = portString; closeConnect(); - connect(port); - send("3" + cmd2); - int id2 = readPortString(); + connect(); + send( RequestCode.PROCESS_CREATE, cmd2); + readPortString(); + final int id2 = portString; closeConnect(); - connect(port); - send("2" + id1 + " " + id2); - readReturnPipedProcesses(); + connect(); + send( RequestCode.PROCESS_PIPE, id1 + " " + id2 ); + readServerResponse(); closeConnect(); - connect(port); - send("4" + id1); - readReturnPipedProcesses(); + connect(); + send( RequestCode.PROCESS_START, Integer.toString( id1 ) ); + readServerResponse(); closeConnect(); - connect(port); - send("4" + id2); - readReturnPipedProcesses(); + connect(); + send( RequestCode.PROCESS_START, Integer.toString( id2 ) ); + readServerResponse(); closeConnect(); portString = id2; portString2 = id1; } + public Integer getProcessReturnCode() + throws LauncherException { + connect(); + send( RequestCode.PROCESS_GET_RETURN_CODE, Integer.toString( portString ) ); + + try { + final String s = inReader.readLine(); + final ResponseCode code = SocketComHelper.responseCode( s ); + + if ( code != ResponseCode.SUCCESS ) { + throw new LauncherException( FAILED ); + } + + final String retCodeStr = SocketComHelper.message( code, s ); + + return Integer.decode( retCodeStr ); + } + catch( IOException io) { + throw new LauncherException( IO_ERROR, io ); + } + catch( final NumberFormatException ex ) { + return null; + } + finally { + closeConnect(); + + sendKillProcessRequest(); + } + } + public void sendFileData(String fileName, String data) throws LauncherException { - connect(port); - send("7" + fileName); + connect(); + send( RequestCode.FILE_PUT, fileName ); sendFileData(data); - send("7" + fileName); - readReturn(); + send( RequestCode.FILE_SAVE, fileName ); + readServerResponse(); closeConnect(); } public String getFileData(String fileName) throws LauncherException { - connect(port); - send("8" + fileName); + connect(); + send( RequestCode.FILE_GET, fileName ); String s = readDataUntilCompletion(); closeConnect(); + return s; } public void deleteFile(String fileName) throws LauncherException { - connect(port); - send("9" + fileName); - readReturn(); + connect(); + send( RequestCode.FILE_DELETE, fileName ); + readServerResponse(); closeConnect(); } - public void sendKillProcessRequest() throws LauncherException { - connect(port); - send("6" + portString); - closeConnect(); - if(portString2 != -1) { - connect(port); - send("6" + portString2); - closeConnect(); + public void sendKillProcessRequest() + throws LauncherException { + connect(); + send( RequestCode.PROCESS_KILL, Integer.toString( portString ) ); + + try { + readServerResponse(); + } + finally { + closeConnect(); + + if ( portString2 != -1 ) { + connect(); + send( RequestCode.PROCESS_KILL, Integer.toString( portString2 ) ); + + try { + readServerResponse(); + } + finally { + closeConnect(); + } + } } } public void sendKillAllProcessRequest() throws LauncherException { - connect(port); - send("5"); + connect(); + send( RequestCode.PROCESS_KILL_ALL ); + readServerResponse(); closeConnect(); } + + private BufferedReader createBufferedReader( final Socket socket ) + throws IOException { + return new BufferedReader( new InputStreamReader( socket.getInputStream() ) ); + } - public String getDataFromProcess() throws LauncherException { - go = true; + public String getDataFromProcess() + throws LauncherException { + // go = true; StringBuffer bf = new StringBuffer(); //System.out.println("Connect"); - connect(portString); - - String s; - - //System.out.println("Waiting for data"); - while (((s = readProcessData()) != null) && (go == true)) { - bf.append(s + "\n"); + final Socket socket = connect( portString ); + + try { + final BufferedReader reader = createBufferedReader( socket ); + + String data; + + //System.out.println("Waiting for data"); + while ( ( data = readProcessData( reader ) ) != null /*&& go*/ ) { + bf.append( data + "\n" ); + } + + return new String(bf); } - - //System.out.println("no more data : stopped"); - closeConnect(); - //System.out.println("Closed"); - - return new String(bf); - } - - public void fillJTA(JTextArea jta) throws LauncherException { - go = true; - - //System.out.println("Connect"); - connect(portString); - - String s; - - //TraceManager.addDev("Waiting for process data"); - while (((s = readProcessData()) != null) && (go == true)) { - //TraceManager.addDev("Adding to jta:" + s); - jta.append(s + "\n"); + catch ( final IOException ex ) { + throw new LauncherException( IO_ERROR, ex ); + } + finally { + closeConnect( socket ); } - - //System.out.println("no more data : stopped"); - closeConnect(); - //System.out.println("Closed"); - } - public void fillJTAByLine(JTextArea jta) throws LauncherException { - go = true; + public void writeCommandMessages( final Writer output ) + throws LauncherException { + + // Issue #18: the interruption is sent on the server side and we just continue writing until there is no more messages + // to empty the stream. + //go = true; - //System.out.println("Connect"); - connect(portString); + // Issue #18: There was a problem when killing the remote process since the old code would override the socked created + // by the killing command + final Socket socket = connect( portString ); + //connect(portString); - String s; - - //System.out.println("Waiting for data"); - while (((s = readProcessData()) != null) && (go == true)) { - jta.append(s + "\n"); + try { + final BufferedReader reader = createBufferedReader( socket ); + String readLine = reader.readLine(); + + while ( readLine != null ) { + final ResponseCode code = SocketComHelper.responseCode( readLine ); + final String message = SocketComHelper.message( code, readLine ); + + switch ( code ) { + case PROCESS_OUTPUT_ERROR : + output.append( message + "\n" ); + + break; + + default: + output.append( message + "\n" ); + + break; + } + + readLine = reader.readLine(); + } + } + catch( final IOException io ) { + throw new LauncherException( IO_ERROR, io ); + } + finally { + closeConnect( socket ); } - - //System.out.println("no more data : stopped"); - closeConnect(); - //System.out.println("Closed"); - + } +// Issue #18: This does the same as the method above so commented out +// public void fillJTAByLine(JTextArea jta) throws LauncherException { +// go = true; +// +// //System.out.println("Connect"); +// connect(portString); +// +// String s; +// +// //System.out.println("Waiting for data"); +// while (((s = readProcessData()) != null) && go ) { +// jta.append(s + "\n"); +// } +// +// //System.out.println("no more data : stopped"); +// closeConnect(); +// //System.out.println("Closed"); +// +// } + + public void closeConnect() + throws LauncherException { + closeConnect( clientSocket ); } - public void closeConnect() throws LauncherException { + private void closeConnect( final Socket socket ) + throws LauncherException { try { - clientSocket.close(); - } catch (IOException io) { - throw new LauncherException(SERV_NOT_RESP+host); + socket.close(); + } + catch ( IOException io ) { + throw new LauncherException( SERV_NOT_RESP + host, io ); } } - /* -- private -- */ - - - - private void send(String s) throws LauncherException { - TraceManager.addDev("Sending: " + s); + private void send(final RequestCode code ) + throws LauncherException { + send( code, "" ); + } - if (sk != null) { - // cipher the information - s = AESEncryptor.encrypt(sk, RshServer.iv, s); - TraceManager.addDev("Ciphered message to server=" + s); - } + private void send( final RequestCode code, + String message ) + throws LauncherException { + //TraceManager.addDev( "Sending message: " + message ); +// message = code.name() + message; +// +// if (sk != null) { +// // cipher the information +// message = AESEncryptor.encrypt(sk, RshServer.iv, message); +// TraceManager.addDev( "Ciphered message to server=" + message ); +// } try { - out.println(s); - out.flush(); - } catch (Exception e) { - throw new LauncherException(IO_ERROR); + SocketComHelper.send( out, code, message, sk ); +// out.println( message); +// out.flush(); + } + catch ( Throwable th ) { + throw new LauncherException( IO_ERROR, th ); } } private void sendFileData(String data) throws LauncherException { - //System.out.println("Sending data"); StringReader sr = new StringReader(data); BufferedReader br = new BufferedReader(sr); String s; + try { while((s = br.readLine()) != null) { - send("8" + s); + send( RequestCode.FILE_APPEND, s ); +// send("8" + s); } } catch (Exception e) { - throw new LauncherException(FILE_FAILED); + throw new LauncherException( FILE_FAILED, e ); } } - /*private boolean sendData(PrintStream out, FileInputStream fis) throws LauncherException { - System.out.println("Send data "); - - byte [] ba = new byte[BUFSIZE]; - int nbRead; - - //StringReader sr = new StringReader(data); - //BufferedReader br = new BufferedReader(sr); - try { - while((nbRead = fis.read(ba)) > -1) { - respond(out, "8" + new String(ba, 0, nbRead)); - } - fis.close(); - } catch (Exception e) { - return false; - } - return true; - }*/ - - public String readProcessData() throws LauncherException { - int nb; - String s = null; + private static String readProcessData( BufferedReader reader ) + throws LauncherException { + //int nb; + //String s = null; + try { - s = in.readLine(); - nb = Integer.decode(s.substring(0,1)).intValue(); - } catch(IOException io) { - throw new LauncherException(IO_ERROR); - } + final String line = reader.readLine(); + + final ResponseCode code = SocketComHelper.responseCode( line ); + //nb = Integer.decode(s.substring(0,1)).intValue(); + + if ( code == ResponseCode.PROCESS_END ) { + //if (nb == 5) { + return null; + } - if (nb == 5) { - return null; - } + String message = SocketComHelper.message( code, line ); //s = s.substring(1, s.length()); + +// if ( message == null ) { +// message = ""; +// } - s = s.substring(1, s.length()); - if (s == null) { - s = ""; + return message; + } + catch( final IOException io ) { + throw new LauncherException( IO_ERROR, io ); } - - return s; } - private String readDataUntilCompletion() throws LauncherException { - int nb=0, nbTotal, cpt = 0; - String s = null; - StringBuffer ret = new StringBuffer(); - char []c = new char[BUFSIZE+1]; - int read; - + private String readDataUntilCompletion() + throws LauncherException { try { +// int nbTotal, cpt = 0; + StringBuffer ret = new StringBuffer(); + //System.out.println("Reading first data "); - s = in.readLine(); - nb = Integer.decode(s.substring(0,1)).intValue(); - if (nb == 8) { - nbTotal = Integer.decode(s.substring(1,s.length())).intValue(); + String s = inReader.readLine(); + + final ResponseCode code = SocketComHelper.responseCode( s ); +// nb = Integer.decode(s.substring(0,1)).intValue(); + + if ( ResponseCode.FILE_DATA == code ) { + //if (nb == 8) { + char[] c = new char[BUFSIZE+1]; + int read; + int cpt = 0; + int nbTotal = Integer.decode( SocketComHelper.message( code, s ) );//Integer.decode(s.substring(1,s.length())).intValue(); //System.out.println("Total= " + nbTotal); - while (((cpt < nbTotal) && (read = in.read(c, 0, Math.min(BUFSIZE, nbTotal - cpt))) > -1)) { - //s = new String(c, 0, read); - //System.out.println("Nb read: " + read + " size of s =" + s.length()); - //nb = Integer.decode(s.substring(0,1)).intValue(); - //ret.append(s.substring(0, s.length())); + while (((cpt < nbTotal) && (read = inReader.read(c, 0, Math.min(BUFSIZE, nbTotal - cpt))) > -1)) { ret.append(c, 0, read); cpt += read; } - // Read last info - //System.out.println("Reading last info"); - nb = readReturn(); - //System.out.println("Return = " + nb); - //read = in.read(c, 0, 1); - //s = new String(c, 0, read); - //System.out.println("Last s=" + s + " read=" + read); - //nb = Integer.decode(s.substring(0,1)).intValue(); - //System.out.println("Last info=" + nb); - //nb= 3; - } - } catch(IOException io) { - throw new LauncherException(IO_ERROR); - } - - if (nb != 3) { - throw new LauncherException(FILE_FAILED); - } - return new String(ret); - } - - /*private String readDataUntilCompletionInfoLine() throws LauncherException { - int nb = 8; - String s = null; - StringBuffer ret = new StringBuffer(); - - - try { - //System.out.println("Reading data"); - while ((nb == 8) && ((s = in.readLine()) != null)) { - //System.out.println("read: " + s); - nb = Integer.decode(s.substring(0,1)).intValue(); - if (nb == 8) { - ret.append(s.substring(1, s.length()) + "\n"); - } - } - } catch(IOException io) { - throw new LauncherException(IO_ERROR); - } - - if (nb != 3) { - throw new LauncherException(FILE_FAILED); - } - - return new String(ret); - }*/ - - private int readReturn() throws LauncherException { - int nb; - String s = null; + // Read last info and check for success + readServerResponse(); +// +// if (nb != 3) { +// throw new LauncherException(FILE_FAILED); +// } + } - try { - //System.out.println("Reading line"); - s = in.readLine(); - TraceManager.addDev("Got from Server:" + s); - //System.out.println("Line read"); - //System.out.println("Converting nb s=>" + s + "<"); - nb = Integer.decode(s.substring(0,1)).intValue(); - //System.out.println("Nb = " + nb); - } catch(IOException io) { - System.out.println("Exception 0"); - throw new LauncherException(IO_ERROR); + return new String(ret); } - - if (nb != 3) { - System.out.println("Exception 1"); - throw new LauncherException(FILE_FAILED); + catch(IOException io) { + throw new LauncherException( IO_ERROR, io ); } - return nb; } - private int readId() throws LauncherException { - int nb; - String s = null; + private void readServerResponse() + throws LauncherException { + // int nb; + //String s = null; try { - s = in.readLine(); - nb = Integer.decode(s.substring(0,1)).intValue(); - } catch(IOException io) { - throw new LauncherException(IO_ERROR); + final String s = inReader.readLine(); + TraceManager.addDev("Got from Server:" + s); + + final ResponseCode code = SocketComHelper.responseCode( s ); + //nb = Integer.decode(s.substring(0,1)).intValue(); + + if ( code != ResponseCode.SUCCESS ) { + throw new LauncherException( FAILED ); + } } - - if (nb == 0) { - throw new LauncherException(ID_FAILED); + catch( IOException io ) { + throw new LauncherException( IO_ERROR, io ); } - - return nb; +// +// if (nb != 3) { +// System.out.println("Exception 1"); +// throw new LauncherException(FILE_FAILED); +// } +// return nb; } - private void readReturnPipedProcesses() throws LauncherException { - int nb; - String s = null; + private int readId() + throws LauncherException { +// int nb; +// String s = null; try { - s = in.readLine(); - nb = Integer.decode(s.substring(0,1)).intValue(); - } catch(IOException io) { - throw new LauncherException(IO_ERROR); - } + final String s = inReader.readLine(); + final int nb = Integer.decode(s.substring(0,1)); - if (nb != 3) { - throw new LauncherException(PROC_FAILED); + if ( nb == 0 ) { + throw new LauncherException(ID_FAILED); + } + + return nb; + } + catch( IOException io ) { + throw new LauncherException( IO_ERROR, io ); } +// +// return nb; } - - private int readPortString() throws LauncherException { - int nb; - String s = null; +// +// private void readReturnPipedProcesses() throws LauncherException { +//// int nb; +//// String s = null; +// try { +// final String s = inReader.readLine(); +// final ResponseCode code = SocketComHelper.responseCode( s ); +// //nb = Integer.decode(s.substring(0,1)).intValue(); +// +// if ( code != ResponseCode.SUCCESS ) { +// //if (nb != 3) { +// throw new LauncherException( PROC_FAILED ); +// } +// } +// catch(IOException io) { +// throw new LauncherException( IO_ERROR, io ); +// } +// } + + private void readPortString() throws LauncherException { + // int nb; + //String s = null; + try { - s = in.readLine(); - nb = Integer.decode(s.substring(0,1)).intValue(); - } catch(IOException io) { - throw new LauncherException(IO_ERROR); - } + final String s = inReader.readLine(); + final ResponseCode code = SocketComHelper.responseCode( s ); + //nb = Integer.decode(s.substring(0,1)).intValue(); - if (nb == 2) { - throw new LauncherException(PROC_FAILED); - } + if ( code == ResponseCode.FAILED ) { + //if (nb == 2) { + throw new LauncherException( PROC_FAILED ); + } - portString = -1; - portString2 = -1; - try { - portString = Integer.decode(s.substring(1, s.length())).intValue(); - } catch (Exception e) { - throw new LauncherException(IO_ERROR); - } + //portString = -1; + portString2 = -1; + + portString = Integer.decode( SocketComHelper.message( code, s ) );//// Integer.decode(s.substring(1, s.length())).intValue(); - if (portString <1) { - throw new LauncherException(PROC_FAILED); + if ( portString < 1) { + throw new LauncherException( PROC_FAILED ); + } + } + catch( IOException io ) { + throw new LauncherException( IO_ERROR, io ); } - - return portString; + } + + private void connect() + throws LauncherException { + clientSocket = connect( port ); + + try { + inReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + out = new PrintStream(clientSocket.getOutputStream()); + } + catch ( IOException ex ) { + throw new LauncherException(SERV_NOT_RESP+host, ex ); + } } - private void connect(int portNet) throws LauncherException { - InetAddress ina = null; - - //System.out.println("Connecting on port " + portNet); - + private Socket connect( final int portNet ) + throws LauncherException { if (host == null) { throw new LauncherException(NO_HOST); } try { - ina = InetAddress.getByName(host); - } catch (UnknownHostException e) { - throw new LauncherException(INET + host); - } + final InetAddress ina = InetAddress.getByName(host); - try { - clientSocket = new Socket(ina, portNet); - } catch (IOException io) { - throw new LauncherException(SERV_NOT_RESP+host); + try { + return new Socket( ina, portNet ); + } + catch ( IOException ex ) { + throw new LauncherException(SERV_NOT_RESP+host, ex ); + } } - - try { - in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); - //in2 = new DataInputStream(clientSocket.getInputStream()); - out = new PrintStream(clientSocket.getOutputStream()); - //System.out.println("Connected on port " + portNet); - } catch (Exception e) { - throw new LauncherException(SERV_NOT_RESP+host); + catch (UnknownHostException e) { + throw new LauncherException(INET + host, e ); } } - - /*private void basicConnect() throws LauncherException { - InetAddress ina = null; - - if (host == null) { - throw new LauncherException(NO_HOST); - } - - try { - ina = InetAddress.getByName(host); - } catch (UnknownHostException e) { - throw new LauncherException(INET + host); - } - - try { - clientSocket = new Socket(ina, port); - } catch (IOException io) { - throw new LauncherException(SERV_NOT_RESP+host); - } - - try { - in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); - //in2 = new DataInputStream(clientSocket.getInputStream()); - out = new PrintStream(clientSocket.getOutputStream()); - } catch (Exception e) { - throw new LauncherException(SERV_NOT_RESP+host); - } - }*/ - } diff --git a/src/launcher/RshServer.java b/src/launcher/RshServer.java index 5d982995cc..318cf882c7 100755 --- a/src/launcher/RshServer.java +++ b/src/launcher/RshServer.java @@ -55,6 +55,7 @@ import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; +import java.util.Iterator; import java.util.Vector; import myutil.AESEncryptor; @@ -65,7 +66,7 @@ public class RshServer { private int port = PORT_NUMBER; private ServerSocket server = null; - private int id = 0; + //private int id = 0; private Vector<ExecutionThread> processes; private int MAX_PROC = 255; public static final String VERSION = "0.61"; @@ -80,46 +81,50 @@ public class RshServer { public static String iv = "Wh4t4b0utThisKe?"; public RshServer() { - startingServer(); + startingServer(); } public RshServer(String _sk) { - sk = _sk; - startingServer(); + sk = _sk; + startingServer(); } private void startingServer() { - processes = new Vector<ExecutionThread>(); - int i = 0; - for(i=0; i<100; i++) { - try { - server = new ServerSocket(port+i); - break; - } catch (Exception e) { - //System.out.println("Server could not start(Socket pb)"); - } - } - if (i == 100) { - TraceManager.addDev("Launching external applications is disabled: no socket is available"); - } else { - port = port +i; - launcher.RshClient.PORT_NUMBER = port; - TraceManager.addDev("Using port: " + port); - } + processes = new Vector<ExecutionThread>(); + int i = 0; + + for(i=0; i < 100; i++) { + try { + server = new ServerSocket(port+i); + + break; + } + catch (Exception e) { + //System.out.println("Server could not start(Socket pb)"); + } + } + + if (i == 100) { + TraceManager.addDev("Launching external applications is disabled: no socket is available"); + } + else { + port = port +i; + launcher.RshClient.PORT_NUMBER = port; + TraceManager.addDev("Using port: " + port); + } } - public void setNonSecure() { isSecure = false; } public String getSecretKey() { - return sk; + return sk; } public String getIV() { - return iv; + return iv; } private void printProcessRunning() { @@ -145,22 +150,50 @@ public class RshServer { } private Socket waitForClient() { - Socket s = null; + //Socket s = null; TraceManager.addDev("Waiting for command"); + try { - s = server.accept(); - } catch (Exception e) { + return server.accept(); + } + catch (Exception e) { nbTry ++; + return null; } - return s; + // return s; + } + + private void respond( final PrintStream out, + final ResponseCode code ) { + respond( out, code, null ); + } + + private void respond( final PrintStream out, + final String message ) { + respond( out, null, message ); } - private void respond(PrintStream out, String s) { + private void respond( final PrintStream out, + final ResponseCode code, + final String message ) { try { - out.println(s); - out.flush(); - } catch (Exception e) { + SocketComHelper.send( out, code, message ); +// final StringBuilder sentMess = new StringBuilder(); +// +// if ( code != null ) { +// sentMess.append( code.name() ); +// } +// +// if ( message != null ) { +// sentMess.append( message ); +// } +// +// out.println( sentMess.toString() ); +// out.flush(); + } + catch (Exception e) { + TraceManager.addError( e ); } } @@ -173,7 +206,7 @@ public class RshServer { // } // } - private int startNewProcess(String path) { + private int startNewProcess( String path ) { if (processes.size() >= MAX_PROC) { return -1; } @@ -192,7 +225,7 @@ public class RshServer { } - private int createNewProcess(String path) { + private int createNewProcess( final String path ) { if (processes.size() >= MAX_PROC) { return -1; } @@ -220,18 +253,26 @@ public class RshServer { } private boolean startProcess(int id) { - ExecutionThread et; - for(int i=0; i<processes.size(); i++) { - et = (ExecutionThread)(processes.elementAt(i)); - if (et.getPort() == id) { - if (et.isStarted()) { - return false; - } - et.start(); - return true; - } + ExecutionThread et = getExecutionThread( id ); + + if ( et == null || et.isStarted() ) { + return false; } - return false; + + et.start(); + + return true; +// for(int i=0; i<processes.size(); i++) { +// et = (ExecutionThread)(processes.elementAt(i)); +// if (et.getPort() == id) { +// if (et.isStarted()) { +// return false; +// } +// et.start(); +// return true; +// } +// } +// return false; } private ExecutionThread getExecutionThread(int id) { @@ -280,28 +321,46 @@ public class RshServer { printProcessRunning(); } - public void killProcess(int id) { + public boolean killProcess(int id) { ExecutionThread et; for(int i=0; i<processes.size(); i++) { et = processes.elementAt(i); + if (et.getPort() == id) { et.stopProcess(); processes.removeElement(et); TraceManager.addDev("Process " + id + " killed"); - return; + + return true; } } + printProcessRunning(); + + return false; } public void killAllProcesses() { - ExecutionThread et; - for(int i=0; i<processes.size(); i++) { - et = processes.elementAt(i); - et.stopProcess(); - processes.removeElement(et); - TraceManager.addDev("Process " + id + " killed"); + //ExecutionThread et; + final Iterator<ExecutionThread> procIt = processes.iterator(); + + while ( procIt.hasNext() ) { + final ExecutionThread et = procIt.next(); + et.stopProcess(); + procIt.remove(); + + TraceManager.addDev( "Process " + et.getId() + " killed." ); } + + // DB: Issue #18: This code does not iterate through all the elements because process.size() changes at every iteration +// ExecutionThread et; +// for(int i=0; i<processes.size(); i++) { +// et = processes.elementAt(i); +// et.stopProcess(); +// processes.removeElement(et); +// TraceManager.addDev("Process " + id + " killed"); +// } + printProcessRunning(); } @@ -320,114 +379,221 @@ public class RshServer { try { info = in.readLine(); - } catch (Exception e) { - TraceManager.addDev("Exception when reading client information=" + info); - return; + } + catch (Exception e) { + TraceManager.addError("Exception when reading client information=" + info, e ); + + return; } if (sk != null) { info = checkSecurity(info); - } - TraceManager.addDev("Got from client:" + info); + TraceManager.addDev("Got from client:" + info); - if (info != null) { + if ( info != null ) { + final RequestCode reqCode = SocketComHelper.requestCode( info ); + TraceManager.addDev("Received request code " + reqCode + "." ); + final String message = SocketComHelper.message( reqCode, info ); + TraceManager.addDev("Received request message '" + message + "'." ); - if (info.substring(0, 1).equals("0")) { // Session id - if (info.substring(1, 2).equals("0")) { // Get session id + switch ( reqCode ) { + // Session id + case GET_SESSION_ID: { +// if (info.substring(0, 1).equals("0")) { // Session id + //if (info.substring(1, 2).equals("0")) { // Get session id int id = getSessionId(); TraceManager.addDev("-> New session id = " + id); - respond(out, ""+id); // A zero response means error - } else { + respond(out, "" + id ); // A zero response means error + + break; + } + case FREE_SESSION_ID: { + //} else { try { - int id = Integer.decode(info.substring(1, 2)).intValue(); - freeSessionId(id); - TraceManager.addDev("-> Session id=" + id + " terminated"); - respond(out, ""+id); - } catch (Exception e) { - respond(out, "0"); + int id = Integer.decode( message );//.intValue(); + freeSessionId( id ); + TraceManager.addDev("-> Free session id=" + id + " terminated"); + respond( out, "" + id ); } - } - } else if (info.substring(0, 1).equals("1")) { - // start process at once - int id = startNewProcess(info.substring(1, info.length())); - if (id <0) { - respond(out, "2"); // fail - } else { - TraceManager.addDev("Process accepted on port " + id); - respond(out, "3" + id); // process created - } - } else if (info.substring(0, 1).equals("2")) { - // Piped processes - TraceManager.addDev("Piped processes"); - String str = info.substring(1, info.length()); - String str1, str2; - int index = str.indexOf(' '); - TraceManager.addDev("index = " + index); - if (index > 0) { - str1 = str.substring(0, index); - str2 = str.substring(index + 1, str.length()); - TraceManager.addDev("str = " + str + " str1 = *" + str1 + "* str2 = *" + str2 + "*"); - if (pipeProcesses(str1, str2)) { - TraceManager.addDev("Making piped processes"); - respond(out, "3"); // OK - } else { - TraceManager.addDev("Making piped processes FAILED"); - respond(out, "2"); // fail + catch ( Exception e ) { + respond( out, ResponseCode.FAILED ); + + TraceManager.addError( e ); } - } else { - TraceManager.addDev("Making piped processes FAILED"); - respond(out, "2"); // fail + + break; } - - } else if (info.substring(0, 1).equals("3")) { + case PROCESS_CREATE_START: { + //} else if (info.substring(0, 1).equals("1")) { + // start process at once + int id = startNewProcess( message );//info.substring(1, info.length())); + + if ( id < 0 ) { + respond(out, ResponseCode.FAILED ); // fail + } + else { + TraceManager.addDev("Process accepted on port " + id); + respond( out, ResponseCode.SUCCESS, Integer.toString( id ) ); // process created + } + + break; + } + case PROCESS_CHECK_RETURN_CODE: { + final ExecutionThread process = getExecutionThread( Integer.decode( message ) ); + + if ( process == null ) { + TraceManager.addError( "Process " + message + " not created!" ); + respond( out, ResponseCode.FAILED ); + } + else { + TraceManager.addDev("Process " + message + " will send its return code." ); + process.setSendReturnCode( true ); + respond( out, ResponseCode.SUCCESS ); // process created + } + + break; + } + case PROCESS_GET_RETURN_CODE: { + final ExecutionThread process = getExecutionThread( Integer.decode( message ) ); + + if ( process == null ) { + TraceManager.addError( "Process " + message + " not created!" ); + respond( out, ResponseCode.FAILED ); + } + else { + final String retCodeStr = String.valueOf( process.getReturnCode() ); + TraceManager.addDev("Sending return code " + retCodeStr + " for process " + message + "." ); + respond( out, ResponseCode.SUCCESS, retCodeStr ); + } + + break; + } + case PROCESS_PIPE: { + //else if (info.substring(0, 1).equals("2")) { + // Piped processes + TraceManager.addDev("Piped processes."); + //String str = info.substring(1, info.length()); + //String str1, str2; + final int index = message.indexOf(' '); + //TraceManager.addDev("index = " + index); + + if (index > 0) { + final String str1 = message.substring(0, index); + final String str2 = message.substring(index + 1 ); + TraceManager.addDev("str = " + message + " str1 = *" + str1 + "* str2 = *" + str2 + "*"); + + if (pipeProcesses(str1, str2)) { + TraceManager.addDev("Making piped processes..."); + respond( out, ResponseCode.SUCCESS ); // OK + } + else { + TraceManager.addDev("Making piped processes failed!"); + respond(out, ResponseCode.FAILED ); // fail + } + } + else { + TraceManager.addDev("Making piped processes FAILED"); + respond(out, ResponseCode.FAILED ); // fail + } + + break; + } + case PROCESS_CREATE: { + // } else if (info.substring(0, 1).equals("3")) { // create process - int id = createNewProcess(info.substring(1, info.length())); - if (id <0) { - respond(out, "2"); // fail - } else { - TraceManager.addDev("Process accepted on port " + id); - respond(out, "3" + id); // process created - } - } else if (info.substring(0, 1).equals("4")) { + int id = createNewProcess( message ); + + if ( id < 0 ) { + respond( out, ResponseCode.FAILED ); // fail + } + else { + TraceManager.addDev( "Process accepted on port " + id ); + respond( out, ResponseCode.SUCCESS, Integer.toString( id ) ); // process created + } + + break; + } + case PROCESS_START: { + //} else if (info.substring(0, 1).equals("4")) { // start already created process - if (startProcess(info.substring(1, info.length()))) { - TraceManager.addDev("Process started on port " + id); - respond(out, "3" + id); // process created - } else { - respond(out, "2"); // fail - } - } else if (info.substring(0, 1).equals("5")) { - // kill all processes - try { - killAllProcesses(); - } catch (Exception e) { - - } - }else if (info.substring(0, 1).equals("6")) { + if ( startProcess( message ) ) { + TraceManager.addDev("Process started on port " + message ); + respond(out, ResponseCode.SUCCESS, message ); // process created + } + else { + respond( out, ResponseCode.FAILED ); // fail + } + + break; + } + case PROCESS_KILL_ALL: { + //} else if (info.substring(0, 1).equals("5")) { + // kill all processes + try { + killAllProcesses(); + + respond( out, ResponseCode.SUCCESS ); + } + catch (Exception e) { + TraceManager.addError( e ); + + respond( out, ResponseCode.FAILED ); // fail + } + + break; + } + case PROCESS_KILL: { + //}else if (info.substring(0, 1).equals("6")) { // kill process - try { - int id = Integer.decode(info.substring(1, info.length())).intValue(); - TraceManager.addDev("Demand to kill: " + id); - killProcess(id); - } catch (Exception e) { - - } - } else if (info.substring(0, 1).equals("7")) { - //file : put - String fileName = info.substring(1, info.length()); - makeFileFromData(in, out, fileName); - } else if (info.substring(0, 1).equals("8")) { - //file : get - String fileName = info.substring(1, info.length()); - sendDataFile(in, out, fileName); - } else if (info.substring(0, 1).equals("9")) { - //file : delete - String fileName = info.substring(1, info.length()); - deleteFile(in, out, fileName); - } else { - System.exit(0); + try { + int id = Integer.decode( message ); + TraceManager.addDev("Demand to kill: " + id); + + if ( killProcess( id ) ) { + respond( out, ResponseCode.SUCCESS ); + } + else { + respond( out, ResponseCode.FAILED ); + } + } + catch (Exception e) { + TraceManager.addError( e ); + + respond( out, ResponseCode.FAILED ); // fail + } + + break; + } + case FILE_PUT: { + //} else if (info.substring(0, 1).equals("7")) { + //file : put + //String fileName = info.substring(1, info.length()); + makeFileFromData( in, out, message ); + + break; + } + case FILE_GET: { +// } else if (info.substring(0, 1).equals("8")) { + //file : get + //String fileName = info.substring(1, info.length()); + sendDataFile( in, out, message ); + + break; + } + case FILE_DELETE: { + //} else if (info.substring(0, 1).equals("9")) { + //file : delete + //String fileName = info.substring(1, info.length()); + deleteFile( in, out, message ); + + break; + } + default: + //} else { + // TODO: Is this really a good behavior? + System.exit(0); } } } @@ -438,7 +604,8 @@ public class RshServer { if (!isFileOkForSave(file)) { TraceManager.addDev("Cannot make file"); - respond(out, "2"); // fail + respond( out, ResponseCode.FAILED ); // fail + return; } @@ -446,52 +613,75 @@ public class RshServer { String info; TraceManager.addDev("Waiting for file data"); - while(true) { + + while( true ) { try { info = in.readLine(); - } catch (Exception e) { - return; + } + catch (Exception e) { + TraceManager.addError( e ); + + return; } - if (sk != null) { - info = checkSecurity(info); - } + if ( sk != null ) { + info = checkSecurity(info); + } + + final RequestCode code = SocketComHelper.requestCode( info ); + final String message = SocketComHelper.message( code, info ); - if ((info == null) || (info.length() == 0)) { + if ( code == null || code == RequestCode.FILE_SAVE ) {//|| (info.length() == 0)) { // Assumes it is an EOF TraceManager.addDev("Wrong EOF -> assumes it is an EOF"); + try { FileOutputStream fos = new FileOutputStream(file); fos.write((new String(fileData)).getBytes()); fos.close(); - } catch (Exception e) { - TraceManager.addDev("Error when feeding file"); - respond(out, "2"); // fail + } + catch (Exception e) { + TraceManager.addError("Error when feeding file", e ); + + respond( out, ResponseCode.FAILED ); // fail + return; } - respond(out, "3"); // file created + + respond( out, ResponseCode.SUCCESS ); // file created + return; - } else if (info.substring(0, 1).equals("8")) { + } + else if ( code == RequestCode.FILE_APPEND ) {//== info.substring(0, 1).equals("8")) { // fileData - fileData.append(info.substring(1, info.length()) + "\n"); - } else if (info.substring(0, 1).equals("7")) { - // EOF - TraceManager.addDev("EOF"); - try { - FileOutputStream fos = new FileOutputStream(file); - fos.write((new String(fileData)).getBytes()); - fos.close(); - } catch (Exception e) { - TraceManager.addDev("Error when feeding file"); - respond(out, "2"); // fail - return; - } - respond(out, "3"); // file created - return; - } else { + fileData.append( message + "\n" ); + } +// else if ( code == RequestCode.FILE_SAVE ) { +// // EOF +// TraceManager.addDev("EOF"); +// +// try { +// FileOutputStream fos = new FileOutputStream(file); +// fos.write((new String(fileData)).getBytes()); +// fos.close(); +// } +// catch (Exception e) { +// TraceManager.addError("Error when feeding file", e ); +// +// respond( out, ResponseCode.FAILED ); // fail +// +// return; +// } +// +// respond( out, ResponseCode.SUCCESS ); // file created +// +// return; +// } + else { TraceManager.addDev("Unknown PDU (file)=" + info); - respond(out, "2"); // fail + respond( out, ResponseCode.FAILED ); // fail + return; } } @@ -502,31 +692,30 @@ public class RshServer { File file = new File(fileName); if (!isFileOkForRead(file)) { - //System.out.println("Cannot read file"); - respond(out, "2"); // fail + respond( out, ResponseCode.FAILED ); // fail + return; } try { FileInputStream fis = new FileInputStream(file); - /*int nb = fis.available(); - System.out.println("New byte " + fileName); - byte [] ba = new byte[nb]; - fis.read(ba); - System.out.println("Reading " + fileName); - fis.close();*/ if (sendData(out, fis)) { //System.out.println("Sending 3 info to say OK"); - respond(out, "3"); - } else { + respond( out, ResponseCode.SUCCESS ); + } + else { TraceManager.addDev("Sending failed"); - respond(out, "2"); + respond( out, ResponseCode.FAILED ); } - } catch(Exception e) { - respond(out, "2"); // fail + } + catch(Exception e) { + TraceManager.addError( e ); + respond( out, ResponseCode.FAILED ); // fail + return; } + TraceManager.addDev("Sending completed"); } @@ -536,11 +725,15 @@ public class RshServer { try { file.delete(); - } catch(Exception e) { - respond(out, "2"); // fail + + respond( out, ResponseCode.SUCCESS ); + } + catch(Exception e) { + TraceManager.addError( e ); + respond( out, ResponseCode.FAILED ); // fail + return; } - respond(out, "3"); } public void startServer() { @@ -573,9 +766,11 @@ public class RshServer { return false; } } catch (Exception e) { - System.out.println("Exception file " + e.getMessage()); - return false; + TraceManager.addError( "Exception file " + e.getMessage(), e ); + + return false; } + return true; } @@ -588,16 +783,18 @@ public class RshServer { try { if (!file.exists()) { if (!file.createNewFile()) { - TraceManager.addDev("creation pb"); + TraceManager.addError("creation pb"); return false; } } if (!file.canWrite()) { - TraceManager.addDev("write pb"); + TraceManager.addError("write pb"); return false; } - } catch (Exception e) { - System.out.println("Exception file " + e.getMessage()); + } + catch (Exception e) { + TraceManager.addError( e ); + return false; } @@ -614,7 +811,8 @@ public class RshServer { //BufferedReader br = new BufferedReader(sr); try { // Sending first line : 8 + nbByte - respond(out, new String("8" + fis.available())); + respond(out, ResponseCode.FILE_DATA, Integer.toString( fis.available() ) ); +// respond(out, new String("8" + fis.available())); int cpt = 0; while((nbRead = fis.read(ba, 0, BUFSIZE)) > -1) { @@ -622,29 +820,32 @@ public class RshServer { out.write(ba, 0, nbRead); cpt += nbRead; } + TraceManager.addDev("Nb written:" + cpt); fis.close(); - } catch (Exception e) { - TraceManager.addDev("Exception when sending file: " + e.getMessage()); + } + catch (Exception e) { + TraceManager.addError( "Exception when sending file: " + e.getMessage(), e ); + return false; } + return true; } private String checkSecurity(String _ciphered) { - if (!isSecure) { - return _ciphered; // The string is in fact not ciphered - } - - if (sk == null) { - return null; - } - - String deciphered = AESEncryptor.decrypt(sk, iv, _ciphered); - - TraceManager.addDev("Deciphered=" + deciphered); - return deciphered; + if (!isSecure) { + return _ciphered; // The string is in fact not ciphered + } + + if (sk == null) { + return null; + } + + String deciphered = AESEncryptor.decrypt(sk, iv, _ciphered); + TraceManager.addDev("Deciphered=" + deciphered); + return deciphered; } } diff --git a/src/ui/window/JDialogSystemCGeneration.java b/src/ui/window/JDialogSystemCGeneration.java index 2e58d14652..baad7eac42 100755 --- a/src/ui/window/JDialogSystemCGeneration.java +++ b/src/ui/window/JDialogSystemCGeneration.java @@ -59,6 +59,7 @@ import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; +import java.util.List; import java.util.Vector; import javax.swing.ButtonGroup; @@ -74,6 +75,8 @@ import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ListSelectionModel; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; @@ -84,34 +87,29 @@ import myutil.GraphicLib; import myutil.MasterProcessInterface; import myutil.ScrolledJTextArea; import myutil.TraceManager; -//import ui.ebrdd.*; import req.ebrdd.EBRDD; import tepe.TEPE; -import tmltranslator.tomappingsystemc2.IDiploSimulatorCodeGenerator; import tmltranslator.tomappingsystemc2.DiploSimulatorFactory; +import tmltranslator.tomappingsystemc2.IDiploSimulatorCodeGenerator; import ui.AvatarRequirementPanelTranslator; import ui.IconManager; +import ui.JTextAreaWriter; import ui.MainGUI; import ui.avatarpd.AvatarPDPanel; - public class JDialogSystemCGeneration extends javax.swing.JDialog implements ActionListener, Runnable, MasterProcessInterface, ListSelectionListener { protected MainGUI mgui; - private static String textSysC1 = "Generate SystemC code in"; - private static String textSysC2 = "Compile SystemC code in"; - //private String textSysC3 = "with"; + private static String textSysC1 = "Generate C++ simulator code in"; + private static String textSysC2 = "Compile C++ simulator code in"; private static String textSysC4 = "Run simulation to completion:"; private static String textSysC5 = "Run interactive simulation:"; private static String textSysC6 = "Run formal verification:"; - private static String unitCycle = "1"; - - /*private static String[] simus = { "SystemC Simulator - LabSoC version", - "C++ Simulator - LabSoc version" };*/ + private static float unitCycleValue = 1; - private static String[] simus = { "C++ Simulator - LabSoc version" }; + private static String[] simus = { "Diplodocus C++ Simulator - LabSoc version" }; private static int selectedItem = 0; @@ -130,10 +128,9 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act protected final static int ERROR=4; int mode; - - //components protected JTextArea jta; + private JTextAreaWriter textAreaWriter; protected JButton start; protected JButton stop; protected JButton close; @@ -142,46 +139,29 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act protected ButtonGroup exegroup; protected JLabel gen, comp; protected JTextField code1, code2, unitcycle, compiler1, exe1, exe2, exe3, exe2int, exe2formal; - protected JTabbedPane jp1; + protected JTabbedPane tabbedPane; protected JScrollPane jsp; protected JCheckBox removeCppFiles, removeXFiles, debugmode, optimizemode; - protected JComboBox versionSimulator; - - //EBRDD - /*private static Vector validated, ignored; - private Vector val, ign; - private JList listIgnored; - private JList listValidated; - private JButton allValidated; - private JButton addOneValidated; - private JButton addOneIgnored; - private JButton allIgnored; - private JPanel panele1, panele2, panele3, panele4, panel5, panel6;*/ - + protected JComboBox<String> versionSimulator; //TEPED - private static Vector validatedTepe, ignoredTepe; - private Vector valTepe, ignTepe; - private JList listIgnoredTepe; - private JList listValidatedTepe; + private static Vector<AvatarPDPanel> validatedTepe, ignoredTepe; + private Vector<AvatarPDPanel> valTepe, ignTepe; + private JList<AvatarPDPanel> listIgnoredTepe; + private JList<AvatarPDPanel> listValidatedTepe; private JButton allValidatedTepe; private JButton addOneValidatedTepe; private JButton addOneIgnoredTepe; private JButton allIgnoredTepe; - private JPanel panele1Tepe, panele2Tepe, panele3Tepe, panele4Tepe, panel5Tepe, panel6Tepe; - - - + private JPanel panele1Tepe, panele2Tepe, panele3Tepe, panele4Tepe;//, panel5Tepe, panel6Tepe; private Thread t; private boolean go = false; - //private ProcessThread pt; - private boolean hasError = false; +// private boolean hasError = false; + private int errorTabIndex = -1; protected boolean startProcess = false; - //private TURTLE2Java t2j; - - private String hostSystemC; + private String simulatorHost; protected RshClient rshc; @@ -196,7 +176,7 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act /** Creates new form */ - public JDialogSystemCGeneration(Frame f, MainGUI _mgui, String title, String _hostSystemC, String _pathCode, String _pathCompiler, String _pathExecute, String _pathInteractiveExecute, String _graphPath, int _automatic) { + public JDialogSystemCGeneration(Frame f, MainGUI _mgui, String title, String _simulatorHost, String _pathCode, String _pathCompiler, String _pathExecute, String _pathInteractiveExecute, String _graphPath, int _automatic) { super(f, title, true); mgui = _mgui; @@ -228,7 +208,7 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act } } - hostSystemC = _hostSystemC; + simulatorHost = _simulatorHost; automatic = _automatic; @@ -238,7 +218,6 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act myInitComponents(); pack(); - //getGlassPane().addMouseListener( new MouseAdapter() {}); getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if (automatic > 0) { @@ -248,17 +227,17 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act protected void makeLists() { if (validatedTepe == null) { - validatedTepe = new Vector(); + validatedTepe = new Vector<AvatarPDPanel>(); } if (ignoredTepe == null) { - ignoredTepe = new Vector(); + ignoredTepe = new Vector<AvatarPDPanel>(); } - valTepe = new Vector(); - ignTepe = new Vector(); + valTepe = new Vector<AvatarPDPanel>(); + ignTepe = new Vector<AvatarPDPanel>(); - ArrayList<AvatarPDPanel> al = mgui.getAllAvatarPDPanels(); + final List<AvatarPDPanel> al = mgui.getAllAvatarPDPanels(); for(AvatarPDPanel panel: al) { if(validatedTepe.contains(panel)) { @@ -284,7 +263,7 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act c.setLayout(new BorderLayout()); //setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - jp1 = new JTabbedPane(); + tabbedPane = new JTabbedPane(); JPanel jp01 = new JPanel(); GridBagLayout gridbag01 = new GridBagLayout(); @@ -313,7 +292,6 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act c01.gridheight = 1; gen = new JLabel(textSysC1); - //genJava.addActionListener(this); jp01.add(gen, c01); code1 = new JTextField(pathCode, 100); @@ -325,7 +303,7 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act c01.gridwidth = GridBagConstraints.REMAINDER; //end row jp01.add(new JLabel("1 time unit = "), c01); - unitcycle = new JTextField(unitCycle, 10); + unitcycle = new JTextField( Float.toString( unitCycleValue ), 10); jp01.add(unitcycle, c01); jp01.add(new JLabel("cycle"), c01); @@ -348,11 +326,10 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act jp01.add(new JLabel("Simulator used:"), c01); - versionSimulator = new JComboBox(simus); + versionSimulator = new JComboBox<String>(simus); versionSimulator.setSelectedIndex(selectedItem); versionSimulator.addActionListener(this); jp01.add(versionSimulator, c01); - //System.out.println("selectedItem=" + selectedItem); //devmode = new JCheckBox("Development version of the simulator"); //devmode.setSelected(true); @@ -364,7 +341,7 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act panele1Tepe = new JPanel(); panele1Tepe.setLayout(new BorderLayout()); panele1Tepe.setBorder(new javax.swing.border.TitledBorder("Ignored TEPE Diagrams")); - listIgnoredTepe = new JList(ignTepe); + listIgnoredTepe = new JList<AvatarPDPanel>(ignTepe); //listIgnored.setPreferredSize(new Dimension(200, 250)); listIgnoredTepe.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); listIgnoredTepe.addListSelectionListener(this); @@ -376,7 +353,7 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act panele2Tepe = new JPanel(); panele2Tepe.setLayout(new BorderLayout()); panele2Tepe.setBorder(new javax.swing.border.TitledBorder("TEPE Diagrams taken into account")); - listValidatedTepe = new JList(valTepe); + listValidatedTepe = new JList<AvatarPDPanel>(valTepe); //listValidated.setPreferredSize(new Dimension(200, 250)); listValidatedTepe.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); listValidatedTepe.addListSelectionListener(this); @@ -435,7 +412,7 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act //GraphicLib.enableComponents(jp01, false); } - jp1.add("Generate code", jp01); + tabbedPane.add("Generate code", jp01); // Panel 02 c02.gridheight = 1; @@ -446,7 +423,6 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act c02.gridheight = 1; comp = new JLabel(textSysC2); - //compJava.addActionListener(this); jp02.add(comp, c02); code2 = new JTextField(pathCode, 100); @@ -459,7 +435,7 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act jp02.add(new JLabel(" "), c02); - jp1.add("Compile", jp02); + tabbedPane.add("Compile", jp02); // Panel 03 c03.gridheight = 1; @@ -473,7 +449,6 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act exe = new JRadioButton(textSysC4, false); exe.addActionListener(this); exegroup.add(exe); - //exeJava.addActionListener(this); jp03.add(exe, c03); exe2 = new JTextField(pathExecute, 100); @@ -484,7 +459,6 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act exeint = new JRadioButton(textSysC5, true); exeint.addActionListener(this); exegroup.add(exeint); - //exeJava.addActionListener(this); jp03.add(exeint, c03); exe2int = new JTextField(pathInteractiveExecute, 100); jp03.add(exe2int, c02); @@ -499,23 +473,33 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act jp03.add(new JLabel(" "), c03); - jp1.add("Execute", jp03); + tabbedPane.add("Execute", jp03); - c.add(jp1, BorderLayout.NORTH); + c.add(tabbedPane, BorderLayout.NORTH); if (automatic > 0) { - //GraphicLib.enableComponents(jp03, false); - GraphicLib.enableComponents(jp1, false); + GraphicLib.enableComponents(tabbedPane, false); } + + // Issue #18 + tabbedPane.addChangeListener( new ChangeListener() { + + @Override + public void stateChanged(ChangeEvent e) { + setButtons(); + } + } ); jta = new ScrolledJTextArea(); jta.setEditable(false); jta.setMargin(new Insets(10, 10, 10, 10)); jta.setTabSize(3); if (automatic == 0) { - jta.append("Select options and then, click on 'start' to launch SystemC code generation / compilation\n"); + jta.append("Select options and then, click on 'start' to launch simulator C++ code generation / compilation\n"); } Font f = new Font("Courrier", Font.BOLD, 12); jta.setFont(f); + textAreaWriter = new JTextAreaWriter( jta ); + jsp = new JScrollPane(jta, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); c.add(jsp, BorderLayout.CENTER); @@ -589,6 +573,7 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act if (mode == STARTED) { stopProcess(); } + updateStaticList(); optimizeModeSelected = optimizemode.isSelected(); wasClosed = true; @@ -601,7 +586,7 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act public void stopProcess() { try { - rshc.stopFillJTA(); + rshc.stopCommand(); } catch (LauncherException le) { } @@ -634,71 +619,83 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act } private void testGo() throws InterruptedException { - if (go == false) { + if ( !go ) { throw new InterruptedException("Stopped by user"); } } + + private boolean hasError() { + return errorTabIndex > -1; + } + + private void resetError() { + mode = NOT_STARTED; + errorTabIndex = - 1; + } + + private boolean canSwitchNextTab() { + return !hasError() && tabbedPane.getSelectedIndex() < 2; + } + + private boolean canExecute() { + return errorTabIndex < 0 || tabbedPane.getSelectedIndex() <= errorTabIndex; + } public void run() { - // String cmd; - // String data; - - - hasError = false; - try { - - if (automatic > 0) { - + if ( automatic > 0 ) { generateCode(); testGo(); - compileCode(); - testGo(); - executeSimulation(); - - } else { - - - // Code generation - if (jp1.getSelectedIndex() == 0) { - generateCode(); - } - - testGo(); - - - // Compilation - if (jp1.getSelectedIndex() == 1) { - compileCode(); - + + if ( canExecute() ) { + compileCode(); + + if ( canExecute() ) { + testGo(); + executeSimulation(); + } } - - if (jp1.getSelectedIndex() == 2) { - executeSimulation(); - } - - if ((hasError == false) && (jp1.getSelectedIndex() < 2)) { - jp1.setSelectedIndex(jp1.getSelectedIndex() + 1); + } + else { + if ( canExecute() ) { + resetError(); + + if ( tabbedPane.getSelectedIndex() == 0 ) { + generateCode(); + } + else if ( tabbedPane.getSelectedIndex() == 1 ) { + compileCode(); + } + else { + executeSimulation(); + } + + if ( canSwitchNextTab() ) { + tabbedPane.setSelectedIndex( tabbedPane.getSelectedIndex() + 1 ); + } } - } - - } catch (InterruptedException ie) { + } + catch (InterruptedException ie) { jta.append("Interrupted\n"); } - jta.append("\n\nReady to process next command\n"); + if ( hasError() ) { + jta.append("\nAn error occured when processing command!\n"); + } + else { + jta.append("\nReady to process next command.\n"); + } - checkMode(); + //updateMode(); setButtons(); - - //System.out.println("Selected item=" + selectedItem); } - private void generateCode() throws InterruptedException { + private void generateCode() + throws InterruptedException { String list; - jta.append("Generating SystemC code\n"); + jta.append("Generating simulator C++ code\n"); if (removeCppFiles.isSelected()) { jta.append("Removing all old h files\n"); @@ -728,118 +725,165 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act } testGo(); - - try { - unitCycle = unitcycle.getText(); - } - catch ( Exception e) { - jta.append("Wrong number of cycles: " + unitcycle.getText()); - jta.append("Aborting"); - jta.append("\n\nReady to process next command\n"); - checkMode(); - setButtons(); - - return; + + if ( !validateData() ) { + return; } +// try { +// defaultUnitCycleValue = unitcycle.getText(); +// } +// catch ( final Throwable th ) { +// final String message = "Wrong number of cycles: " + unitcycle.getText() + "!"; +// jta.append( message ); +// jta.append("Aborting"); +// jta.append("\n\nReady to process next command\n"); +// //checkMode(); +// TraceManager.addError( message, th ); +// setError(); +// +// return; +// } + selectedItem = versionSimulator.getSelectedIndex(); switch( selectedItem ) { //Old SystemC generator - case 0: { //Simulator without CPs (Daniel's version) - // Making EBRDDs - ArrayList<EBRDD> al = new ArrayList<EBRDD>(); - ArrayList<TEPE> alTepe = new ArrayList<TEPE>(); - TEPE tepe; - AvatarRequirementPanelTranslator arpt = new AvatarRequirementPanelTranslator(); - for(int k=0; k<valTepe.size(); k++) { - testGo(); - tepe = arpt.generateTEPESpecification((AvatarPDPanel)(valTepe.get(k))); - jta.append("TEPE: " + tepe.getName() + "\n"); - jta.append("Checking syntax\n"); - // tepe.checkSyntax(); - alTepe.add(tepe); - jta.append("Done.\n"); - } - - final IDiploSimulatorCodeGenerator tml2systc; - - // Generating code - if (mgui.gtm.getTMLMapping() == null) { - if (mgui.gtm.getArtificialTMLMapping() == null) { - tml2systc = DiploSimulatorFactory.INSTANCE.createCodeGenerator( mgui.gtm.getTMLModeling(), al, alTepe ); - //tml2systc = new tmltranslator.tomappingsystemc2.TML2MappingSystemC(mgui.gtm.getTMLModeling(), al, alTepe); - } - else { - TraceManager.addDev("Using artifical mapping"); - tml2systc = DiploSimulatorFactory.INSTANCE.createCodeGenerator( mgui.gtm.getArtificialTMLMapping(), al, alTepe ); - //tml2systc = new tmltranslator.tomappingsystemc2.TML2MappingSystemC(mgui.gtm.getArtificialTMLMapping(), al, alTepe); - } - } - else { - tml2systc = DiploSimulatorFactory.INSTANCE.createCodeGenerator( mgui.gtm.getTMLMapping(), al, alTepe ); -// tml2systc = new tmltranslator.tomappingsystemc2.TML2MappingSystemC(mgui.gtm.getTMLMapping(), al, alTepe); - } - - try { - tml2systc.generateSystemC(debugmode.isSelected(), optimizemode.isSelected()); - testGo(); - jta.append("SystemC code generation done\n"); + case 0: { //Simulator without CPs (Daniel's version) + // Making EBRDDs + List<EBRDD> al = new ArrayList<EBRDD>(); + List<TEPE> alTepe = new ArrayList<TEPE>(); + TEPE tepe; + AvatarRequirementPanelTranslator arpt = new AvatarRequirementPanelTranslator(); + + for(int k=0; k<valTepe.size(); k++) { + testGo(); + tepe = arpt.generateTEPESpecification( valTepe.get(k) ); + jta.append("TEPE: " + tepe.getName() + "\n"); + jta.append("Checking syntax\n"); + // tepe.checkSyntax(); + alTepe.add(tepe); + jta.append("Done.\n"); + } - for(TEPE tep: alTepe) { - TraceManager.addDev(tep.toString()); + final IDiploSimulatorCodeGenerator tml2systc; + + // Generating code + if (mgui.gtm.getTMLMapping() == null) { + if (mgui.gtm.getArtificialTMLMapping() == null) { + tml2systc = DiploSimulatorFactory.INSTANCE.createCodeGenerator( mgui.gtm.getTMLModeling(), al, alTepe ); + //tml2systc = new tmltranslator.tomappingsystemc2.TML2MappingSystemC(mgui.gtm.getTMLModeling(), al, alTepe); + } + else { + TraceManager.addDev("Using artifical mapping"); + tml2systc = DiploSimulatorFactory.INSTANCE.createCodeGenerator( mgui.gtm.getArtificialTMLMapping(), al, alTepe ); + //tml2systc = new tmltranslator.tomappingsystemc2.TML2MappingSystemC(mgui.gtm.getArtificialTMLMapping(), al, alTepe); + } + } + else { + tml2systc = DiploSimulatorFactory.INSTANCE.createCodeGenerator( mgui.gtm.getTMLMapping(), al, alTepe ); + // tml2systc = new tmltranslator.tomappingsystemc2.TML2MappingSystemC(mgui.gtm.getTMLMapping(), al, alTepe); } - jta.append("Generating SystemC file\n"); - pathCode = code1.getText(); - tml2systc.saveFile(pathCode, "appmodel"); - jta.append("SystemC files generated\n"); - } - catch ( final Exception ex ) { - final String message = "Could not generate simulator code!"; - jta.append( message + System.lineSeparator() ); - TraceManager.addError( message );ex.printStackTrace(); - } - break; - } + + try { + tml2systc.generateSystemC(debugmode.isSelected(), optimizemode.isSelected()); + testGo(); + jta.append("Simulator code generation done\n"); + + for( final TEPE tep : alTepe ) { + TraceManager.addDev( tep.toString() ); + } + + jta.append("Saving C++ files...\n"); + + pathCode = code1.getText(); + tml2systc.saveFile(pathCode, "appmodel"); + + jta.append( "C++ files saved." + System.lineSeparator() ); + } + catch ( final Throwable th ) { + final String message = "Could not generate simulator code!"; + jta.append( System.lineSeparator() + message + System.lineSeparator() ); + + TraceManager.addError( message, th ); + setError(); + } + + break; + } } } //End of method generateCode() - public void compileCode() throws InterruptedException { + private boolean validateData() { + switch ( tabbedPane.getSelectedIndex() ) { + case 0: { + try { + unitCycleValue = Float.parseFloat( unitcycle.getText() ); + } + catch ( final NumberFormatException ex ) { + final String message = "Wrong number of cycles: " + unitcycle.getText() + "!"; + jta.append( message ); + jta.append("Aborting"); + jta.append("\n\nReady to process next command\n"); + TraceManager.addError( message, ex ); + setError(); + + return false; + } + + break; + } + default: + break; + } + + return true; + } + private void compileCode() + throws InterruptedException { String cmd = compiler1.getText(); - jta.append("Compiling SystemC code with command: \n" + cmd + "\n"); + jta.append("Compiling simulator code with command: \n" + cmd + "\n"); - rshc = new RshClient(hostSystemC); - // Assuma data are on the remote host - // Command + rshc = new RshClient( simulatorHost ); + + // Assume data are on the remote host Command try { - processCmd(cmd, jta); - if (jta.getText().contains("Error ")){ - mode = ERROR; - setButtons(); + if ( !processCmd( cmd, jta, 0 ) ) { + + // Issue #18: This check does not work when for example the locale is French so we + // explicitly return and test the value of the return code + //if ( jta.getText().contains("Error ") ) { +// mode = ERROR; +// setButtons(); + setError(); + return; } - //jta.append(data); - jta.append("Compilation done\n"); - } catch (LauncherException le) { - jta.append("Error: " + le.getMessage() + "\n"); - mode = STOPPED; - setButtons(); - return; - } catch (Exception e) { - mode = STOPPED; - setButtons(); - return; + jta.append("Compilation done.\n"); } + catch ( final Throwable th ) { + jta.append( "Error: " + th.getMessage() + ".\n"); + // mode = STOPPED; + //setButtons(); + TraceManager.addError( th ); + setError(); + + return; + } +// catch (Exception e) { +// mode = STOPPED; +// setButtons(); +// return; +// } } - public void executeSimulation() throws InterruptedException { - if (hasError) { - jta.append("Simulation not executed: error"); - return; - } - + private void executeSimulation() throws InterruptedException { +// if (hasError) { +// jta.append("Simulation not executed: error"); +// return; +// } int toDo = automatic; if (toDo == 0) { @@ -852,42 +896,32 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act } } - - // String cmd; - switch(toDo) { - case ONE_TRACE: - executeSimulationCmd(exe2.getText(), "Generating one simulation trace"); - break; - case ANIMATION: - dispose(); - mgui.interactiveSimulationSystemC(getPathInteractiveExecute()); - break; - case FORMAL_VERIFICATION: - executeSimulationCmd(exe2formal.getText(), "Running formal verification"); - break; - + case ONE_TRACE: + executeSimulationCmd(exe2.getText(), "Generating one simulation trace"); + break; + case ANIMATION: + dispose(); + mgui.interactiveSimulationSystemC(getPathInteractiveExecute()); + break; + case FORMAL_VERIFICATION: + executeSimulationCmd(exe2formal.getText(), "Running formal verification"); + break; } - } - - public void executeSimulationCmd(String cmd, String text) throws InterruptedException { - - + private void executeSimulationCmd(String cmd, String text) throws InterruptedException { try { - - jta.append(text + " with command: \n" + cmd + "\n"); - rshc = new RshClient(hostSystemC); + rshc = new RshClient(simulatorHost); // It assumes that data are on the remote host // Command - processCmd(cmd, jta); - //jta.append(data); + processCmd(cmd, jta, 0 ); jta.append("Execution done\n"); - } catch (LauncherException le) { + } + catch (LauncherException le) { jta.append("Error: " + le.getMessage() + "\n"); mode = STOPPED; setButtons(); @@ -899,25 +933,23 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act } } + protected boolean processCmd( final String cmd, + final JTextArea _jta, + final Integer okReturnCode ) + throws LauncherException { + rshc.setCmd( cmd ); + rshc.sendExecuteCommandRequest( okReturnCode != null ); - - - protected void processCmd(String cmd, JTextArea _jta) throws LauncherException { - rshc.setCmd(cmd); - String s = null; - rshc.sendProcessRequest(); - rshc.fillJTA(_jta); - //if ( - //s = rshc.getDataFromProcess(); - //return s; - return; - } - - protected void checkMode() { - if (mode!=ERROR){ - mode = NOT_STARTED; - } + rshc.writeCommandMessages( textAreaWriter ); + + return okReturnCode == null || okReturnCode.equals( rshc.getProcessReturnCode() ); } +// +// protected void checkMode() { +// if (mode!=ERROR){ +// mode = NOT_STARTED; +// } +// } protected void setButtons() { if (automatic == 0) { @@ -926,37 +958,44 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act start.setEnabled(true); stop.setEnabled(false); close.setEnabled(true); - //setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); getGlassPane().setVisible(false); + break; case STARTED: start.setEnabled(false); stop.setEnabled(true); close.setEnabled(false); getGlassPane().setVisible(true); - //setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + break; case STOPPED: break; case ERROR: - start.setEnabled(false); - stop.setEnabled(false); + start.setEnabled( canExecute() ); + stop.setEnabled( false ); close.setEnabled(true); + + // Issue #18: Resets the busy cursor to normal + getGlassPane().setVisible(false); + break; default: start.setEnabled(false); stop.setEnabled(false); close.setEnabled(true); getGlassPane().setVisible(false); + break; } - } else { + } + else { close.setEnabled(true); } } + @Override public boolean hasToContinue() { - return (go == true); + return go; } public void appendOut(String s) { @@ -964,7 +1003,9 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act } public void setError() { - hasError = true; + errorTabIndex = tabbedPane.getSelectedIndex(); + mode = ERROR; + //hasError = true; } public boolean isInteractiveSimulationSelected() { @@ -1015,12 +1056,12 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act private void addOneIgnoredTepe() { int [] list = listValidatedTepe.getSelectedIndices(); - Vector v = new Vector(); - Object o; + Vector<AvatarPDPanel> v = new Vector<AvatarPDPanel>(); + //Object o; for (int i=0; i<list.length; i++){ - o = valTepe.elementAt(list[i]); - ignTepe.addElement(o); - v.addElement(o); + final AvatarPDPanel panel = valTepe.elementAt(list[i]); + ignTepe.addElement( panel ); + v.addElement( panel ); } valTepe.removeAll(v); @@ -1031,12 +1072,12 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act private void addOneValidatedTepe() { int [] list = listIgnoredTepe.getSelectedIndices(); - Vector v = new Vector(); - Object o; + Vector<AvatarPDPanel> v = new Vector<AvatarPDPanel>(); + //Object o; for (int i=0; i<list.length; i++){ - o = ignTepe.elementAt(list[i]); - valTepe.addElement(o); - v.addElement(o); + final AvatarPDPanel panel = ignTepe.elementAt(list[i]); + valTepe.addElement( panel ); + v.addElement( panel ); } ignTepe.removeAll(v); @@ -1062,8 +1103,8 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act } private void updateStaticList() { - validatedTepe = new Vector(); - ignoredTepe = new Vector(); + validatedTepe = new Vector<AvatarPDPanel>(); + ignoredTepe = new Vector<AvatarPDPanel>(); int i; for(i=0; i<ignTepe.size(); i++) { -- GitLab