# VM Bridge FAQ

This file contains answers to frequently asked questions. Please see http://php-java-bridge.sourceforge.net for more information.

## General questions

#### Which alternatives exist?

There are at least 4 other php to java bridges which offer a similar API. One was distributed with PHP 4.0.0 and has been discontinued. Two other bridges are proprietary software, built into a vendor-specific framework from Zend or a J2EE application server from Caucho. Furthermore IBM's Zero framework for Eclipse contains a PHP interpreter written in pure Java and a php to java bridge which can call Java methods in-process.

The only free alternatives are SOAP and XML-RPC, which are up to 50 times slower than the XML protocol implementation used by this VM Bridge.

#### How do I enable the Java extension in my php.ini file?

A Java extension does not exist, so you can't enable it.

The VM Bridge is a network protocol, it requires a running Java VM, for example the servlet container Apache/Tomcat. Or, if you want to call PHP libraries from Java, a running PHP container, e.g. Apache or IIS.

#### What do I need to communicate with Java?

Only the PHP code from `Java.inc` and a running Java application, for example `JavaBridge.jar`, or a running Java servlet, for example `JavaBridge.war`.

Test code:

> `<?php require_once("http://localhost:8080/JavaBridge/java/Java.inc");
> echo java("java.lang.System")->getProperties(); ?>`

#### What do I need to communicate with PHP?

Only the PHP code from `JavaProxy.php` within your PHP web application, the Java libraries `JavaBridge.jar`, `php-script.jar` and `php-servlet.jar`, and a `ContextLoaderListener` declaration in your `WEB-INF/web.xml`

Test code:

> `<% javax.script.ScriptEngine e = php.java.script.servlet.EngineFactory.getInvocablePhpScriptEngine (this, application, request, response, new java.net.URI("http://yourIntranetHost:80/yourPhpWebApp/JavaProxy.php"));
> out.println("yourIntranetHost running PHP version: " + (String)((javax.script.Invocable)e).invokeFunction("phpversion", new Object[]{}));
> ((java.io.Closeable)e).close(); %>`

#### Which versions are supported?

- PHP >= 5.1.2. PHP >= 5.3 recommended.
- Java >= 1.4. Java >= 6 recommended.
- J2EE >= 1.3.

#### Why doesn't the bridge throw a java.lang.RuntimeException or Error as a PHP JavaException by default?

All exceptions crossing the php/java container must be declared. If you want to catch `java.lang.RuntimeException` or `java.lang.Error` from PHP code, add a "throws" declaration. Example:

> `public Object calculateValue(...) throws RuntimeException;`

It is a good programming practice to not allow `java.lang.RuntimeException` and `java.lang.Error` to cross an application container boundary. A JEE "enterprise java beans" container for example will terminate a transaction immediately if it encounters an exception derived from Error or RuntimeException.

However, since PHP/Java Bridge version 5.5.3 the bridge reports a java.lang.RuntimeException/Error as a PHP JavaException if the option `JAVA_PREFER_VALUES` is set. Please see the NEWS entry for version 5.5.3 from the PHP/Java Bridge documentation download for details.

#### Do I need a Java Application Server or Servlet Engine?

Yes, Java needs an execution environment. Experienced users may use the execution environment built into JavaBridge.jar, see `java -jar JavaBridge.jar --help` for help.

You can also add PHP support to your standalone Java application by adding the following line to its main class:

> `static final php.java.bridge.JavaBridgeRunner runner = php.java.bridge.JavaBridgeRunner.getInstance(8087);`

The above code opens the port 8087, so that local PHP scripts can call methods/procedures from your Java application, as long as your Java application is running.

The third option is the standard JSR 223 script interface, which allows one to execute PHP code/scripts from Java applications.

