I am executing a.jar file from PHP through Command Line. However, if there is any error/exception, the error is not being displayed.
I am using the following PHP script.
<?php
exec('java -jar D:\\ABC\\JavaApplication2\\dist\\JavaApplication2.jar', $result, $returnCode);
var_dump($result);
$count = count($result);
for($i=0; $i<$count;$i++){
print($result[$i]);
}
?>
The output for the above code is : 'array(0) { }'
don't use exec() if you want to handle I/O, instead use popen() for simple stuff (either read or write) or proc_open() for full fd connectivity, with stdin, stdout, stderr, and possibly other fd's connected (e.g. for openssl).
Probably you need to pipe the output of the jar to some file and listen to that file in PHP.
Related
I tried JAVA bridge to get output from my jar file followed this https://stackoverflow.com/a/10253798/1870048, I am using XAMP Server and from that Apache and Tomcat server is been used
require_once("http://localhost:8080/JavaBridge/java/Java.inc");
$cartObj = Java("Cart"); //Javav("Cart");
$cartObj->Cart("098765");
$cartObj->setLang("EN");
echo $cartObj->getLang();
but gives error :
Fatal error: Call to undefined function Javav()
What should I exactly I look into?
Also I tried below way also to call the jar file by placing the jar file in my zampp htdoc folder: (D:\xampp\htdocs\jar)
// Using shell_exec
exec('java -jar AutoDiscounts.jar '.$jsonRequest.' 2>&1', $result);
print_r($result);
// Using shell_exec
$arg1 = $jsonRequest;//"My_INPUT_PARAMETER";
$output = '';
$output =shell_exec("java -jar AutoDiscounts.jar $arg1");
echo "Done calling shell exec:";
echo $output;
But both above cases does not give any output .Basically my jar will do some cart processing and return output and it works in the JDevloper
When I run myTest.jar, it outputs alot of information in STDOUT (not in a file) and I am trying to read/search that file for a specific string to put as a variable in my bash script.
java stdout:
line 1 info............
line 2 info...........
....
...
Successful (either 'Successful' or 'Failed')
How do I search for, in bash, the last line in the stdout or for ('Successful' or 'Failed') without redirecting the stdout to a file?
Thanks in advance
This is not a good way of checking for success or failure.
You should instead rewrite myTest.jar to use System.exit(0) on success and System.exit(1) (or higher) on error. If the program is well written, it will already do this.
You can then check for success or failure in bash using e.g.
if java -jar mytest.jar
then
echo "The command succeeded :D"
else
echo "The command failed :("
fi
All UNIX programs work this way, and you should make sure that myTest.jar is no exception.
To make this work, you would need to redirect stdout to a file and then cat/vim/search that file. Bash doesn't save the output of commands on its own.
Alternatively, you could use a program like screen that allows you to save a transcript of your session to a file. You would get the output of everything and the command lines though.
for future users, I used "that other guys' " method with some minor adjustments:
1) the exit code and what your doing have to be right after the running jar, wouldn't work for me in other segments
2) I read the exit code I was receiving and made an if loop for my conditions (0-2) exit code was given in java
3) piece of my bash code
EXIT_CODE=$?
echo Exit code: $EXIT_CODE
if [ $EXIT_CODE = "0" ]
then
...............do something
elif [$EXIT_CODE = "1"]
then
...............do something
else
...............do something
fi
I have two java classes that reside in .../jtest/StepRegTest directory and include "package StepRegTest;" directive.
Option 1. I call it directly from shell:
[jtest]# java StepRegTest.Main
Everything works fine.
Option 2. I call java via PHP exec:
<?php
echo getcwd() . "\n";
exec("java StepRegTest.Main 2>&1", $output);
print_r( $output );
?>
The PHP file is in the same directory jtest as for the Option 1, when I call it from the shell. However, it returns an error:
Exception in thread "main" java.lang.NoClassDefFoundError: com/quinncurtis/matpackjava/DMatBase
The jar archive that refers to these missing classes is in the CLASSPATH.
The import reference for that class is:
import com.quinncurtis.matpackjava.DDMat;
Note that everything works fine when I execute the code from the shell.
What is the problem here? Why does it work from the shell, but not from PHP?
Thanks!
If the CLASSPATH environment variable is being used, verify it's set at the time the php exec() call is made; it may be getting lost.
One easy way to check is this:
<?php
echo getcwd() . "\n";
exec("env", $output);
print_r( $output );
?>
To set the CLASSPATH variable in the php script, the following can be done:
putenv("CLASSPATH=/path/to/lib.jar");
Here's a page that describes putenv():
http://php.net/manual/en/function.putenv.php
I have the following script where I call a java program that writes a YAML output to Strandard output stream, and that is echoed (Simple).
#!/bin/bash
echo `/usr/lib/jvm/jre/bin/java -jar /etc/puppet/enc/enc.jar $1`
I have the above script in file/etc/puppet/enc/javaEnc.sh When I execute this providing node name as argument I get the following output.
---
classes:
class1:
class2:
The problem is, on the agent node, I get the error message
err: Could not retrieve catalog from remote server: Error 400 on SERVER: Could not find node 'node-agent-1'; cannot compile
warning: Not using cache on failed catalog
err: Could not retrieve catalog; skipping run
I have found that the script does not execute (or rather my java program is not called, don't know why) - In my java program I write the output to a file in addition to doing a System.out.print.
I have a another script where I read the file (data.yaml) that contains the same data as I mentioned as output and writes it to output stream by following script.
#!/bin/bash
cat "/etc/puppet/enc/data.yaml"
When this script is mentioned against external_nodes, it works fine, the puppet agent configures itself. Can I please get an idea where I am getting it wrong.? The java program actually queries some external resources and classifies the classes and produces the output - it takes around 10 seconds to get this done. Could this be a problem ? I have seen ruby and python solutions - couldn't get them to work either. I would like it done with Java most preferably.
In my puppet.conf file I have the following.
[master]
node_terminus = exec
external_nodes = /etc/puppet/enc/javaEnc.sh
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
?>