Linux is not executing command by Java - java

I am trying to run some servers from a bot, but I can't get it run my screen and host the server. I've tried debugging and getting some kind of code to debug, but I come up with nothing. Maybe it's something in my syntax?
These are the value you can run in: name = factorio, path = /opt/factorio/bin/x64/factorio, args = --start-server map.zip
Together makes:
screen -dmS factorio -m bash -c "/opt/factorio/bin/x64/factorio --start-server map.zip"
public boolean run() {
try {
System.out.println("screen -dmS "+serverName+" -m bash -c \""+path+" "+args+"\"");
Process proc = rt.exec("screen -dmS "+serverName+" -m bash -c \""+path+" "+args+"\"");
BufferedReader read = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String str = null;
while ( (str = read.readLine()) != null)
System.out.println(str);
try {
proc.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Exit value: "+proc.exitValue());
this.setStatus(ONLINE);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}

Related

Executing imagemagick commands with java gives no output

I am writing a java aplication that edits images using imagemagick commands;
However, the comands do not work and I am getting no output from them;
Actually, the comand identify is not recognized and I get CreateProcess error=2;
This seems odd, because the imagemagick instalation folder is included in my Path variable.
Here's my code:
public class Test {
public static void main(String argv[]) {
Runtime ru = Runtime.getRuntime();
Process p = null;
try {
//I've added this as a bouns, this should not be neccessary(methinks)
String[] s = {"C:\\Program Files\\ImageMagick-6.8.6-Q16"};
String[] cmd = {"convert", "acc-logo.jpg","-flip", "edited.jpg"};
p = ru.exec(cmd,s);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader ina = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = null;
try {
while ((line = ina.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You have a space in the path to the executable, and the Runtime.exec() call is having problems with it. Use ProcessBuilder instead; it handles spaces in arguments much more easily.

Calling a batch from java requires to be started from the current batch file folder

I am starting a batch file from my java program which will stop some tomcats, the batch itself works if it will be started from the command line. But starting it from java it does not work, the problem is that the batch wont be called from the folder where its persited. So it cannot find some files, My question is how can i switch to the folder where the batch lies and then start the batch, so that it is runninng from its folder and will find the necessary files.
For example the batch lies in the folder c:\foobar\mybatch.cmd
Here is my code how currently the batch will be called from java
public void startBatch(Path batchPath) {
if (batchPath == null) {
throw new IllegalArgumentException("cannot start batch without path to it");
}
if (!Files.exists(batchPath)){
throw new IllegalArgumentException("batch does not exist " + batchPath.toString());
}
try {
log.info("starting batch " + batchPath.toAbsolutePath().toString());
String command = "cmd.exe /c " + batchPath.toAbsolutePath().toString();
Process p;
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
log.info(line);
line = reader.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
}
You should just put cd c:\foobar\ in the batch file itself.

Windows cmd-output (Java)

I've found this topic, but the code doesn't work for me... Return Windows cmd text from Java?
After pressing a button I want to execute a batch-file, for testing purposes it's just the ipconfig-command.
The cmd-output should be written into a JTextFiled, but all I get is no text...
Here the code for writing it into the JTextField:
btnLock.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String g = "";
try {
Runtime.getRuntime().exec(new String[] {"ipconfig", g});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Process p = null;
try {
p = Runtime.getRuntime().exec(new String[] {"ipconfig", g});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream s = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(s));
String temp;
try {
while ((temp = in.readLine()) != null)
{
System.out.println(temp);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnLock.setBounds(10, 68, 89, 23);
contentPane.add(btnLock);
So what do I do wrong?
It's my first project with cmd-input, so please don't get mad cause of silly mistakes I made. ;)
Thx
Try the exec command that just takes a String parameter. The following test code worked on my system (though I was only printing to console, not to textfield):
BufferedReader in = null;
try{
Process p = Runtime.getRuntime().exec("ipconfig");
InputStream s = p.getInputStream();
in = new BufferedReader(new InputStreamReader(s));
String temp;
while ((temp = in.readLine()) != null) {
System.out.println(temp);
}
} catch (Exception e){
e.printStackTrace();
} finally {
if (in != null) in.close();
}
Also your code in the original post is also using a System.out.println. As far as I'm aware, you can't print to a JTextField using System.out.println.... You'd have to use the setText method.
If I run
ipconfig ""
I get
** Error: unrecognized or incomplete command line.**
You can only run from Java, commands which work on the command line.
BTW: If you are looking for errors, you need to read the error stream.
I would Runtime.getRuntime().exec(new String[] {"ipconfig > temp.txt"}); and then just read it as a text file using a BufferedReader.
I hope this helps.

Run a .dmg file through java code

How can I mount a .dmg file through java code under OS X?
This will work (but only on OS X):
try {
String[] command = {"/usr/bin/hdiutil", "attach", "/Users/path/to/your.dmg"};
String sendback = "";
Process proc = Runtime.getRuntime().exec(command);
InputStream istr = proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
String str;
while ((str = br.readLine()) != null) {
sendback = sendback + str;
}
int resultCode = proc.waitFor();
br.close();
if (resultCode != 0) {
throw new Exception("failed to open system profiler");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DMGs are not executables, are apple diskimages
reference is here
thus you can't "run" it.
You can use a Process, of course. But it won't work anywhere except on a Mac.
Saying that is like asking how to run an ISO file through Java. You simply can't; it's a disk image.

Why does my "if (p.exitValue() != 0)" code run twice?

When I execute a shell script using the method below, my "if (p.exitValue() != 0)" code runs TWICE when it is successful... anyone know why? Also, when the shell script fails, the else code runs once, and then the success code runs again anyway. What am I doing wrong?
void exec(String commander){
Process p = null;
try {
p = Runtime.getRuntime().exec(commander);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StreamGobbler errorGobbler = new
StreamGobbler(p.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new
StreamGobbler(p.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = 1;
try {
exitVal = p.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ExitValue: " + exitVal);
if (p.exitValue() != 0)
{
//SUCCESS Code RUNS TWICE
}
else {
//FAILURE Code Runs Once, then Success Code Runs anyway!! WHY?
}
}
Maybe your void exec(String commander) is being called twice too. Did you check that?

Categories