Source for file JavaProxy.inc

Documentation is available at JavaProxy.inc

  1. <?php /*-*- mode: php; tab-width:4 -*-*/
  2.  
  3.   /* java_Proxy.php -- contains the main interface
  4.  
  5.   Copyright (C) 2003-2007 Jost Boekemeier
  6.  
  7.   This file is part of the PHP/Java Bridge.
  8.  
  9.   The PHP/Java Bridge ("the library") is free software; you can
  10.   redistribute it and/or modify it under the terms of the GNU General
  11.   Public License as published by the Free Software Foundation; either
  12.   version 2, or (at your option) any later version.
  13.  
  14.   The library is distributed in the hope that it will be useful, but
  15.   WITHOUT ANY WARRANTY; without even the implied warranty of
  16.   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  17.   General Public License for more details.
  18.  
  19.   You should have received a copy of the GNU General Public License
  20.   along with the PHP/Java Bridge; see the file COPYING.  If not, write to the
  21.   Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  22.   02111-1307 USA.
  23.  
  24.   Linking this file statically or dynamically with other modules is
  25.   making a combined work based on this library.  Thus, the terms and
  26.   conditions of the GNU General Public License cover the whole
  27.   combination.
  28.  
  29.   As a special exception, the copyright holders of this library give you
  30.   permission to link this library with independent modules to produce an
  31.   executable, regardless of the license terms of these independent
  32.   modules, and to copy and distribute the resulting executable under
  33.   terms of your choice, provided that you also meet, for each linked
  34.   independent module, the terms and conditions of the license of that
  35.   module.  An independent module is a module which is not derived from
  36.   or based on this library.  If you modify this library, you may extend
  37.   this exception to your version of the library, but you are not
  38.   obligated to do so.  If you do not wish to do so, delete this
  39.   exception statement from your version. */
  40.  
  41. require_once(java_get_base()."/Client.inc");
  42.  
  43. /**
  44.  * Implemented by JavaException and Java.
  45.  * @see Java
  46.  * @see JavaException
  47.  * @access public
  48.  */
  49. interface java_JavaType {};
  50.  
  51. /** Global flag is set if a client exists */
  52. $java_initialized false;
  53.  
  54. /**
  55.  * @access private
  56.  */
  57. function __javaproxy_Client_getClient({
  58.   static $client null;
  59.   if(!is_null($client)) return $client;
  60.   
  61.   if (function_exists("java_create_client")) $client java_create_client();
  62.   else {
  63.     global $java_initialized;
  64.     $client=new java_Client();
  65.     $java_initialized true;
  66.   }
  67.   
  68.   return $client;
  69. }
  70.  
  71. /**
  72.  * Return the last stored Java exception.
  73.  
  74.  * The last stored Java exception is the first undeclared
  75.  * java.lang.RuntimeException or java.lang.Error after the last
  76.  * java_last_exception_clear() invocation or, if no
  77.  * RuntimeException/Error occured, the last declared exception
  78.  * reported via the script engine's try/catch mechanism.
  79.  * 
  80.  * Useful for script engines which do not support try/catch or if
  81.  * you want to handle java.lang.RuntimeException or java.lang.Error
  82.  * in your PHP code.
  83.  * <br>
  84.  * Note the distinction between java.lang.Exception, which can be
  85.  * caught on PHP level, and
  86.  * java.lang.RuntimeException/java.lang.Error, which raise a fatal PHP
  87.  * error at the end of the php script (unless the error condition is
  88.  * cleared using java_last_exception_clear()).
  89.  * <br>
  90.  * java.lang.Exception is a typical exception in your business logic,
  91.  * java.lang.RuntimeException is an exception caused by a bug in your
  92.  * program, for example java.lang.NullPointerException.
  93.  * java.lang.Error marks a serious problem, for example
  94.  * java.lang.OutOfMemoryError.
  95.  * 
  96.  * Example:
  97.  * <code>
  98.  * define ("JAVA_PREFER_VALUES", false);
  99.  * require_once("http://localhost:8080/JavaBridge/java/Java.inc");
  100.  * try {
  101.  * new java("java.lang.String", null); // raises java.lang.RuntimeException
  102.  * assert (is_null(java_last_exception_get());
  103.  * } catch (JavaException $e) {
  104.  *    echo $e;
  105.  * }
  106.  * </code>
  107.  *
  108.  * 
  109.  * @return mixed The last stored Java exception or null
  110.  * @access public
  111.  * @see java_last_exception_clear()
  112.  * @see JAVA_PREFER_VALUES
  113.  */
  114.   $client=__javaproxy_Client_getClient();
  115.   return $client->invokeMethod(0"getLastException"array());
  116. }
  117. /**
  118.  * Clear a stored Java exception.
  119.  *  
  120.  * @access public
  121.  * @see java_last_exception_get()
  122.  */
  123.   $client=__javaproxy_Client_getClient();
  124.   $client->invokeMethod(0"clearLastException"array());
  125. }
  126. /**
  127.  * Only for internal use
  128.  * @access private
  129.  */
  130. function java_values_internal($object{
  131.   if(!$object instanceof java_JavaTypereturn $object;
  132.   $client=__javaproxy_Client_getClient();
  133.   return $client->invokeMethod(0"getValues"array($object));
  134. }
  135. /**
  136.  * Invoke a method dynamically.
  137.  
  138.  * Example:
  139.  * <code>
  140.  * java_invoke(new java("java.lang.String","hello"), "toString", array())
  141.  * </code>
  142.  *
  143.  *<br> Any declared exception can be caught by PHP code. <br>
  144.  * Exceptions derived from java.lang.RuntimeException or Error should
  145.  * not be caught unless declared in the methods throws clause -- OutOfMemoryErrors cannot be caught at all,
  146.  * even if declared.
  147.  *
  148.  * @param object java object or type
  149.  * @param string A method string
  150.  * @param array A argument array
  151.  */
  152. function java_invoke($object$method$args{
  153.   $client=__javaproxy_Client_getClient();
  154.   $id ($object==null$object->__java;
  155.   return $client->invokeMethod($id$method$args);
  156. }
  157.  
  158. /**
  159.  * Unwrap a Java object.
  160.  * 
  161.  * Fetches the PHP object which has been wrapped by java_closure(). Example:
  162.  * <code>
  163.  * class foo { function __toString() {return "php"; } function toString() {return "java";} }
  164.  * $foo = java_closure(new foo());
  165.  * echo $foo;
  166.  * => java;
  167.  * $foo = java_unwrap($foo);
  168.  * echo $foo;
  169.  * => php
  170.  * </code>
  171.  */
  172. function java_unwrap ($object{
  173.   if(!$object instanceof java_JavaTypethrow new java_IllegalArgumentException($object);
  174.   $client=__javaproxy_Client_getClient();
  175.   return $client->globalRef->get($client->invokeMethod(0"unwrapClosure"array($object)));
  176. }  
  177.  
  178. /**
  179.  * Evaluate a Java object.
  180.  * 
  181.  * Evaluate a object and fetch its content, if possible. Use java_values() to convert a Java object into an equivalent PHP value.
  182.  *
  183.  * A java array, Map or Collection object is returned
  184.  * as a php array. An array, Map or Collection proxy is returned as a java array, Map or Collection object, and a null proxy is returned as null. All values of java types for which a primitive php type exists are returned as php values. Everything else is returned unevaluated. Please make sure that the values do not not exceed
  185.  * php's memory limit. Example:
  186.  *
  187.  * 
  188.  * <code>
  189.  * $str = new java("java.lang.String", "hello");
  190.  * echo java_values($str);
  191.  * => hello
  192.  * $chr = $str->toCharArray();
  193.  * echo $chr;
  194.  * => [o(array_of-C):"[C@1b10d42"]
  195.  * $ar = java_values($chr);
  196.  * print $ar;
  197.  * => Array
  198.  * print $ar[0];
  199.  * => [o(Character):"h"]
  200.  * print java_values($ar[0]);
  201.  * => h
  202.  * </code>
  203.  * 
  204.  * @see java_closure()
  205.  * @param object  java object or type.
  206.  * @access public
  207.  */
  208. function java_values($object{
  209.   return java_values_internal($object);
  210. }
  211. /**
  212.  * Only for internal use.
  213.  * @access private
  214.  */
  215. function java_reset({
  216.   $client=__javaproxy_Client_getClient();
  217.   return $client->invokeMethod(0"reset"array());
  218. }
  219. /**
  220.  * Only for internal use
  221.  * @access private
  222.  */
  223. function java_inspect_internal($object{
  224.   if(!$object instanceof java_JavaTypethrow new java_IllegalArgumentException($object);
  225.   $client=__javaproxy_Client_getClient();
  226.   return $client->invokeMethod(0"inspect"array($object));
  227. }
  228. /**
  229.  * Returns the contents (public fields, public methods, public
  230.  * classes) of object as a string.
  231.  *
  232.  * Example:
  233.  * <code>
  234.  * echo java_inspect(java_context());
  235.  * </code>
  236.  * @param object java object or type.
  237.  * @access public
  238.  */
  239. function java_inspect($object{
  240.   return java_inspect_internal($object);
  241. }
  242. /**
  243.  * Set the java file encoding, for example UTF-8 or ASCII.
  244.  *
  245.  * Needed
  246.  * because php does not support unicode. All string to byte array
  247.  * conversions use this encoding. Example:
  248.  * <code>
  249.  * java_set_file_encoding("ISO-8859-1");
  250.  * </code>
  251.  *
  252.  * @param string A valid file.encoding string. Please see your Java
  253.  *  <code>file.encoding</code> documentation for a list of valid
  254.  *  encodings.
  255.  * @access public
  256.  */
  257. function java_set_file_encoding($enc{
  258.   $client=__javaproxy_Client_getClient();
  259.   return $client->invokeMethod(0"setFileEncoding"array($enc));
  260. }
  261. /**
  262.  * Only for internal use
  263.  * @access private
  264.  */
  265. function java_instanceof_internal($ob$clazz{
  266.   if(!$ob instanceof java_JavaTypethrow new java_IllegalArgumentException($ob);
  267.   if(!$clazz instanceof java_JavaTypethrow new java_IllegalArgumentException($clazz);
  268.   $client=__javaproxy_Client_getClient();
  269.   return $client->invokeMethod(0"instanceOf"array($ob$clazz));
  270. }
  271. /**
  272.  * Tests if object is an instance of clazz.
  273.  *
  274.  * Example:
  275.  * <code>
  276.  * return($o instanceof Java && $c instanceof Java && java_instanceof($o, $c));
  277.  * </code>
  278.  * @param object java object
  279.  * @param object java object or type.
  280.  * @access public
  281.  */
  282. function java_instanceof($ob$clazz{
  283.   return java_instanceof_internal($ob$clazz);
  284. }
  285. /**
  286.  * Only for internal use
  287.  * @access private
  288.  */
  289. function java_cast_internal($object$type
  290.     if(!$object instanceof java_JavaType{
  291.       switch($type[0]{
  292.     case 'S'case 's':
  293.       return (string)$object;
  294.     case 'B'case 'b':
  295.       return (boolean)$object;
  296.     case 'L'case 'I'case 'l'case 'i':
  297.       return (integer)$object;
  298.     case 'D'case 'd'case 'F'case 'f':
  299.       return (float) $object;
  300.     case 'N'case 'n':
  301.       return null;
  302.     case 'A'case 'a':
  303.       return (array)$object;
  304.     case 'O'case 'o':
  305.       return (object)$object;
  306.       }
  307.     }    
  308.     return $object->__cast($type)
  309. }
  310. /**
  311.  * Converts the java object obj into a PHP value.
  312.  *
  313.  * This procedure converts the Java argument and then calls java_values() to fetch
  314.  * its content. Use java_values() if the conversion is not necessary.
  315.  * 
  316.  * The second argument
  317.  * must be [s]tring, [b]oolean, [i]nteger, [f]loat or [d]ouble,
  318.  * [a]rray, [n]ull or [o]bject (which does nothing).
  319.  *
  320.  * <br>
  321.  * Example:
  322.  * <code>
  323.  * $str = new java("java.lang.String", "12");
  324.  * echo is_string ($str) ? "#t":"#f";
  325.  * => #f
  326.  * $phpString = (string)$str;
  327.  * echo is_string ($phpString) ? "#t":"#f";
  328.  * => #t
  329.  * $phpNumber = (integer)(string)$str;
  330.  * echo $phpNumber;
  331.  * => 12
  332.  * $phpNumber2 = java_cast($str, "integer");
  333.  * echo $phpNumber2;
  334.  * => 12
  335.  * </code>
  336.  * @see java_values()
  337.  * @param object java object
  338.  * @param string A PHP type description, either [Ss]tring, [Bb]oolean, [Ll]ong or [Ii]nteger, [Dd]ouble or [Ff]loat, [Nn]ull, [Aa]rray, [Oo]bject.
  339.  * @access public
  340.  */
  341. function java_cast($object$type
  342.   return java_cast_internal($object$type);
  343. }
  344.  
  345. /**
  346.  * Set the library path. This function should not be used in new programs.
  347.  * Please use <a href="http://php-java-bridge.sourceforge.net/pjb/webapp.php>tomcat or jee hot deployment</a> instead.
  348.  * @access public
  349.  */
  350. function java_require($arg{
  351.   $client=__javaproxy_Client_getClient();
  352.   return $client->invokeMethod(0"updateJarLibraryPath"
  353.                                array($argini_get("extension_dir")getcwd()ini_get("include_path")));
  354. }
  355. /**
  356.  * @access private
  357.  */
  358. function java_get_lifetime ()
  359. {
  360.   $session_max_lifetime=ini_get("session.gc_maxlifetime");
  361.   return $session_max_lifetime ? (int)$session_max_lifetime 1440;
  362. }
  363.   
  364. /**
  365.  * Only for internal use
  366.  * @access private
  367.  */
  368. function java_session_array($args{
  369.   $client=__javaproxy_Client_getClient();
  370.   if(!isset($args[0])) $args[0]=null;
  371.   if(!isset($args[1])) $args[1]=false;
  372.   if(!isset($args[2])) {
  373.     $args[2java_get_lifetime ();
  374.   }
  375.   return $client->getSession($args);
  376. }
  377. /**
  378.  * Return a session handle.
  379.  *
  380.  * When java_session() is called without
  381.  * arguments, the session is shared with java.
  382.  * Example:
  383.  * <code>
  384.  * java_session()->put("key", new Java("java.lang.Object"));
  385.  * [...]
  386.  * </code>
  387.  * The java components (jsp, servlets) can retrieve the value, for
  388.  * example with:
  389.  * <code>
  390.  * getSession().getAttribute("key");
  391.  * </code>
  392.  *
  393.  * When java_session() is called with a session name, the session
  394.  * is not shared with java and no cookies are set. Example:
  395.  * <code>
  396.  * java_session("myPublicApplicationStore")->put("key", "value");
  397.  * </code>
  398.  *
  399.  * When java_session() is called with a second argument set to true,
  400.  * a new session is allocated, the old session is destroyed if necessary.
  401.  * Example:
  402.  * <code>
  403.  * java_session(null, true)->put("key", "val");
  404.  * </code>
  405.  *
  406.  * The optional third argument specifies the default lifetime of the session, it defaults to <code> session.gc_maxlifetime </code>. The value 0 means that the session never times out.
  407.  *
  408.  * The synchronized init() and onShutdown() callbacks from
  409.  * java_context() and the JPersistenceAdapter (see
  410.  * JPersistenceAdapter.php from the php_java_lib directory) may also
  411.  * be useful to load a Java singleton object after the JavaBridge
  412.  * library has been initialized, and to store it right before the web
  413.  * context or the entire JVM will be terminated.
  414.  *
  415.  * @access public
  416.  * @see java_
  417.  * @see java_context()
  418.  */
  419. function java_session({
  420.   return java_session_array(func_get_args());
  421. }
  422.  
  423. /**
  424.  * Returns the name of the back-end or null, if the back-end is not running.
  425.  *
  426.  * Example:
  427.  * <code>
  428.  * $backend = java_server_name();
  429.  * if(!$backend) wakeup_administrator("back-end not running");
  430.  * echo "Connected to the back-end: $backend\n";
  431.  * </code>
  432.  * @access public
  433. */
  434. function java_server_name({
  435.   try {
  436.     $client=__javaproxy_Client_getClient();
  437.     return $client->getServerName();
  438.   catch (java_ConnectException $ex{
  439.     return null;
  440.   }
  441. }
  442.  
  443. /**
  444.  * Returns the jsr223 script context handle.
  445.  *
  446.  * Example which closes over the current environment and passes it back to java:
  447.  * <code>
  448.  * define ("ENGINE_SCOPE", 100);
  449.  * $ctx = java_context();
  450.  * if(java_is_false($ctx->call(java_closure()))) die "Script should be called from java";
  451.  * </code>
  452.  * 
  453.  * A second example which shows how to invoke PHP methods without the JSR 223 getInterface() and invokeMethod()
  454.  * helper procedures. The Java code can fetch the current PHP continuation from the context using the key "php.java.bridge.PhpProcedure":
  455.  * <code>
  456.  * String s = "<?php class Runnable { function run() {...} };
  457.  *            // example which captures an environment and
  458.  *            // passes it as a continuation back to Java
  459.  *            $Runnable = java('java.lang.Runnable');
  460.  *            java_context()->call(java_closure(new Runnable(), null, $Runnable));
  461.  *            ?>";
  462.  * ScriptEngine e = new ScriptEngineManager().getEngineByName("php-invocable");
  463.  * e.eval (s);
  464.  * Thread t = new Thread((Runnable)e.get("php.java.bridge.PhpProcedure"));
  465.  * t.join ();
  466.  * ((Closeable)e).close ();
  467.  * </code>
  468.  *
  469.  * A synchronized init() procedure can be called from the context to initialize a library once, and a shutdown hook can be registered to destroy the library before the (web-) context is destroyed. The init hook can be written in PHP, but the shutdown hook must be written in Java. Example:
  470.  * <code>
  471.  * function getShutdownHook() { return java("myJavaHelper")->getShutdownHook(); }
  472.  * function call() { // called by init()
  473.  *   ...
  474.  *   // register shutdown hook
  475.  *   java_context()->onShutdown(getShutdownHook());
  476.  * }
  477.  * java_context()->init(java_closure(null, null, java("java.util.concurrent.Callable")));
  478.  * </code>
  479.  * 
  480.  * It is possible to access implicit web objects (the session, the
  481.  * application store etc.) from the context. Please see the JSR223
  482.  * documentation for details. Example:
  483.  * <code>
  484.  * $req = $ctx->getHttpServletRequest();
  485.  * $res = $ctx->getHttpServletResponse();
  486.  * </code>
  487.  *
  488.  * Example which fetches the servlet-, config and context:
  489.  * <code>
  490.  * $config = $ctx->getAttribute ( "php.java.servlet.ServletConfig",  ENGINE_SCOPE);
  491.  * $context = $ctx->getAttribute( "php.java.servlet.ServletContext", ENGINE_SCOPE);
  492.  * $servlet = $ctx->getAttribute( "php.java.servlet.Servlet", ENGINE_SCOPE);
  493.  * </code>
  494.  *
  495.  * @access public
  496.  * @see java_session()
  497.  */
  498. function java_context({
  499.   $client=__javaproxy_Client_getClient();
  500.   return $client->getContext();
  501. }
  502. /**
  503.  * Only for internal use
  504.  * @access private
  505.  */
  506. function java_closure_array($args{
  507.   if(isset($args[2]&& ((!($args[2instanceof java_JavaType))&&!is_array($args[2])))
  508.     throw new java_IllegalArgumentException($args[2]);
  509.  
  510.   $client=__javaproxy_Client_getClient();
  511.   $args[0= isset($args[0]$client->globalRef->add($args[0]0;
  512.  
  513.   /* The following is identical to 
  514.    return $client->invokeMethod(0, "makeClosure", $args); 
  515.    except that the ref (args[0]) must be an unsigned value */
  516.   $client->protocol->invokeBegin(0"makeClosure");
  517.   $n count($args);
  518.   $client->protocol->writeULong($args[0])// proper PHP "long" -> Java 64 bit value conversion
  519.   for($i=1$i<$n$i++{
  520.     $client->writeArg($args[$i]);
  521.   }
  522.   $client->protocol->invokeEnd();
  523.   $val $client->getResult();
  524.   return $val;
  525. }
  526. /**
  527.  * Wraps a PHP environment.
  528.  * 
  529.  * Closes over the php environment and packages it up as a java
  530.  * class. Use java_closure() to convert a PHP object into an equivalent Java object.
  531.  *
  532.  * Example:
  533.  * <code>
  534.  * function toString() {return "helloWorld";};
  535.  * $object = java_closure();
  536.  * echo "Java says that PHP says: $object\n";
  537.  * </code>
  538.  *
  539.  * When a php instance is supplied as an argument, the instance will be used
  540.  * instead. When a string or key/value map is supplied as a second argument,
  541.  * the java procedure names are mapped to the php procedure names. Example:
  542.  * <code>
  543.  * function hello() {return "hello";};
  544.  * echo (string)java_closure(null, "hello");
  545.  * </code>
  546.  * 
  547.  * When an array of java interfaces is supplied as a third argument,
  548.  * the environment must implement these interfaces.
  549.  * Example:
  550.  * <code>
  551.  * class Listener {
  552.  *   function actionPerformed($actionEvent) {
  553.  *       ...
  554.  *     }
  555.  * }
  556.  * function getListener() {
  557.  *     return java_closure(new Listener(), null, array(new Java("java.awt.event.ActionListener")));
  558.  * }
  559.  * </code>
  560.  * @see java_values()
  561.  * @access public
  562.  */
  563. function java_closure({
  564.   return java_closure_array(func_get_args());
  565. }
  566.  
  567. /**
  568.  * Enters stream mode (asynchronuous protocol).
  569.  *
  570.  * The statements are
  571.  * sent to the back-end in one XML stream.
  572.  *
  573.  * Use this protocol
  574.  * mode when you have a large number of set operations and you don't
  575.  * expect an exception. Any exception raised during stream mode is
  576.  * reported when java_end_document() is called.
  577.  * @deprecated
  578.  * @access private
  579.  */
  580. function java_begin_document({
  581. }
  582. /**
  583.  * Ends stream mode.
  584.  * 
  585.  * Fires a JavaException if any statement executed during
  586.  * stream mode raised an exception.
  587.  * @deprecated
  588.  * @access private
  589.  */
  590. function java_end_document({
  591. }
  592.  
  593. /**
  594.  * @access private
  595.  */
  596. class java_JavaProxy implements java_JavaType {
  597.   public $__serialID$__java;
  598.   public $__signature;
  599.   public $__client;
  600.   public $__tempGlobalRef;
  601.  
  602.   function java_JavaProxy($java$signature)
  603.     $this->__java=$java;
  604.     $this->__signature=$signature;
  605.     $this->__client __javaproxy_Client_getClient();
  606.   }
  607.   function __cast($type{
  608.     return $this->__client->cast($this$type);
  609.   }
  610.   function __sleep({
  611.     $args array($thisjava_get_lifetime());
  612.     $this->__serialID $this->__client->invokeMethod(0"serialize"$args);
  613.     $this->__tempGlobalRef $this->__client->globalRef;
  614.     if(JAVA_DEBUGecho "proxy sleep called for $this->__java$this->__signature\n";
  615.     return array("__serialID""__tempGlobalRef");
  616.   }
  617.   function __wakeup({
  618.     $args array($this->__serialIDjava_get_lifetime());
  619.     if(JAVA_DEBUGecho "proxy wakeup called for $this->__java$this->__signature\n";
  620.     $this->__client __javaproxy_Client_getClient();
  621.     if($this->__tempGlobalRef)
  622.         $this->__client->globalRef $this->__tempGlobalRef;
  623.     $this->__tempGlobalRef null;
  624.     $this->__java $this->__client->invokeMethod(0"deserialize"$args);
  625.   }
  626.   function __destruct(
  627.     if(isset($this->__client)) 
  628.       $this->__client->unref($this->__java);
  629.   }
  630.   function __get($key
  631.     return $this->__client->getProperty($this->__java$key);
  632.   }
  633.   function __set($key$val{
  634.     $this->__client->setProperty($this->__java$key$val);
  635.   }
  636.   function __call($method$args
  637.     return $this->__client->invokeMethod($this->__java$method$args);
  638.   }
  639.   function __toString({
  640.     try {
  641.       return $this->__client->invokeMethod(0,"ObjectToString",array($this));
  642.     catch (JavaException $ex{
  643.       trigger_error("Exception in Java::__toString(): "java_truncate((string)$ex)E_USER_WARNING);
  644.       return "";
  645.     }
  646.   }
  647. }
  648.  
  649. /**
  650.  * @access private
  651.  */
  652. class java_objectIterator implements Iterator {
  653.   private $var;
  654.  
  655.   function java_ObjectIterator($javaProxy{
  656.     $this->var java_cast ($javaProxy"A");
  657.   }
  658.   function rewind({
  659.     reset($this->var);
  660.   }
  661.   function valid({
  662.     return $this->current(!== false;
  663.   }
  664.   function next({
  665.     return next($this->var);
  666.   }
  667.   function key({
  668.     return key($this->var);
  669.   }
  670.   function current({
  671.     return current($this->var);
  672.   }
  673. }
  674. /**
  675.  * @access private
  676.  */
  677. class java_IteratorProxy extends java_JavaProxy implements IteratorAggregate {
  678.   function getIterator({
  679.     return new java_ObjectIterator($this);
  680.   }
  681. }
  682. /**
  683.  * @access private
  684.  */
  685. class java_ArrayProxy extends java_IteratorProxy implements ArrayAccess {
  686.   function offsetExists($idx{
  687.     $ar array($this$idx);
  688.     return $this->__client->invokeMethod(0,"offsetExists"$ar);
  689.   }  
  690.   function offsetGet($idx{
  691.     $ar array($this$idx);
  692.     return $this->__client->invokeMethod(0,"offsetGet"$ar);
  693.   }
  694.   function offsetSet($idx$val{
  695.     $ar array($this$idx$val);
  696.     return $this->__client->invokeMethod(0,"offsetSet"$ar);
  697.   }
  698.   function offsetUnset($idx{
  699.     $ar array($this$idx);
  700.     return $this->__client->invokeMethod(0,"offsetUnset"$ar);
  701.   }
  702. }
  703. /**
  704.  * @access private
  705.  */
  706. class java_ExceptionProxy extends java_JavaProxy {
  707.   function __toExceptionString($trace{
  708.     $args array($this$trace);
  709.     return $this->__client->invokeMethod(0,"ObjectToString",$args);
  710.   }
  711. }
  712. /**
  713.  * This decorator/bridge overrides all magic methods and delegates to
  714.  * the proxy so that it may handle them or pass them on to the
  715.  * back-end.  The actual implementation of this bridge depends on the
  716.  * back-end response, see PROTOCOL.TXT: "p: char ([A]rray,
  717.  * [C]ollection, [O]bject, [E]xception)". See the getProxy() and
  718.  * create() methods in Client.php and writeObject() and getType() in
  719.  * Response.java.<p>
  720.  *
  721.  * The constructor is an exception. If it is called, the user has
  722.  * already allocated Java, so that $wrap is false and the proxy is
  723.  * returned and set into $__delegate.
  724.  * @access private
  725.  * @see java_InternalJava
  726. */
  727. abstract class java_AbstractJava implements IteratorAggregate,ArrayAccess,java_JavaType {
  728.   public $__client;
  729.   
  730.   public $__delegate;
  731.  
  732.   public $__serialID;
  733.  
  734.   public $__factory;
  735.   public $__java$__signature;
  736.  
  737.   public $__cancelProxyCreationTag;
  738.  
  739.   function __createDelegate({
  740.     $proxy $this->__delegate 
  741.       $this->__factory->create($this->__java$this->__signature);
  742.     $this->__java $proxy->__java;
  743.     $this->__signature $proxy->__signature;
  744.   }
  745.   function __cast($type{
  746.     if(!isset($this->__delegate)) $this->__createDelegate();
  747.     return $this->__delegate->__cast($type);
  748.   }
  749.   function __sleep({
  750.     if(!isset($this->__delegate)) $this->__createDelegate();
  751.     $this->__delegate->__sleep();
  752.     return array("__delegate");
  753.   }
  754.   function __wakeup({
  755.     if(!isset($this->__delegate)) $this->__createDelegate();
  756.     $this->__delegate->__wakeup();
  757.     $this->__java $this->__delegate->__java;
  758.     $this->__client $this->__delegate->__client;
  759.   }
  760.   function __get($key
  761.      if(!isset($this->__delegate)) $this->__createDelegate();
  762.     return $this->__delegate->__get($key);
  763.   }
  764.   function __set($key$val{
  765.      if(!isset($this->__delegate)) $this->__createDelegate();
  766.     $this->__delegate->__set($key$val);
  767.   }
  768.   function __call($method$args
  769.     if(!isset($this->__delegate)) $this->__createDelegate();
  770.     return $this->__delegate->__call($method$args);
  771.   }
  772.   function __toString({
  773.     if(!isset($this->__delegate)) $this->__createDelegate();
  774.     return $this->__delegate->__toString();
  775.   }
  776.  
  777.   // The following functions are for backward compatibility
  778.   function getIterator({
  779.     if(!isset($this->__delegate)) $this->__createDelegate();
  780.     if(func_num_args()==0return $this->__delegate->getIterator();
  781.     $args func_get_args()return $this->__call("getIterator"$args);
  782.   }
  783.   function offsetExists($idx{
  784.     if(!isset($this->__delegate)) $this->__createDelegate();
  785.     if(func_num_args()==1return $this->__delegate->offsetExists($idx);
  786.     $args func_get_args()return $this->__call("offsetExists"$args);
  787.   }
  788.   function offsetGet($idx{
  789.     if(!isset($this->__delegate)) $this->__createDelegate();
  790.     if(func_num_args()==1return $this->__delegate->offsetGet($idx);
  791.     $args func_get_args()return $this->__call("offsetGet"$args);
  792.   }
  793.   function offsetSet($idx$val{
  794.     if(!isset($this->__delegate)) $this->__createDelegate();
  795.     if(func_num_args()==2return $this->__delegate->offsetSet($idx$val);
  796.     $args func_get_args()return $this->__call("offsetSet"$args);
  797.   }
  798.   function offsetUnset($idx{
  799.     if(!isset($this->__delegate)) $this->__createDelegate();
  800.     if(func_num_args()==1return $this->__delegate->offsetUnset($idx);
  801.     $args func_get_args()return $this->__call("offsetUnset"$args);
  802.   }
  803. }
  804.  
  805. /**
  806.  * The Java proxy class.
  807.  * 
  808.  * Use this class to create a Java instance. Use the Java function to access a Java type.
  809.  *
  810.  * Example which creates an instance:
  811.  * <code>
  812.  * $s = new Java("java.lang.String", "hello");
  813.  * </code>
  814.  *
  815.  *<br> Any declared exception can be caught by PHP code. <br>
  816.  * Exceptions derived from java.lang.RuntimeException or Error should
  817.  * not be caught unless declared in the methods throws clause --
  818.  * OutOfMemoryErrors cannot be caught at all, even if declared.
  819.  *
  820.  * @access public
  821.  * @see JavaException
  822.  * @see function Java
  823.  */
  824. class Java extends java_AbstractJava {
  825.   /**
  826.    * Create a new instance.
  827.    *
  828.    * This constructor can be
  829.    * used to create an instance of a Java class to access its
  830.    * features.<br>
  831.    *
  832.    * To access constants or procedures within a class, use the java function instead.<br>
  833.    *
  834.    * To convert a Java object into a PHP value, use the java_values() function.<br>
  835.    *
  836.    * Example which creates an instance:
  837.    * <code>
  838.    * $s = new Java("java.lang.String", "hello");
  839.    * </code>
  840.    * 
  841.    * Example which accesses the System class:
  842.    * <code>
  843.    * $s = Java("java.lang.System");
  844.    * </code>
  845.    *
  846.    * If the option JAVA_PREFER_VALUES is set, Java values are automatically coerced to PHP values.
  847.    * Example which sets the option JAVA_PREFER_VALUES:
  848.    * <code>
  849.    * define("JAVA_PREFER_VALUES", true);
  850.    * require_once("java/Java.inc");
  851.    * ...
  852.    * if (java("java.lang.System")->getProperty("foo", false)) ...
  853.    * </code>
  854.    * Otherwise java_values() must be used to fetch a PHP value from a Java object or Java value.
  855.    * The same example which usually executes 5 times faster:
  856.    * <code>
  857.    * require_once("java/Java.inc");
  858.    * ...
  859.    * if (java_values(java("java.lang.System")->getProperty("foo", false))) ...
  860.    * </code>
  861.    *
  862.    * @see JAVA_PREFER_VALUES
  863.    * @see function Java
  864.    * @see function java_values
  865.    */
  866.   function Java({
  867.     $client $this->__client __javaproxy_Client_getClient();
  868.     
  869.     $args func_get_args();
  870.     $name array_shift($args);
  871.  
  872.     // compatibility with the C implementation
  873.     if(is_array($name)) {$args $name$name array_shift($args);}
  874.  
  875.     /* do not delete this line, it is used when generating Mono.inc from Java.inc */
  876.  
  877.     $sig="&{$this->__signature}@{$name}";
  878.     $len = count($args);
  879.     $args2 = array();
  880.     for($i=0; $i<$len; $i++) {
  881.       switch(gettype($val = $args[$i])) {
  882.       case 'boolean'array_push($args2, $val); $sig.='@b'; break; 
  883.       case 'integer'array_push($args2, $val); $sig.='@i'; break; 
  884.       case 'double'array_push($args2, $val); $sig.='@d'; break; 
  885.       case 'string'array_push($args2, htmlspecialchars($val, ENT_COMPAT)); $sig.='@s'; break; 
  886.       case 'array':$sig="~INVALID"; break; 
  887.       case 'object':
  888.         if($val instanceof java_JavaType) {
  889.           array_push($args2, $val->__java);
  890.           $sig.="@o{$val->__signature}"; 
  891.         }
  892.         else {
  893.           $sig="~INVALID";
  894.         }
  895.         break;
  896.       case 'resource'array_push($args2, $val); $sig.='@r'; break; 
  897.       case 'NULL'array_push($args2, $val); $sig.='@N'; break; 
  898.       case 'unknown type'array_push($args2, $val); $sig.='@u'; break;
  899.       default: throw new java_IllegalArgumentException($val);
  900.       }
  901.     }
  902.  
  903.     if(array_key_exists($sig, $client->methodCache)) {
  904.       if(JAVA_DEBUG) { echo "cache hit for new Java: $sig\n"; }
  905.       $cacheEntry = &$client->methodCache[$sig];
  906.       $client->sendBuffer.= $client->preparedToSendBuffer;
  907.       if(strlen($client->sendBuffer)>=JAVA_SEND_SIZE{
  908.           if($client->protocol->handler->write($client->sendBuffer)<=0
  909.              throw new java_IllegalStateException("Connection out of sync, check backend log for details.");
  910.           $client->sendBuffer=null;
  911.       }
  912.       
  913.       $client->preparedToSendBuffer=vsprintf($cacheEntry->fmt$args2);
  914.  
  915.       if(JAVA_DEBUG{print_r($args2); echo "set prepared to send buffer: $client->preparedToSendBuffer$cacheEntry->fmt, for key: $sig\n";}
  916.       $this->__java = ++$client->asyncCtx;
  917.  
  918.       if(JAVA_DEBUG{echo "setresult from new Java cache: object:"; echo sprintf("%x", $client->asyncCtx)echo "\n";}
  919.       $this->__factory $cacheEntry->factory;
  920.         $this->__signature $cacheEntry->signature;
  921.  
  922.       $this->__cancelProxyCreationTag = ++$client->cancelProxyCreationTag;
  923.     } else {
  924.       if(JAVA_DEBUG) { echo "cache miss for new Java: $sig\n"; }
  925.           $client->currentCacheKey $sig;
  926.       $delegate $this->__delegate $client->createObject($name$args);
  927.       $this->__java $delegate->__java;
  928.       $this->__signature $delegate->__signature;
  929.     }
  930.   }
  931.   /** @access private */
  932.   function __destruct() {
  933.     if(!isset($this->__client)) return;
  934.     $client $this->__client;
  935.  
  936.     $preparedToSendBuffer &$client->preparedToSendBuffer;
  937.  
  938.     // Cancel proxy creation: If the created instance is collected
  939.     // before the next java statement is executed, we set the result
  940.     // type to void
  941.     if($preparedToSendBuffer &&
  942.        $client->cancelProxyCreationTag==$this->__cancelProxyCreationTag{
  943.  
  944.       $preparedToSendBuffer[6]="3";
  945.       if(JAVA_DEBUG) {echo "cancel result proxy creation:"; echo $this->__javaecho " {$client->preparedToSendBuffer}"; echo "\n";}
  946.       $client->sendBuffer.=$preparedToSendBuffer;
  947.       $preparedToSendBuffer null;
  948.       $client->asyncCtx -= 1;
  949.     } else {
  950.       if(!isset($this->__delegate)) { // write unref ourselfs if we don't have a delegate yet (see cachedJavaPrototype and Java::__factory in __call below)
  951.         if(JAVA_DEBUG) {echo "unref java:"; echo $this->__javaecho "\n";}
  952.         $client->unref($this->__java);
  953.       }
  954.     }    
  955.   }
  956.   /**
  957.    * Call a method on a Java object
  958.    *
  959.    * Example:
  960.    *<code>
  961.    * $s->substring(1, 10);
  962.    * </code>
  963.    * @param string The method name
  964.    * @param array The argument array
  965.    */
  966.   function __call($method, $args) { 
  967.     $client = $this->__client;
  968.  
  969.     $sig="@{$this->__signature}@$method";
  970.     $len = count($args);
  971.     $args2=array($this->__java);
  972.     for($i=0$i<$len$i++{
  973.       switch(gettype($val = $args[$i])) {
  974.       case 'boolean'array_push($args2, $val); $sig.='@b'; break; 
  975.       case 'integer'array_push($args2, $val); $sig.='@i'; break; 
  976.       case 'double'array_push($args2, $val); $sig.='@d'; break; 
  977.       case 'string'array_push($args2, htmlspecialchars($val, ENT_COMPAT)); $sig.='@s'; break; 
  978.       case 'array':$sig="~INVALID"; break; 
  979.       case 'object':
  980.         if($val instanceof java_JavaType) {
  981.           array_push($args2, $val->__java);
  982.           $sig.="@o{$val->__signature}"; 
  983.         }
  984.         else {
  985.           $sig="~INVALID";
  986.         }
  987.         break;
  988.       case 'resource'array_push($args2, $val); $sig.='@r'; break; 
  989.       case 'NULL'array_push($args2, $val); $sig.='@N'; break; 
  990.       case 'unknown type'array_push($args2, $val); $sig.='@u'; break; 
  991.       default: throw new java_IllegalArgumentException($val);
  992.       }
  993.     }
  994.  
  995.     if(array_key_exists($sig, $client->methodCache)) {
  996.       if(JAVA_DEBUG) { echo "cache hit for __call: $sig\n"; }
  997.       $cacheEntry = &$client->methodCache[$sig];
  998.       $client->sendBuffer.=$client->preparedToSendBuffer;
  999.       if(strlen($client->sendBuffer)>=JAVA_SEND_SIZE{
  1000.           if($client->protocol->handler->write($client->sendBuffer)<=0
  1001.              throw new java_IllegalStateException("Out of sync. Check backend log for details.");
  1002.           $client->sendBuffer=null;
  1003.       }
  1004.       $client->preparedToSendBuffer=vsprintf($cacheEntry->fmt$args2);
  1005.       if(JAVA_DEBUG{print_r($args2); echo "set prepared to send buffer: {$client->preparedToSendBuffer}, {$cacheEntry->fmt}\n";}
  1006.       if($cacheEntry->resultVoid{
  1007.         $client->cancelProxyCreationTag += 1// expire tag
  1008.         return null;
  1009.       } else {
  1010.         $result = clone($client->cachedJavaPrototype);
  1011.         $result->__factory $cacheEntry->factory;
  1012.         $result->__java = ++$client->asyncCtx;
  1013.         if(JAVA_DEBUG{echo "setresult from __call cache: object:"; echo sprintf("%x", $client->asyncCtx)echo "\n";}
  1014.         $result->__signature $cacheEntry->signature;
  1015.         $result->__cancelProxyCreationTag = ++$client->cancelProxyCreationTag;
  1016.         return $result;
  1017.       }
  1018.     } else {
  1019.       if(JAVA_DEBUG) { echo "cache miss for __call: $sig\n"; }
  1020.       $client->currentCacheKey $sig;
  1021.       $retval parent::__call($method$args);
  1022.       return $retval;
  1023.     }
  1024.   }
  1025. }
  1026.  
  1027. /**
  1028.  * @access private
  1029.  */
  1030. class java_InternalJava extends Java {
  1031.   function java_InternalJava($proxy) {
  1032.     $this->__delegate $proxy;
  1033.     $this->__java $proxy->__java;
  1034.     $this->__signature $proxy->__signature;
  1035.     $this->__client $proxy->__client;
  1036.   }
  1037. }
  1038.  
  1039. /**
  1040.  * @access private
  1041.  */
  1042. class java_class extends Java {
  1043.   function java_class() {
  1044.     $this->__client __javaproxy_Client_getClient();
  1045.  
  1046.     $args func_get_args();
  1047.     $name array_shift($args);
  1048.  
  1049.     // compatibility with the C implementation
  1050.     if(is_array($name)) { $args = $name; $name = array_shift($args); }
  1051.  
  1052.     /* do not delete this line, it is used when generating Mono.inc from Java.inc */
  1053.  
  1054.     $delegate = $this->__delegate $this->__client->referenceObject($name$args);
  1055.  
  1056.     $this->__java $delegate->__java;
  1057.     $this->__signature $delegate->__signature;
  1058.   }
  1059. }
  1060. /**
  1061.  * @access private
  1062.  */
  1063. class JavaClass extends java_class{}
  1064. /**
  1065.  * A decorator pattern which overrides all magic methods.
  1066.  * 
  1067.  * @access private
  1068.  */
  1069. class java_exception extends Exception implements java_JavaType {
  1070.   /** @access private */
  1071.   public $__serialID, $__java, $__client;
  1072.   /** @access private */
  1073.   public $__delegate;
  1074.   /** @access private */
  1075.   public $__signature;
  1076.   /** @access private */
  1077.   public $__hasDeclaredExceptions;
  1078.   
  1079.   /**
  1080.    * Create a new Exception.
  1081.    * 
  1082.    * Example:
  1083.    * <code>
  1084.    * $ex = new java_exception("java.lang.NullPointerException");
  1085.    * throw $ex;
  1086.    * </code>
  1087.    */
  1088.   function java_exception() {
  1089.     $this->__client __javaproxy_Client_getClient();
  1090.  
  1091.     $args func_get_args();
  1092.     $name array_shift($args);
  1093.  
  1094.     // compatibility with the C implementation
  1095.     if(is_array($name)) { $args = $name; $name = array_shift($args); }
  1096.  
  1097.     if (count($args) == 0) 
  1098.       Exception::__construct($name);
  1099.     else
  1100.       Exception::__construct($args[0]);
  1101.  
  1102.     /* do not delete this line, it is used when generating Mono.inc from Java.inc */
  1103.  
  1104.     $delegate = $this->__delegate $this->__client->createObject($name$args);
  1105.  
  1106.     $this->__java $delegate->__java;
  1107.     $this->__signature $delegate->__signature;
  1108.     $this->__hasDeclaredExceptions 'T';
  1109.   }
  1110.   /**
  1111.    * @access private
  1112.    */
  1113.   function __cast($type) {
  1114.     return $this->__delegate->__cast($type);
  1115.   }
  1116.   /**
  1117.    * @access private
  1118.    */
  1119.   function __sleep() {
  1120.     $this->__delegate->__sleep();
  1121.     return array("__delegate");
  1122.   }
  1123.   /**
  1124.    * @access private
  1125.    */
  1126.   function __wakeup() {
  1127.     $this->__delegate->__wakeup();
  1128.     $this->__java $this->__delegate->__java;
  1129.     $this->__client $this->__delegate->__client;
  1130.   }
  1131.   /**
  1132.    * @access private
  1133.    */
  1134.   function __get($key) { 
  1135.     return $this->__delegate->__get($key);
  1136.   }
  1137.   /**
  1138.    * @access private
  1139.    */
  1140.   function __set($key, $val) {
  1141.     $this->__delegate->__set($key$val);
  1142.   }
  1143.   /**
  1144.    * @access private
  1145.    */
  1146.   function __call($method, $args) { 
  1147.     return $this->__delegate->__call($method$args);
  1148.   }
  1149.   /**
  1150.    * @access private
  1151.    */
  1152.   function __toString() {
  1153.     return $this->__delegate->__toExceptionString($this->getTraceAsString());
  1154.   }
  1155. }
  1156. /**
  1157.  * The java exception proxy.
  1158.  *
  1159.  * Example:
  1160.  * <code>
  1161.  * $ex = new JavaException("java.lang.NullPointerException");
  1162.  * throw $ex;
  1163.  * </code>
  1164.  * 
  1165.  * @access public
  1166.  */
  1167. class JavaException extends java_exception {}
  1168.  
  1169. /**
  1170.  * @access private
  1171.  */
  1172. class java_InternalException extends JavaException {
  1173.   function java_InternalException($proxy, $exception) {
  1174.     $this->__delegate $proxy;
  1175.     $this->__java $proxy->__java;
  1176.     $this->__signature $proxy->__signature;
  1177.     $this->__client $proxy->__client;
  1178.     $this->__hasDeclaredExceptions $exception;
  1179.   }
  1180. }
  1181.  
  1182. /**
  1183.  * @access private
  1184.  */
  1185. class java_JavaProxyProxy extends Java {
  1186.   function java_JavaProxyProxy($client) {
  1187.     $this->__client $client;
  1188.   }
  1189. }
  1190.  

Documentation generated on Sun, 06 Dec 2009 17:38:21 +0100 by phpDocumentor 1.4.2