#### Ho do I enable logging?

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`

Example for the standalone container:

> `java -Dphp.java.bridge.default_log_level=5 -jar JavaBridge.jar SERVLET:8080`

#### How can I set Java options?

With the -D flag. See `java -jar JavaBridge.jar --help for details. If tomcat is being used, one can set these options as follows:`

> `JAVA_OPTS="-D... -D..." /opt/tomcat/bin/catalina.sh run`

#### How can I increase the memory available to Java?

Use a VM >= 1.6 and add more RAM to your computer. Older Java versions support the `Xmx` flag:

> `java -Xmx512M ... -jar JavaBridge.jar SERVLET:8080`

#### How can I set PHP options?

With a `define` before a PHP library is loaded. Global options can also be set in the `php.ini` file. Use phpinfo() to see the location of this file.

#### How can I configure the bridge?

Useful options which can be set before the Java.inc is loaded are:

> `define ("JAVA_PREFER_VALUES", false);
> define ("JAVA_HOSTS", "127.0.0.1:8080");
> require_once ("java/Java.inc");
> ...`

Please see the Options.inc for details.

Server-side options can be set in the php.java.bridge.global.properties file, see the JavaBridge.jar zip file (contained in the JavaBridge.war zip file) for details.

#### Can I use Java libraries without installing java?

Yes. On a GNU operating system (e.g.: GNU/Linux, GNU/windows (aka "cygwin"), ...) you can use the GCC compiler to compile Java classes to native code. 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.

GCJ support has been removed in PHP/Java Bridge version 6. If you want to compile JavaBridge.jar to native code, please use PHP/Java Bridge version 5.5.4 instead.

#### I can't load the resource or file from the current working directory!?!

The "current working directory" is not useful, as the Java back end may be running on a different server or from a different working directory. Use a full path or a URL resource instead.

#### I get a blank page or some other error!?!

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.

#### Can I use Python instead of PHP?

Yes, see the examples folder from the source download.

#### Can I access Mono or .NET libraries using the pure PHP implementation?

Yes, PHP/Java Bridge version < 6 contains a PHP library "Mono.inc" generated from "Java.inc" and a "MonoBridge.exe" generated from "JavaBridge.jar". If you want to compile from source, use the configure option `--with-mono`.

Mono/.NET support has been removed in PHP/Java Bridge version 6. If you want to access Mono/.NET libraries, please use PHP/Java Bridge version 5.5.4 instead.

#### What does a "protocol error ..." mean?

That your Java has problems, for example an OutOfMemoryError. Check the back end (Tomcat/J2EE/...) log for details.

It could also indicate a setup problem. If you use a servlet back end but haven't set the `java.servlet` or `JAVA_SERVLET` option, the PHP library `Java.inc` will confuse the HTML response from the servlet engine with the XML protocol used by the bridge.

#### Does it support PHP 4?

Start a simple socket listener and use the following "Java" class:

> `<?php
> // The following is the "Java" class definition, stripped down to fit
> // into one line. To use this sample start Java with: java -jar
> // JavaBridge.jar INET:9267. Then type: php sample.php
> //
> class P{var$Pc="<C v=\"%s\" p=\"I\">",$PC="</C>",$Pi="<I v=\"%d\" m=\"%s\" p=\"I\">",$PI="</I>",$Ps="<S v=\"%s\"/>",$Pl="<L v=\"%d\" p=\"%s\"/>",$Po="<O v=\"%d\"/>",$c;function str($s){fwrite($this->c,sprintf($this->Ps,$s));}function obj($s){fwrite($this->c,sprintf($this->Po,$s->j));}function P(){$this->c=fsockopen("127.0.0.1",9267);}function cB($s){fwrite($this->c,sprintf($this->Pc,$s));}function cE(){fwrite($this->c,$this->PC);}function iB($o,$m){fwrite($this->c,sprintf($this->Pi,$o,$m));}function iE(){fwrite($this->c,$this->PI);}function v($s){if(is_object($s))$this->obj($s);else$this->str((string)$s);}function res(){$r=sscanf(fread($this->c,8192),"%s v=\"%[^\"]\"");return$r[1];}}function gP(){static$p;if(!$p)$p=new P();return$p;}class Java{var$j,$p;function Java(){if(!func_num_args())return;$this->p=gP();$ar=func_get_args();$this->p->cB(array_shift($ar));foreach($ar as$arg)$this->p->v($arg);$this->p->cE();$ar=sscanf($this->p->res(),"%d");$this->j=$ar[0];}function __call($m,$a,&$rv){$this->p->iB($this->j,$m);foreach($a as$arg)$this->p->v($arg);$this->p->iE();$p=new Java();$ar=sscanf($this->p->res(),"%d");$p->j=$ar[0];$p->p=$this->p;$rv=$p;return true;}function toString(){$this->p->iB("","castToString");$this->p->v($this);$this->p->iE();return base64_decode($this->p->res());}}overload("Java");
> // Test
> $i1 = new Java("java.math.BigInteger", "1");
> $i2 = new Java("java.math.BigInteger", "2");
> $i3 = $i1->add($i2);
> echo $i3->toString() . "\n";
> ?>
> `

## Class loading questions

#### Why has java_require() been deprecated?

Because Java doesn't have a module system.

For example a library "lucene-2.3.1.jar" required by application B, cannot be loaded if an older version of the library, required by application A, is already cached.
An attempt to link the library anyway will cause "NoClassDefFound" or "NoSuchMethod" errors at runtime. Or some procedures may throw checked exceptions even though they haven't declared them.

To protect PHP developers from Java's "jar hell", I have removed the dynamic class loading mechanism from PHP/Java Bridge version 6.0; java_require() issues a warning.

A proper Java module system must use special Java VM hooks, which don't exist until now.

#### How do I load Java libraries?

You should link your Java application as described in the Java standalone or Java webapps documents.

#### Where can I store my java libraries for the VM Bridge?

In your web application `WEB-INF/lib` directory.

If libraries should be available globally, store them in `java.ext.dirs`, for example in `/usr/share/java/ext`.

#### Why do I get a ClassNotFoundException?

You probably haven't loaded 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 your web application WEB-INF/lib directory.

#### Why do I get a NoClassDefFoundError?

Because Java doesn't have a module system.

All libraries and their dependencies must be loaded by one, and only one class loader.

Please read the previous sentence until you understand what it means; for example a simple file system copy(!) operation may be the cause for a NoClassDefFoundError.

Please do not report NoClassDefFoundErrors to the mailing list or via the bug tracker. This is not a bug and we cannot help you any further!

#### How do I load impure Java libraries?

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`.

