What is the PHP/Java bridge?
The PHP/Java bridge is a PHP module ("java.so" or "php_java.dll") with an associated backend ("JavaBridge.jar", "JavaBridge.war" or "MonoBridge.exe") which connect the PHP object system with the Java or ECMA 335 object system. It implements JSR 223 (where applicable) and can be used to access CLR (e.g. VB.NET, C#) or Java (e.g. Java, KAWA, JRuby) based applications from PHP scripts. The PHP/Java Bridge communicates with the VM through local sockets using an efficient communication protocol. Each request-handling PHP process of a multi-process HTTP server communicates with a corresponding thread spawned by the VM.
Requests from more than one HTTP server may either be routed to an application server running the PHP/Java Bridge or each HTTP server may own a PHP/Java Bridge and communicate with a J2EE java application server by exchanging java value objects; the necessary client-stub classes (ejb client .jar) can be loaded at run-time.
ECMA 335 based classes can be accessed if at least one backend is running inside a ECMA complient VM, for example Novell's MONO or Microsoft's .NET. Special features such as varargs, reflection or assembly loading are also supported.
Clustering and load balancing is available if the backend runs in a servlet environment supporting these features, tomcat 5 for example.
Unlike previous attempts (the ext/java or the JSR223 sample implementation) the PHP/Java Bridge does not use the java native interface ("JNI"). In case a php instance crashes, it will not take down the java application server or servlet engine.
The bridge adds the following primitives to PHP. The type mappings are shown in table 1.
For java values the PHP syntax
new Java("CLASSNAME")
: References and instanciates the class CLASSNAME.
After script
execution the referenced classes may be garbage collected. Example:
<?php
header("Content-type: application/x-excel");
header("Content-Disposition: attachment; filename=downloaded.xls");
java_require("http://php-java-bridge.sf.net/poi.jar");
// create a 200x200 excel sheet and return it to the client
$workbook = new java("org.apache.poi.hssf.usermodel.HSSFWorkbook");
$sheet = $workbook->createSheet("new sheet");
$style = $workbook->createCellStyle();
// access the inner class AQUA within HSSFColor, note the $ syntax.
$Aqua = new JavaClass('org.apache.poi.hssf.util.HSSFColor$AQUA');
$style->setFillBackgroundColor($Aqua->index);
$style->setFillPattern($style->BIG_SPOTS);
for($y=0; $y<200; $y++) {
$row = $sheet->createRow($y);
for($x=0; $x<200; $x++) {
$cell = $row->createCell($x);
$cell->setCellValue("This is cell $x . $y");
$cell->setCellStyle($style);
}
}
// create and return the excel sheet to the client
$memoryStream = new java ("java.io.ByteArrayOutputStream");
$workbook->write($memoryStream);
$memoryStream->close();
echo $memoryStream->toByteArray();
?>
new JavaClass("CLASSNAME")
: References the class CLASSNAME without creating an instance. The object returned is the class object itself, not an object of the class.
After script
execution the referenced classes may be garbage collected. Example:
$Object = new JavaClass("java.lang.Object");
$obj = $Object->newInstance();
$Thread = new JavaClass("java.lang.Thread");
$Thread->sleep(10);
java_require("JAR1;JAR2")
: Makes additional libraries
available to the current script. JAR can either be
a "http:", "ftp:", "file:" or a "jar:" location. On "Security Enhanced Linux" (please see the README) the location must be tagged with a lib_t security context. Example:
$file=new java("java.io.File", "WEB_INF/web.xml");
java_require("xerces.jar;jdom.jar");
$builder = new java("org.jdom.input.SAXBuilder");
$doc = $builder->build($file);
$root = $doc->getRootElement();
$servlets = $root->getChildren("servlet");
echo "this file has " . $servlets->size() . " servlets\n";
java_closure(ENVIRONMENT, MAP, TYPE)
: Makes it possible to call PHP code from java. It closes over the PHP environment and packages it up as a java class. If the ENVIRONMENT is missing, the current environment is used. If MAP is missing, the PHP procedures must have the same name as the required procedures. If TYPE is missing, the generated class is "generic", i.e. the interface it implements is determined when the closure is applied. Example which uses PHP and Mono:
The java_closure can also be used to emulate try/catch functionality in PHP4. The following example calls the "strategy.call()" method which catches the exception raised in the php method m1() and calls the php method e($ex) with the raised exception as an argument:
class GtkDemo {
var $Application;
function GtkDemo() {
mono_require("gtk-sharp"); // link the gtk-sharp library
}
function delete($sender, $e) {
echo "delete called\n";
$this->Application->Quit();
}
function clicked($sender, $e) {
echo "clicked\n";
}
function init() {
$this->Application = $Application = new Mono("Gtk.Application");
$Application->Init();
$win = new Mono("Gtk.Window", "Hello");
$win->add_DeleteEvent (
new Mono(
"GtkSharp.DeleteEventHandler",
mono_closure($this, "delete")));
$btn = new Mono("Gtk.Button", "Click Me");
$btn->add_Clicked(
new Mono(
"System.EventHandler",
mono_closure($this, "clicked")));
$win->Add($btn);
$win->ShowAll();
}
function run() {
$this->init();
$this->Application->Run();
}
}
$demo = new GtkDemo();
$demo->run();
interface IStrategy {
public void m1();
public int m2();
public int e(Exception ex);
public class Strategy {
public int call(IStrategy phpClosure) {
try {
phpClosure.m1();
return phpClosure.m2();
} catch (Exception ex) {
return phpClosure.e(ex);
}
}
}
}
<?php
function m1 () {
$str=new java("java.lang.String", null); //raises NP exception
if(java_last_exception_get()) return;
echo "in m1"; //never reached
}
function m2 () {
echo "in m2";
return 1;
}
function e($ex) {
echo "exception raised on php level: $ex";
return 2;
}
$s = new Java('IStrategy$Strategy');
$result = $s->call(java_closure());
echo $result; // should display 2
?>
$session=java_get_session(SESSIONNAME)
: Creates or retrieves the session SESSIONNAME
. If SESSIONNAME
is missing, the session is either taken from the J2EE environment if the backend is running in a J2EE application server or servlet environment, otherwise it is taken from PHP. The primitive returns a session handle which can be used to store and retrieve values which survive the current script. The session can be invalidated with $session->destroy(). The java_get_session
shall be used before creating java instances. Session sharing between PHP and JSP is only possible when java_get_session()
is called without a SESSIONNAME
and when the JavaBridge.war is running in a J2EE application server or servlet engine. Please see the ISession interface documentation for details. $_SESSION['var']=val
is equivalent to java_get_session(session_id())->put('var', val)
and val=$_SESSION['var']
is equivalent to java_get_session(session_id())->get('var')
.
The
$session=java_get_session("testSession");
if($session->isNew()) {
echo "new session\n";
$session->put("a", 1);
$session->put("b", 5);
} else {
echo "cont session\n";
}
$session->put("a", $session->get("a")+1);
$session->put("b", $session->get("b")-1);
$val=$session->get("a");
echo "session var: $val\n";
if($session->get("b")==0) $session->destroy();
java_get_session
primitive is meant for values which must survive the current script. If you want to cache data which is expensive to create, bind the data to a class. Example:
// Compile this class, create cache.jar and copy it to /usr/share/java
public class Cache {
public static Cache instance = makeInstance();
}
<?php
java_require("cache.jar");
$Cache = new JavaClass("Cache");
$instance=$Cache->instance; //instance will stay in the VM until the VM runs short of memory
?>
JavaException
: A java exception class. Available in PHP 5 and
above only. Example:
try {
new java("java.lang.String", null);
} catch(JavaException $ex) {
$trace = new java("java.io.ByteArrayOutputStream");
$ex->printStackTrace(new java("java.io.PrintStream", $trace));
print "java stack trace: $trace\n";
}
foreach(COLLECTION)
: It is possible to iterate over values of java classes that implement java.util.Collection or java.util.Map. Available in PHP 5 and above only. Example:
$conversion = new java("java.util.Properties");
$conversion->put("long", "java.lang.Byte java.lang.Short java.lang.Integer");
$conversion->put("boolean", "java.lang.Boolean");
foreach ($conversion as $key=>$value)
echo "$key => $value\n";
[index]
: It is possible to access elements of java arrays or elements of java classes that implement the java.util.Map interface. Available in PHP 5 and above only. Example:
$Array = new JavaClass("java.lang.reflect.Array");
$String = new JavaClass("java.lang.String");
$entries = $Array->newInstance($String, 3);
$entries[0] ="Jakob der Lügner, Jurek Becker 1937--1997";
$entries[1] ="Mutmassungen über Jakob, Uwe Johnson, 1934--1984";
$entries[2] ="Die Blechtrommel, Günter Grass, 1927--";
for ($i = 0; $i < $Array->getLength($entries); $i++) {
echo "$i: " . $entries[$i] ."\n";
}
java_instanceof(JAVA_OBJ, JAVA_CLASS)
: Tests if JAVA_OBJ is an instance of JAVA_CLASS. Example:
$Collection=new JavaClass("java.util.Collection");
$list = new java("java.util.ArrayList");
$list->add(0);
$list->add(null);
$list->add(new java("java.lang.Object"));
$list->add(new java("java.util.ArrayList"));
foreach ($list as $value) {
if($value instanceof java && java_instanceof($value, $Collection))
/* iterate through nested ArrayList */
else
echo "$value\n";
}
java_last_exception_get()
: Returns the last exception instance or
null. Since PHP 5 you can use try/catch
instead.
java_last_exception_clear()
: Clears the error condition. Since PHP 5 you can use try/catch
instead.
PHP | Java | Description | Example |
---|---|---|---|
object | java.lang.Object | An opaque object handle. However, we guarantee that the first handle always starts with 1 and that the next handle is n+1 for all n < 1024 (useful if you work with the raw XML protocol, see the python and scheme examples). | $buf=new java("java.io.ByteArrayOutputStream"); $outbuf=new java("java.io.PrintStream", $buf); |
null | null | NULL value | $outbuf->println(null); |
exact number | long | 64 bit integer | $outbuf->println(100); |
boolean | boolean | boolean value | $outbuf->println(true); |
inexact number | double | IEEE floating point | $outbuf->println(3.14); |
string | byte[] | binary data, unconverted | $bytes=$buf->toByteArray(); |
string | java.lang.String | An UTF-8 encoded string. Since PHP does not support unicode, all java.lang.String values are auto-converted into a byte[] (see above) using UTF-8 encoding. The encoding can be changed with the java_set_file_encoding() primitive. | $string=$buf->toString(); |
array (as array) | java.util.Collection or T[] | PHP4 sends and receives arrays as values. PHP5 sends arrays as values and receives object handles which implement the new iterator and array interface. | // pass a Collection to Vector $ar=array(1, 2, 3); $v=new java("java.util.Vector", $ar); echo $v->capacity(); // pass T[] to asList() $A=new JavaClass("java.util.Arrays"); $lst=$A->asList($ar); echo $lst->size(); |
array (as hash) | java.util.Map | PHP4 sends and receives hashtables as values. PHP5 sends hashtables as values and receives object handles which implement the new iterator interface. | $h=array("k"=>"v", "k2"=>"v2"); $m=new java("java.util.HashMap",$h); echo $m->size(); |
JavaException | java.lang.Exception | A wrapped exception class. The original exception can be retrieved with $exception->getCause(); | ... catch(JavaException $ex) { echo $ex->getCause(); } |
The PHP/Java bridge is a replacement for the experimental ext/java bridge shipped with PHP 4. It is not possible to run the build-in bridge and the PHP/Java bridge at the same time.
The module has been tested on a Mandrake Linux System (Version 9.2), on RedHat Enterprise 3, RedHat Fedora Core 1..4, FreeBSD 5.3, Solaris 9 (Sparc, 64 bit JVM) and Windows with RedHat Cygwin, but it should run on all Unix-like operating systems.
Custom java libraries (.jar files) can be stored in the following
locations:
.jar
files can only be loaded from locations which are tagged with the lib_t security context.
/usr/share/java/
directory, if it exists and is accessible
when the JVM starts the bridge. On Security Enhanced Linux this directory is tagged with the lib_t security context.
The PHP/Java Bridge can operate in 4 different modes: Furthermore the PHP/Java Bridge can be: Installation
instructions If
you have a RedHat Linux system (RedHat 9, RedHat Enterprise 3 or
Fedora), you can download the 32bit RPM and type Make sure you
have java version 1.4 or higher, gcc 3.2 or higher, apache 1.3 or
higher, libtool 1.4.3 or higher, automake 1.6.3 or higher, GNU make, autoconf 2.57 or higher and php 4.3.2 or higher
installed. You can check the version numbers with the commands Download
the source code of the bridge from
http://www.sourceforge.net/projects/php-java-bridge Extract the file
with the command: In
the directory php-java-bridge-v.x.y build the module
for a 32 bit JVM (if you run a 64 Bit JVM, use the Then
install the module as root. Type: Restart
the apache service with the command: You can now test
the web installation. Copy the test.php file to the document root (usually /var/www/html) and invoke the file with your browser. You should see that the bridge module is activated and running. The bridge starts or re-starts automatically whenever you start or re-start the web-server.
In a production environment it is recommended to separate the java VM and the HTTP process by setting the communication channel. The
rpm -i
php-java-bridge-v.x.y-z-i386.rpm
to install it (if you run a 64bit system and a 64bit JVM you need to install the 64bit RPM instead). For other operating systems please follow
the instructions below (on Security Enhanced Linux please use the RPM or please read the README before installation).
java
-version
, gcc --version
, apachectl -version
, libtool --version
, automake --version
, make null --version
, autoconf --version
and
php-config --version
. Make sure that the java version you use
matches the kernel version. RedHat NPTL kernels or kernel >= 2.6
require either an IBMJava2, Sun Java >= 1.4.2_02. For RedHat Enterprise Linux an appropriate java RPM is
available on CD#9. GNU Java is currently only supported on Linux and Solaris if you use the GCC 3.3.x or the upcoming GCC 4.x releases.
cat php-java-bridge_v.x.y.tar.bz2 | bunzip2 |
tar xf -
-m64
flag instead): phpize && ./configure --disable-servlet
--with-java=/opt/IBMJava2-14 && make CFLAGS="-m32"
su -c 'make
install'
<enter password>apachectl restart
java.socketname
should be set to the name of the socket, it will be created if it doesn't exist. The .ini
file should contain:
extension = java.so
[java]
java.socketname="/var/run/.php-java-bridge_socket"
The advantage of this mode is that the java VM no longer depends on the web server and can be examined and re-started independently. The download file contains a script, php-java-bridge.service
, which can be used to start/stop the PHP/Java Bridge as system service. All available .ini
options are listed in table 2.
.ini
options
Name | Default | Description | Example |
---|---|---|---|
java.java_home | compile time option. | The java installation directory. | java.java_home="/opt/jdk1.5" |
java.java | compile time option. | The java executable. | java.java="/opt/jdk1.5/jre/bin/java" |
java.socketname | /var/run/.php-java-bridge_socket | The name of the communication channel for the local backend. Must be an integer on windows. | java.socketname="9167" |
java.log_level | 1 | The log level from 0 (log off) to 4 (log debug). | java.log_level="3" |
java.log_file | /var/log/php-java-bridge.log | The log file for the local PHP/Java Bridge backend. | java.log_file="/tmp/php-java-bridge.log" |
java.hosts | <none> | Additional bridge hosts which are used when the local backend is not available. | java.hosts="127.0.0.1:9168;127.0.0.1:9169" |
java.servlet | Off | The communication protocol. If set to "On", the bridge uses HTTP to communicate with the java.hosts backends. | ;; Make sure that this option is only set java.servlet="On" |
java.classpath | compile time option. | The java classpath. Please do not change the default value | java.classpath="/tmp/myJavaBridge.jar:/tmp/myCasses/" |
java.libpath | compile time option. | The directory which contains the natcJavaBridge.so used for local ("unix domain") sockets. Please do not change the default value. | java.libpath="/tmp/" |
For further
information please read the README, INSTALL and INSTALL.WINDOWS documents contained in
the download files.
Related