How to start Rserve automatically from Java? - java

I am writing a Java application in IntelliJ IDE. The application used Rserve package to connect to R and perform some functions. When I want to run my code for the first time, I have to launch R in the command line and start the Rserve as a daemon, which looks something like this:
R
library(Rserve)
Rserve()
After doing this, I can easily access all the function in R without any errors. However, since this Java code would be bundled as an executable file, so is there a way that Rserve() is invoked automatically as soon as the code is run so that I have to skip this manual step of starting Rserve using the command line?

Here is the code for the Class I wrote to get Rserve working from Java
public class InvokeRserve {
public static void invoke() {
String s;
try {
// run the Unix ""R CMD RServe --vanilla"" command
// using the Runtime exec method:
Process p = Runtime.getRuntime().exec("R CMD RServe --vanilla");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
// System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}

I know this question has been asked a long back . I think You have the answer. But the below answer may help others. That's why I am posting my answer.
answer:- Instead of going again and again to the R console to start Rserve. One thing you can do is you can write a java program to start Rserve.
Below code you can use in a java program to start Rserve.
https://www.sitepoint.com/community/t/call-linux-command-from-java-application/3751. This is the link where you will get the code to run a linux command from java.I have changed the command only and posting below.
package javaapplication13;
import java.io.*;
public class linux_java {
public static void main(String[] args) {
try {
String command ="R CMD Rserve";
BufferedWriter out = new BufferedWriter(new FileWriter(
new File(
"/home/jayshree/Desktop/testqavhourly.tab"), true));
final Process process = Runtime.getRuntime().exec(command);
BufferedReader buf = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line;
while ((line = buf.readLine()) != null) {
out.write(line);
out.newLine();
}
buf.close();
out.close();
int returnCode = process.waitFor();
System.out.println("Return code = " + returnCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

When I am running java program manually from terminal it is working fine but it is not working when i am running from eclipse

My program is not running from eclipse but it is running through terminal in ubuntu.
Below is the shell script that i am running in java
#!/usr/bin/env bash
# Running sqoop commands
s="$(sqoop help)"
echo "$s"
Below is the java code
package flexibility;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Flex {
public static void main(String args[]) throws Exception {
String s = null;
String line = "";
String sqoopCommand = "sqoop help";
try {
Process p = Runtime.getRuntime().exec("/home/avinash/sqoop.sh");
p.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = stdInput.readLine()) != null) {
output.append(line + "\n");
}
while ((line = stdError.readLine()) != null) {
output.append(line + "\n");
}
System.out.println("### " + output);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
error message :
/home/avinash/sqoop.sh: line 5: sqoop: command not found
Try with the command "sh /home/avinash/sqoop.sh". I feel since the ubuntu isn't aware what kind of file it is,It's clearly throwing command not found error.
The error message is from your script. Not from Eclipse.
Eclipse (or the JVM to be more precise) does not know about the environment variables or working directory of the script. In contrast: If you run the script from command line environment variables (e.g. PATH) or working directory are known.
You can use method Runtime.exec(String command, String[] envp, File dir) to specify this in your Java code. So I guess this should work:
Process p =
Runtime.getRuntime().exec("/home/avinash/sqoop.sh", null, new File("/home/avinash/"));

java run bash script, command not found

I tried to use java to run some bash script and store the terminal output in a string. However, there are a lot of commands don't work in this way. It keeps showing command not found, but I can run those commands correctly in terminal, ex node --version, go --version. I guess is the path issue, but have no idea how to fix it.
Another question, when I run "python --version", it shows "Python 2.7.10" but it is in getErrorStream. Can anyone give me some hint?
public static void runscript() throws IOException {
Runtime rt = Runtime.getRuntime();
String[] commands = { "/bin/bash", "-c", "node --version" };
Process proc = null;
try {
proc = rt.exec(commands);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
Reply #VishalKamat comment.
when I tried using the output of "which node" as my path, which is "/usr/local/bin/node". It works!!!
But, does that mean I have to change the path when I need to get different application version info?
I thought I can easily get the info just like I do in terminal.
I try to print $PATH by java in this way
String[] commands = { "/bin/bash","-c", "$PATH" };
The error msg is :
/bin/bash: /usr/bin:/bin:/usr/sbin:/sbin: No such file or directory

Runtime.getRuntime failed to get output same time but later

I'm currently making firefox addon development GUI tool using Java. However I am stuck when trying to get output of a .bat file.
When I run .bat file using java I can see the output, but there are 3 commands written in the bat file. When first command executes I can get the output simultaneously. But when it execute second command output not coming. And when .bat file exist I get all the output which didn't come simultaneously.
I'm getting output immediately when it execute:
call "C:\mozilla-build\addon-sdk-1.16\bin\activate.bat
But I'm not getting output simultaneously for following command:
call cfx run
But I know it's executing because firefox window pops up. I get all the output suddenly when I execute proc.destroy();
This is my bat file:
#echo off
call %1
cd C:\Users\Madhawa.se\Desktop\workingfox\beauty
call cfx run
pause
This is my Java code:
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
Runtime rt = Runtime.getRuntime();
String[] commands = {"C:\\Users\\Madhawa.se\\Desktop\\workingfox\\runner\\foxrun.bat", "C:\\mozilla-build\\addon-sdk-1.16\\bin\\activate.bat"};
proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
proc.waitFor();
System.out.println("success");
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
t.start();
How to get output immediately and why it acts differently for this command?
i was able to fix it using process builder instead of runtime.exec .and inheriteIo doesn't work .it blocks the realtime output
Thread t = new Thread(new Runnable() {
private String s;
#Override
public void run() {
try {
Component selectedComponent = jTabbedPane2.getSelectedComponent();
if (selectedComponent instanceof MyTextArea) {
String response = "";
System.out.println("yes");
MyTextArea temptextarea = (MyTextArea) selectedComponent;
String xpiPath = new File(temptextarea.getNameX()).getParentFile().getPath();
String[] commands = {"C:\\Users\\Madhawa.se\\Desktop\\workingfox\\runner\\foxrun.bat", "C:\\mozilla-build\\addon-sdk-1.16\\bin\\activate.bat
ProcessBuilder process = new ProcessBuilder(commands);
process.redirectErrorStream(true);
Process shell = process.start();
//shell.waitFor();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(shell.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(shell.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println("s:" + s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println("w:" + s);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}

How to Execute Windows Commands Using Java - Change Network Settings

In Java, I want to be able to execute a Windows command.
The command in question is netsh. This will enable me to set/reset my IP address.
Note that I do not want to execute a batch file.
Instead of using a batch file, I want to execute such commands directly. Is this possible?
Here is my implemented Solution for Future Reference:
public class JavaRunCommand {
private static final String CMD =
"netsh int ip set address name = \"Local Area Connection\" source = static addr = 192.168.222.3 mask = 255.255.255.0";
public static void main(String args[]) {
try {
// Run "netsh" Windows command
Process process = Runtime.getRuntime().exec(CMD);
// Get input streams
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// Read command standard output
String s;
System.out.println("Standard output: ");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// Read command errors
System.out.println("Standard error: ");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
Runtime.getRuntime().exec("netsh");
See Runtime Javadoc.
EDIT: A later answer by leet suggests that this process is now deprecated. However, as per the comment by DJViking, this appears not to be the case: Java 8 documentation. The method is not deprecated.
Use ProcessBuilder
ProcessBuilder pb=new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process process=pb.start();
BufferedReader inStreamReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
while(inStreamReader.readLine() != null){
//do something with commandline output.
}
You can run the command with Runtime.getRuntime().exec("<command>") (eg. Runtime.getRuntime().exec("tree")). But, this will only run executables found in path, not commands like echo, del, ... But only stuff like tree.com, netstat.com, ... To run regular commands, you will have to put cmd /c before the command (eg Runtime.getRuntime().exec("cmd /c echo echo"))
public static void main(String[] args) {
String command="netstat";
try {
Process process = Runtime.getRuntime().exec(command);
System.out.println("the output stream is "+process.getOutputStream());
BufferedReader reader=new BufferedReader( new InputStreamReader(process.getInputStream()));
String s;
while ((s = reader.readLine()) != null){
System.out.println("The inout stream is " + s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
This works.
Runtime#exec().

how to execute dos command with options in java

I want to execute dos based external command through java program if there there is any way please help me
String[] options = new String[]{"option1", "option2"};
Runtime.getRuntime().exec("command", options);
The following bit of code will run the dir command, and then print out for you as well as error. Taken and adapted from (http://www.devdaily.com/java/edu/pj/pj010016)
import java.io.*;
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
try {
// run the Windows command (dir)
// using the Runtime exec method:
Process p = Runtime.getRuntime().exec("dir");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened
- here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
} }

Categories

Resources