## J2EE/Servlet questions

#### I want to ship my own PHP web application. Where do I put PHP and PHP extensions?

PHP binaries go to `WEB-INF/cgi/` and should be named `php-cgi-ARCHITECTURE-OS.exe` (Windows) or `php-cgi-ARCHITECTURE-OS` (Linux/Unix).

PHP extensions go to `WEB-INF/cgi/ARCHITECTORE-OS/ext`. The extension can be customized with a `WEB-INF/cgi/ARCHITECTURE-OS/conf.d/EXTENSION.ini` file.

Pure PHP libraries go to `WEB-INF/pear/`.

Example for the PHP mysql extension for Linux and Windows (i386/x86):

> `WEB-INF --- cgi --- php-cgi-x86-windows.exe
> |
> --- x86-windows --- conf.d --- mysql.ini [extension="php_mysql.dll"]
> | |
> | --- ext --- php_mysql.dll
> |
> |
> --- php-cgi-i386-linux
> |
> --- i386-linux --- conf.d --- mysql.ini [extension="mysql.so"]
> |
> --- ext --- mysql.so
> `

#### I have written my own servlet. How do I call it from PHP?

Add the following code to your servlet:

> `public String hello() { return "hello from MyServlet"; }
> [...]
> protected void doPut (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
> IContextFactory ctx = new RemoteHttpServletContextFactory(this, getServletContext(), req, req, res);
> res.setHeader("X_JAVABRIDGE_CONTEXT", ctx.getId());
> res.setHeader("Pragma", "no-cache");
> res.setHeader("Cache-Control", "no-cache");
> try { ctx.getBridge().handleRequests(req.getInputStream(), res.getOutputStream()); } finally { ctx.destroy(); }
> }
> `

Then copy the libraries `JavaBridge.jar` and `php-servlet.jar` to your `WEB-INF/lib` directory and re-deploy your web application.

If your servlet is programmed so that it listens on localhost:8080/MyWebApp/MyServlet, set `JAVA_HOSTS` and `JAVA_SERVLET` to these values:

> `<?php define("JAVA_HOSTS", "localhost:8080");
> define("JAVA_SERVLET", "/MyWebApp/MyServlet");
> require_once("java/Java.inc");
> echo java_context()->getServlet()->hello();
> ?>`

#### How do I set up a load balancer for the VM Bridge cluster?

Set up the VM 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/balancer-manager/`.

Please see the `mod_rewrite` documentation for more information how to rewrite incoming URLs.

#### Ho do I set up a tomcat cluster?

Download tomcat 5 or higher, a Java JRE 5 or higher and the VM Bridge 4.1.6 or higher.

The following example uses two nodes running on two machines called "carlos" and "diego".

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=/usr/java/default bin/catalina.sh run`

Please see your HTTP server documentation and the description above how to set it up as a load balancer.

#### I want to use PHP for all tomcat applications. Apache and IIS are not available, but performance is important. How do I install it?

