Run nodejs using java - java

I need to run some node.js program using java
my code looks like this
String filePath= "/home/gilles/eclipse-workspace/informationGewinnungApp/videotool/src/videotool.js";
String option1 = "-m resources/WetterBerich";
String option2 = "--bg_content resources/logo.png";
ProcessBuilder Pb =
new ProcessBuilder("node",filePath+option1+option2);
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("/usr/bin"));
File log = new File("log");
// pb.redirectErrorStream(true);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
pb.redirectOutput(Redirect.appendTo(log));
Process p = pb.start();
assert pb.redirectInput() == Redirect.PIPE;
assert pb.redirectOutput().file() == log;
assert p.getInputStream().read() == -1;
but I get this Error
module.js:549
throw err;
^

Mostly dupe: Cannot ProcessBuilder to execute command for ffmpeg -i shortWav.wav -af silenceremove=1:0:-50dB shortWavCued.mp3
You are putting multiple (all) options in ONE argument.
When you give a command line node this that to a shell, it passes this and that to node as separate arguments, and that is how node expects to receive them. ProcessBuilder does not split strings into separate arguments like a shell does, you must do it:
ProcessBuilder Pb = new ProcessBuilder("node",filePath,
"-m", "resources/WetterBerich",
"--bg_content", "resources/logo.png");
PS: using /usr/bin for your working directory is typically not a good idea.

Related

Java switch directories and then fire command with parameters

Hey all I am trying to change directories and then run my command with parameters.
final String path = "\\Local// Apps\\IBM\\SDP\\scmtools\\eclipse";
final String command = "scm help";
final String dosCommand = "cmd /c \"" + path + "\"" + command;
final Process process = Runtime.getRuntime().exec(dosCommand);
final InputStream in = process.getInputStream();
int ch;
while((ch = in.read()) != -1) {
System.out.print((char)ch);
}
It runs without errors but outputs nothing. However, this is what shows up after it finishes:
<terminated, exit value: 0>C:\Local Apps\IBM\SDP\jdk\bin\javaw.exe (Jul 22, 2019, 11:21:37 AM)
The expected output should be:
So am I doing this correctly?
AS suggested by Andreas
Process p = null;
ProcessBuilder pb = new ProcessBuilder("scm.exe");
pb.directory(new File("C:/Local Apps/IBM/SDP/scmtools/eclipse"));
p = pb.start();
I get the following error:
Cannot run program "scm.exe" (in directory "C:\Local Apps\IBM\SDP\scmtools\eclipse"): CreateProcess error=2, The system cannot find the file specified
You should use ProcessBuilder instead of Runtime.exec, e.g.
Process proc = new ProcessBuilder("scm.exe", "help")
.directory(new File("C:\\Local Apps\\IBM\\SDP\\scmtools\\eclipse"))
.inheritIO()
.start();
proc.waitFor(); // optional
You can also go through the command interpreter if needed, e.g. if the command is a script (.bat or .cmd file):
Process proc = new ProcessBuilder("cmd", "/c", "scm", "help")
.directory(new File("C:\\Local Apps\\IBM\\SDP\\scmtools\\eclipse"))
.inheritIO()
.start();
proc.waitFor();
The inheritIO() means that you don't need to process the commands output. It will be sent to the console, or wherever Java's own output would go.

Running Jar File from Java Program

I am trying to run a .jar from within my Java program. I am using ProcessBuilder to do so, but it is not working correctly.
I am wondering if I am missing something.
This is what I currently have that is trying to run the .jar
ProcessBuilder pb = new ProcessBuilder("java", "-jar", System.getProperty("user.home") + "/JARFile/JARFile.jar");
Process p = pb.start();
I have the directory correct, so I am not positive why this is not working properly.
Do I have something wrong with my parameters in the new ProcessBuilder?
1) in third argument set full path to file:
ProcessBuilder pb = new ProcessBuilder("java", "-jar",
"/home/meiskalt7/Documents/runJar-55056616-1.0-SNAPSHOT.jar");
Result will be look like this:
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("java", "-jar",
"/home/meiskalt7/Documents/runJar-55056616-1.0-SNAPSHOT.jar");
Process p = pb.start();
InputStream in = p.getInputStream();
System.out.println(new BufferedReader(new InputStreamReader(in))
.lines().collect(Collectors.joining("\n")));
}
and in console you will see result of execution
2) If everything will be good then you must check your system property with
System.out.println(System.getProperty("user.home"))
and if path looks like path in first step then you must compare path with equals operator:
System.out.println((System.getProperty("user.home") + "/JARFile/JARFile.jar")
.equals([YOUR FULL PATH]))
Maybe your problem with symbols of another language in path
2*) if something go wrong then you can check error of process execution in error stream of your process:
InputStream err = p.getErrorStream();
System.out.println(new BufferedReader(new InputStreamReader(err))
.lines().collect(Collectors.joining("\n")));

