Run cmd-line in java fails - java

I am facing the following problem:
I am writing a java-application in Eclipse. Inside my application I want to start a cmd command:
C:/Users/User1/Content-Integration Testing Framework/JDBC Connector/bin/connect -h
The command 'connect -h' is a an enterprise internal application which works fine.
If I would use a comand line a would have to chance my current directory like that:
cd C:/Users/User1/Content-Integration Testing Framework/JDBC Connector/bin/
and afterwards I would just type connect -h
This works great. But I am not really shure how to execute this command within a java application.
Here they tell me how to run a cmd inside a java application:
How to use "cd" command using Java runtime?
But if I do that:
Runtime.getRuntime().exec("'C:/Users/User1/Content-Integration Testing Framework/JDBC Connector/bin/connect' -h");
Eclipse tells me:
java.io.IOException: Cannot run program "'C:/Users/User1/Content-Integration": CreateProcess error=2, Das System kann die angegebene Datei nicht finden
at java.lang.ProcessBuilder.start(Unknown Source)
It cuts my command at "Content-Integration".
can someone help me please?

You should use the version of exec() that takes multiple args via a String array.
Runtime.exec(String s) will split your string using a tokenizer (this is why quoting the string won't work, and why you see the behaviour you do). If you resolve the executable and arguments yourself, and pass each as an array element in the above e.g.
String[] args = new String[]{"executable", "arg1", "arg2"};
Runtime.getRuntime().exec(args); // don't forget to collect stdout/err etc.
then you will bypass Runtime.exec(String s)'s splitting behaviour.

Have you tried:
Runtime.getRuntime().exec("\"C:/Users/User1/Content-Integration Testing Framework/JDBC Connector/bin/connect\" -h");

This happens because your path contains spaces. Make sure to wrap it in "" and it will work.
Runtime.getRuntime().exec("\"C:/Users/User1/Content-Integration Testing Framework/JDBC Connector/bin/connect\" -h");

Related

Getting No such File or Directory Exception on Ubuntu when trying compile a java project from java.lang.Process

Recently, I have switched to Ubuntu v20.04 from Windows 10 Pro v2004 because of performance purposes. When, I was on Windows I can freely compile a java project from another java program by writing:
String pathToCompiler = "\"C:/Program Files/Java/jdk-14/bin/javac\"";
Process compileProcess = Runtime.getRuntime().exec(pathToCompiler+" -d bin #.sources", null, new File("ProjectPath"))
Where the sources file is a file containing the list of classes of the project
The code above works successfully on Windows 10.
But On Linux(Ubuntu):
if I substitute the value of variable pathToCompiler as
pathToCompiler = "\"/usr/lib/jvm/java-11-openjdk-amd64/bin/javac\""
the below exception is raised up and the program executing the command exits:
"/usr/lib/jvm/java-11-openjdk-amd64/bin/javac" -d bin #.sources
java.io.IOException: Cannot run program ""/usr/lib/jvm/java-11-openjdk-amd64/bin/javac"" (in directory "/home/arham/Documents/Omega Projects/Project0"): error=2, No such file or directory
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at java.base/java.lang.Runtime.exec(Runtime.java:592)
at java.base/java.lang.Runtime.exec(Runtime.java:416)
at ide.utils.systems.BuildView.lambda$3(BuildView.java:267)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.io.IOException: error=2, No such file or directory
at java.base/java.lang.ProcessImpl.forkAndExec(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:340)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:271)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
The problem is that the file actually exists but it says No Such File or Directory
Actually, The program which is compiling the project is a Java IDE that I am creatiing.
Someone please tell if he/she knows how to fix this bug
The Runtime.exec method has several problems that make it difficult to use, and this is one of them. Use the newer ProcessBuilder class instead.
String pathToCompiler = "C:/Program Files/Java/jdk-14/bin/javac";
Process compileProcess = new ProcessBuilder(pathToCompiler, "-d", "bin", "#.sources")
.directory(new File("ProjectPath"))
.start();
The differences are:
Remove the extra quotes from around the path to the executable. If quoting is needed, the system takes care of it.
Pass the each command line arguments as a separate string. This way you don't have to worry about quoting.
Update the path to the following:
String pathToCompiler = "/usr/lib/jvm/java-11-openjdk-amd64/bin/javac/";

