How to run a script from Java - java

I have a script, which is test.sh on Ubuntu. I want to run it from Java. I know I have to use Runtime.getRuntime().exec();
Don't I have to fill the exec parenthesis with the location of test.sh? I am typing /home/main/ss/test.sh
I do not get any error messages but when I searched the folder, I saw that script did not work. How can I fix it?

You should really look at Process Builder. It is really built for this kind of thing.
ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
Process p = pb.start();

Did you try to call your script directly, or did you specify a shell to use? You may need to specify the shell on your exec call if it's not specified (and processed) from the first line of the script.

From looking at your description, how you conclude the script didn't work:
I do not get any error messages but when I searched the folder, I saw
that script did not work. How can I fix it?
I conclude, the script creates a new file, and there is none, after starting from Java.
Maybe you assume, that the output of the script will, if sent to the current directory, end in the directory of the script, not in the directory where you started your Java application.
This might be the Desktop, if you start your class from the UI with an Icon as starter, it might be your home or project dir, if you compile the class from hand, or a directory, set up by your IDE, if you develop with eclipse or the like.
If your script writes to an absolute path like /tmp/script.out, you could verify fast, whether this might be your issue.

Related

Gazebo model path issue when starting from Java

My team is currently working on a project in Java that involves the robot simulation software Gazebo. To launch Gazebo with a specific world, we have written a shell script that we want to execute with the Runtime.getRuntime().exec(...) command in Java (or ProcessBuilder).
Here is our problem:
If we start that script from the terminal, everything works perfectly i.e. you can see a world with one of our models (pylons):
However, if we try to execute that script from within our Java application, it just shows this (models are recognized but not visualized):
We assume that Gazebo doesn't find the gazebo model path although they are defined in ~/.bashrc.
Has anyone an idea why it is not working. We know that most of you may not know Gazebo, but maybe some of you have dealt with similar issues.
Thanks in advance!
I found a solution that works for us:
Instead of the "Runtime.getRuntime().exec(...)" command, I use the ProcessBuilder.
ProcessBuilder builder = new ProcessBuilder();
builder.command(your_command);
builder.directory(new File(your_path));
Map<String, String> env = builder.environment();
env.put("GAZEBO_MODEL_PATH", variable_content);
Process process = builder.start();
Now, we can set GAZEBO_MODEL_PATH here and Gazebo loads all worlds correctly

executing bash commands from a specific directory

From my application I have to execute an external jar of which I do not have the source.
Given an input file, it processes it, creates an "output" directory and puts in it an mxml output file. Problem is: it creates said directory in tomcat/bin instead of inside the directory of the original file.
Here's what I've tried so far.
Initially
Process p = new ProcessBuilder("java -jar "+newfile.getParent()+"\\converter.jar "+newfile.getPath()+" -mxml").start();
Then, seeing how from console the "output" directory was created in the directory the command was called from, I tried:
String startSim[] = {"cd "+newfile.getParent()+"\\" , "java -jar converter.jar "+newfile.getName()+" -mxml"};
try {
Runtime.getRuntime().exec(startSim).waitFor();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Log non creato.");
}
But with this I get the "file not found" exception for the first instruction. Does anyone know how to possibly solve this problem? I'd like to avoid having to reach for my output file all the way in my tomcat/bin directory.
Thanks for any suggestion!
Paolo
P.s.: by the way, before trying all this I tried simply calling the method I need from the library, but had the same exact problem. So I resolved to execute the jar, instead. And here we are. :)
You can set working directory using ProcessBuilder.directory() method:
ProcessBuilder pb = new ProcessBuilder();
pb.directory(new File("mydirectory"));
pb.command(......);
etc
This does not work for you when you are using Runtime.exec() because cd command is a functionality of shell. You could solve it using this technique but you have to create platform specific command with prefix like cmd /c on windows or /bin/sh on Linux. This way is definitely not recommended.
But in your specific case you do not neither first nor second solution. Actually you are starting one java process from another. Why? you can easily invoke the main() method of the second process directly.
Take a look on META-INF/MANIFEST.mf file from converter.jar. Field Main-Class contains the fully qualified name of main class. Let's say it is com.converters.Main (just for example). In this case you can invoke
com.converters.Main.main(new String[] {newFile.getPath(), "-mxml"});
directly from your code. Just add the jar to your classpath.
Concerning to changing working directory in this case. Check again whether you really need this or your converters.jar supports parameter that does this.
A lazy approach to this may be going to the root directory and descending from there to your tomcat bin directory .

