Call "interactive" Perl script from Java - java

I want to call an "interactive" Perl script from a Java program. Just for the clarity, the other way around (from Perl to Java) is not good for me.
The script is interactive in the sense that it requires a small configuration dialog with the user. For example, calling the script in cmd.exe would lead to a dialog like:
Do you want to overwrite the old settings? [yes,no (default=no)]
and the user should choose between writing yes, no or nothing at all in the command line.
And depending on the user choice another message would appear: "Do you want to...." and the user will respond etc etc. I think you got the picture.
My question is how can I have the same dialog with the user when the script is called in a Java program? I mean, how can I capture the script's questions to the user, show them to user and then send the user's answer (got in the Java program) to the script?
A simple Runtime.getRuntime().exec() doesn't work in this case.
Hope I expressed clear enough the question.
Thank you for your help!

You must use getInputStream/getOutputStream methods to get access to stdin and stdout of perl stript. You can read and write to these streams to simulate user's behavior
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
Process process = Runtime.getRuntime ().exec ("...");
stdin = process.getOutputStream ();
stderr = process.getErrorStream ();
stdout = process.getInputStream ();
// "write" the parms into stdin
String line = "data\n";
stdin.write(line.getBytes());
stdin.flush();
stdin.close();
// clean up if any output in stdout
BufferedReader brCleanUp =
new BufferedReader (new InputStreamReader (stdout));
while ((line = brCleanUp.readLine ()) != null) {
//System.out.println ("[Stdout] " + line);
}
brCleanUp.close();
// clean up if any output in stderr
brCleanUp =
new BufferedReader (new InputStreamReader (stderr));
while ((line = brCleanUp.readLine ()) != null) {
//System.out.println ("[Stderr] " + line);
}
brCleanUp.close();

This is a job for Expect. In Java: ExpectJ, expect4j

If (1) your call is from Java to Perl, and (2) you are not parsing the Perl script itself, why not use a JOptionPane.showConfirmDialog() from the Java code? Shouldn't be a big deal if a Yes/No is all your are getting from the script. Whatever you are printing to display to the user can be included in that confirm dialog as a plain ASCII text, too.

Related

Start and get output of a .jar (E.g. Minecraft Bukkit .jar)