1. Download the PHP/Java Bridge binary.
2. Copy `JavaBridge.jar`, `php-servlet.jar` and `php-script.jar` from the `JavaBridge.war` zip archive to `$CATALINA_HOME/lib`.
3. Add the following 9 lines marked with a `+` to the tomcat `$CATALINA_HOME/conf/web.xml` web app:

   > `
   > <web-app xmlns=... >
   > + <listener><listener-class>php.java.servlet.ContextLoaderListener</listener-class></listener>
   > + <servlet><servlet-name>PhpJavaServlet</servlet-name><servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
   > + </servlet>
   > + <servlet><servlet-name>PhpCGIServlet</servlet-name><servlet-class>php.java.servlet.fastcgi.FastCGIServlet</servlet-class>
   > + <init-param><param-name>prefer_system_php_exec</param-name><param-value>On</param-value></init-param>
   > + <init-param><param-name>php_include_java</param-name><param-value>On</param-value></init-param>
   > + </servlet>
   > + <servlet-mapping><servlet-name>PhpJavaServlet</servlet-name><url-pattern>*.phpjavabridge</url-pattern> </servlet-mapping>
   > + <servlet-mapping><servlet-name>PhpCGIServlet</servlet-name><url-pattern>*.php</url-pattern></servlet-mapping>
   > ...
   > </web-app>`

4. Start tomcat.

To test the above settings, add a file `test.php`:

> `<?php echo java("java.lang.System")->getProperties(); ?>`

to some web context, for example "examples", and browse to `http://yourHost.com:8080/examples/test.php`.

In case you don't need to access Java from all of your scripts, you can set the `php_include_java` option to `Off` and `require_once("java/Java.inc")`, if needed.

#### How do I create a standalone PHP web application for distribution and how can users deploy it into tomcat?

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.fastcgi.FastCGIServlet</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`.

#### I want to use Tomcat's security manager, how do I install the bridge?

Install the PHP/Java Bridge for all web application as described here.

#### I want to use Apache/IIS as a front-end and tomcat as a back end. How do I enable PHP and JSP for all my applications?

Set up Apache or IIS so that it forwards requests to the back end. Please see the description above for details.

#### Does the bridge run native code within my servlet engine or application server?

No. The bridge back end is written in pure java, it doesn't use any native code. Native PHP runs within Apache, IIS, or a FCGI server. 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.

#### The EJB example works with the Sun J2EE server, but in JBoss I get a ClassCastException, what's wrong?

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 = java("DocumentHome");
> $PortableRemoteObject = java("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`.

#### How do I install PHP into the Nutch, Spring, JSF, ..., Framework?

By providing JSR 223 based PHP beans and a description how to manage them, as usual. The code

> `javax.script.ScriptEngine e =
> php.java.script.EngineFactory.getInvocablePhpScriptEngine (this,
> application,
> request, response);
> `

can be used to access the JSR 223 ScriptEngine from the framework, provided that a listener has been configured in the WEB-INF/web.xml:

> `<listener> <listener-class>php.java.servlet.ContextLoaderListener</listener-class> </listener>`

## General runtime questions

#### How do I include a local (*.asp, *.jsp, ...) resource?

Use the `virtual()` or `java_virtual()` function.

Warning: Do not open a "loop back" url connection (e.g. via `fopen("http://localhost.../foo.asp")`) to include the local resource. This might exceed the HTTP server's pool size and create a deadlock!

#### How do I reference a class w/o creating an instance?

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);
> }`

#### Why does java_context()->getHttpServletRequest()->getSession() return null?

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();
> `

#### Where is my output?

