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

Documentation generated on Tue, 03 Mar 2009 19:18:08 +0100 by phpDocumentor 1.4.2