Using Runtime.getRuntime().exec() to run perl code in java - java

I have a perl script called pbp that takes an html file as an argument and then creates an output file. Here is my current code. Infile is obtained earlier from a JFile Chooser. I don't get any errors but there is no ouput from the perl script.
try {
Process p = Runtime.getRuntime().exec(new String[] {"perl", "C:\\Users\\Roger\\Downloads\\The_Long-Awaited_Product_Specification_and_Sample_Files\\casey\\pbp", inFile.getAbsolutePath()});
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
System.out.println(p.waitFor());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

You will not get the output of per script directly. You need to capture it using the below code:
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
// read the output from the command
System.out.println("EXE OUTPUT");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}

Related

JNA .FindWindow with regex

Hello I'm working on a program which uses JNA 4.5.1.
I need to know whether a specific program is running or not.
Here is my problem:
hwnd = User32.INSTANCE.FindWindow
(null, "Session Dev/Prod - [32 x 80]");
if (hwnd == null) {
System.out.println("Session Dev/Prod is not running");
Process p = null;
try {
p = Runtime.getRuntime()
.exec("rundll32
url.dll,FileProtocolHandler C:
/ProgramData/Microsoft/Windows/Start
Menu/Programs/IBM Personal
Communications/TNHost");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
p.waitFor();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else{
System.out.println("Host Already open");
User32.INSTANCE.ShowWindow(hwnd, User32.SW_MAXIMIZE );
User32.INSTANCE.SetForegroundWindow(hwnd);
}
The Problem is that the Window-Title changes depending on the monitor size.
hwnd = User32.INSTANCE.FindWindow(null, "Session Dev/Prod - [32 x 80]");
The title is always "Session Dev/Prod" + the size which changes.
I need to find the window which starts with "Session Dev/Prod".
Does anyone know how to do this. Or is there an other way to find out whether a program is running or not? I've tried to do it with Regex as parameter but the function accepts just a String.
Thank you
I had the task once to check whether a program was running or not (and if so kill it) and solved it like this:
public static void isProcessRunning(String processName) throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder("tasklist.exe");
Process process = processBuilder.start();
// handle errors: process.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith(processName)) {
System.out.println("Yes program is running");
break;
}
// else {
// System.out.println("No program is not running");
// }
}
}
To find out the name of your task call tasklist in the commandline and look for the name. If it is really 'Session Dev/Prod - [32 x 80]' then you can use 'Session Dev/Prod' as a string...
But note that this is a windows solution. For linux you have to use something like ps -ef

How to read lines from a C script from Java's BufferedReader?

I'm running this java program on a raspberry pi. The program is supposed to run the script "hello_pixy" and scan what it prints out. When I run hello_pixy manually, it prints out lines normally (Via C's printf line). But when I run the program, nothing is printed out and the BufferedReader didn't read any lines.
If I substitute the script for something like "ls", then the BufferedReader reads it and prints it out. Is there a way I can change the "printf"s in C to send to the InputStream (I don't really know C, just enough from Java experience)?
Process process = null;
try {
process = Runtime.getRuntime().exec("sudo .ss/pixy/build/hello_pixy/hello_pixy");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //for Windows
try {
process.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
String print = "";
try {
while ((line = reader.readLine()) != null) {
print += line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\nCodescan:\n\n" + print);
The code I'm executing is here: https://github.com/De-etz/pixy/blob/master/src/host/hello_pixy/hello_pixy.cpp
You're doing this back to front. You must read all the process's output first, and then call waitFor(). Your way you will probably just deadlock, as the process can't exit until it has produced all its output, and if you're not reading it, it will eventually block.
Notes:
C is not a scripting language, and a compiled program is not a script by definition.
Code that depends on the success of code in a prior try block must be inside that try block. At present you are continuing after exceptions as though they didn't happen. Don't write code like this.

How could I pass in commands into a terminal that is already running in java (linux)

I have been researching how to run a terminal command in java. I am doing this to make a program I can use to ssh into another pc (just as a project). How could I keep continuing putting commands in this terminal? If I run this I get a message to put in my password and if I do so it will print out what the messages the terminal spits out at the :
while((line = in.readLine()) != null){
System.out.println(line + "\n");
}
line, but a few seconds after that my program will stop working.
I currently have a GUI that is just a button and if I press the button it will run this code. Could someone help me to fix the issue of it stopping and give me information on how I could continue to put commands into the terminal? Thanks.
Process p = null;
String[] command = {"/bin/sh", "-c", "ssh 192.168.2.100"};
ProcessBuilder pb = new ProcessBuilder(command);
String line = null;
try {
term = pb.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream is = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
try {
while((line = in.readLine()) != null){
System.out.println(line + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can not pass the argument to live JVM, But there is way in which you can modify the some of the parameters which done using JMX, with this you can connect to live JVM and send the parameters. which will be taken the effect immediately.
Hope that helps

Running a Perl script in Java using ProcessBuilder

I am using ProcessBuilder in Java to run a Perl script. When I run the Perl script while printing the InputStream of the process, the Java program seems to run for the duration of the Perl script. However if I comment out the getOutPut method in main the Java program terminates very fast and the Perl script does not run at all. Why does this occur?
private final static String SCENARIO = "scen";
/**
* #param args
*/
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("perl", SCENARIO+".pl");
pb.directory(new File("t:/usr/aman/"+SCENARIO));
try {
Process p = pb.start();
getOutput(p.getInputStream(), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static List getOutput(InputStream is, boolean print) {
List output = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String s = null;
try {
while ((s = reader.readLine()) != null) {
output.add(s);
if(print){
System.out.println(s);
}
}
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
return null;
}
return output;
}
Likely the OS's output stream buffer for your PERL script process gets filled because nothing is emptying this buffer, and this will kill the process. You need to gobble the output stream for this reason which is what your getOutput method does for you.
Please read the classic reference on this problem: When Runtime.exec() won't. Per this article:
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

how to pass the arguments to the shell command through java?

I am new to this kind of integration of java with Unix.
what i am trying to do is
String command="passwd";
Runtime rt=Runtime.getRuntime();
try {
Process pc=rt.exec(command);
try {
pc.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader buf = new BufferedReader(new InputStreamReader(pc.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null) {
System.out.println(line);
}
BufferedReader buf1 = new BufferedReader(new InputStreamReader(pc.getErrorStream()));
String line1 = "";
while ((line1=buf1.readLine())!=null) {
System.out.println("Error--"+line1);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("IOException---"+e1.getMessage());
}
now when i am trying to pass the "passwd" command the Unix environment goes to suspended mode.
I want to know how can i pass the old password ,new password and confirm new password to the shell using the java code.
You need to pass it in using the confusing named Process.getOutputStream(). From the doc:
Gets the output stream of the subprocess. Output to the stream is
piped into the standard input stream of the process represented by
this Process object
Note that you need to capture the processes stdout/err simultaneously to avoid blocking. See this answer for more details.
There is a utility called expect. If u installed u can pass argument for any thing. So construct as string execute by
String ConstructedCommand;
Process p=Runtime.getRuntime().exec(ConstructedCommand);
This link will be deserve your need. http://linux.die.net/man/1/expect

Categories

Resources