`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 VMBridge.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.

#### How do I make my script state (objects or variables) persistent?

If you must code it yourself: with e.g. `java_session()->put("buf", $stringBuffer)`

#### How many threads does the bridge start?

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.

#### How do I access enums or inner classes?

With the `classname$inner` syntax. For example
`public interface php {
public class java {
public enum bridge {JavaBridge, JavaBridgeRunner};
}
}
`
can be accessed with:
`<?php
$bridge = new java('php$java$bridge');
echo $bridge->JavaBridgeRunner;
?>
`
The above code is not a good programming example but it demonstrates why a different syntax is used to access inner classes.

#### How do I create a primitive array?

Primitive types are wrapped by associated java classes. The following example uses `reflect.Array` to create a new `byte` array:
`$Byte = java("java.lang.Byte");
$byte = $Byte->TYPE;
$Array = java("java.lang.reflect.Array");
$byteArray = $Array->newInstance($byte, 255);
$System = java("java.lang.System");
$length = $System->in->read($byteArray);
$str = new Java("java.lang.String", $byteArray, 0, $length);
echo "You have typed: $str\n";
`

#### How fast is it?

The following scripts were executed on one 1.5 GHZ x86 cpu running RedHat Fedora 10 Linux and Sun jdk1.6.0_02. We have tested "Mozilla Rhino" 1.6 release 2 from JDK 1.6, Caucho "Quercus" version 3.2.1, the PHP/Java Bridge version 5.4.4, and PHP 4's ext/java.

The PHP code (`t11.php`):

`<?php
$buf=new java("java.lang.StringBuilder");
for ($i=0; $i<400000; $i++) $buf->append($i);
echo $buf->length() . "\n";
?>`

Another PHP code is necessary for Quercus 3.2.1 because it cannot run the above standard PHP code correctly (`t12.php`):

`<?php
$buf=new java("java.lang.StringBuilder");
for ($i=0; $i<400000; $i++) $buf->append(new java("java.lang.String", $i));
echo $buf->length() . "\n";
?>`

The ECMAScript ("Mozilla Rhino") code (`t11.js`):

`buf = new java.lang.StringBuilder();
for(i=0; i<400000; i++) buf.append(new java.lang.Integer(i));
print (buf.length());
`

Command | Script Engine | Communication Channel | Execution time (real, user, sys)
--- | --- | --- | ---
time jrunscript -l js t11.js | "Mozilla Rhino" 1.6 release 2 | none (native code) | 0m7.932s, 0m7.701s, 0m0.113s
time jrunscript -classpath quercus.jar:resin-util.jar:servlet-api.jar -l quercus t12.php | Quercus 3.2.1 | none (native code) | 0m7.134s, 0m5.050s, 0m1.934s
time jrunscript -classpath JavaBridge.jar -l php t11.php | PHP/Java Bridge 5.4.4 | named pipes (XML protocol) | 0m16.059s, 0m15.341s, 0m0.197s
php t11.php | PHP 4.4.7/PHP-Java extension | JNI (binary protocol) | 0m57.689s, 0m56.243s, 0m0.467s

#### How does the bridge handle OutOfMemoryErrors?

OutOfMemoryErrors may happen because a cached object cannot be released, either because

1. the object is permanently referenced by a request-handling thread or
2. the object has been entered into the session or application store or the object is referenced by a thread outside of the scope of the VM Bridge.

When a `java.lang.OutOfMemoryError` reaches the request-handling thread, the VM Bridge thread pool removes the thread from its pool and writes a message `FATAL: OutOfMemoryError` to the VM 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 VM Bridge has caused this error condition.

OutOfMemory conditions can be debugged by running the back end with e.g.:
`java -agentlib:hprof=heap=sites -jar JavaBridge.jar
`

#### How can PHP classes extend Java classes and Java methods?

By using `java_closure()` and the visitor pattern for example.

In PHP 5.3 or above the following code can be used:

> `use java\lang\String as JString;
> class String extends JString {
> function toString(){return "I am " . parent::toString();}
> function __toString() {return $this->toString();}
> }
> echo new String("foo");
> => I am foo`

#### How can I convert a Java object into a PHP value?

With `java_values()`. For example:

> `$ar = java("java.lang.reflect.Array")->newInstance(java("java.lang.Integer"), 2);
> $ar[0] = new java("java.lang.Integer", 2);$ar[1] = new java("java.lang.Integer", 5);
> print_r(java_values($ar));
> `

#### How can I convert a PHP object into a Java object?

With `java_closure()`. For example:

> `class Foo {
> function toString() {return "php::foo";}
> }
> $foo = new Foo();
> $jObj = java_closure($foo);
> $String = java("java.lang.String");
> echo $String->valueOf($jObj);
> `

#### How do I call JSP tags from PHP?

Example:

> `require_once("http://localhost:8080/JavaBridge/java/Java.inc");
> $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.

#### How does the bridge support Java generics?

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.

#### What about Java 5 varargs?

Pass them as a PHP array. Example:

> `<?php require_once("http://localhost:8080/JavaBridge/java/Java.inc");
> $t1 = new java('Varargs$Test', 1);
> $t2 = new java('Varargs$Test', 2);
> echo java("Varargs")->varargs(array($t1, $t2));
> ?>`

