javacommandopenoffice.orgruntime.execsoffice

Problem with starting OpenOffice service (soffice) from Java (command working in commandline, but not from Java)


I want to exceute a simple command which works from the shell but doesn't work from Java. This is the command I want to execute, which works fine:

soffice -headless "-accept=socket,host=localhost,port=8100;urp;" 

This is the code I am excecuting from Java trying to run this command:

String[] commands = new String[] {"soffice","-headless","\"-accept=socket,host=localhost,port=8100;urp;\""};
Process process = Runtime.getRuntime().exec(commands)
int code = process.waitFor();
if(code == 0)
    System.out.println("Commands executed successfully");

When I run this program I get "Commands executed successfully". However the process is not running when the program finishes. Is it possible that the JVM kills the program after it has run?

Why doesn't this work?


Solution

  • I would like to say how I solved this. I created a sh script that basically run the command of soffice for me.

    Then from Java I just run the script, and it works fine, like this:

    public void startSOfficeService() throws InterruptedException, IOException {
            //First we need to check if the soffice process is running
            String commands = "pgrep soffice";
            Process process = Runtime.getRuntime().exec(commands);
            //Need to wait for this command to execute
            int code = process.waitFor();
    
            //If we get anything back from readLine, then we know the process is running
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            if (in.readLine() == null) {
                //Nothing back, then we should execute the process
                process = Runtime.getRuntime().exec("/etc/init.d/soffice.sh");
                code = process.waitFor();
                log.debug("soffice script started");
            } else {
                log.debug("soffice script is already running");
            }
    
            in.close();
        }
    

    I also kill the soffice process by calling this method:

    public void killSOfficeProcess() throws IOException {
            if (System.getProperty("os.name").matches(("(?i).*Linux.*"))) {
                Runtime.getRuntime().exec("pkill soffice");
            }
        }
    

    Note that this only works in Linux.