Java runtime exec getInputStream when process pauses - java

I am creating a wrapper for a executable that runs on the windows command line. The executable takes a few commands then attempts to connect to another device. then it outputs and ERROR! or Ready For "Device Name" i do not get this message until the app exits. The problem is this app is a tunnel allowing me to run telnet on the external box but i need to make sure the Device is ready this is my code.
public void startUDPTunnel() {
//TODO Pull Amino serial number from webportal
Properties prop = new Properties();
InputStream inConfig = getClass().getClassLoader().getResourceAsStream("config.properties");
try {
prop.load(inConfig);
} catch (IOException e) {
System.out.println(e.getMessage());
}
String server = prop.getProperty("server");//config.GetProp("server");
System.out.println(server);
String port = prop.getProperty("port");//config.GetProp("port");
System.out.println(port);
String location = prop.getProperty("location");//config.GetProp("location");
System.out.println(location);
String url = prop.getProperty("URL");
System.out.println(url);
String input = "";
try {
input = getSerial(url);
System.out.println(input);
Process p = Runtime.getRuntime().exec(location+"udptunnel.exe -c 127.0.0.1 23 "+input+" "+server+" "+port+" 127.0.0.1 23");
threadSleep();
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
if(line.equals("ERROR!")){
System.out.println("There was an ERROR");
}
if(line.equals("Ready for \""+input+"\"")){
System.out.println("Load Telnet");
}
}
p.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
Sorry there is a lot of debug code left in this function.
EDIT
OK I am pretty sure know what the issue is bufferReader.readLine() requires a \n or \r or just hangs is there anyway to watch the stream with out the buffer?

You should use a ProcessBuilder, and then use redirectErrorStream(). I think this will cause stdout of the process to be unbuffered. And even if it doesn't, you'll only have to read from one InputStream to get both stdout and stderr.

I have figured out my problem the applications that i am executing with java do not have a EOL at the end of the line in fact they just hang on the line For example telnet waits for the username then the password. i am not sure this is proper but it works and is what i am going to use for now
while((i=br.read())!=-1){
ch += (char)i;
}
This outputs every char as they come in when then i just make sure the string contains what i am looking for!

Related

using java to manipulate a minecraft server input/output

I'm trying to manage my minecraft server through java but even though i can read outputs easily I can't manage to get commands or even text in:
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd C:\\my\\path\\ && java -jar server.jar nogui");
builder.redirectErrorStream(true);
Process p;
p = builder.start();
this.p = p;
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (loop) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
This works just fine but when I try to send commands it doesn't work at all:
OutputStream os = BotData.minecraftServer.getOutputStream();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(os));
String stop = "stop";
try {
out.write(stop + "\n");
out.write("\n");
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I've tried with "Command:>>" + stop + "\n"
with or without / before stop etc.
Killing the process, forcibly or not, starting it in a thread I'd then stop...
I can get neither text nor commands to work.
document says commands from cmd should come with a leading /.
Try send /stop instead of stop.
Also mind, the line line = r.readLine(); may never return a null while the process is alive(by default).
OK found it, it is needed to use write() newline() then flush() to send anything to the console.
My second problem was a dead reference to my process.
destroying the process doesn't work, but the stop command does.
using / is useless, \n doesn't replace newline()

how to open beyond compare from java program give two files as input and store the result file somewhere

I need to actually have a batch job.
I have tried opening simple programs like notepad in java but I am not aware how to open beyond compare
I need to open beyond compare from java code and give two files as input and give the result file stored locally and then later on find the percentage of similarity.
Any link would be of great help.
Here is what i have tried so far
ProcessBuilder processBuilder = new ProcessBuilder("C:\\Program Files\\Beyond Compare 4\\BCompare.exe",
file1path, file2path,"/qc=bin", "\\silent");
Process ps;
try {
ps = processBuilder.start();
OutputStream os = ps.getOutputStream();
os.close();
InputStream inputStream = ps.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
System.out.println(line);
}
ps.waitFor();
System.out.println("Exit value :" + ps.exitValue());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
But it just prints exit value and program terminates
If you are opening the beyond compare, the file names need to be select for comparison.
The left file and Right file need to be choose to be compare.

How to check if two files are having same content using Beyond Compare java api?

I have two files to be given as an input and I am using Beyond Compare tool Java API to check whether the contents in both the files are same or not.
I want to do this without opening the Beyond Compare window. Below is the code which I am using currently.
ProcessBuilder processBuilder = new ProcessBuilder("C:\\Program Files\\Beyond Compare 4\\BCompare.exe",
"file1path", "file2path","/qc=bin", "\silent");
Process ps;
try {
ps = processBuilder.start();
OutputStream os = ps.getOutputStream();
os.close();
InputStream inputStream = ps.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
}
ps.waitFor();
System.out.println("Exit value :" + ps.exitValue());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
As mentioned here enter link description here, using /silent will not open the window. Despite using /silent, I can still see the window pop up of Beyond Compare tool. Please suggest some work around to achieve the same
I met my requirement by slightly changing the arguments passed to the Process Builder. Below is the change I made.
ProcessBuilder processBuilder = new ProcessBuilder("C:\\Program Files\\Beyond Compare 4\\BCompare.exe",
"file1path", "file2path","/fv=Text Compare", "/qc=binary");
This worked for me.

Using ProcessBuilder to read/write to telnet process

I am trying to read/write values from/to telnet process by means of ProcessBuilder.
public static void main(String[] args) {
try {
telnetProcess = new ProcessBuilder("C:\\Windows\\System32\\telnet.exe","x.x.x.x").start();
telnetInputReader = new BufferedReader(new InputStreamReader(telnetProcess.getInputStream()));
telnetOuputWriter = new BufferedWriter(new OutputStreamWriter(telnetProcess.getOutputStream()));
expectPattern("login:");
sendCmd("user");
expectPattern("password:");
sendCmd("pwd");
expectPattern("switch>#");
sendCmd("exit");
expectPattern("Connection to host lost");
} catch (IOException ex) {
System.out.println("Exception : " + ex);
}
}
I got the following error
java.io.IOException: Cannot run program "C:\Windows\System32\telnet.exe": CreateProcess error=2, The system cannot find the file specified
I tried to change the file path to unix formatted style like C:/Windows/System32/telnet.exe and no luck. (Though I expected it to not to work). Then copied the telnet.exe from it's location to some other user's home directory and I was not getting any errors. (???)
But, I didn't see the output as expected. I didn't get any response from the process and the code exited.
public static void sendCmd(String cmd) {
System.out.println(cmd);
try {
telnetOuputWriter.write(cmd + "\n", 0, cmd.length());
} catch (IOException ex) {
Logger.getLogger(TelnetProcessHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static String expectPattern(String pattern) {
String cmdResponse = "";
try {
String line = "";
// Always getting 'null' here
while ((line = telnetInputReader.readLine()) != null) {
System.out.println(line);
cmdResponse += line;
if (line.contains(pattern)) {
break;
}
}
} catch (IOException ex) {
System.out.println("ex : " + ex);
}
return cmdResponse;
}
What is wrong in this ? Then, one other query. I have tried using PrintWriter for writing to process which in turn has BufferedWriter in it, like,
telnetOuputWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(telnetProcess.getOutputStream())));
Is this fine to use PrintWriter in this context ?
Note : Due to some reasons, I would like to stick with using telnet by means of process, not with Socket or TelnetClient or expect4j.
The telnet program does not use the standard input and output streams to communicate with the user, it needs to use the console device directly. You'll have to find an alternative way of doing what you're trying to do.
For example you could use a Java library that implements the telnet protocol. See this question for example: Open source Telnet Java API

How to detect java process exit?

In a java program, I am generating an sh script for use on a centOS machine, which will use sox and lame to decode an MP3 audio file, then apply some gain to the file respectively. Im having some issues getting the Process.waitFor() method to do anything other than hang indefinitely. Here is the code:
try
{
// TODO code application logic here
String reviewPath = "/SomeDirectory/";
String fileName = "FileName";
String extension = ".mp3";
StringBuilder sb = new StringBuilder();
sb.append("#!/bin/bash\n");
sb.append("cd " + reviewPath + "\n");
sb.append("lame --decode " + fileName + extension + "\n");
File script = new File(reviewPath + fileName + ".sh");
script.createNewFile();
script.setExecutable(true);
FileWriter writer = new FileWriter(script);
writer.write(sb.toString());
writer.close();
Process p = Runtime.getRuntime().exec(script.getAbsolutePath());
String line;
BufferedReader bri = new BufferedReader
(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p.getErrorStream()));
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
p.waitFor();
System.out.println("Done.");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
The odd part is that when I run the .sh file it generates by hand, it runs and exits nicely, but when I execute it from a process object in java, it never exits. The exitValue of the process is always "Process has not exited". Ive tried adding set -e to the script, and exit to the end of the script. Short of using the kill command (which I dont really think I can do here) Im at a loss as to what is going on here. Any suggestions?
Add something like while(p.getInputStream().read() != -1); after starting the process. The buffer will get filled and the process will stop waiting for something (in this case, your program) to read from it to free up space.
I figured it out! The problem here was indeed that the output streams needed to be flushed for the application to exit, but simply reading from the streams is not enough. I used Suresh Koya's suggestion and used the processBuilder api, and redirected the error stream on the process before starting it, and read from the streams. This fixed the issues I was having :D

Categories