> `public class Varargs {
> public static class Test {
> public int i;
> public Test (int i) {
> this.i = i;
> }
> public String toString() {
> return String.valueOf(i);
> }
> }
> public static String varargs(Test ...tests) {
> StringBuffer buf = new StringBuffer();
> for (Test test : tests) {
> buf.append(test);
> }
> return buf.toString();
> }
> }
> `

#### NULL tests

Use `java_is_null($value)` or `is_null (java_values ($value))` to test for a (Java-) NULL value.

#### How do I start the bridge back end when there's another Java VM listening on port 8080?

Simply deploy the VM Bridge web archive into the servlet engine or application server listening on port 8080. Or use a different port.

#### What's the difference between SERVLET_LOCAL:8080 and INET_LOCAL:8080?

The standalone option SERVLET_LOCAL emulates a servlet engine and starts a HTTP server which can select the fastest channel supported on this operating system. On Linux this is a named pipe created in /dev/shm or INET_LOCAL as a fall back.

INET_LOCAL always uses local TCP socket communication.

#### Whenever I reboot my computer I have to start the bridge back end again. How can I automate this?

Download and install a servlet engine or J2EE server as a Windows or Unix service.

#### Do I have to require Java.inc in each of my scripts? Isn't that very slow?

In order to communicate with Java, a PHP "Java" class definition is needed. Here's a simple PHP "Java" class definition which fits into one line:

> `<?php
> // The following is the "Java" class definition, stripped down to fit
> // into one line. To use this sample start Java with: java -jar
> // JavaBridge.jar INET:9267.Then type: php sample.php
> //
> class P{var$Pc="<C v=\"%s\" p=\"I\">",$PC="</C>",$Pi="<I v=\"%d\" m=\"%s\" p=\"I\">",$PI="</I>",$Ps="<S v=\"%s\"/>",$Pl="<L v=\"%d\" p=\"%s\"/>",$Po="<O v=\"%d\"/>",$c;function str($s){fwrite($this->c,sprintf($this->Ps,$s));}function obj($s){fwrite($this->c,sprintf($this->Po,$s->j));}function P(){$this->c=fsockopen("127.0.0.1",9267);}function cB($s){fwrite($this->c,sprintf($this->Pc,$s));}function cE(){fwrite($this->c,$this->PC);}function iB($o,$m){fwrite($this->c,sprintf($this->Pi,$o,$m));}function iE(){fwrite($this->c,$this->PI);}function v($s){if(is_object($s))$this->obj($s);else$this->str((string)$s);}function res(){$r=sscanf(fread($this->c,8192),"%s v=\"%[^\"]\"");return$r[1];}}function gP(){static$p;if(!$p)$p=new P();return$p;}class Java{var$j,$p;function Java(){if(!func_num_args())return;$this->p=gP();$ar=func_get_args();$this->p->cB(array_shift($ar));foreach($ar as$arg)$this->p->v($arg);$this->p->cE();$ar=sscanf($this->p->res(),"%d");$this->j=$ar[0];}function __call($m,$a){$this->p->iB($this->j,$m);foreach($a as$arg)$this->p->v($arg);$this->p->iE();$p=new Java();$ar=sscanf($this->p->res(),"%d");$p->j=$ar[0];$p->p=$this->p;return$p;}function toString(){$this->p->iB("","castToString");$this->p->v($this);$this->p->iE();return base64_decode($this->p->res());}};
> // Test
> $i1 = new Java("java.math.BigInteger", "1");
> $i2 = new Java("java.math.BigInteger", "2");
> $i3 = $i1->add($i2);
> echo $i3->toString() . "\n";
> ?>
> `

The above simple "Java" class assumes that some Java VM has been started on host "127.0.0.1", port "9267". And it cannot handle values larger than 8192 bytes. Therefore the VM Bridge library `Java.inc` should be used. Scripts should contain the statement

> `require_once("...java/Java.inc");`

at the beginning of each script. PHP compiles and caches PHP scripts, the `Java.inc` library is loaded only once.

#### What does "The requested method PUT is not allowed ... at localhost Port 80" mean?

It means that `request.getServerPort()` is lying. Port 80 is privileged and therefore cannot be the servlet engine's server port.

If you use the AJP connector, for example via `ProxyPassMatch ^(/.*\.jsp)$ ajp://127.0.0.1$1`, set the correct `proxyPort` in `tomcat/conf/server.xml`. Example:

> `<!-- Define an AJP 1.3 Connector on port 8009 -->
> - <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
> + <Connector port="8009" protocol="AJP/1.3" proxyPort="8080" redirectPort="8443" />
> `

Please see the AJP documentation for details.