Error while running docker build command from java code

I am running docker build command from java using following code -
Process p = new ProcessBuilder("docker","build","-f",Dockerfile,"--build-arg",some arguments,"-t","com.test:t-v16",".").start();
But ut gives me error -
Docker build requires exactly 1 arguments.
When googled, it was mentioned, there should be a dot (.) In the end of command. I have added it and still facing the issue.
Same command works on command line.
That's because you need to give a space before the "." in your String array.
Can you try and check it now.
String[] createBaseImage = {"docker","build","-f",Dockerfile,"--build-arg",some arguments,"-t","com.test:t-v16"," ."}:

ProcessBuilder can't find perl

I'm trying to execute a perl script from java with the following code:
ProcessBuilder script =
new ProcessBuilder("/opt/alert-ssdb.pl");
Process tmp = script.start();
But when I execute it it returns
java.io.IOException: Cannot run program "/opt/alert-ssdb.pl": java.io.IOException: error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:488)
at scripttest.main(scripttest.java:11)
Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.<init>(UNIXProcess.java:164)
at java.lang.ProcessImpl.start(ProcessImpl.java:81)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:470)
... 1 more
about the file
ls -l alert-ssdb.pl
-rwxr-xr-x. 1 root root alert-ssdb.pl
I tried running /usr/bin/perl/ with the script as an argument and it also failed with the same exception.
/bin/ls and other simple commands run without a problem though.
Also the first line of the script is #!/usr/bin/perl
and when run on command line it works
what am I missing?
//Update:
The big picture is that I'm trying to call the script via a storm bolt and it fails at that point.
I managed to make it work by defining a python script as a bolt
using
super(python,myscript.py)
(myscript imports the storm library) and from myscript I call the perl script.
I haven't tried yet but I suppose that If I modify the perl script to be a storm bolt it will run nicely.
Try changing
new ProcessBuilder("/opt/alert-ssdb.pl");
to:
new ProcessBuilder("/usr/bin/perl", "/opt/alert-ssdb.pl");
I've had past experiences where not all my environment variables from the shell exist when using ProcessBuilder.
Edited to reflect #dcsohl's comment.

Executing python compiled script (.pyc) in Java

