R. Haroon
R. Haroon

Reputation: 103

How to start rserve automatically from java in windows

I have created a java application in eclipse. The application used Rserve package to connect to R and run r scripts. Before running my application, i have to start rserve from within Rstudio like this:

library(Rserve)
Rserve()

This Java code would be bundled as an executable file, so is there a way that Rserve() is invoked automatically(in windows) as soon as the code is run so that I can skip this manual step of starting Rserve using through RStudio?

Upvotes: 0

Views: 1121

Answers (2)

subes
subes

Reputation: 1832

The https://github.com/yannrichet/rsession project achieves exactly that for you.

Though it might be interesting to have a look at this: https://github.com/subes/invesdwin-context-r As it integrates RSession and keeps a pool of Rserve connections for performance reasons without you having to do much for it. You can also switch to other runtime solutions like JRI, RCaller, Renjin without having to change your script code.

Upvotes: 1

lolynns
lolynns

Reputation: 339

I'm not sure if there's a cleaner way to do this, but the way I've solved this is by starting it up console style from within my java program. For this to work, you have to put the path to the R executables in your systems path:

public Process rserve = null;

public static void startRServer() throws InterruptedException, IOException {
    // check the runtime environment to see if there's an active Rserve running
    String existingRserve = "";
    try {
        Process p = Runtime.getRuntime().exec("tasklist /FI \"IMAGENAME eq Rserve.exe\"");
        p.waitFor();
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        existingRserve = in.readLine();
    } catch(IOException e){}

    if(rserve == null || existingRserve.contains("No tasks are running")) {
        // start and rserve if we don't have one for this run yet, 
        // or if it has unexpectedly failed since we last used it
        try {
            rserve = Runtime.getRuntime().exec("Rscript -e \"library(Rserve); Rserve()\"");
            rserve.waitFor();
        } catch (IOException e) {
            System.out.print("*** R Error: Unable to start the R server ***");
        }
    }
}

Upvotes: 1

Related Questions