Run JAR file in PHP and write a file - java

I have the following problem in php when excecuting a jar file. I use the following command:
exec("java -jar JavaProject4.jar";
The JavaProject4.jar creates a txt file in a path given in the java code.
When i run the project in NetBeans the txt file is created. However, when i excecute the jar in php i don't get any errors but i can't get the file.
Here the java code I use to write the file:
public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException {
Main a = new Main();
List<Double> l1 = new ArrayList<Double>();
l1 = a.compute_features();
//System.out.println(l1);
FileWriter fstream1 = new FileWriter("C:/wamp/www/test/out.txt");
BufferedWriter out1 = new BufferedWriter(fstream1);
out1.write(l1.toString());
out1.newLine();
out1.close();
}
Im using a wamp server with php 5.2.4 and the latest java version.
Thanks a lot!
EDIT:
Problem solved, I moved the main java file in NetBeans to the default package and also fixed a wrong path and now everything is working as expected.
Thanks everyone

When you run it with PHP, how are you doing so? Are you using the PHP CLI (Command Line Interface), or are you running it through an Apache Module (CGI or otherwise)? The reason I ask, is because the problem you are having could have something to do with the user who the script is executing as. If you are using the CLI, you are running as your Windows User, however, if you are running it through Apache, then it is running as whatever user Apache is running as. Therefore, you might need to give the relevant permissions to the Apache user for that directory you are writing to.
Regards,
Ralfe

I think that you need to specify the full path for :
- the java executable
- your jar
Example :
exec("/usr/bin/java -jar /my/java/project/path/JavaProject4.jar");

Related

Execution of Windows batch file using Java ProcessBuilder always returns exit code 0

I'm trying to execute a batch file and get the error code from it in Windows 7 Enterprise 64-bit.
My batch file is c:\test.cmd and contains a single line:-
exit 1
My code for executing the batch file is:-
public static void main(String[] args) throws Exception {
Process process = new ProcessBuilder("c:\\test.cmd").start();
System.out.println(process.waitFor());
}
The output is zero. If I try with:-
new String[] {"cmd", "/c", "c:\\test.cmd"}
the result is again zero.
There doesn't seem to be much magic to the ProcessBuilder API that I'm missing. Can anyone see where my code is going wrong?
Shouldn't I be able to capture the exit code of the batch file?
I think there is something wrong (or different) with my PC. The Apache Commons Exec project source code I downloaded failed unit tests when capturing return codes. Looks to be unsolvable on my PC and haven't found a workaround.

exec not working with java 1.7.21, but in netbeans works fine

I made a little program and it worked fine, but now. First, it mux the xml chapter file in the mkv file, so we get a muxed mkv file. Some day ago I updated java to 1.7.21 and I think this is the problem why it is not working now. It's a little strange, but when I run in netbeans everything is fine, but when I build and I run the .jar file, it is not working. It create the xml file, but not mux in the mkv file (and because not muxed not delete the xml file). Here is the code: (filename=xml file path; mkv=mkv file path)
public void muxing() {
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("c:\\Program Files\\MKVtoolnix\\mkvpropedit.exe --chapters \""+filename+"\" \""+mkv+"\"");
if (p.waitFor()==0) {
File xmlfile=new File(filename);
xmlfile.delete();
}
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
The program worked with java 1.6 and I think with 1.7.17 too. Win7 32bit. Sorry for my bad English.
Oracle has made breaking changes to Runtime.exec() in Java 7 update 21 (and 6 update 45).
If the program name contains spaces, you need to specify command and arguments in an array:
Process p = Runtime.getRuntime().exec(new String[] {
"C:\\Program Files\\MKVtoolnix\\mkvpropedit.exe",
"--chapters", "\""+filename+"\"", "\""+mkv+"\""});
Another option is to use java.lang.ProcessBuilder:
Process p = new ProcessBuilder("C:\\Program Files\\MKVtoolnix\\mkvpropedit.exe",
"--chapters", "\""+filename+"\"", "\""+mkv+"\"").start();
As stated by Oracle:
Applications that need to launch programs with spaces in the program name should consider using the variants of Runtime.exec that allow the command and arguments to be specified in an array.
Alternatively, the preferred way to create operating systems processes since JDK 5.0 is using java.lang.ProcessBuilder. The ProcessBuilder class has a much more complete API for setting the environment, working directory and redirecting streams for the process.

Getting ERROR 4010 when trying to run Pig through Java

I'm trying to run a Pig script through Java. Here's what my code looks like right now:
public static void main(String[] args) throws JSONException, InterruptedException, IOException {
Properties props = new Properties();
props.setProperty("fs.default.name", "hdfs://<some-value>:8020");
props.setProperty("mapred.job.tracker", "<some-value>:54311");
PigServer pigServer = new PigServer(ExecType.MAPREDUCE, props);
Map<String, String> params = new LinkedHashMap<String, String>();
params.put("INPUT_PATH", "hdfs://<some-input-value>");
params.put("OUTPUT_FILE", "hdfs:///user/<some-username>/last-login-out");
pigServer.registerScript("last-login-by-userid.pig", params);
}
But whenever I run the program, I get:
Exception in thread "main" org.apache.pig.backend.executionengine.ExecException: ERROR 4010: Cannot find hadoop configurations in classpath (neither hadoop-site.xml nor core-site.xml was found in the classpath). If you plan to use local mode, please put -x local option in command line.
I've moved the pig-0.10.1 folder that I downloaded from the Apache website into Applications and have added export PIG_HOME=/Applications/pig-0.10.1 in my ~/.bash_profile.
When I log into the <some-value>:8020 server, I'm able to run the Pig script just fine.
Where is your hadoop installation? On my system, the configuration is under /etc/hadoop/conf. Add this to the classpath of your Java program.
For example, for various reasons, I don't use the installed pig bash script; I just call Pig's Main class like this:
java -cp /path/to/pig-0.10.0.jar:/etc/hadoop/conf org.apache.pig.Main`
I have faced the same exception while running Pig from Java. This has been resolved after adding path of hadoop conf directory to the project property libraries add jar/folder
Ref: http://helpmetocode.blogspot.in/2012/04/exception-in-thread-main.html
Thanks,
Kalai

how to launch java file program with processbuilder?

here i'm trying to launch a java program inside another java program.
after some search in the forum i found some clues but my code launches only .exe file and not .java file why?
import java.io.*;
public class Mana
{
public static void main(String args[])
throws IOException, InterruptedException
{
try
{
Process p=Runtime.getRuntime().exec(" D:\\NetBeansProjects\\GetIPAddress\\dist\\GetIPAddress.jar");
}
catch(IOException e1) {System.out.println(e1);}
}
}
for java file you must run javaw.exe(not java, because java.exe shows new console window) from jre:
Process p=Runtime.getRuntime().exec("javaw -jar D:\\NetBeansProjects\\GetIPAddress\\dist\\GetIPAddress.jar");
If you are ok to use 3rd party library, you can use:
http://code.google.com/p/jlibs/wiki/JavaProcessBuilder
Okay, looks like you have several problems.
First, to call a java program as a jar file, you need to have the jar file. Your question first looked like you already had one (producted by Netbeans). So try this:
java -jar D:\NetBeansProjects\GetIPAddress\dist\GetIPAddress.jar
in a console window (cmd.exe on Windows). If this works, then your call as given by Sergey should work too. If it does not work, then you have to look at how to create this jar file.

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