How to call the linux command "source FILE_NAME" from Java?

Actually I have two commands :
source FILE_NAME
Install ABCD
Before executing the second command, i need to execute the first one. I tied to execute both the command using Runtime.getRuntime().exec(cmd) methos, but second command failed, since it depends on the first one. I tried many combinations, but not succeeded. Can anybody please help me?
You're probably executing two separate exec commands, spawning separate processes, and so whatever you do in the first process is not visible to the second. Resolve this by putting all of your commands into a script (bash, ksh, etc) and call it once from your Java program.
Paramterize your script so you can pass arguments.
Here's some help on writing your first shell script
[Edit] As mentioned by #RNJ you can look at using ProcessBuilder to pass in environment variables to each of the processes spawned. This will be fine if you can specify the name of the file being created ahead of time. Example code taken from the API link above...
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
Process p = pb.start();

Change PWD of linux from JSP

I need to execute linux commands from JSP.
It is working fine.
But i need to start some sh file in a particular directory in linux through JSP. say /home/username/something/start.sh
try{
String command= "cd /home/username/something";
Runtime.getRuntime().exec(command);
Runtime.getRuntime().exec("./start.sh")
out.println("Child");
}
catch(Exception e)
{ out.println("Error");
}
It says FIle or Directory not found.
I tried Runtime.getRuntime().exec("pwd"), It is showing something like "java.lang.UNIXProcess#fc9d2b" !! :O
I need to change the pwd and execute some commands through jsp. How can i do that??
Any help would be appreciated.
You shouldn't (and actually, it seems you can't) set a working directory like that. Each Process object given by Runtime.exec() will have its own working directory.
As answered in How to use “cd” command using java runtime?, you should be using the three argument version of Runtime.exec(), in which you provide a File that will be the working directory. From its javadoc:
Executes the specified command and arguments in a separate process with the specified environment and working directory.
Or even better, use ProcessBuilder along with ProcessBuilder.directory() instead:
ProcessBuilder pb = new ProcessBuilder("start.sh");
pb.directory(new File("/home/username/something"));
Process p = pb.start();

Running .jar file within JSP page

I'm trying to develop a website that takes user input and converts to a text file. The text file is then used as an input for a .jar file. (e.g. java -jar encoder.jar -i text.txt), the jar then outputs a .bin file for the user to download.
This jar is designed to be run from command line and I really don't know the best way to implement it within a .jsp page. I have created a few java test classes but nothing has worked so far.
Does anyone have any suggestions on possible methods?
An alternative to running it as an external process is to invoke its main class in the current JVM:
Extract/open META-INF/MANIFEST.MF of the jar
Identify the Main-Class:. Say it is called EncoderMainClass
Invoke its main method: EncoderMainClass.main("-i", "text.txt")
This aught to be faster because a new OS process does not need to be created, but there may be security considerations.
Have you tried somrthing like this,
Create a java file
use a ProcessBuilder and start a new JVM.
Here is something to get you started:
ProcessBuilder pb = new ProcessBuilder("/path/to/java", "-jar", "your.jar", "thetextfile.txt");
pb.directory(new File("preferred/working/directory"));
Process p = pb.start();
ps: do handle to destroy process else it will eat up all memory
You can put this jar to the web application on the classpath and use it's class and methods. Better if you have javadoc if you don't have sources. But even if not in classpath you can try the example or this example.

Categories