I'm trying to start some .jar inside an .jar using this code: (I'm trying with craftbukkit server right know)
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("java -jar craft.jar");
BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter in = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
this.running = true;
while(this.running){
String line;
if((line = out.readLine()) != null){
System.out.println(line);
}
}
The problem is, it work for a moment, but after a while it stops outputting or just print '>' as show in the image below. How can I fix this? **Plus, Which is the correct way to send commands to the bukkit server?
Thanks!
When using a Process in Java, it is crucial to read stdout and stderr in two independend threads (your while loop). Otherwise the child process can lock up waiting for the filled buffer to be drained.
With Java 7 you can actually redirect stderr to stdout, and possibly redirect the resulting stream to the parents stdout. With older versions you need to attach the seperate threads.
Besides: you should not use the "single string" variant of exec, but specify the args as arrays. This is safer (less vulnerable to parsing problems).
(But I am not sure if this is your actual problem. Maybe you should dump the error stream and see if it helps)
I do it like that:
#Override
public void run(){
// ...
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); //of course proc is an instance of Process, and it's set up
while(true){
String line = stdInput.readLine();
if(line == null) break; //this is essential, when process terminates, line gets null
System.out.println(">"+line);
}
// ...
}
Give it a try.
(Technically it's similiar how you did, but it works for me so i share it)

How do I read and write from an external process in Java?

I want to run PianoBar from a Java GUI (PianoBar is a program that runs Pandora from command line). I thought this would be quick and dirty, but I guess I don't know enough about interaction between programs.
I use ProcessBuilder to launch an instance of PianoBar like so:
private Process createPianoBarProcess() throws IOException {
String[] command = {"CMD", "/C", "pianobar"};
ProcessBuilder probuilder = new ProcessBuilder( command );
probuilder.redirectErrorStream(true);
probuilder.directory(new File("~~location where pianobar.exe is~~"));
Process process = probuilder.start();
return process;
}
After I create the process, I create a BufferedReader to read in the PianoBar output:
Process pianoBar = createPianoBarProcess();
InputStream inS = pianoBar.getInputStream();
InputStreamReader isr = new InputStreamReader(inS);
BufferedReader br = new BufferedReader(isr);
But when I read the output from PianoBar via this reader, it spits out the first line of PianoBar ("Welcome to pianobar (2013.05.19-win32)! Press ? for a list of commands."), then it spits out the next line ("[?] Email:"). Then it just hangs.
Obviously, it is waiting for the user to input their email. But no matter what I try, I can't get my Java program to write the email to the PianoBar process when prompted - it just hangs as soon as it reads out the last character.
Is it possible to do what I am trying to do? I thought it would be an easy thing to look for on the internet, but I haven't been able to find anything. All I want is an easy way to write to the external process when prompted. Seems like this should be easy...
You may use the following code snippet to get working:
String s;
//s = email
BufferedWriter bufferedwriter = new BufferedWriter(new OutputStreamWriter(pianoBar.getOutputStream()));
bufferedwriter.write(s);
bufferedwriter.flush();
Done!
Remember to surround the code block with appropriate try/catch

Java run Process unable to get standard out

I have my code below. I am trying to run my ruby script and get the standard out, I don't really need standard error in this case. For some reason, I could not get any output at all in my production host, and I only get empty string. The same code works fine in my desktop. If I run my ruby script myself, I could get output from it. My ruby script only has a puts statement for now. Any one know the reason? Is it that I need to some kind of block to wait for the ruby script to finish?
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("ruby", "tests.rb");
Process process = processBuilder.start();
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder output = new StringBuilder();
String line;
while ((line = bufferReader.readLine()) != null) {
System.out.println("Line is: " + line);
output.append(line + "\n");
}
bufferReader.close();
return output.toString();
I have redhat machine running zsh.
You need to close the process's output stream (its standard input), and you should probably merge the output and error streams. You might think you don't want them both but you might be wrong, and if the process produces enough unread error output it will stall.

Calling gnuplot from java? (ubuntu)

I'm not sure if this is possible, especially since Java runs through a VM, but can I call gnuplot from within Java? Perhaps I could have Java open a terminal and input
gnuplot
plot ...
etc?
Use gnujavaplot.
If you can get gnuplot to take all input from the command line or standard input (or read it from a file) and write its output to files as well, then there should be no problem doing this using ProcessBuilder.
This works on Debian:
String[] s = {"/usr/bin/gnuplot",
"-e",
"set term jpeg large size 800,600;set autoscale; set grid;set format y \"%0.f\";set output \"plot.jpg\";set xdata time;set timefmt \"%Y-%m-%d-%H:%M:%S\";set xlabel \"Dates\";set ylabel \"Data transferred (bytes)\";plot \""+x+"\" using 1:2 title \"Total:"+tot+"\" with linespoints;"
};
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(s);
InputStream stdin = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
System.err.println("gnuplot:"+line);
int exitVal = proc.waitFor();
if (exitVal != 0)
log("gnuplot Process exitValue: " + exitVal);
proc.getInputStream().close();
proc.getOutputStream().close();
proc.getErrorStream().close();
} catch (Exception e) {
System.err.println("Fail: " + e);
}
Use the JavaGnuplotHybrid library.
It is very light weight (only 3 core classes) and enables hybrid programming with Java and Gnuplot.
Hybrid programming with Java and Gnuplot
Very light weight (just three core Classes)
Use tags in Gnuplot code to execute functions or get fields' values
in Java.
Support both synchronized and asynchronized running of Gnuplot in
Java. (synchronized: your java program will wait until you close the
popped Gnuplot window; asynchronized: you java program will not
wait.)
Capture error/normal text output of Gnuplot to the java terminal
Read Gnuplot code from xml files
Support Gnuplot code template.
For more details:
Project page: https://github.com/mleoking/JavaGnuplotHybrid
Examples: https://github.com/mleoking/JavaGnuplotHybrid/blob/master/javagnuplothybrid/doc/examples.md
You can launch any external application using the "exec" commands.
http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html
See this page for a few examples.
http://www.rgagnon.com/javadetails/java-0014.html
EDIT: I forgot about ProcessBuilder. Michael Borgwardt's answer is a more robust solution.

Running other programs from Java

I need to run a couple of other programs from my own Java program, basically I need to run these command line statements.
svn log --xml -v > svn.log
and
java -jar example.jar arg1 arg2
and I need to use the text outputs written to the console from these programs in my own program. I've tried Runtime.getRuntime().exec() with the svn, but it doesn't seem to be doing anything because it doesn't make a svn.log file. Also both programs need to be called in different places, the svn line needs to be called from inside one folder and the java line needs to be called from another.
Any ideas on how to go about this? If this is not possible in Java, is there a way to do it in C#?
Thanks
Here:
ProcessBuilder processbuilder
try
{
processbuilder.directory(file);
processbuilder.redirectErrorStream(true);
process = processbuilder.start();
String readLine;
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
// include this too:
// BufferedReader output = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while((readLine = output.readLine()) != null)
{
m_Logger.info(readLine);
}
process.waitFor();
}
I've used something similar. You'll actually want to do something with the readLine. I just copied and pasted from code where I didn't care what it said.
The redirection > (like the pipe |) is a shell construct and only works when you execute stuff via /bin/sh (or equivalent). So the above isn't really going to work. You could execute
/bin/sh -c "svn log --xml -v > svn.log"
and read svn.log.
Alternatively, you can read the output from the process execution and dump that to a file (if you need to dump it to a file, or just consume it directly as you read it). If you choose this route and consume stdout/stderr separately, note that when you consume the output (stdout), you need to consume stderr as well, and concurrently, otherwise buffers will block (and your spawned process) waiting for your process to consume this. See this answer for more details.
instead of piping in your command, just let it print to standard output and error output. You can access those streams from your process object that is returned from exec.
For the svn stuff use java SVNKit API.
Seeing your two commands, why don't you do it directly from Java, without executing ? You could use SVNKit for the svn part, and include directly the jars in your classpath.
Try this
public static void main(String[] args) {
try {
// Execute a command with an argument that contains a space
System.out.println(args[0]);
String[]commands = new String[]{"svn", "info", args[0]};
Process process = Runtime.getRuntime().exec(commands);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.println(result);
}catch(Exception e){
System.out.print(e);
}
}

Categories