I have a python compiled script (script.pyc , I haven't the .py file)that work well from my windows command prompt, and I want to execute it from my Java's application.
I tried to use runtime() method :
Runtime runtime = Runtime.getRuntime();
runtime.exec(new String[] {"C:\\toto\\tools\\script.pyc" ,"arg","arg2" });
but I get an error :
Exception in thread "main" java.io.IOException: Cannot run program "C:\Nuance\VoCon Hybrid\SDK_v4_3\tools\clctodict.pyc": CreateProcess error=193, %1 n?est pas une application Win32 valid
The script work well in my terminal ("arg" is a txt file, "arg2" is the output name, and the script does its job without any problem).
I also try to launch my script with getDesktop() :
File fie = new File("C:\\toto\\tools\\script.pyc" ,"arg","arg2");
Desktop.getDesktop().open(fie);
There is no problem, but I can't add argument, so I can just see a terminal windows opening during a few second before disappearing instantly.
I have also tried to use JPython, without success too (maybe we can't use methode "execfile" on a .pyc????)
You can do something like
Process p = Runtime.getRuntime().exec(new String[]{"python.exe" ... other args)
Then you can invoke p.waitFor() to wait for the end of the process and p.exitValue() to test if the program exited successfully.
You can also get the output stream via p.getOutputStream() to retrieve the text printed by your python script
Please refer to the class documentation for further information : http://docs.oracle.com/javase/6/docs/api/java/lang/Process.html
Just like you need a jvm to run a .class, you need a python interpreter to run a .pyc.
Try something like:
runtime.exec(new String[] {"c:\\Python26\\bin\\python.exe", "C:\\toto\\tools\\script.pyc" ,"arg","arg2" });

How can I execute a Java program within a php script?

I am writing a simple web upload script.
The goal is to upload a file using php, and then calling a java program to process this file.
I have done the work for uploading the file, but I cannot get a java program to be successfully run from within the php script.
I have tried exec(), shell_exec(), and system() with no results.
For the command, I have used "java Test", "java < directory >/Test", "/usr/bin/java < directory >/Test", I have even set up the application as a jar file with no results. The actual line of code I have used is:
echo shell_exec("java Test");
Usually there is no output. However, if I have just shell_exec("java"), then the last line of the help from java ("show splash screen with specified image") is displayed, which shows that the command has been executed. If I use, for example, shell_exec("whoami") I get "nobody" returned, which is correct. The only thing the java file does is create a file so that I can see that the application has been successfully run (the application runs successfully if I run it on the command line). I have set the permissions for the java file to 777 to rule out any possibility of permission errors. I have been struggling with this for a while trying all sorts of options with no results - the file is never created (the file is created with an absolute path so it's not being created and I just can't find the file). Does anyone have any ideas?
Thanks.
I have been struggling with this for a
while trying all sorts of options with
no results - the file is never created
(the file is created with an absolute
path so it's not being created and I
just can't find the file). Does anyone
have any ideas?
What I think the problem is. Apache runs as "nobody" group??(apache user??) which will execute the java script which will try to create a file on disc somewhere. I assume it does not have permission to write to that location. you should chown that folder so that apache user can write to that folder.
==
First off I would like to point out to you that calling exec() from a script could really blow up your server. I would advice you to use something like redis(see below) instead.
==
Second I think I know what the problem is. You should first try to run the simple example below which worked fine for me.
==
First be sure permission are set right. Because apache runs as nobody(most of the times).
I tried this simple test myself on ubuntu with php installed from repo.
test.java
class test {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
test.php
echo exec('java test');
Ran test.php
$ php test.php
Hello World!
==
Or you could try 1 of the following solutions(which would even be a better solution):
Write your java program as a webservice for example on top of atmosphere-spade-server(simple/embedded jar). This could be written insanely fast. But on high load this will not be best option I guess. Still I think this will be more than fast enough for you probably. Even this way it will be much faster as executing it, because you won't have the overhead running JVM. Could blow up your server, not as fast as exec()
Do a blocking pop/push from a redis(*nix) list structure. This will be pretty easy to write on *nux because there are client libraries for both java/php. The speed will best I guess because redis is written in C. I use redis myself.
Use a JMS like for example activemq. Also pretty easy to write because good library support. I have not used a JMS myself. I use redis solution. The speed I guess would be a little less then with redis solution.
I dont realy know, but i came a cross PHP-JAVA bridge maybe it can help
http://php-java-bridge.sourceforge.net/pjb/
Update:
I tested this with Jasper Reports, and it is working really nice. It will allow you to Extend Java classes with PHP or just use Java class lik it was PHP.
use java\lang\String as JString;
require_once("javabridge/java/Java.inc");
class String extends JString {
function toString () {
return "hello " . parent::toString();
}
}
$str = new String("Java");
echo $str->toString();
or
$temp = new Java('java.sql.Timestamp');
$javaObject = $temp->valueOf('2007-12-31 0:0:0');
$params = new Java("java.util.HashMap");
$params->put("text", "This is a test string");
$params->put("date",$javaObject);
More examples: http://php-java-bridge.sourceforge.net/pjb/FAQ.html
It's possible it has to do with the path that the exec is defaulting to. You may need to explicitly define your classpath with an absolute path to your .class or jar files when calling java.
<?php
$PATH="C:\Program Files\Java\jdk1.7.0_09\bin";
echo exec("javac theNameOfYourJavaProgram.java 2>&1");//shows # of errors
echo "<br />";
echo exec("java theNameOfYourJavaProgram 2>&1");//this line executes it
echo "<br />";
echo shell_exec("javac theNameOfYourJavaProgram.java 2>&1 ");//compiles it
?>

Categories

Resources