No. The bridge and the VM can run as a sub component of IIS or Apache. The C based extension automatically starts a VM in the minit()
and terminates it in the mshutdown()
hook. The request-handling threads attach themselfs to the persistent VM using the PHP/Java Bridge protocol.
The pure PHP implementation contained in Java.inc
is created during compilation from the other *.inc files located in the java folder. Since some older PHP implementations don't have a opcode cache (sometimes called "accelerator"), we have removed all comments and white space from the source files. Use
require_once("http://localhost:8080/JavaBridge/java/JavaBridge.inc");
if you want to run the original code.
Yes. Simply compile the C based extension and omit the
--with-java=
configure option. The bridge will use the
libgcj
library, which is part of the GNU gcc compiler. This library also uses much less system
resources (memory, files) than a "real" Java VM.
Yes. If your C compiler cannot compile Java classes to native code, use the --disable-backend
configure option and add a java.java=/path/to/your/java/executable
option to your php.ini [java]
section.
Yes, see the examples folder from the source download.
No. You need to compile the C implementation and use the configure option --with-mono
.
The three config options java.log_level
, java.servlet
and java.hosts
can be changed in the php.ini
file (C based implementation) or Java.inc
, which is created from Options.inc
(pure PHP implementation).
Then the bridge uses the next entry from the java.hosts
list. If there are no more entries, the php function java_server_name()
returns null and all other java procedures cannot be used anymore.
Yes. Simply use require_once("http://YOURSERVER:PORT/CONTEXT/java/Java.inc");
Simply deploy the PHP/Java Bridge web archive into the servlet engine or application server listening on port 8080.
Tomcat starts and stops as a system service on Unix and Windows.
Download and install the tomcat servlet engine, deploy the PHP/Java Bridge web archive into the tomcat servlet engine and configure it so that it only listens for requests from local PHP scripts (default).
The PHP/Java Bridge library Java.inc
must be included before it can be used. Therefore the scripts should contain the statement
require_once("...java/Java.inc");
at the beginning of the script. PHP compiles and caches PHP scripts, the Java.inc
library is loaded only once.
Check the PHP error log, see your php.ini
file for details. If the command:
echo '<?php require_once("http://localhost:8080/JavaBridge/java/Java.inc"); echo java("java.lang.System")->getProperties();?>' | php -n -d allow_url_include=On
works in the shell but not within apache, then there's something wrong with your php.ini
file.
Check if your ISP supports Java. Look for a servlet engine like "tomcat" or a J2EE application server like "resin". Check if your ISP supports PHP >= 4.3.2.
In the following example we'll call our web context "webContext".
Unzip the JavaBridge.jar file and edit Java.inc, replace 8080 with your j2EE port number and JAVA_SERVLET=On to JAVA_SERVLET=User. Example for Linux:
mkdir webContext
cd webContext
jar xvf ../JavaBridge.war
Edit java/Java.inc
as follows (lines marked with a "-" should be
removed, lines marked with a "+" should be added):
if(!defineHostFromInitialQuery($JAVA_BASE)) {
- define("JAVA_HOSTS", "127.0.0.1:8080");
+ define("JAVA_HOSTS", "127.0.0.1:YOUR_J2EE_PORT_NUMBER");
- define("JAVA_SERVLET", "On");
+ define("JAVA_SERVLET", "User");
}
Create a Java web archive, for example "webContext.war". Example for Linux:
# ... still within the webContext directory ...
cp ../myJavaLibs/*.jar WEB-INF/lib/
cp ../myPhpPages/*.php .
jar cvf ../webContext.war *
Deploy it into the J2EE application server or servlet engine. Example for Linux:
cp ../webContext.war /usr/share/tomcat5/webapps/
Copy or symlink the web context "webContext" (or whatever you've called it) to the Apache or IIS htdocs (sometimes called "public_html") directory. Example for Linux:
ln -s /usr/share/tomcat5/webapps/webContext $HOME/public_html/webContext
If you want to use the C implementation, "java.so" or "php_java.dll", edit the php.ini so that the java.hosts and java.servlet point to your servlet/J2EE back end. Example:
java.hosts=127.0.0.1:8080 # replace 8080 with the port number of your J2EE server
java.servlet="User" # or "On" or "/webContext/JavaBridge.phpjavabridge"
Browse to http://HOSTNAME/webContext/yourPhpScript.php
. Again, replace the web context "webContext" with the name of your web context.
NOTE: If you want to run the Java VM on a different computer, start
Tomcat or the J2EE server on that computer using the option -Dphp.java.bridge.promiscuous=true
.
Change the 127.0.0.1
above to the IP address of the computer running
the Java VM and make sure that the computer cannot be accessed directly from the internet!
Set up the PHP/Java Bridge cluster as described below. The example uses two nodes named "carlos" and "diego". The HTTP server front end runs on the web server "timon".
Install Apache 2.2.0 or higher.
Enable proxy_module
and proxy_balancer_module
. The following example is for Linux (lines marked with "+" should be added to the conf/httpd.conf
file):
LoadModule rewrite_module modules/mod_rewrite.so
+ LoadModule proxy_module modules/mod_proxy.so
+ LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule cache_module modules/mod_cache.so
Add the following code to the bottom of your conf/httpd.conf
file:
ProxyPass /JavaBridge balancer://mycluster maxattempts=2
<Proxy balancer://mycluster>
BalancerMember http://diego:8080/JavaBridge
BalancerMember http://carlos:8080/JavaBridge
</Proxy>
<Location /balancer-manager>
SetHandler balancer-manager
Deny from all
Allow from 127.0.0.1
</Location>
Start the cluster nodes on "carlos" and "diego".
Browse to http://timon/JavaBridge/
(note the trailing slash) and click on the test.php. Click on refresh. Check if both nodes respond.
Browse to http://timon/JavaBridge/sessionSharing.php
and click on refresh. Check the cookie value.
Browse to http://timon/JavaBridge/numberGuess.jsp
. You should get an exception saying that the class does not implement java.io.Serializable
.
Browse to http://timon/balancer-manager/
.
Please see the mod_rewrite
documentation for more information how to rewrite incoming URLs.
With the configure option --with-java=COMPILETIME_JAVA_HOME,RUNTIME_JAVA_HOME
. For example:
phpize &&
./configure --with-java=/opt/jdk1.5,/usr/java/default &&
make &&
make install
Usually with a java policy
file. An example file has been installed in the php extension directory and can be enabled with:
java.security_policy=On
The bridge uses a wrapper binary which can carry the SUID bit and can be tagged with the SEL security context. This wrapper also allows you to change the standard options, which are: java -Djava.library.path=... -Djava.class.path=... -Djava.awt.headless=true -Dphp.java.bridge.base=... php.java.bridge.JavaBridge SOCKET_NAME LOG_LEVEL LOG_FILE
.
A custom wrapper can be set with:
java.wrapper=/path/to/wrapper/binary
On Unix the bridge terminates the sub-process hierarchy with SIGTERM
, sleep 5 seconds and SIGTERM
, if necessary, sleep 5 seconds and SIGKILL
, if necessary. On Windows the bridge emulates the Unix kill behaviour, the bridge kills the entire sub-process hierarchy so that you can use a cmd /c
wrapper.
Please see the wrapper RunJavaBridge
for an example.
With java_require("foo.jar;bar.jar;...");
. See the README for details.
In php.java.bridge.base
/lib.
When the system property php.java.bridge.base
is not set, libraries are loaded from $HOME/lib
where $HOME
denotes the home directory of the person or component which has started the java VM.
If libraries should be available globally, store them in java.ext.dirs
, for example in /usr/share/java/ext
.
If a library is not yet API-stable, store it into a sub directory of the lib
directory and use the java_require()
procedure. For example java_require("myLibs0.2/foo.jar")
loads foo.jar
from php.java.bridge.base/lib/myLibs0.2
.
It probably doesn't have the permission to access it. Check if baz.jar is a valid Java archive and if its main class is public. Try to disable Security Enhanced Linux and store the jar file into a folder accessible by the apache user and then extract the required Security Enhanced Linux permissions from the audit log.
You probably haven't required the relevant Java library. Or the
class doesn't exist or it is not public or it throws a java.lang.Error
during initialization. Check which library exports the feature and add
the library to the java_require()
statement.
Because Java doesn't have a module system. All interconnected libraries must be loaded with a single java_require()
call. See the README for details.
The java_require()
uses the current class loader, not the bootstrap loader. Use:
java_require("foo.jar");
...
Class.forName("foo",true,Thread.currentThread().getContextClassLoader());
instead.
You can't. Java libraries must be pure Java.
Please read the
documentation of your J2EE server, Servlet engine or Java VM to see if and
how the environment can handle impure Java libraries. A common approach is to store the Java part in java.ext.dirs
and the native part in java.library.path
.
This is a known bug in all PHP/Java Bridge versions < 4.1.0.
Please upgrade to a PHP/Java Bridge version >= 4.1.0 or use a PHP/Java Bridge version <= 3.0.8 and switch off persistent connections: java.persistent_connections=Off
.
Since version 4.1.0, the PHP/Java Bridge correctly uses the current thread context class loader so that, when the Java.inc is loaded from a webApp
, the class loader from that web application is used. For example:
require_once("http://localhost:8080/webApp1/java/Java.inc");
echo java("my.TestClass")->getId(); // assuming that a getId() procedure exists
=> TestClass of webApp1
require_once("http://localhost:8080/webApp2/java/Java.inc");
echo java("my.TestClass")->getId(); // assuming that a getId() procedure exists
=> TestClass of webApp2
Copy log4j.jar
into java.ext.dirs
. Example for JDK 6:
cp log4j.jar /usr/java/packages/lib/ext
Start the log4j viewer. Example for JDK 6:
/opt/jdk1.6/bin/java org.apache.log4j.chainsaw.Main
Start the application server with the options -Dphp.java.bridge.default_log_level=LEVEL
. Example for tomcat:
JAVA_HOME=/opt/jdk1.6 JAVA_OPTS="-Dphp.java.bridge.default_log_level=5" bin/catalina.sh run
Download tomcat 5 or higher, a Java JRE 5 or higher and the PHP/Java Bridge 4.1.6 or higher.
The following example uses two nodes running on two machines called "carlos" and "diego". The web server is running on a third machine which has full access to both nodes (at least it needs access to the ports from the range [9267, [9367).
On all nodes: Extract the tomcat distribution into a directory.
On "diego" add the following to conf/server.xml
:
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
channelSendOptions="8">
<Manager className="org.apache.catalina.ha.session.DeltaManager"
expireSessionsOnShutdown="false"
notifyListenersOnReplication="true"/>
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
address="diego"
port="4000"
autoBind="100"
selectorTimeout="5000"
maxThreads="6"/>
</Channel>
</Cluster>
On "carlos" add the following to conf/server.xml
:
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
channelSendOptions="8">
<Manager className="org.apache.catalina.ha.session.DeltaManager"
expireSessionsOnShutdown="false"
notifyListenersOnReplication="true"/>
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
address="carlos"
port="4000"
autoBind="100"
selectorTimeout="5000"
maxThreads="6"/>
</Channel>
</Cluster>
Copy the "JavaBridge.war" into the "webapps" directory on "diego" and "carlos" and start both nodes. For example with the command:
JAVA_OPTS="-Dphp.java.bridge.promiscuous=true" JAVA_HOME=/opt/jdk1.5 bin/catalina.sh run
Start the web server on the third computer "timon". For example with the command:
apachectl restart
Create a PHP script called "sessionSharing-diego.php" and copy it into the web server document root (usually "/var/www/html" or "~/public_html") on "timon":
<?php
require_once("http://diego:8080/JavaBridge/java/Java.inc"); // change to "java/Java.inc" if you use a load balancer
$session = java_session();
if(is_null($session->get("counter")))
$session->put("counter", new Java("java.lang.Integer", 1));
$counter = java_values($session->get("counter"));
print "HttpSession variable \"counter\": $counter<br>\n";
$next = new Java("java.lang.Integer", $counter+1);
$session->put("counter", $next);
?>
Create a PHP script called "sessionSharing-carlos.php" and copy it into the web server document root (usually "/var/www/html" or "~/public_html") on "timon":
<?php
require_once("http://carlos:8080/JavaBridge/java/Java.inc"); // change to "java/Java.inc" if you use a load balancer
$session = java_session();
if(is_null($session->get("counter")))
$session->put("counter", new Java("java.lang.Integer", 1));
$counter = java_values($session->get("counter"));
print "HttpSession variable \"counter\": $counter<br>\n";
$next = new Java("java.lang.Integer", $counter+1);
$session->put("counter", $next);
?>
Start a web brower and remove all cookies
Browse to http://timon/sessionSharing-carlos.php
and check the generated cookie. It should have the key "JSESSIONID", host attribute "timon" and the path attribute "/". The value should be "1". Click on the browser refresh button to increase the value.
Use the same browser window and navigate to http://timon/sessionSharing-diego.php
and check if there is still only one cookie with the same attributes as before. The value should be "3"
Use the same browser window and navigate to http://timon/sessionSharing-carlos.php
and check if there is still only one cookie with the same attributes as before. The value should be "4".
Switch off "diego" and start it again.
Use the same browser window and navigate to http://timon/sessionSharing-diego.php
and check if there is still only one cookie with the same attributes as before. The value should be "5"
Switch off "carlos".
Use the same browser window and navigate to http://timon/sessionSharing-carlos.php
and check if you get an exception.
Start "carlos".
Use the same browser window and navigate to http://timon/sessionSharing-carlos.php
and check if there is still only one cookie with the same attributes as before. The value should be "6"
Please see your HTTP server documentation and the description above how to set it up as a load balancer. This differs from the architecture described above in that the load balancer forwards the requests to the nodes and the nodes run PHP using the FastCGI mechanism.
Check if your PHP cgi binary supports the -b
flag. If not, compile PHP with the --enable-fastcgi
option
Download and install the J2EE binary: copy JavaBridge.war
into the tomcat webapps
folder.
Copy the JavaBridge.jar
and the php-servlet.jar
from the JavaBridge.war into the tomcat shared/lib
folder. Uncomment the shared_fast_cgi_pool
parameter in the JavaBridge/WEB-INF/web.xml
and add the lines marked with a +
to the tomcat conf/web.xml
:
<!-- ================== Built In Servlet Definitions ==================== -->
+ <!-- PHP Servlet -->
+ <servlet>
+ <servlet-name>GlobalPhpJavaServlet</servlet-name>
+ <servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
+ </servlet>
+ <!-- PHP CGI Servlet -->
+ <servlet>
+ <servlet-name>GlobalPhpCGIServlet</servlet-name>
+ <servlet-class>php.java.servlet.PhpCGIServlet</servlet-class>
+ <init-param>
+ <!-- Remember to set the shared_fast_cgi_pool option -->
+ <!-- in JavaBridge/WEB-INF/web.xml to On, too. -->
+ <param-name>shared_fast_cgi_pool</param-name>
+ <param-value>On</param-value>
+ </init-param>
+ </servlet>
<!-- The default servlet for all web applications, that serves static -->
<!-- resources. It processes all requests that are not mapped to other -->
[...]
<!-- ================ Built In Servlet Mappings ========================= -->
+ <!-- PHP Servlet Mapping -->
+ <servlet-mapping>
+ <servlet-name>GlobalPhpJavaServlet</servlet-name>
+ <url-pattern>*.phpjavabridge</url-pattern>
+ </servlet-mapping>
+ <!-- CGI Servlet Mapping -->
+ <servlet-mapping>
+ <servlet-name>GlobalPhpCGIServlet</servlet-name>
+ <url-pattern>*.php</url-pattern>
+ </servlet-mapping>
<!-- The servlet mappings for the built in servlets defined above. Note -->
<!-- that, by default, the CGI and SSI servlets are *not* mapped. You -->
</web-app>
To test the above settings create a directory testapp
and copy the test.php
file from the JavaBridge.war
into this folder. Type cd testapp; jar cf ../testapp.war *
and copy the testapp.war into the tomcat webapps
folder.
Restart tomcat, browse to
http://yourHost.com:8080/testapp/test.php
.
Check if the PHP Fast-CGI server is running. The process list should display 5 (default) PHP instances waiting in the PHP Fast-CGI pool. If not, check if your PHP binary has been compiled with Fast-CGI enabled. Copy a Fast-CGI enabled binary into the webapps/JavaBridge/WEB-INF/cgi/
folder, if necessary.
Create a directory myApplication
, create the directories myApplication/WEB-INF/lib/
and myApplication/WEB-INF/cgi/
.
Download the J2EE binary and copy the JavaBridge.jar
and the php-servlet.jar
from the JavaBridge.war to the myApplication/WEB-INF/lib/
folder. Copy the contents of the cgi
folder to myApplication/WEB-INF/cgi/
. Create the file myApplication/WEB-INF/web.xml
with the following content:
<web-app>
<!-- PHP Servlet -->
<servlet>
<servlet-name>PhpJavaServlet</servlet-name>
<servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
</servlet>
<!-- PHP CGI processing servlet, used when Apache/IIS are not available -->
<servlet>
<servlet-name>PhpCGIServlet</servlet-name>
<servlet-class>php.java.servlet.PhpCGIServlet</servlet-class>
</servlet>
<!-- PHP Servlet Mapping -->
<servlet-mapping>
<servlet-name>PhpJavaServlet</servlet-name>
<url-pattern>*.phpjavabridge</url-pattern>
</servlet-mapping>
<!--PHP CGI Servlet Mapping -->
<servlet-mapping>
<servlet-name>PhpCGIServlet</servlet-name>
<url-pattern>*.php</url-pattern>
</servlet-mapping>
<!-- Welcome files -->
<welcome-file-list>
<welcome-file>index.php</welcome-file>
</welcome-file-list>
</web-app>
Copy the files sessionSharing.jsp
and sessionSharing.php
from the JavaBridge.war
to myApplication
and create myApplication.war
, for example with the commands: cd myApplication; jar cf ../myApplication.war *
.
The web archive can now be distributed, copy it to the tomcat webapps
directory and re-start tomcat. Visit http://localhost/myApplication/sessionSharing.php
and http://localhost/myApplication/sessionSharing.jsp
.
Download and install the J2EE binary: copy JavaBridge.war
into the tomcat webapps
folder.
Check if the tomcat webapps
directory is shared with the Apache/IIS htdocs
directory. If not, change the Apache/IIS setting, the following example is for Apache 2. Edit e.g. /etc/httpd/conf/httpd.conf
as follows:
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
-DocumentRoot "/var/www/html"
+DocumentRoot "/var/lib/tomcat5/webapps"
#
# Each directory to which Apache has access can be configured with respect
#
# This should be changed to whatever you set DocumentRoot to.
#
-<Directory "/var/www/html">
+<Directory "/var/lib/tomcat5/webapps">
Edit the java.host
and java.servlet
options in your Java.inc
or, if you use the C implementation, the php.ini
:
[java]
java.hosts = 127.0.0.1:8080
java.servlet = On
To test the above settings create a directory testapp
and copy the sessionSharing.php
file from the JavaBridge.war
into this folder. Type cd testapp; jar cf ../testapp.war *
and copy the testapp.war into the tomcat webapps
folder.
Restart Apache or IIS and tomcat, browse to
http://localhost/testapp
, click on sessionSharing.php and check the generated cookie value. The path
value must be /
.
Download the J2EE binary and copy the JavaBridge.jar
and the php-servlet.jar
from the JavaBridge.war into the tomcat shared/lib
folder. Add the lines marked with a +
to the tomcat conf/web.xml
:
<!-- ================== Built In Servlet Definitions ==================== -->
+ <!-- PHP Servlet -->
+ <servlet>
+ <servlet-name>GlobalPhpJavaServlet</servlet-name>
+ <servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
+ </servlet>
<!-- The default servlet for all web applications, that serves static -->
<!-- resources. It processes all requests that are not mapped to other -->
[...]
<!-- ================ Built In Servlet Mappings ========================= -->
+ <!-- PHP Servlet Mapping -->
+ <servlet-mapping>
+ <servlet-name>GlobalPhpJavaServlet</servlet-name>
+ <url-pattern>*.phpjavabridge</url-pattern>
+ </servlet-mapping>
<!-- The servlet mappings for the built in servlets defined above. Note -->
<!-- that, by default, the CGI and SSI servlets are *not* mapped. You -->
</web-app>
Check if the tomcat webapps
directory is shared with the Apache/IIS htdocs
directory. If not, change the Apache/IIS setting, the following example is for Apache 2. Edit e.g. /etc/httpd/conf/httpd.conf
as follows:
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
-DocumentRoot "/var/www/html"
+DocumentRoot "/var/lib/tomcat5/webapps"
#
# Each directory to which Apache has access can be configured with respect
#
# This should be changed to whatever you set DocumentRoot to.
#
-<Directory "/var/www/html">
+<Directory "/var/lib/tomcat5/webapps">
Now that tomcat knows how to handle PHP .phpjavabridge
requests and Apache or IIS can access the tomcat webapps, connect the two components: Edit the java.host
and java.servlet
options in your Java.inc
or, if you use the C implementation, the php.ini
:
[java]
java.hosts = 127.0.0.1:8080
java.servlet = User
The above User
setting enables session sharing between PHP and JSP, it forwards from http://host/myApp/foo.php
to the tomcat back end at 127.0.0.1:8080
using the request PUT /myApp/foo.phpjavabridge
. This triggers the GlobalPhpJavaServlet
configured in the tomcat web.xml
.
Now you need to do the same for JSP. Unlike the PHP/Java Bridge, which only forwards embedded java statements, the tomcat mod_jk
adapter must forward all JSP requests.
Download and install mod jk
, for example
jakarta-tomcat-connectors-1.2.14.1-src.tar.gz
, extract the file into a
folder and type the following commands:
cd jakarta-tomcat-connectors-1.2.14.1-src/jk/native/
./configure --with-apxs && make && su -c "make install"
Add the following lines to the end of the httpd.conf
, the following example is for Apache 2:
LoadModule jk_module modules/mod_jk.so
JkAutoAlias /var/lib/tomcat5/webapps
JkMount *.jsp ajp13
To test the above settings create a directory testapp
and copy the sessionSharing.php
and sessionSharing.jsp
from the JavaBridge.war
into this folder. Type cd testapp; jar cf ../testapp.war *
and copy the testapp.war into the tomcat webapps
folder.
Restart Apache or IIS and tomcat, browse to
http://localhost/testapp
, click on sessionSharing.php and check the generated cookie value. The path
value must be /testapp
. Click on sessionSharing.jsp.
No. The bridge back end is written in pure java, it doesn't use any native code. Native PHP runs within Apache, IIS, a FCGI server or via CGI. If the PHP instance crashes, an error page is returned to the client and the Apache, IIS, CGI container usually starts a new PHP instance for the next request.
If you see the message:
Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://127.0.0.1:8443
(Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?)
this means that PHP cannot connect back to the official SSL port.
Please check the
"Registered Stream Socket Transports" from the phpinfo()
(see the test.php
page), it should display: tcp, udp, ssl, sslv3, sslv2, tls
. If not, please recompile PHP with SSL enabled, use the flag --with-openssl
.
A workaround is to use the official non-SSL port or to open a dedicated local port for the PHP-Java communication. The following example is for Tomcat:
override_hosts
in the web application WEB-INF/web.xml
:
<init-param>
<param-name>override_hosts</param-name>
<param-value>Off</param-value>
</init-param>
Open a local port in the tomcat conf/server.xml
(only necessary if you have disabled the official non-SSL port):
<Service name="Catalina">
[...]
<Connector port="9157" address="127.0.0.1" />
[...]
</Service>
Set the communication port in the PHP .ini
(the phpinfo()
or test.php
displays the location of the responsible .ini
file):
[java]
java.hosts = 127.0.0.1:9157
java.servlet = User
java.hosts
line accordingly.
Restart the application server or servlet engine. Check the settings by running phpinfo()
or by visiting the test.php
page.
It's a JBoss problem, although this problem may also appear in other application servers which do not strictly separate the application/bean domains. The JavaBridge.war already contains the documentClient.jar
as a library, so JBoss references the library classes instead of the bean classes. Just remove the documentClient.jar
from the JavaBridge.war
, re-deploy JavaBridge.war
and run the test again.
In JBoss' default setup the code:
// access the home interface
$DocumentHome = new JavaClass("DocumentHome");
$PortableRemoteObject = new JavaClass("javax.rmi.PortableRemoteObject");
$home=$PortableRemoteObject->narrow($objref, $DocumentHome);
refences the DocumentHome
from the library, which is assignment-incompatible to DocumentHome
from the enterprise bean (DocumentHome@WebAppClassLoader
!= DocumentHome@BeanClassLoader
), so you get a ClassCastException in narrow
.
In contrast the Sun J2EE server correctly separates the beans/applications; the $objref
is a unique proxy generated by a parent of the WebAppClassLoader
, so that narrow
can always cast the proxy to DocumentHome@WebAppClassLoader
, even if a class with the same name is already available from the WebAppClassLoader
.
By providing PHP beans and a description how to manage them, as usual. IOC (sometimes called "dependency injection") requires that you give up control so that the framework can call you when it becomes necessary. The code
class Bean { ... }
java_context()->call(java_closure(new Bean())) || header("$framework");
can be used to pass control from the web server to the framework running on a J2EE node.
The standard java script interface or the proxy used by the invocable interface can be used to call from the framework running on a J2EE node into the allocated PHP scripts running on the web server. The following excerpt from the JSF implementation calls methods from the above PHP bean:
((Invocable)((PhpFacesContext)FacesContext.getCurrentInstance()).getScriptEngine(this, new URL(phpScript))).invoke(method, args);
Please see the JSF implementation for a reference.
With the java
function, for example: java("java.lang.System")
.
The function is defined in http://localhost:8080/JavaBridge/java/Java.inc
as:
function java($clazz) {
static $classMap = array();
if(array_key_exists($clazz, $classMap)) return $classMap[$clazz];
return classMap[$clazz]=new JavaClass($clazz);
}
PHP scripts must explicitly allocate a session with java_session()
. For example:
java_session();
// now the (Remote-)HttpServletRequest knows about the session:
echo java_context()->getHttpServletRequest()->getSession();
System.out
and
System.err
are redirected to the server log file(s). When
PHP scripts are invoked from a java framework (Java Server Faces for
example), even the PHP output is redirected. For the standalone back
end the output appears in the
/var/log/php-java-bridge.log
or in JavaBridge.log, see
.ini option java.log_file
. For the j2ee back end the
location of the log file(s) depends on the j2ee server
configuration.
If you must code it yourself: with
e.g. java_session()->put("buf", $stringBuffer)
or via
$_SESSION["buf"]=$stringBuffer
. The
$_SESSION
is syntactic sugar provided by the php session
module, it uses java_session()
internaly. If you don't want depend on the PHP session module, for
example if you have compiled PHP without the session.so
,
use java_session() instead.
Request-handling threads are started
from a thread pool, which limits the number of user requests to 20
(default), see system property
php.java.bridge.threads
. All further requests have to
wait until one of the worker threads returns to the pool.
When running in a servlet engine, a ContextServer is started which handles the pipe or local socket communication channel.
When java invokes local scripts outside of a HTTP environment, the bridge starts a HttpServer, a ContextServer and a HttpProxy. The HttpProxy represents the PHP continuation and the HttpServer the request-handling java continuation associated with the JSR223 script.
classname$inner
syntax. For example
public interface php {
public class java {
public enum bridge {JavaBridge, JavaBridgeRunner};
}
}
<?php
java_require(getcwd()); // load php.class
$bridge = new java('php$java$bridge');
echo $bridge->JavaBridgeRunner;
?>
Primitive types are wrapped by associated java classes.
The following example uses reflect.Array
to create a new byte
array:
$Byte = new JavaClass("java.lang.Byte");
$byte = $Byte->TYPE;
$Array = new JavaClass("java.lang.reflect.Array");
$byteArray = $Array->newInstance($byte, 255);
$System = new JavaClass("java.lang.System");
$length = $System->in->read($byteArray);
$str = new Java("java.lang.String", $byteArray, 0, $length);
echo "You have typed: $str\n";
The following scripts were executed on one 1.688 GHZ x86 cpu running RedHat Fedora Core 4 Linux and Sun jdk1.6.0:
The PHP 5.1.2 code
<?php
$String = new JavaClass("java.lang.String");
$buf=new java("java.lang.StringBuffer");
$i=0;
java_begin_document();
while($i<400000) {
$i=$i+1;
$buf->append(new java("java.lang.String", $String->valueOf($i)));
}
java_end_document();
print $buf->length() . "\n";
?>
buf=new java.lang.StringBuffer();
int i=0;
while(i<400000) {
i=i+1;
buf.append(new String(String.valueOf(i)));
}
print (buf.length()); print("\n");
buf = new java.lang.StringBuffer();
for(i=0; i<400000; i++) buf.append(new String(i));
print (buf.toString().length());
Command | Script Engine | Communication Channel | Execution time (real, user, sys) |
---|---|---|---|
time jrunscript -l php t11.php | PHP5 + PHP/Java Bridge 3.0.8 | named pipes | 0m20.112s, 0m18.999s, 0m0.651s |
time jrunscript -l bsh t11.bsh | BSH 2.0 | none (native code) | 0m21.342s, 0m20.779s, 0m0.291s |
time jrunscript -J-Xmx512M -J-Xms512M -l js t11.js | ECMA script | none (native code) | 1m36.877s, 0m55.398s, 0m0.323s |
On modern operating systems (Windows, Solaris and Linux) and PHP >= 5.1.4 with an opcode cache enabled, the pure PHP implementation is only 2-3 times slower than either the C based implementation or compiled JSP (=Java servlets).
The following table displays the result of the command:
time for i in `seq 200`
do wget -O/dev/null -o/dev/null http://localhost:8080/JavaBridge/sessionSharing.[php|jsp]
done
OS | PHP (tcp sockets) | PHP (named pipes) | JSP |
---|---|---|---|
Linux (RedHat Fedora 6) | 0m9.465s | 0m9.477s | 0m3.126s |
WinNT (2000) | 0m39.439s | not available | 0m22.904s |
During development the bridge back end can be started with java -jar JavaBridge.jar SERVLET_LOCAL:port#
. Unfortunately the simple servlet engine built into JavaBridge.jar is not very efficient. Please use some other servlet engine instead.
The tomcat servlet engine for example contains scripts which allow you to start Java as a system service on Windows and Unix/Linux.
If you have compiled the C implementation, Apache or IIS can automatically start/stop the Java VM as a sub component.
But in this setup the Java VM runs with the same (restricted) rights as the HTTP server, which may or may not be what you want. On Linux for example the VM is started by a RunJavaBridge executable as a child of the Apache main process. The Java VM runs as user apache/apache and uses the Security Enhanced Linux domain javabridge_t
. It cannot access files such as /etc/passwd and it cannot open tcp sockets to other servers.
Unless you know how to pass options to child processes on Windows or Unix (see the java.wrapper option), and how set/change permissions (see chcon, chmod, chown), we recommend to start the PHP/Java Bridge via a servlet engine or J2EE server. -- You probably already have a servlet engine or J2EE server listening on 8080 or some other port, so that it might not be necessary to install a servlet engine or J2EE server to start the bridge back end.
OutOfMemoryErrors may happen because a cached object cannot be released, either because
When a java.lang.OutOfMemoryError
reaches the request-handling thread, the PHP/Java Bridge thread pool removes the thread from its pool and writes a message FATAL: OutOfMemoryError
to the PHP/Java Bridge log file. The session store is cleaned and all client connections are terminated without confirmation.
If the OutOfMemoryError persists, this means that a thread outside of the PHP/Java Bridge has caused this error condition.
The following code example could cause an OutOfMemoryError:
<?php
session_start();
if(!$_SESSION["buffer"]) $_SESSION["buffer"]=new java("java.lang.StringBuffer");
$_SESSION["buffer"]->append(...);
?>
OutOfMemory conditions can be debugged by running the back end with e.g.:
java -agentlib:hprof=heap=sites -jar JavaBridge.jar
By using java_closure()
and the visitor pattern for example. The tests.php5
folder contains a script_api.php
example which shows how to implement java.lang.Runnable
to run multiple PHP threads, concurrently accessing a shared resource.
With java_begin_document()/java_end_document()
. For example:
java_begin_document();
$s = new Java("java.lang.StringBuffer");
for($i=0; $i<10000; $i++) $s->append($i);
java_end_document();
The above code sends the PHP code as an XML image to the server and executes it there.
With java_values()
. For example:
$s = new Java("java.lang.String");
$c = $chr = $s->toCharArray();
print (java_values($s));
print_r(java_values($c));
With java_closure()
. For example:
class Foo {
function toString() {return "php::foo";}
}
$foo = new Foo();
$jObj = java_closure($foo);
$String = new Java("java.lang.String");
echo $String->valueOf($jObj);
Example:
require_once("http://localhost:8080/JavaBridge/java/Java.inc");
java_require("myLibs/baz-taglib.jar");
$tag = new Java("foo.bar.BazTag");
$session = java_session();
$ctx = java_context();
$servlet = $ctx->getAttribute("php.java.servlet.Servlet");
$response = $ctx->getAttribute("php.java.servlet.HttpServletResponse");
$request = $ctx->getAttribute("php.java.servlet.HttpServletRequest");
$factory = java("javax.servlet.jsp.JspFactory")->getDefaultFactory();
$pc = $factory->getPageContext($servlet, $request, $response, null, true, 8192, false);
$tag->setPageContext($pc);
$value = $tag->doStartTag();
if(($value != Java("javax.servlet.jsp.tagext.Tag")->SKIP_BODY) {
if($value != Java("javax.servlet.jsp.tagext.Tag")->EVAL_BODY_INCLUDE)) {
$tag->setBodyContent($pc->pushBody());
$tag->doInitBody();
}
do {
...
} while($tag->doAfterBody() == Java("javax.servlet.jsp.tagext.BodyTag")->EVAL_BODY_AGAIN)
}
if($value != Java("javax.servlet.jsp.tagext.Tag")->EVAL_BODY_INCLUDE) $pc->popBody();
$tag->doEndTag();
The generated content (if any) can be retrieved from the servlet output stream with:
java_values($response->getBufferContents();
Please see the php_java_lib/JspTag.php
and tests.php5/tag.php
for details.
You can ignore the parameter type.
Java doesn't support real generics on byte-code level. The generics in JDK 1.5 and above are implemented as "erasures"; they are syntactic sugar, useful only for the Java compiler. The generated byte-code is the same as in JDK 1.4.