Error when using linux grep command in java

I'm trying to get the output of grep linux shell command in java by using process builder. But i got a stuck in this case. Please help me.
Thank in advice!
String[] args = new String[7];
args[0] = "/bin/bash";
args[1] = "-c";
args[2] = "grep";
args[3] = "-n";
args[4] = "-e";
args[5] = "KERNELVERSION";
args[6] = kernelFilePath.trim();
ProcessBuilder pb;
Process process = null;
try {
pb = new ProcessBuilder(args);
pb = pb.directory(new File(directory));
pb.inheritIO();
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
process = pb.start();
process.waitFor();
} catch (IOException | InterruptedException e) {
System.out.println("executeCmdWithOutput() exception : " + e.toString());
} finally {
if (process != null) {
process.destroy();
}
}
==> Error:
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
I tried the command in bash and it worked fine:
grep -n -e KERNELVERSION ..../Makefile
Have you tried change the args[2] as full command?
Also, you can use pgrep, it does not require you to use pipe.
You don't need to explicitly run /bin/bash in order to execute the grep process. Just call it directly and ProcessBuilder will run it:
String[] args = {"grep", "-n", "KERNELVERSION", kernelFilePath.trim()};
Also, you don't need to use the -e option, unless there are multiple patterns that you are searching for.
If you really wanted to run grep in /bin/bash:
String[] args = {"/bin/bash", "-c", "grep -n KERNELVERSION " + kernelFilePath.trim()};
passes a single argument to bash containing the full command and arguments to execute.

Executing openssl command using Java runtime [duplicate]

How am I to execute a command in Java with parameters?
I've tried
Process p = Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php -m 2"});
which doesn't work.
String[] options = new String[]{"option1", "option2"};
Runtime.getRuntime().exec("command", options);
This doesn't work as well, because the m parameter is not specified.
See if this works (sorry can't test it right now)
Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php", "-m", "2"});
Use ProcessBuilder instead of Runtime#exec().
ProcessBuilder pb = new ProcessBuilder("php", "/var/www/script.php", "-m 2");
Process p = pb.start();
The following should work fine.
Process p = Runtime.getRuntime().exec("php /var/www/script.php -m 2");
Below is java code for executing python script with java.
ProcessBuilder:
First argument is path to virtual environment
Second argument is path to python file
Third argument is any argumrnt you want to pass to python script
public class JavaCode {
public static void main(String[] args) throws IOException {
String lines = null;
ProcessBuilder builder = new ProcessBuilder("/home/env-scrapping/bin/python",
"/home/Scrapping/script.py", "arg1");
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((lines = reader.readLine())!=null) {
System.out.println("Line: " + lines);
}
}
}
First is virtual environment path

Passing parameters from a Java program to shell script

I am developing a web application wherein I am using JSP as my front end and shell script as my back end. Thus I would be passing parameters from input JSP to the shell script via a Java Program(Business Layer). I would like to know how would I be able to pass parameters from Java to shell script and execute the same.Thank you.
you can use ProcessBuilder to pass parameter to shell script.
ProcessBuilder pb = new ProcessBuilder("shellscript", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory("myDir");
Process p = pb.start();
I have figured out the answer and I think this might be helpful for people.
Please refer to the code
public static BufferedReader process() throws IOException
{
ProcessBuilder pb = new ProcessBuilder("/home/XXXX/Desktop/request.sh","Apple");
String line;
Process process=pb.start();
java.io.InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
return br;
}
Here "Apple" is the input parameter for the shell script and that will be stored in $1(environmental variable) and this could be accessed from shell script and when something needs to be sent from shell script to Java, echo from shell script and get that from process.inputStream() in Java ..

Categories

Resources