URI is not hierarchical. How to get File Path using getResourceAsStream - java

private void generateDATFiles() throws Exception {
File shellScriptPath= new File((this.getClass().getResource("/Vorlagen/Simulation/test.sh").toURI()));
ProcessBuilder pb = new ProcessBuilder(shellScriptPath.getAbsolutePath());
Process p = pb.start();
}
So I have a shell script which I want to execute. The problem is that I need the file path and I can get it using getResource but I get the error that my uri is not hierarchical so I found out that I need to use getResourceAsStream to avoid the error, but my question is how I can get the file path using getResourceAsStream?

Unfortunately it won't be an easy thing to do. If you pack the .sh script together with the other part of the program in a single .jar it won't work. You can only access it as a resourcestream and not as an URI (even if in development mode you can get the actual URI). That's because the .sh AND the class files and everything is actually in the same file for the file system (.jar).
It's not so much a java limitation as the OS. If the .sh is bundled in the jar/war/any other archive you cannot run it from the java code. (Actually you cannot do it from the command prompt either).
In order to solve it you can get the input stream and write the contents in a temporary file (you can use the java createTempFile functionality) and then execute that one. Or you can extract the .sh file from the jar(zip) and execute it

Try to do with this way.
class J{
public static void main (String a[]){
{
System.out.println(J.class.getResourceAsStream("/file.txt")
}
}

Related

Java JAR file runs on local machine but missing file on others

The JAR file consists of the ffmpeg.exe file and it can run normally on my machine without any problems. However, if I try to run it on another computer it would tell me that java.io.IOException: Cannot run program "ffmpeg.exe": CreateProcess error=2,The system cannot find the file specified from the stacktrace. The way I imported it was
FFMpeg ffmpeg = new FFMpeg("ffmpeg.exe"); //in res folder
...
//ffmpeg class
public FFMPEG(String ffmepgEXE) {
this.ffmepgEXE = ffmepgEXE;
}
The quick fix is you have to put ffmpeg.exe in the same folder with your .jar file.
If you want to read file from resources folder, you have to change this code:
URL resource = Test.class.getResource("ffmpeg.exe");
String filepath = Paths.get(resource.toURI()).toFile().getAbsolutePath();
FFMpeg ffmpeg = new FFMpeg(filepath);

Cannot execute Python script from Java in different directories

I am trying to execute a python script from java which script is in a different directory.
I am calling the following code from Java:
private final String PATH_TO_PREDICTIONS_SCRIPT = "C:\\Users\\User\\Desktop\\Final Year Project\\Documentation\\Predictive Model\\Prediction Model ~ v0.4 10-03-2018\\predictions.py";
public TrainTestResults() throws IOException {
initComponents(); //JFrame
Process p = Runtime.getRuntime().exec("python " + this.PATH_TO_PREDICTIONS_SCRIPT);
}
This python script will save a file with some results in the directory specified which I will read from Java later on.
I am sure it has something to do with the directory formatting as when I execute python scripts from the cmd I have to do this if working in a different directory:
os.chdir(r'path')
Any help on how to do this straight away from the Java runtime process and without moving the files into the same directory would be much appreciated.
Thank you!

Running .JAR file from java code (netbeans)

Im trying to run a jar file from java code, But unfortunately does not success.
A few details about the jar file:
The jar file located in a different folder (For example - "Folder").
The jar file using a files and folders are in the root folder (the same "Folder" i mentioned above).
What im trying to do so far:
JAR file project.
In netbeans i checked that the main class are defiend (Project properties -> Run -> Main Class).
Other JAVA program
Trying to run with the command:
Runtime.getRuntime().exec("javaw -jar "C:\\Software\\program.jar");
&&
Runtime.getRuntime().exec("javaw -jar "C:\\Software\\program.jar" "C:\\Software");
The jar file opened well, But he doesnt know and recognize his inner folders and files (the same "Folder" i mention above).
In short, it does not recognize its root folder.
Trying to run with ProcessBuilder
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "start", "javaw", "-jar", "C:\\Software\\program.jar");
pb.directory(new File("C:\\Software"));
try {
pb.start();
} catch (IOException ex) {
}
In Some PC's its works fine, But in other pc's its not work and i got an error message: "Could not find the main class"
** Offcourse if i run the jar with double click its works.
So how can i run a jar file from other java program ?
Use this variant of .exec where you specify working folder as the third argument. (In your examples, you always only use one argument.)
exec("javaw -jar "C:\\Software\\program.jar", null, "C:\\Software");
You can try to call it something like below. There are 2 types of calling it.
public class JarExecutor {
public static void main(String[] args) throws IOException, InterruptedException {
//This is first way of calling.
Process proc=Runtime.getRuntime().exec(new String[]{"java","-jar" ,"C:\\Users\\Leno\\Desktop\\JarsPractise\\JarsPrac.jar"});
//This is second way of calling.
Process proc=Runtime.getRuntime().exec(new String[]{"java","-cp","C:\\Users\\Leno\\Desktop\\JarsPractise\\JarsPrac.jar","com.shiva.practise.FloydTriangle"});
proc.waitFor();
BufferedInputStream is=new BufferedInputStream(proc.getInputStream());
byte[] byt=new byte[is.available()];
is.read(byt,0,byt.length);
System.out.println(new String(byt));
}
}

Get working directory of another Java process

I can get working directory of current Java program using this code:
Path path = Paths.get(*ClassName*.class.getProtectionDomain().getCodeSource().getLocation().toURI());
Also I can get CommandLine parameters (but there is no directory in the output) of running Java processes using this command wmic process get CommandLine where name='java.exe' /value
It is possible to get working directory of another Java process (better programmatically)? Probably it can be solved with some jdk/bin utilities?
You can get this information via the Attach API. To use it, you have to add the tools.jar of your jdk to your class path. Then, the following code will print the current working directories of all recognized JVM processes:
for(VirtualMachineDescriptor d: VirtualMachine.list()) {
System.out.println(d.id()+"\t"+d.displayName());
try {
VirtualMachine vm = VirtualMachine.attach(d);
try(Closeable c = vm::detach) {
System.out.println("\tcurrent dir: "+vm.getSystemProperties().get("user.dir"));
}
}
catch(AttachNotSupportedException|IOException ex) {
System.out.println("\t"+ex);
}
}

Running shell script on tomcat7

I have been breaking my head for two days trying to fix the file permissions for my tomcat7 server. I have a library class (.jar file included in myapp/WEB-INF) which needs to run a shell script. The library is written by me and works fine within NetBeans ie. no hassle in creating,reading and deleting files. That is because NetBeans runs the program as blumonkey(my username on my Ubuntu System). But when I import this into tomcat and run it, tomcat "executes" the command, produces no definite output, tries to check for a file(which will be generated when the script succeeds) and throws a FileNotFoundException.
More Details as follows:
Tomcat7 installed using apt-get, has its data in 2 locations - /var/lib/tomcat7 with conf and webapps folders and /usr/share/tomcat7 with the bin and lib folders
The user uploads a .zip file which is stores to /home/blumonkey/data. Rest of the program runs on the documents stored here. All new folders/files uploaded by tomcat have, obviously, tomcat7 as the owner.
I have tried things like changing the ownership to blumonkey, adding tomcat7 to blumonkey user group but none of the methods worked (Somewhere around here I probably messed up changing permissions carelessly :/ ). Apparently tomcat7 is unable to process on the files it owns.(How can this be?).
The script works when I run it in the terminal. But it doesn't work when I do a sudo -u tomcat7 script.sh, ie run it as tomcat7. It just exits with no message. I doubt that this it what is happening as I have tried to debug by redirecting the errors and outputs in ProcessBuilder but they came empty.
Any help regarding how to fix the issue and get the script running would be greatly appreciated. Please comment if you need any more info.
The code for script execution
private static void RunShellCommandFromJava(String command,String fn, String arg1,String arg2) throws Exception
{
try
{
System.out.println(System.getProperty("user.name"));
ProcessBuilder pbuilder = new ProcessBuilder("/bin/bash",command,fn,arg1,arg2);
System.out.println(pbuilder.command());
pbuilder.redirectErrorStream(true);
Process p = pbuilder.start();
p.waitFor();
}
catch(Exception ie)
{
throw ie;
}
}
The command which needs to be executed
"/bin/bash /abs/path/to/script.sh /abs/path/to/doc/in/data-folder maxpages=30 maxsearches=3"
PS : I have followed this question but it didn't help. I also tried other options like Runtime.exec(), bash,/bin/bash/ and /bin/bash/ -c, some of them don't work at all, others give no results.
Try to use Runtime and check standard error to find out what was the problem (probably permissions or paths):
// run command
String[] fixCmd = new String[] { "/bin/bash", "/abs/path/to/script.sh", "/abs/path/to/doc/in/data-folder", "maxpages=30", "maxsearches=3" };
Process start = Runtime.getRuntime().exec(fixCmd);
// monitor standard error to find out what's wrong
BufferedReader r = new BufferedReader(new InputStreamReader(start.getErrorStream()));
String line = null;
while ((line = r.readLine()) != null) {
System.out.println(line);
}

Categories