Search code examples
javaubuntucommand-lineagents-jademulti-agent

how can I execute "java" command by java code?


I'm trying to run a multi-agent system using JADE by code. Usually, I can run the jade system by command line using the following command:

java jade.Boot -gui

It also works well using Netbeans IDE by changing the project properties and pointing the run configuration to the jade.Boot class.

My problem is: I want to run this system by java code... let's say, when a user clicks a button, and as far as I know, this command specified above should work using the following code:

Process p=null;                                                                                                                                                     
try {
    p = Runtime.getRuntime().exec("java jade.Boot -gui;");
} 
catch (IOException ex) {
    Logger.getLogger(SimulationCreator.class.getName()).log(Level.SEVERE, null, ex);
}
            
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
try {
    while ((s = stdInput.readLine()) != null) {
           System.out.println(s);
    }
} catch (IOException ex) {
      Logger.getLogger(SimulationCreator.class.getName()).log(Level.SEVERE, null, ex);
}

But I'm getting nothing, neither the JADE system is running nor I'm getting any error.

What am I missing ?

P.S.: I'm working on ubuntu 20.0.

P.S.: running other commands by code like "ps -aux" works very well!


Solution

  • Your problem may be a difference between PATH of the current running VM, compared the shell (bash etc) you use and implicit passing of CLASSPATH. Check the location of java which which java in the shell that works and try using in your exec.

    Also you won't see all issues when running as you don't access the error stream at same time as the output stream, changing to ProcessBuilder allows easier debugging as you can redirect the out/err streams to a file. But if JADE runs for a long time or produces a lot of output you should consumer STDOUT+ERR in background threads.

    Try this in jshell:

    String[] cmd = new String[]{"java", "jade.Boot", "-gui"};
    ProcessBuilder pb = new ProcessBuilder(cmd); 
    File fileOut = new File("stdout.log"); 
    File fileErr = new File("stderr.log"); 
    pb.redirectError(fileErr); 
    pb.redirectOutput(fileOut); 
    Process p = pb.start(); 
    int rc = p.waitFor();
    String stdout = Files.readString(fileOut.toPath());
    String stderr = Files.readString(fileErr.toPath());
    
    System.out.println("Exit   : "+rc +' '+(rc == 0 ? "OK":"**** ERROR ****"));
    System.out.println("STDOUT : "+stdout);
    System.out.println("STDERR : "+stderr);