PageRenderTime 69ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/Scones/java/Java.inc

https://github.com/structureddynamics/Scones
PHP | 2084 lines | 2074 code | 1 blank | 9 comment | 268 complexity | a43dcb6247c9040fa963ebe61eea6946 MD5 | raw file
Possible License(s): Apache-2.0
  1. <?php
  2. # Java.inc -- The PHP/Java Bridge PHP library. Compiled from JavaBridge.inc.
  3. # Copyright (C) 2003-2009 Jost Boekemeier.
  4. # Distributed under the MIT license, see Options.inc for details.
  5. # Customization examples:
  6. # define ("JAVA_HOSTS", 9267); define ("JAVA_SERVLET", false);
  7. # define ("JAVA_HOSTS", "127.0.0.1:8787");
  8. # define ("JAVA_HOSTS", "ssl://my-secure-host.com:8443");
  9. # define ("JAVA_SERVLET", "/MyWebApp/servlet.phpjavabridge");
  10. # define ("JAVA_PREFER_VALUES", 1);
  11. if(!function_exists("java_get_base")) {
  12. 1.0E512;
  13. function java_get_base() {
  14. $ar=get_required_files();
  15. $arLen=sizeof($ar);
  16. if($arLen>0) {
  17. $thiz=$ar[$arLen-1];
  18. return dirname($thiz);
  19. } else {
  20. return "java";
  21. }
  22. }
  23. function java_truncate($str) {
  24. if (strlen($str)>955)
  25. return substr($str,0,475).'[...]'.substr($str,-475);
  26. return $str;
  27. }
  28. class java_JavaException extends Exception {
  29. function __toString() {return $this->getMessage();}
  30. };
  31. class java_RuntimeException extends java_JavaException {};
  32. class java_IOException extends java_JavaException {};
  33. class java_ConnectException extends java_IOException {};
  34. class java_IllegalStateException extends java_RuntimeException {};
  35. class java_IllegalArgumentException extends java_RuntimeException {
  36. function __construct($ob) {
  37. parent::__construct("illegal argument: ".gettype($ob));
  38. }
  39. };
  40. function java_autoload_function5($x) {
  41. $s=str_replace("_",".",$x);
  42. $c=__javaproxy_Client_getClient();
  43. if(!($c->invokeMethod(0,"typeExists",array($s)))) return false;
  44. $i="class ${x} extends Java {".
  45. "static function type(\$sub=null){if(\$sub) \$sub='\$'.\$sub; return java('${s}'.\"\$sub\");}".
  46. 'function __construct() {$args=func_get_args();'.
  47. 'array_unshift($args,'."'$s'".'); parent::__construct($args);}}';
  48. eval ("$i");
  49. return true;
  50. }
  51. function java_autoload_function($x) {
  52. $idx=strrpos($x,"\\"); if (!$idx) return java_autoload_function5($x);
  53. $str=str_replace("\\",".",$x);
  54. $client=__javaproxy_Client_getClient();
  55. if(!($client->invokeMethod(0,"typeExists",array($str)))) return false;
  56. $package=substr($x,0,$idx);
  57. $name=substr($x,1+$idx);
  58. $instance="namespace $package; class ${name} extends \\Java {".
  59. "static function type(\$sub=null){if(\$sub) \$sub='\$'.\$sub;return \\java('${str}'.\"\$sub\");}".
  60. "static function __callStatic(\$procedure,\$args) {return \\java_invoke(\\java('${str}'),\$procedure,\$args);}".
  61. 'function __construct() {$args=func_get_args();'.
  62. 'array_unshift($args,'."'$str'".'); parent::__construct($args);}}';
  63. eval ("$instance");
  64. return true;
  65. }
  66. if(!defined("JAVA_DISABLE_AUTOLOAD") && function_exists("spl_autoload_register")) spl_autoload_register("java_autoload_function");
  67. function java_autoload($libs=null) {
  68. trigger_error('Please use <a href="http://php-java-bridge.sourceforge.net/pjb/webapp.php>tomcat or jee hot deployment</a> instead',E_USER_WARNING);
  69. }
  70. function java_virtual($path,$return=false) {
  71. $req=java_context()->getHttpServletRequest();
  72. $req=new java("php.java.servlet.VoidInputHttpServletRequest",$req);
  73. $res=java_context()->getHttpServletResponse();
  74. $res=new java("php.java.servlet.RemoteHttpServletResponse",$res);
  75. $req->getRequestDispatcher($path)->include($req,$res);
  76. if ($return) return $res->getBufferContents();
  77. echo $res->getBufferContents();
  78. return true;
  79. }
  80. function Java($name) {
  81. static $classMap=array();
  82. if(array_key_exists($name,$classMap)) return $classMap[$name];
  83. return $classMap[$name]=new JavaClass($name);
  84. }
  85. function java_get_closure() {return java_closure_array(func_get_args());}
  86. function java_wrap() {return java_closure_array(func_get_args());}
  87. function java_get_values($arg) { return java_values($arg); }
  88. function java_get_session() {return java_session_array(func_get_args());}
  89. function java_get_context() {return java_context(); }
  90. function java_get_server_name() { return java_server_name(); }
  91. function java_isnull($value) { return is_null (java_values ($value)); }
  92. function java_is_null($value) { return is_null (java_values ($value)); }
  93. function java_istrue($value) { return (boolean)(java_values ($value)); }
  94. function java_is_true($value) { return (boolean)(java_values ($value)); }
  95. function java_isfalse($value) { return !(java_values ($value)); }
  96. function java_is_false($value) { return !(java_values ($value)); }
  97. function java_set_encoding($enc) { return java_set_file_encoding ($enc); }
  98. function java_call_with_continuation($kontinuation=null) {
  99. if (java_getHeader("X_JAVABRIDGE_INCLUDE",$_SERVER) && !java_getHeader("X_JAVABRIDGE_INCLUDE_ONLY",$_SERVER)) {
  100. if (is_null($kontinuation))
  101. java_context()->call(java_closure());
  102. elseif (is_string($kontinuation))
  103. java_context()->call(call_user_func($kontinuation));
  104. elseif ($kontinuation instanceof java_JavaType)
  105. java_context()->call($kontinuation);
  106. else
  107. java_context()->call(java_closure($kontinuation));
  108. }
  109. }
  110. function java_defineHostFromInitialQuery($java_base) {
  111. if($java_base!="java") {
  112. $url=parse_url($java_base);
  113. if(isset($url["scheme"]) && ($url["scheme"]=="http" || $url["scheme"]=="https")) {
  114. $scheme=$url["scheme"]=="https" ? "ssl://" : "";
  115. $host=$url["host"];
  116. $port=$url["port"];
  117. $path=$url["path"];
  118. define ("JAVA_HOSTS","${scheme}${host}:${port}");
  119. $dir=dirname($path);
  120. define ("JAVA_SERVLET","$dir/servlet.phpjavabridge");
  121. return true;
  122. }
  123. }
  124. return false;
  125. }
  126. define("JAVA_PEAR_VERSION","6.2.1");
  127. if(!defined("JAVA_SEND_SIZE"))
  128. define("JAVA_SEND_SIZE",8192);
  129. if(!defined("JAVA_RECV_SIZE"))
  130. define("JAVA_RECV_SIZE",8192);
  131. if(!defined("JAVA_HOSTS")) {
  132. if(!java_defineHostFromInitialQuery(java_get_base())) {
  133. if ($java_ini=get_cfg_var("java.hosts")) define("JAVA_HOSTS",$java_ini);
  134. else define("JAVA_HOSTS","127.0.0.1:8080");
  135. }
  136. }
  137. if(!defined("JAVA_SERVLET")) {
  138. if (!(($java_ini=get_cfg_var("java.servlet"))===false)) define("JAVA_SERVLET",$java_ini);
  139. else define("JAVA_SERVLET",1);
  140. }
  141. if(!defined("JAVA_LOG_LEVEL"))
  142. if (!(($java_ini=get_cfg_var("java.log_level"))===false)) define("JAVA_LOG_LEVEL",(int)$java_ini);
  143. else define("JAVA_LOG_LEVEL",null);
  144. if (!defined("JAVA_PREFER_VALUES"))
  145. if ($java_ini=get_cfg_var("java.prefer_values")) define("JAVA_PREFER_VALUES",$java_ini);
  146. else define("JAVA_PREFER_VALUES",0);
  147. class java_SimpleFactory {
  148. public $client;
  149. function java_SimpleFactory($client) {
  150. $this->client=$client;
  151. }
  152. function getProxy($result,$signature,$exception,$wrap) {
  153. return $result;
  154. }
  155. function checkResult($result) {
  156. }
  157. }
  158. class java_ProxyFactory extends java_SimpleFactory {
  159. function create($result,$signature) {
  160. return new java_JavaProxy($result,$signature);
  161. }
  162. function createInternal($proxy) {
  163. return new java_InternalJava($proxy);
  164. }
  165. function getProxy($result,$signature,$exception,$wrap) {
  166. $proxy=$this->create($result,$signature);
  167. if($wrap) $proxy=$this->createInternal($proxy);
  168. return $proxy;
  169. }
  170. }
  171. class java_ArrayProxyFactory extends java_ProxyFactory {
  172. function create($result,$signature) {
  173. return new java_ArrayProxy($result,$signature);
  174. }
  175. }
  176. class java_IteratorProxyFactory extends java_ProxyFactory {
  177. function create($result,$signature) {
  178. return new java_IteratorProxy($result,$signature);
  179. }
  180. }
  181. class java_ExceptionProxyFactory extends java_SimpleFactory {
  182. function create($result,$signature) {
  183. return new java_ExceptionProxy($result,$signature);
  184. }
  185. function getProxy($result,$signature,$exception,$wrap) {
  186. $proxy=$this->create($result,$signature);
  187. if($wrap) $proxy=new java_InternalException($proxy,$exception);
  188. return $proxy;
  189. }
  190. }
  191. class java_ThrowExceptionProxyFactory extends java_ExceptionProxyFactory {
  192. function getProxy($result,$signature,$exception,$wrap) {
  193. $proxy=$this->create($result,$signature);
  194. $proxy=new java_InternalException($proxy,$exception);
  195. return $proxy;
  196. }
  197. function checkResult($result) {
  198. if (JAVA_PREFER_VALUES || ($result->__hasDeclaredExceptions=='T'))
  199. throw $result;
  200. else {
  201. trigger_error("Unchecked exception detected: ".java_truncate($result->__toString()),E_USER_WARNING);
  202. }
  203. }
  204. }
  205. class java_CacheEntry {
  206. public $fmt,$signature,$factory,$java;
  207. public $resultVoid;
  208. function java_CacheEntry($fmt,$signature,$factory,$resultVoid) {
  209. $this->fmt=$fmt;
  210. $this->signature=$signature;
  211. $this->factory=$factory;
  212. $this->resultVoid=$resultVoid;
  213. }
  214. }
  215. class java_Arg {
  216. public $client;
  217. public $exception;
  218. public $factory,$val;
  219. public $signature;
  220. function java_Arg($client) {
  221. $this->client=$client;
  222. $this->factory=$client->simpleFactory;
  223. }
  224. function linkResult(&$val) {
  225. $this->val=&$val;
  226. }
  227. function setResult($val) {
  228. $this->val=&$val;
  229. }
  230. function getResult($wrap) {
  231. $rc=$this->factory->getProxy($this->val,$this->signature,$this->exception,$wrap);
  232. $factory=$this->factory;
  233. $this->factory=$this->client->simpleFactory;
  234. $factory->checkResult($rc);
  235. return $rc;
  236. }
  237. function setFactory($factory) {
  238. $this->factory=$factory;
  239. }
  240. function setException($string) {
  241. $this->exception=$string;
  242. }
  243. function setVoidSignature() {
  244. $this->signature="@V";
  245. $key=$this->client->currentCacheKey;
  246. if($key && $key[0]!='~') {
  247. $this->client->currentArgumentsFormat[6]="3";
  248. $cacheEntry=new java_CacheEntry($this->client->currentArgumentsFormat,$this->signature,$this->factory,true);
  249. $this->client->methodCache[$key]=$cacheEntry;
  250. }
  251. }
  252. function setSignature($signature) {
  253. $this->signature=$signature;
  254. $key=$this->client->currentCacheKey;
  255. if($key && $key[0]!='~') {
  256. $cacheEntry=new java_CacheEntry($this->client->currentArgumentsFormat,$this->signature,$this->factory,false);
  257. $this->client->methodCache[$key]=$cacheEntry;
  258. }
  259. }
  260. }
  261. class java_CompositeArg extends java_Arg {
  262. public $parentArg;
  263. public $idx;
  264. public $type;
  265. public $counter;
  266. function java_CompositeArg($client,$type) {
  267. parent::java_Arg($client);
  268. $this->type=$type;
  269. $this->val=array();
  270. $this->counter=0;
  271. }
  272. function setNextIndex() {
  273. $this->idx=$this->counter++;
  274. }
  275. function setIndex($val) {
  276. $this->idx=$val;
  277. }
  278. function linkResult(&$val) {
  279. $this->val[$this->idx]=&$val;
  280. }
  281. function setResult($val) {
  282. $this->val[$this->idx]=$this->factory->getProxy($val,$this->signature,$this->exception,true);
  283. $this->factory=$this->client->simpleFactory;
  284. }
  285. }
  286. class java_ApplyArg extends java_CompositeArg {
  287. public $m,$p,$v,$n;
  288. function java_ApplyArg($client,$type,$m,$p,$v,$n) {
  289. parent::java_CompositeArg($client,$type);
  290. $this->m=$m;
  291. $this->p=$p;
  292. $this->v=$v;
  293. $this->n=$n;
  294. }
  295. }
  296. class java_Client {
  297. public $RUNTIME;
  298. public $result,$exception;
  299. public $parser;
  300. public $simpleArg,$compositeArg;
  301. public $simpleFactory,
  302. $proxyFactory,$iteratorProxyFacroty,
  303. $arrayProxyFactory,$exceptionProxyFactory,$throwExceptionProxyFactory;
  304. public $arg;
  305. public $asyncCtx,$cancelProxyCreationCounter;
  306. public $globalRef;
  307. public $stack;
  308. public $defaultCache=array(),$asyncCache=array(),$methodCache;
  309. public $isAsync=0;
  310. public $currentCacheKey,$currentArgumentsFormat;
  311. public $cachedJavaPrototype;
  312. public $sendBuffer,$preparedToSendBuffer;
  313. public $inArgs;
  314. function java_Client() {
  315. $this->RUNTIME=array();
  316. $this->RUNTIME["NOTICE"]='***USE echo java_inspect(jVal) OR print_r(java_values(jVal)) TO SEE THE CONTENTS OF THIS JAVA OBJECT!***';
  317. $this->parser=new java_Parser($this);
  318. $this->protocol=new java_Protocol($this);
  319. $this->simpleFactory=new java_SimpleFactory($this);
  320. $this->proxyFactory=new java_ProxyFactory($this);
  321. $this->arrayProxyFactory=new java_ArrayProxyFactory($this);
  322. $this->iteratorProxyFactory=new java_IteratorProxyFactory($this);
  323. $this->exceptionProxyFactory=new java_ExceptionProxyFactory($this);
  324. $this->throwExceptionProxyFactory=new java_ThrowExceptionProxyFactory($this);
  325. $this->cachedJavaPrototype=new java_JavaProxyProxy($this);
  326. $this->simpleArg=new java_Arg($this);
  327. $this->globalRef=new java_GlobalRef();
  328. $this->asyncCtx=$this->cancelProxyCreationCounter=0;
  329. $this->methodCache=$this->defaultCache;
  330. $this->inArgs=false;
  331. }
  332. function read($size) {
  333. return $this->protocol->read($size);
  334. }
  335. function setDefaultHandler() {
  336. $this->methodCache=$this->defaultCache;
  337. }
  338. function setAsyncHandler() {
  339. $this->methodCache=$this->asyncCache;
  340. }
  341. function handleRequests() {
  342. $tail_call=false;
  343. do {
  344. $this->stack=array($this->arg=$this->simpleArg);
  345. $this->idx=0;
  346. $this->parser->parse();
  347. if((count($this->stack)) > 1) {
  348. $arg=array_pop($this->stack);
  349. $this->apply($arg);
  350. $tail_call=true;
  351. } else {
  352. $tail_call=false;
  353. }
  354. $this->stack=null;
  355. } while($tail_call);
  356. return 1;
  357. }
  358. function getWrappedResult($wrap) {
  359. return $this->simpleArg->getResult($wrap);
  360. }
  361. function getInternalResult() {
  362. return $this->getWrappedResult(false);
  363. }
  364. function getResult() {
  365. return $this->getWrappedResult(true);
  366. }
  367. function getProxyFactory($type) {
  368. switch($type[0]) {
  369. case 'E':
  370. $factory=$this->exceptionProxyFactory;
  371. break;
  372. case 'C':
  373. $factory=$this->iteratorProxyFactory;
  374. break;
  375. case 'A':
  376. $factory=$this->arrayProxyFactory;
  377. break;
  378. default:
  379. case 'O':
  380. $factory=$this->proxyFactory;
  381. }
  382. return $factory;
  383. }
  384. function link(&$arg,&$newArg) {
  385. $arg->linkResult($newArg->val);
  386. $newArg->parentArg=$arg;
  387. }
  388. function getExact($str) {
  389. return hexdec($str);
  390. }
  391. function getInexact($str) {
  392. $val=null;
  393. sscanf($str,"%e",$val);
  394. return $val;
  395. }
  396. function begin($name,$st) {
  397. $arg=$this->arg;
  398. switch($name[0]) {
  399. case 'A':
  400. $object=$this->globalRef->get($this->getExact($st['v']));
  401. $newArg=new java_ApplyArg($this,'A',
  402. $this->parser->getData($st['m']),
  403. $this->parser->getData($st['p']),
  404. $object,
  405. $this->getExact($st['n']));
  406. $this->link($arg,$newArg);
  407. array_push($this->stack,$this->arg=$newArg);
  408. break;
  409. case 'X':
  410. $newArg=new java_CompositeArg($this,$st['t']);
  411. $this->link($arg,$newArg);
  412. array_push($this->stack,$this->arg=$newArg);
  413. break;
  414. case 'P':
  415. if($arg->type=='H') {
  416. $s=$st['t'];
  417. if($s[0]=='N') {
  418. $arg->setIndex($this->getExact($st['v']));
  419. } else {
  420. $arg->setIndex($this->parser->getData($st['v']));
  421. }
  422. } else {
  423. $arg->setNextIndex();
  424. }
  425. break;
  426. case 'S':
  427. $arg->setResult($this->parser->getData($st['v']));
  428. break;
  429. case 'B':
  430. $s=$st['v'];
  431. $arg->setResult($s[0]=='T');
  432. break;
  433. case 'L':
  434. $sign=$st['p'];
  435. $val=$this->getExact($st['v']);
  436. if($sign[0]=='A') $val*=-1;
  437. $arg->setResult($val);
  438. break;
  439. case 'D':
  440. $arg->setResult($this->getInexact($st['v']));
  441. break;
  442. case 'V':
  443. if ($st['n']!='T') {
  444. $arg->setVoidSignature();
  445. }
  446. case 'N':
  447. $arg->setResult(null);
  448. break;
  449. case 'F':
  450. break;
  451. case 'O':
  452. $arg->setFactory($this->getProxyFactory($st['p']));
  453. $arg->setResult($this->asyncCtx=$this->getExact($st['v']));
  454. if($st['n']!='T') $arg->setSignature($st['m']);
  455. break;
  456. case 'E':
  457. $arg->setFactory($this->throwExceptionProxyFactory);
  458. $arg->setException($st['m']);
  459. $arg->setResult($this->asyncCtx=$this->getExact($st['v']));
  460. break;
  461. default:
  462. $this->parser->parserError();
  463. }
  464. }
  465. function end($name) {
  466. switch($name[0]) {
  467. case 'X':
  468. $frame=array_pop($this->stack);
  469. $this->arg=$frame->parentArg;
  470. break;
  471. }
  472. }
  473. function createParserString() {
  474. return new java_ParserString();
  475. }
  476. function writeArg($arg) {
  477. if(is_string($arg)) {
  478. $this->protocol->writeString($arg);
  479. } else if(is_object($arg)) {
  480. if ((!$arg instanceof java_JavaType)) {
  481. error_log((string)new java_IllegalArgumentException($arg));
  482. trigger_error("argument '".get_class($arg)."' is not a Java object,using NULL instead",E_USER_WARNING);
  483. $this->protocol->writeObject(null);
  484. } else {
  485. $this->protocol->writeObject($arg->__java);
  486. }
  487. } else if(is_null($arg)) {
  488. $this->protocol->writeObject(null);
  489. } else if(is_bool($arg)) {
  490. $this->protocol->writeBoolean($arg);
  491. } else if(is_integer($arg)) {
  492. $this->protocol->writeLong($arg);
  493. } else if(is_float($arg)) {
  494. $this->protocol->writeDouble($arg);
  495. } else if(is_array($arg)) {
  496. $wrote_begin=false;
  497. foreach($arg as $key=>$val) {
  498. if(is_string($key)) {
  499. if(!$wrote_begin) {
  500. $wrote_begin=1;
  501. $this->protocol->writeCompositeBegin_h();
  502. }
  503. $this->protocol->writePairBegin_s($key);
  504. $this->writeArg($val);
  505. $this->protocol->writePairEnd();
  506. } else {
  507. if(!$wrote_begin) {
  508. $wrote_begin=1;
  509. $this->protocol->writeCompositeBegin_h();
  510. }
  511. $this->protocol->writePairBegin_n($key);
  512. $this->writeArg($val);
  513. $this->protocol->writePairEnd();
  514. }
  515. }
  516. if(!$wrote_begin) {
  517. $this->protocol->writeCompositeBegin_a();
  518. }
  519. $this->protocol->writeCompositeEnd();
  520. }
  521. }
  522. function writeArgs($args) {
  523. $this->inArgs=true;
  524. $n=count($args);
  525. for($i=0; $i<$n; $i++) {
  526. $this->writeArg($args[$i]);
  527. }
  528. $this->inArgs=false;
  529. }
  530. function createObject($name,$args) {
  531. $this->protocol->createObjectBegin($name);
  532. $this->writeArgs($args);
  533. $this->protocol->createObjectEnd();
  534. $val=$this->getInternalResult();
  535. return $val;
  536. }
  537. function referenceObject($name,$args) {
  538. $this->protocol->referenceBegin($name);
  539. $this->writeArgs($args);
  540. $this->protocol->referenceEnd();
  541. $val=$this->getInternalResult();
  542. return $val;
  543. }
  544. function getProperty($object,$property) {
  545. $this->protocol->propertyAccessBegin($object,$property);
  546. $this->protocol->propertyAccessEnd();
  547. return $this->getResult();
  548. }
  549. function setProperty($object,$property,$arg) {
  550. $this->protocol->propertyAccessBegin($object,$property);
  551. $this->writeArg($arg);
  552. $this->protocol->propertyAccessEnd();
  553. $this->getResult();
  554. }
  555. function invokeMethod($object,$method,$args) {
  556. $this->protocol->invokeBegin($object,$method);
  557. $this->writeArgs($args);
  558. $this->protocol->invokeEnd();
  559. $val=$this->getResult();
  560. return $val;
  561. }
  562. function unref($object) {
  563. if (isset($this->protocol)) $this->protocol->writeUnref($object);
  564. }
  565. function apply($arg) {
  566. $name=$arg->p;
  567. $object=$arg->v;
  568. $ob=($object==null) ? $name : array(&$object,$name);
  569. $isAsync=$this->isAsync;
  570. $methodCache=$this->methodCache;
  571. $currentArgumentsFormat=$this->currentArgumentsFormat;
  572. try {
  573. $res=$arg->getResult(true);
  574. if((($object==null) && !function_exists($name)) || (!($object==null) && !method_exists($object,$name))) throw new JavaException("java.lang.NoSuchMethodError","$name");
  575. $res=call_user_func_array($ob,$res);
  576. if (is_object($res) && (!($res instanceof java_JavaType))) {
  577. trigger_error("object returned from $name() is not a Java object",E_USER_WARNING);
  578. $this->protocol->invokeBegin(0,"makeClosure");
  579. $this->protocol->writeULong($this->globalRef->add($res));
  580. $this->protocol->invokeEnd();
  581. $res=$this->getResult();
  582. }
  583. $this->protocol->resultBegin();
  584. $this->writeArg($res);
  585. $this->protocol->resultEnd();
  586. } catch (JavaException $e) {
  587. $trace=$e->getTraceAsString();
  588. $this->protocol->resultBegin();
  589. $this->protocol->writeException($e->__java,$trace);
  590. $this->protocol->resultEnd();
  591. } catch(Exception $ex) {
  592. error_log($ex->__toString());
  593. trigger_error("Unchecked exception detected in callback",E_USER_ERROR);
  594. die (1);
  595. }
  596. $this->isAsync=$isAsync;
  597. $this->methodCache=$methodCache;
  598. $this->currentArgumentsFormat=$currentArgumentsFormat;
  599. }
  600. function cast($object,$type) {
  601. switch($type[0]) {
  602. case 'S': case 's':
  603. return $this->invokeMethod(0,"castToString",array($object));
  604. case 'B': case 'b':
  605. return $this->invokeMethod(0,"castToBoolean",array($object));
  606. case 'L': case 'I': case 'l': case 'i':
  607. return $this->invokeMethod(0,"castToExact",array($object));
  608. case 'D': case 'd': case 'F': case 'f':
  609. return $this->invokeMethod(0,"castToInExact",array($object));
  610. case 'N': case 'n':
  611. return null;
  612. case 'A': case 'a':
  613. return $this->invokeMethod(0,"castToArray",array($object));
  614. case 'O': case 'o':
  615. return $object;
  616. default:
  617. throw new java_RuntimeException("$type illegal");
  618. }
  619. }
  620. function getContext() {
  621. static $cache=null;
  622. if (!is_null($cache)) return $cache;
  623. return $cache=$this->invokeMethod(0,"getContext",array());
  624. }
  625. function getSession($args) {
  626. return $this->invokeMethod(0,"getSession",$args);
  627. }
  628. function getServerName() {
  629. static $cache=null;
  630. if (!is_null($cache)) return $cache;
  631. return $cache=$this->protocol->getServerName();
  632. }
  633. }
  634. function java_shutdown() {
  635. global $java_initialized;
  636. if (!$java_initialized) return;
  637. if (session_id()) session_write_close();
  638. $client=__javaproxy_Client_getClient();
  639. if (!isset($client->protocol) || $client->inArgs) return;
  640. if ($client->preparedToSendBuffer)
  641. $client->sendBuffer.=$client->preparedToSendBuffer;
  642. $client->sendBuffer.=$client->protocol->getKeepAlive();
  643. $client->protocol->flush();
  644. $client->protocol->keepAlive();
  645. }
  646. register_shutdown_function("java_shutdown");
  647. class java_GlobalRef {
  648. public $map;
  649. function java_GlobalRef() {
  650. $this->map=array();
  651. }
  652. function add($object) {
  653. if(is_null($object)) return 0;
  654. return array_push($this->map,$object);
  655. }
  656. function get($id) {
  657. if(!$id) return 0;
  658. return $this->map[--$id];
  659. }
  660. }
  661. class java_NativeParser {
  662. public $parser,$handler;
  663. public $level,$event;
  664. public $buf;
  665. function java_NativeParser($handler) {
  666. $this->handler=$handler;
  667. $this->parser=xml_parser_create();
  668. xml_parser_set_option($this->parser,XML_OPTION_CASE_FOLDING,0);
  669. xml_set_object($this->parser,$this);
  670. xml_set_element_handler($this->parser,"begin","end");
  671. xml_parse($this->parser,"<F>");
  672. $this->level=0;
  673. }
  674. function begin($parser,$name,$param) {
  675. $this->event=true;
  676. switch($name) {
  677. case 'X': case 'A': $this->level+=1;
  678. }
  679. $this->handler->begin($name,$param);
  680. }
  681. function end($parser,$name) {
  682. $this->handler->end($name);
  683. switch($name) {
  684. case 'X': case 'A': $this->level-=1;
  685. }
  686. }
  687. function getData($str) {
  688. return base64_decode($str);
  689. }
  690. function parse() {
  691. do {
  692. $this->event=false;
  693. $buf=$this->buf=$this->handler->read(JAVA_RECV_SIZE);
  694. $len=strlen($buf);
  695. if(!xml_parse($this->parser,$buf,$len==0)) {
  696. $this->handler->protocol->handler->shutdownBrokenConnection(
  697. sprintf("protocol error: %s,%s at col %d. Check the back end log for OutOfMemoryErrors.",
  698. $buf,
  699. xml_error_string(xml_get_error_code($this->parser)),
  700. xml_get_current_column_number($this->parser)));
  701. }
  702. } while(!$this->event || $this->level>0);
  703. }
  704. function parserError() {
  705. $this->handler->protocol->handler->shutdownBrokenConnection(
  706. sprintf("protocol error: %s. Check the back end log for details.",$this->buf));
  707. }
  708. }
  709. class java_Parser {
  710. public $parser;
  711. function java_Parser($handler) {
  712. if(function_exists("xml_parser_create")) {
  713. $this->parser=new java_NativeParser($handler);
  714. $handler->RUNTIME["PARSER"]="NATIVE";
  715. } else {
  716. $this->parser=new java_SimpleParser($handler);
  717. $handler->RUNTIME["PARSER"]="SIMPLE";
  718. }
  719. }
  720. function parse() {
  721. $this->parser->parse();
  722. }
  723. function getData($str) {
  724. return $this->parser->getData($str);
  725. }
  726. function parserError() {
  727. $this->parser->parserError();
  728. }
  729. }
  730. function java_getHeader($name,$array) {
  731. if (array_key_exists($name,$array)) return $array[$name];
  732. $name="HTTP_$name";
  733. if (array_key_exists($name,$array)) return $array[$name];
  734. return null;
  735. }
  736. function java_checkCliSapi() {
  737. $sapi=substr(php_sapi_name(),0,3);
  738. return ((($sapi=='cgi') && !get_cfg_var("java.session")) || ($sapi=='cli'));
  739. }
  740. function java_getCompatibilityOption($client) {
  741. static $compatibility=null;
  742. if ($compatibility) return $compatibility;
  743. $compatibility=$client->RUNTIME["PARSER"]=="NATIVE"
  744. ? (0103-JAVA_PREFER_VALUES)
  745. : (0100+JAVA_PREFER_VALUES);
  746. if(is_int(JAVA_LOG_LEVEL)) {
  747. $compatibility |=128 | (7 & JAVA_LOG_LEVEL)<<2;
  748. }
  749. $compatibility=chr ($compatibility);
  750. return $compatibility;
  751. }
  752. class java_EmptyChannel {
  753. protected $handler;
  754. private $res;
  755. function java_EmptyChannel($handler) {
  756. $this->handler=$handler;
  757. }
  758. function shutdownBrokenConnection () {}
  759. function fwrite($data) {
  760. return $this->handler->fwrite($data);
  761. }
  762. function fread($size) {
  763. return $this->handler->fread($size);
  764. }
  765. function getKeepAliveA() {
  766. return "<F p=\"A\" />";
  767. }
  768. function getKeepAliveE() {
  769. return "<F p=\"E\" />";
  770. }
  771. function getKeepAlive() {
  772. return $this->getKeepAliveE();
  773. }
  774. function error() {
  775. trigger_error("An unchecked exception occured during script execution. Please check the server log files for details.",E_USER_ERROR);
  776. }
  777. function checkA($peer) {
  778. $val=$this->res[6];
  779. if ($val !='A') fclose($peer);
  780. if ($val !='A' && $val !='E') {
  781. $this->error();
  782. }
  783. }
  784. function checkE() {
  785. $val=$this->res[6];
  786. if ($val !='E') {
  787. $this->error();
  788. }
  789. }
  790. function keepAliveS() {
  791. $this->res=$this->fread(10);
  792. }
  793. function keepAliveSC() {
  794. $this->res=$this->fread(10);
  795. $this->fwrite("");
  796. $this->fread(JAVA_RECV_SIZE);
  797. }
  798. function keepAliveH() {
  799. $this->res=$this->handler->read(10);
  800. }
  801. function keepAlive() {
  802. $this->keepAliveH();
  803. $this->checkE();
  804. }
  805. }
  806. abstract class java_SocketChannel extends java_EmptyChannel {
  807. public $peer,$host;
  808. function java_SocketChannel($peer,$host) {
  809. $this->peer=$peer;
  810. $this->host=$host;
  811. }
  812. function fwrite($data) {
  813. return fwrite($this->peer,$data);
  814. }
  815. function fread($size) {
  816. return fread($this->peer,$size);
  817. }
  818. function shutdownBrokenConnection () {
  819. fclose($this->peer);
  820. }
  821. }
  822. class java_SocketChannelP extends java_SocketChannel {
  823. function getKeepAlive() {return $this->getKeepAliveA();}
  824. function keepAlive() { $this->keepAliveS(); $this->checkA($this->peer); }
  825. }
  826. class java_ChunkedSocketChannel extends java_SocketChannel {
  827. function fwrite($data) {
  828. $len=dechex(strlen($data));
  829. return fwrite($this->peer,"${len}\r\n${data}\r\n");
  830. }
  831. function fread($size) {
  832. $length=hexdec(fgets($this->peer,JAVA_RECV_SIZE));
  833. $data="";
  834. while ($length > 0) {
  835. $str=fread($this->peer,$length);
  836. if (feof ($this->peer)) return null;
  837. $length -=strlen($str);
  838. $data .=$str;
  839. }
  840. fgets($this->peer,3);
  841. return $data;
  842. }
  843. function keepAlive() { $this->keepAliveSC(); $this->checkE(); fclose ($this->peer); }
  844. }
  845. class java_SocketHandler {
  846. public $protocol,$channel;
  847. function java_SocketHandler($protocol,$channel) {
  848. $this->protocol=$protocol;
  849. $this->channel=$channel;
  850. }
  851. function write($data) {
  852. return $this->channel->fwrite($data);
  853. }
  854. function fwrite($data) {return $this->write($data);}
  855. function read($size) {
  856. return $this->channel->fread($size);
  857. }
  858. function fread($size) {return $this->read($size);}
  859. function redirect() {}
  860. function getKeepAlive() {
  861. return $this->channel->getKeepAlive();
  862. }
  863. function keepAlive() {
  864. $this->channel->keepAlive();
  865. }
  866. function dieWithBrokenConnection($msg) {
  867. unset($this->protocol->client->protocol);
  868. trigger_error ($msg?$msg:"unknown error: please see back end log for details",E_USER_ERROR);
  869. }
  870. function shutdownBrokenConnection ($msg) {
  871. $this->channel->shutdownBrokenConnection();
  872. $this->dieWithBrokenConnection($msg);
  873. }
  874. }
  875. class java_SimpleHttpHandler extends java_SocketHandler {
  876. public $headers,$cookies;
  877. public $context,$ssl,$port;
  878. public $host;
  879. function createChannel() {
  880. $channelName=java_getHeader("X_JAVABRIDGE_REDIRECT",$_SERVER);
  881. $context=java_getHeader("X_JAVABRIDGE_CONTEXT",$_SERVER);
  882. $len=strlen($context);
  883. $len0=java_getCompatibilityOption($this->protocol->client);
  884. $len1=chr($len&0xFF); $len>>=8;
  885. $len2=chr($len&0xFF);
  886. $this->channel=new java_EmptyChannel($this);
  887. $this->channel=$this->getChannel($channelName);
  888. $this->protocol->socketHandler=new java_SocketHandler($this->protocol,$this->channel);
  889. $this->protocol->write("\177${len0}${len1}${len2}${context}");
  890. $this->context=sprintf("X_JAVABRIDGE_CONTEXT: %s\r\n",$context);
  891. $this->protocol->handler=$this->protocol->socketHandler;
  892. $this->protocol->handler->write($this->protocol->client->sendBuffer)
  893. or $this->protocol->handler->shutdownBrokenConnection("Broken local connection handle");
  894. $this->protocol->client->sendBuffer=null;
  895. $this->protocol->handler->read(1)
  896. or $this->protocol->handler->shutdownBrokenConnection("Broken local connection handle");
  897. }
  898. function java_SimpleHttpHandler($protocol,$ssl,$host,$port) {
  899. $this->cookies=array();
  900. $this->protocol=$protocol;
  901. $this->ssl=$ssl;
  902. $this->host=$host;
  903. $this->port=$port;
  904. $this->createChannel();
  905. }
  906. function getCookies() {
  907. $str="";
  908. $first=true;
  909. foreach($_COOKIE as $k=> $v) {
  910. $str .=($first ? "Cookie: $k=$v":"; $k=$v");
  911. $first=false;
  912. }
  913. if(!$first) $str .="\r\n";
  914. return $str;
  915. }
  916. function getContextFromCgiEnvironment() {
  917. $ctx=java_getHeader('X_JAVABRIDGE_CONTEXT',$_SERVER);
  918. return $ctx;
  919. }
  920. function getContext() {
  921. static $context=null;
  922. if($context) return $context;
  923. $ctx=$this->getContextFromCgiEnvironment();
  924. $context="";
  925. if($ctx) {
  926. $context=sprintf("X_JAVABRIDGE_CONTEXT: %s\r\n",$ctx);
  927. }
  928. return $context;
  929. }
  930. function getWebAppInternal() {
  931. $context=$this->protocol->webContext;
  932. if(isset($context)) return $context;
  933. return (JAVA_SERVLET=="User" &&
  934. array_key_exists('PHP_SELF',$_SERVER) &&
  935. array_key_exists('HTTP_HOST',$_SERVER))
  936. ? $_SERVER['PHP_SELF']."javabridge"
  937. : null;
  938. }
  939. function getWebApp() {
  940. $context=$this->getWebAppInternal();
  941. if(is_null($context)) $context=JAVA_SERVLET;
  942. if(is_null($context) || $context[0]!="/")
  943. $context="/JavaBridge/JavaBridge.phpjavabridge";
  944. return $context;
  945. }
  946. function write($data) {
  947. return $this->protocol->socketHandler->write($data);
  948. }
  949. function doSetCookie($key,$val,$path) {
  950. $path=trim($path);
  951. $webapp=$this->getWebAppInternal(); if(!$webapp) $path="/";
  952. setcookie($key,$val,0,$path);
  953. }
  954. function read($size) {
  955. return $this->protocol->socketHandler->read($size);
  956. }
  957. function getChannel($channelName) {
  958. $errstr=null; $errno=null;
  959. $peer=pfsockopen($this->host,$channelName,$errno,$errstr,20);
  960. if (!$peer) throw new java_IllegalStateException("No ContextServer for {$this->host}:{$channelName}. Error: $errstr ($errno)\n");
  961. stream_set_timeout($peer,-1);
  962. return new java_SocketChannelP($peer,$this->host);
  963. }
  964. function keepAlive() {
  965. parent::keepAlive();
  966. }
  967. function redirect() {}
  968. }
  969. class java_SimpleHttpTunnelHandler extends java_SimpleHttpHandler {
  970. public $socket;
  971. protected $hasContentLength=false;
  972. function createSimpleChannel () {
  973. $this->channel=new java_EmptyChannel($this);
  974. }
  975. function createChannel() {
  976. $this->createSimpleChannel();
  977. }
  978. function shutdownBrokenConnection ($msg) {
  979. fclose($this->socket);
  980. $this->dieWithBrokenConnection($msg);
  981. }
  982. function checkSocket($socket,&$errno,&$errstr) {
  983. if (!$socket) {
  984. $msg="Could not connect to the JEE server {$this->ssl}{$this->host}:{$this->port}. Please start it.";
  985. $msg.=java_checkCliSapi()
  986. ?" Or define('JAVA_HOSTS',9267); define('JAVA_SERVLET',false); before including 'Java.inc' and try again. Error message: $errstr ($errno)\n"
  987. :" Error message: $errstr ($errno)\n";
  988. throw new java_ConnectException($msg);
  989. }
  990. }
  991. function open() {
  992. $errno=null; $errstr=null;
  993. $socket=fsockopen("{$this->ssl}{$this->host}",$this->port,$errno,$errstr,20);
  994. $this->checkSocket($socket,$errno,$errstr);
  995. stream_set_timeout($socket,-1);
  996. $this->socket=$socket;
  997. }
  998. function fread($size) {
  999. $length=hexdec(fgets($this->socket,JAVA_RECV_SIZE));
  1000. $data="";
  1001. while ($length > 0) {
  1002. $str=fread($this->socket,$length);
  1003. if (feof ($this->socket)) return null;
  1004. $length -=strlen($str);
  1005. $data .=$str;
  1006. }
  1007. fgets($this->socket,3);
  1008. return $data;
  1009. }
  1010. function fwrite($data) {
  1011. $len=dechex(strlen($data));
  1012. return fwrite($this->socket,"${len}\r\n${data}\r\n");
  1013. }
  1014. function close() {
  1015. fwrite($this->socket,"0\r\n\r\n");
  1016. fgets($this->socket,JAVA_RECV_SIZE);
  1017. fgets($this->socket,3);
  1018. fclose($this->socket);
  1019. }
  1020. function java_SimpleHttpTunnelHandler($protocol,$ssl,$host,$port) {
  1021. parent::java_SimpleHttpHandler($protocol,$ssl,$host,$port);
  1022. $this->open();
  1023. }
  1024. function read($size) {
  1025. if(is_null($this->headers)) $this->parseHeaders();
  1026. if (isset($this->headers["http_error"])) {
  1027. if (isset($this->headers["transfer_chunked"])) {
  1028. $str=$this->fread(JAVA_RECV_SIZE);
  1029. } elseif (isset($this->headers['content_length'])) {
  1030. $len=$this->headers['content_length'];
  1031. for($str=fread($this->socket,$len); strlen($str)<$len; $str.=fread($this->socket,$len-strlen($str)))
  1032. if (feof ($this->socket)) break;
  1033. } else {
  1034. $str=fread($this->socket,JAVA_RECV_SIZE);
  1035. }
  1036. $this->shutdownBrokenConnection($str);
  1037. }
  1038. return $this->fread(JAVA_RECV_SIZE);
  1039. }
  1040. function getBodyFor ($compat,$data) {
  1041. $len=dechex(2+strlen($data));
  1042. return "Cache-Control: no-cache\r\nPragma: no-cache\r\nTransfer-Encoding: chunked\r\n\r\n${len}\r\n\177${compat}${data}\r\n";
  1043. }
  1044. function write($data) {
  1045. $compat=java_getCompatibilityOption($this->protocol->client);
  1046. $this->headers=null;
  1047. $socket=$this->socket;
  1048. $webapp=$this->getWebApp();
  1049. $cookies=$this->getCookies();
  1050. $context=$this->getContext();
  1051. $res="PUT ";
  1052. $res .=$webapp;
  1053. $res .=" HTTP/1.1\r\n";
  1054. $res .="Host: {$this->host}:{$this->port}\r\n";
  1055. $res .=$context;
  1056. $res .=$cookies;
  1057. $res .=$this->getBodyFor($compat,$data);
  1058. $count=fwrite($socket,$res) or $this->shutdownBrokenConnection("Broken connection handle");
  1059. fflush($socket) or $this->shutdownBrokenConnection("Broken connection handle");
  1060. return $count;
  1061. }
  1062. function parseHeaders() {
  1063. $this->headers=array();
  1064. $line=trim(fgets($this->socket,JAVA_RECV_SIZE));
  1065. $ar=explode (" ",$line);
  1066. $code=((int)$ar[1]);
  1067. if ($code !=200) $this->headers["http_error"]=$code;
  1068. while (($str=trim(fgets($this->socket,JAVA_RECV_SIZE)))) {
  1069. if($str[0]=='X') {
  1070. if(!strncasecmp("X_JAVABRIDGE_REDIRECT",$str,21)) {
  1071. $this->headers["redirect"]=trim(substr($str,22));
  1072. } else if(!strncasecmp("X_JAVABRIDGE_CONTEXT",$str,20)) {
  1073. $this->headers["context"]=trim(substr($str,21));
  1074. }
  1075. } else if($str[0]=='S') {
  1076. if(!strncasecmp("SET-COOKIE",$str,10)) {
  1077. $str=substr($str,12);
  1078. $this->cookies[]=$str;
  1079. $ar=explode(";",$str);
  1080. $cookie=explode("=",$ar[0]);
  1081. $path="";
  1082. if(isset($ar[1])) $p=explode("=",$ar[1]);
  1083. if(isset($p)) $path=$p[1];
  1084. $this->doSetCookie($cookie[0],$cookie[1],$path);
  1085. }
  1086. } else if($str[0]=='C') {
  1087. if(!strncasecmp("CONTENT-LENGTH",$str,14)) {
  1088. $this->headers["content_length"]=trim(substr($str,15));
  1089. $this->hasContentLength=true;
  1090. } else if(!strncasecmp("CONNECTION",$str,10) && !strncasecmp("close",trim(substr($str,11)),5)) {
  1091. $this->headers["connection_close"]=true;
  1092. }
  1093. } else if($str[0]=='T') {
  1094. if(!strncasecmp("TRANSFER-ENCODING",$str,17) && !strncasecmp("chunked",trim(substr($str,18)),7)) {
  1095. $this->headers["transfer_chunked"]=true;
  1096. }
  1097. }
  1098. }
  1099. }
  1100. function getSimpleChannel() {
  1101. return new java_ChunkedSocketChannel($this->socket,$this->protocol,$this->host);
  1102. }
  1103. function redirect() {
  1104. $this->isRedirect=isset($this->headers["redirect"]);
  1105. if ($this->isRedirect)
  1106. $channelName=$this->headers["redirect"];
  1107. $context=$this->headers["context"];
  1108. $len=strlen($context);
  1109. $len0=chr(0xFF);
  1110. $len1=chr($len&0xFF); $len>>=8;
  1111. $len2=chr($len&0xFF);
  1112. if ($this->isRedirect) {
  1113. $this->protocol->socketHandler=new java_SocketHandler($this->protocol,$this->getChannel($channelName));
  1114. $this->protocol->write("\177${len0}${len1}${len2}${context}");
  1115. $this->context=sprintf("X_JAVABRIDGE_CONTEXT: %s\r\n",$context);
  1116. $this->close ();
  1117. $this->protocol->handler=$this->protocol->socketHandler;
  1118. $this->protocol->handler->write($this->protocol->client->sendBuffer)
  1119. or $this->protocol->handler->shutdownBrokenConnection("Broken local connection handle");
  1120. $this->protocol->client->sendBuffer=null;
  1121. $this->protocol->handler->read(1)
  1122. or $this->protocol->handler->shutdownBrokenConnection("Broken local connection handle");
  1123. } else {
  1124. $this->protocol->handler=$this->protocol->socketHandler=new java_SocketHandler($this->protocol,$this->getSimpleChannel());
  1125. }
  1126. }
  1127. }
  1128. class java_HttpTunnelHandler extends java_SimpleHttpTunnelHandler {
  1129. function fread($size) {
  1130. if ($this->hasContentLength)
  1131. return fread($this->socket,$this->headers["content_length"]);
  1132. else
  1133. return parent::fread($size);
  1134. }
  1135. function fwrite($data) {
  1136. if ($this->hasContentLength)
  1137. return fwrite($this->socket,$data);
  1138. else
  1139. return parent::fwrite($data);
  1140. }
  1141. function close() {
  1142. if ($this->hasContentLength) {
  1143. fwrite($this->socket,"0\r\n\r\n");
  1144. fclose($this->socket);
  1145. } else {
  1146. parent::fclose($this->socket);
  1147. }
  1148. }
  1149. }
  1150. class java_Protocol {
  1151. public $client;
  1152. public $webContext;
  1153. public $serverName;
  1154. function getOverrideHosts() {
  1155. if(array_key_exists('X_JAVABRIDGE_OVERRIDE_HOSTS',$_ENV)) {
  1156. $override=$_ENV['X_JAVABRIDGE_OVERRIDE_HOSTS'];
  1157. if(!is_null($override) && $override!='/') return $override;
  1158. }
  1159. return
  1160. java_getHeader('X_JAVABRIDGE_OVERRIDE_HOSTS_REDIRECT',$_SERVER);
  1161. }
  1162. static function getHost() {
  1163. static $host=null;
  1164. if(is_null($host)) {
  1165. $hosts=explode(";",JAVA_HOSTS);
  1166. $host=explode(":",$hosts[0]);
  1167. while(count ($host) < 3) array_unshift($host,"");
  1168. if (substr($host[1],0,2)=="//") $host[1]=substr($host[1],2);
  1169. }
  1170. return $host;
  1171. }
  1172. function createHttpHandler() {
  1173. $overrideHosts=$this->getOverrideHosts();
  1174. $ssl="";
  1175. if($overrideHosts) {
  1176. $s=$overrideHosts;
  1177. if((strlen($s)>2) && ($s[1]==':')) {
  1178. if($s[0]=='s')
  1179. $ssl="ssl://";
  1180. $s=substr($s,2);
  1181. }
  1182. $webCtx=strpos($s,"//");
  1183. if($webCtx)
  1184. $host=substr($s,0,$webCtx);
  1185. else
  1186. $host=$s;
  1187. $idx=strpos($host,':');
  1188. if($idx) {
  1189. if($webCtx)
  1190. $port=substr($host,$idx+1,$webCtx);
  1191. else
  1192. $port=substr($host,$idx+1);
  1193. $host=substr($host,0,$idx);
  1194. } else {
  1195. $port="8080";
  1196. }
  1197. if($webCtx) $webCtx=substr($s,$webCtx+1);
  1198. $this->webContext=$webCtx;
  1199. } else {
  1200. $hostVec=java_Protocol::getHost();
  1201. if ($ssl=$hostVec[0]) $ssl .="://";
  1202. $host=$hostVec[1];
  1203. $port=$hostVec[2];
  1204. }
  1205. $this->serverName="${ssl}${host}:$port";
  1206. if ((array_key_exists("X_JAVABRIDGE_REDIRECT",$_SERVER)) ||
  1207. (array_key_exists("HTTP_X_JAVABRIDGE_REDIRECT",$_SERVER)))
  1208. return new java_SimpleHttpHandler($this,$ssl,$host,$port);
  1209. return new java_HttpTunnelHandler($this,$ssl,$host,$port);
  1210. }
  1211. function createSimpleHandler($name,$again=true) {
  1212. $channelName=$name;
  1213. $errno=null; $errstr=null;
  1214. if(is_numeric($channelName)) {
  1215. $peer=@pfsockopen($host="127.0.0.1",$channelName,$errno,$errstr,5);
  1216. } else {
  1217. $type=$channelName[0];
  1218. list($host,$channelName)=explode(":",$channelName);
  1219. $peer=pfsockopen($host,$channelName,$errno,$errstr,20);
  1220. if (!$peer)
  1221. throw new java_ConnectException("No Java server at $host:$channelName. Error message: $errstr ($errno)");
  1222. }
  1223. if (!$peer) {
  1224. $java=file_exists(ini_get("extension_dir")."/JavaBridge.jar")?ini_get("extension_dir")."/JavaBridge.jar":(java_get_base()."/JavaBridge.jar");
  1225. if (!file_exists($java))
  1226. throw new java_IOException("Could not find $java in ".getcwd().". Download it from http://sf.net/projects/php-java-bridge/files/Binary%20package/php-java-bridge_".JAVA_PEAR_VERSION."/exploded/JavaBridge.jar/download and try again.");
  1227. $java_cmd="java -Dphp.java.bridge.daemon=true -jar \"${java}\" INET_LOCAL:$channelName 0";
  1228. if (!$again)
  1229. throw new java_ConnectException("No Java back end! Please run it with: $java_cmd. Error message: $errstr ($errno)");
  1230. if (!java_checkCliSapi())
  1231. trigger_error("This PHP SAPI requires a JEE or SERVLET back end. Start it,define ('JAVA_SERVLET',true); define('JAVA_HOSTS',...); and try again.",E_USER_ERROR);
  1232. system ($java_cmd);
  1233. return $this->createSimpleHandler($name,false);
  1234. }
  1235. stream_set_timeout($peer,-1);
  1236. $handler=new java_SocketHandler($this,new java_SocketChannelP($peer,$host));
  1237. $compatibility=java_getCompatibilityOption($this->client);
  1238. $this->write("\177$compatibility");
  1239. $this->serverName="127.0.0.1:$channelName";
  1240. return $handler;
  1241. }
  1242. function java_get_simple_channel() {
  1243. return (JAVA_HOSTS&&(!JAVA_SERVLET||(JAVA_SERVLET=="Off"))) ? JAVA_HOSTS : null;
  1244. }
  1245. function createHandler() {
  1246. if(!java_getHeader('X_JAVABRIDGE_OVERRIDE_HOSTS',$_SERVER)&&
  1247. ((function_exists("java_get_default_channel")&&($defaultChannel=java_get_default_channel())) ||
  1248. ($defaultChannel=$this->java_get_simple_channel())) ) {
  1249. return $this->createSimpleHandler($defaultChannel);
  1250. } else {
  1251. return $this->createHttpHandler();
  1252. }
  1253. }
  1254. function java_Protocol ($client) {
  1255. $this->client=$client;
  1256. $this->handler=$this->createHandler();
  1257. }
  1258. function redirect() {
  1259. $this->handler->redirect();
  1260. }
  1261. function read($size) {
  1262. return $this->handler->read($size);
  1263. }
  1264. function sendData() {
  1265. $this->handler->write($this->client->sendBuffer);
  1266. $this->client->sendBuffer=null;
  1267. }
  1268. function flush() {
  1269. $this->sendData();
  1270. }
  1271. function getKeepAlive() {
  1272. return $this->handler->getKeepAlive();
  1273. }
  1274. function keepAlive() {
  1275. $this->handler->keepAlive();
  1276. }
  1277. function handle() {
  1278. $this->client->handleRequests();
  1279. }
  1280. function write($data) {
  1281. $this->client->sendBuffer.=$data;
  1282. }
  1283. function finish() {
  1284. $this->flush();
  1285. $this->handle();
  1286. $this->redirect();
  1287. }
  1288. function referenceBegin($name) {
  1289. $this->client->sendBuffer.=$this->client->preparedToSendBuffer;
  1290. $this->client->preparedToSendBuffer=null;
  1291. $signature=sprintf("<H p=\"1\" v=\"%s\">",$name);
  1292. $this->write($signature);
  1293. $signature[6]="2";
  1294. $this->client->currentArgumentsFormat=$signature;
  1295. }
  1296. function referenceEnd() {
  1297. $this->client->currentArgumentsFormat.=$format="</H>";
  1298. $this->write($format);
  1299. $this->finish();
  1300. $this->client->currentCacheKey=null;
  1301. }
  1302. function createObjectBegin($name) {
  1303. $this->client->sendBuffer.=$this->client->preparedToSendBuffer;
  1304. $this->client->preparedToSendBuffer=null;
  1305. $signature=sprintf("<K p=\"1\" v=\"%s\">",$name);
  1306. $this->write($signature);
  1307. $signature[6]="2";
  1308. $this->client->currentArgumentsFormat=$signature;
  1309. }
  1310. function createObjectEnd() {
  1311. $this->client->currentArgumentsFormat.=$format="</K>";
  1312. $this->write($format);
  1313. $this->finish();
  1314. $this->client->currentCacheKey=null;
  1315. }
  1316. function propertyAccessBegin($object,$method) {
  1317. $this->client->sendBuffer.=$this->client->preparedToSendBuffer;
  1318. $this->client->preparedToSendBuffer=null;
  1319. $this->write(sprintf("<G p=\"1\" v=\"%x\" m=\"%s\">",$object,$method));
  1320. $this->client->currentArgumentsFormat="<G p=\"2\" v=\"%x\" m=\"${method}\">";
  1321. }
  1322. function propertyAccessEnd() {
  1323. $this->client->currentArgumentsFormat.=$format="</G>";
  1324. $this->write($format);
  1325. $this->finish();
  1326. $this->client->currentCacheKey=null;
  1327. }
  1328. function invokeBegin($object,$method) {
  1329. $this->client->sendBuffer.=$this->client->preparedToSendBuffer;
  1330. $this->client->preparedToSendBuffer=null;
  1331. $this->write(sprintf("<Y p=\"1\" v=\"%x\" m=\"%s\">",$object,$method));
  1332. $this->client->currentArgumentsFormat="<Y p=\"2\" v=\"%x\" m=\"${method}\">";
  1333. }
  1334. function invokeEnd() {
  1335. $this->client->currentArgumentsFormat.=$format="</Y>";
  1336. $this->write($format);
  1337. $this->finish();
  1338. $this->client->currentCacheKey=null;
  1339. }
  1340. function resultBegin() {
  1341. $this->client->sendBuffer.=$this->client->preparedToSendBuffer;
  1342. $this->client->preparedToSendBuffer=null;
  1343. $this->write("<R>");
  1344. }
  1345. function resultEnd() {
  1346. $this->client->currentCacheKey=null;
  1347. $this->write("</R>");
  1348. $this->flush();
  1349. }
  1350. function writeString($name) {
  1351. $this->client->currentArgumentsFormat.=$format="<S v=\"%s\"/>";
  1352. $this->write(sprintf($format,htmlspecialchars($name,ENT_COMPAT)));
  1353. }
  1354. function writeBoolean($boolean) {
  1355. $this->client->currentArgumentsFormat.=$format="<T v=\"%s\"/>";
  1356. $this->write(sprintf($format,$boolean));
  1357. }
  1358. function writeLong($l) {
  1359. $this->client->currentArgumentsFormat.="<J v=\"%d\"/>";
  1360. if($l<0) {
  1361. $this->write(sprintf("<L v=\"%x\" p=\"A\"/>",-$l));
  1362. } else {
  1363. $this->write(sprintf("<L v=\"%x\" p=\"O\"/>",$l));
  1364. }
  1365. }
  1366. function writeULong($l) {
  1367. $this->client->currentArgumentsFormat.=$format="<L v=\"%x\" p=\"O\"/>";
  1368. $this->write(sprintf($format,$l));
  1369. }
  1370. function writeDouble($d) {
  1371. $this->client->currentArgumentsFormat.=$format="<D v=\"%.14e\"/>";
  1372. $this->write(sprintf($format,$d));
  1373. }
  1374. function writeObject($object) {
  1375. $this->client->currentArgumentsFormat.=$format="<O v=\"%x\"/>";
  1376. $this->write(sprintf($format,$object));
  1377. }
  1378. function writeException($object,$str) {
  1379. $this->write(sprintf("<E v=\"%x\" m=\"%s\"/>",$object,htmlspecialchars($str,ENT_COMPAT)));
  1380. }
  1381. function writeCompositeBegin_a() {
  1382. $this->write("<X t=\"A\">");
  1383. }
  1384. function writeCompositeBegin_h() {
  1385. $this->write("<X t=\"H\">");
  1386. }
  1387. function writeCompositeEnd() {
  1388. $this->write("</X>");
  1389. }
  1390. function writePairBegin_s($key) {
  1391. $this->write(sprintf("<P t=\"S\" v=\"%s\">",htmlspecialchars($key,ENT_COMPAT)));
  1392. }
  1393. function writePairBegin_n($key) {
  1394. $this->write(sprintf("<P t=\"N\" v=\"%x\">",$key));
  1395. }
  1396. function writePairBegin() {
  1397. $this->write("<P>");
  1398. }
  1399. function writePairEnd() {
  1400. $this->write("</P>");
  1401. }
  1402. function writeUnref($object) {
  1403. $this->client->sendBuffer.=$this->client->preparedToSendBuffer;
  1404. $this->client->preparedToSendBuffer=null;
  1405. $this->write(sprintf("<U v=\"%x\"/>",$object));
  1406. }
  1407. function getServerName() {
  1408. return $this->serverName;
  1409. }
  1410. }
  1411. class java_ParserString {
  1412. public $string,$off,$length;
  1413. function toString() {
  1414. return $this->getString();
  1415. }
  1416. function getString() {
  1417. return substr($this->string,$this->off,$this->length);
  1418. }
  1419. }
  1420. class java_ParserTag {
  1421. public $n,$strings;
  1422. function java_ParserTag() {
  1423. $this->strings=array();
  1424. $this->n=0;
  1425. }
  1426. }
  1427. class java_SimpleParser {
  1428. public $SLEN=256;
  1429. public $handler;
  1430. public $tag,$buf,$len,$s;
  1431. public $type;
  1432. function java_SimpleParser($handler) {
  1433. $this->handler=$handler;
  1434. $this->tag=array(new java_ParserTag(),new java_ParserTag(),new java_ParserTag());
  1435. $this->len=$this->SLEN;
  1436. $this->s=str_repeat(" ",$this->SLEN);
  1437. $this->type=$this->VOJD;
  1438. }
  1439. public $BEGIN=0,$KEY=1,$VAL=2,$ENTITY=3,$VOJD=5,$END=6;
  1440. public $level=0,$eor=0; public $in_dquote,$eot=false;
  1441. public $pos=0,$c=0,$i=0,$i0=0,$e;
  1442. function RESET() {
  1443. $this->type=$this->VOJD;
  1444. $this->level=0;
  1445. $this->eor=0;
  1446. $this->in_dquote=false;
  1447. $this->i=0;
  1448. $this->i0=0;
  1449. }
  1450. function APPEND($c) {
  1451. if($this->i>=$this->len-1) {
  1452. $this->s=str_repeat($this->s,2);
  1453. $this->len*=2;
  1454. }
  1455. $this->s[$this->i++]=$c;
  1456. }
  1457. function CALL_BEGIN() {
  1458. $pt=&$this->tag[1]->strings;
  1459. $st=&$this->tag[2]->strings;
  1460. $t=&$this->tag[0]->strings[0];
  1461. $name=$t->string[$t->off];
  1462. $n=$this->tag[2]->n;
  1463. $ar=array();
  1464. for($i=0; $i<$n; $i++) {
  1465. $ar[$pt[$i]->getString()]=$st[$i]->getString();
  1466. }
  1467. $this->handler->begin($name,$ar);
  1468. }
  1469. function CALL_END() {
  1470. $t=&$this->tag[0]->strings[0];
  1471. $name=$t->string[$t->off];
  1472. $this->handler->end($name);
  1473. }
  1474. function PUSH($t) {
  1475. $str=&$this->tag[$t]->strings;
  1476. $n=&$this->tag[$t]->n;
  1477. $this->s[$this->i]='|';
  1478. if(!isset($str[$n])){$h=$this->handler; $str[$n]=$h->createParserString();}
  1479. $str[$n]->string=&$this->s;
  1480. $str[$n]->off=$this->i0;
  1481. $str[$n]->length=$this->i-$this->i0;
  1482. ++$this->tag[$t]->n;
  1483. $this->APPEND('|');
  1484. $this->i0=$this->i;
  1485. }
  1486. function parse() {
  1487. while($this->eor==0) {
  1488. if($this->c>=$this->pos) {
  1489. $this->buf=$this->handler->read(JAVA_RECV_SIZE);
  1490. if(is_null($this->buf) || strlen($this->buf)==0)
  1491. $this->handler->protocol->handler->shutdownBrokenConnection("protocol error. Check the back end log for OutOfMemoryErrors.");
  1492. $this->pos=strlen($this->buf);
  1493. if($this->pos==0) break;
  1494. $this->c=0;
  1495. }
  1496. switch(($ch=$this->buf[$this->c]))
  1497. {
  1498. case '<': if($this->in_dquote) {$this->APPEND($ch); break;}
  1499. $this->level+=1;
  1500. $this->type=$this->BEGIN;
  1501. break;
  1502. case '\t': case '\f': case '\n': case '\r': case ' ': if($this->in_dquote) {$this->APPEND($ch); break;}
  1503. if($this->type==$this->BEGIN) {
  1504. $this->PUSH($this->type);
  1505. $this->type=$this->KEY;
  1506. }
  1507. break;
  1508. case '=': if($this->in_dquote) {$this->APPEND($ch); break;}
  1509. $this->PUSH($this->type);
  1510. $this->type=$this->VAL;
  1511. break;
  1512. case '/': if($this->in_dquote) {$this->APPEND($ch); break;}
  1513. if($this->type==$this->BEGIN) { $this->type=$this->END; $this->level-=1; }
  1514. $this->level-=1;
  1515. $this->eot=true;
  1516. break;
  1517. case '>': if($this->in_dquote) {$this->APPEND($ch); break;}
  1518. if($this->type==$this->END){
  1519. $this->PUSH($this->BEGIN);
  1520. $this->CALL_END();
  1521. } else {
  1522. if($this->type==$this->VAL) $this->PUSH($this->type);
  1523. $this->CALL_BEGIN();
  1524. }
  1525. $this->tag[0]->n=$this->tag[1]->n=$this->tag[2]->n=0; $this->i0=$this->i=0;
  1526. $this->type=$this->VOJD;
  1527. if($this->level==0) $this->eor=1;
  1528. break;
  1529. case ';':
  1530. if($this->type==$this->ENTITY) {
  1531. switch ($this->s[$this->e+1]) {
  1532. case 'l': $this->s[$this->e]='<'; $this->i=$this->e+1; break;
  1533. case 'g': $this->s[$this->e]='>'; $this->i=$this->e+1; break;
  1534. case 'a': $this->s[$this->e]=($this->s[$this->e+2]=='m'?'&':'\''); $this->i=$this->e+1; break;
  1535. case 'q': $this->s[$this->e]='"'; $this->i=$this->e+1; break;
  1536. default: $this->APPEND($ch);
  1537. }
  1538. $this->type=$this->VAL;
  1539. } else {
  1540. $this->APPEND($ch);
  1541. }
  1542. break;
  1543. case '&':
  1544. $this->type=$this->ENTITY;
  1545. $this->e=$this->i;
  1546. $this->APPEND($ch);
  1547. break;
  1548. case '"':
  1549. $this->in_dquote=!$this->in_dquote;
  1550. if(!$this->in_dquote && $this->type==$this->VAL) {
  1551. $this->PUSH($this->type);
  1552. $this->type=$this->KEY;
  1553. }
  1554. break;
  1555. default:
  1556. $this->APPEND($ch);
  1557. }
  1558. $this->c+=1;
  1559. }
  1560. $this->RESET();
  1561. }
  1562. function getData($str) {
  1563. return $str;
  1564. }
  1565. function parserError() {
  1566. $this->handler->protocol->handler->shutdownBrokenConnection(
  1567. sprintf("protocol error: %s. Check the back end log for details.",$this->s));
  1568. }
  1569. }
  1570. interface java_JavaType {};
  1571. $java_initialized=false;
  1572. function __javaproxy_Client_getClient() {
  1573. static $client=null;
  1574. if(!is_null($client)) return $client;
  1575. if (function_exists("java_create_client")) $client=java_create_client();
  1576. else {
  1577. global $java_initialized;
  1578. $client=new java_Client();
  1579. $java_initialized=true;
  1580. }
  1581. return $client;
  1582. }
  1583. function java_last_exception_get() {
  1584. $client=__javaproxy_Client_getClient();
  1585. return $client->invokeMethod(0,"getLastException",array());
  1586. }
  1587. function java_last_exception_clear() {
  1588. $client=__javaproxy_Client_getClient();
  1589. $client->invokeMethod(0,"clearLastException",array());
  1590. }
  1591. function java_values_internal($object) {
  1592. if(!$object instanceof java_JavaType) return $object;
  1593. $client=__javaproxy_Client_getClient();
  1594. return $client->invokeMethod(0,"getValues",array($object));
  1595. }
  1596. function java_invoke($object,$method,$args) {
  1597. $client=__javaproxy_Client_getClient();
  1598. $id=($object==null) ? 0 : $object->__java;
  1599. return $client->invokeMethod($id,$method,$args);
  1600. }
  1601. function java_unwrap ($object) {
  1602. if(!$object instanceof java_JavaType) throw new java_IllegalArgumentException($object);
  1603. $client=__javaproxy_Client_getClient();
  1604. return $client->globalRef->get($client->invokeMethod(0,"unwrapClosure",array($object)));
  1605. }
  1606. function java_values($object) {
  1607. return java_values_internal($object);
  1608. }
  1609. function java_inspect_internal($object) {
  1610. if(!$object instanceof java_JavaType) throw new java_IllegalArgumentException($object);
  1611. $client=__javaproxy_Client_getClient();
  1612. return $client->invokeMethod(0,"inspect",array($object));
  1613. }
  1614. function java_inspect($object) {
  1615. return java_inspect_internal($object);
  1616. }
  1617. function java_set_file_encoding($enc) {
  1618. $client=__javaproxy_Client_getClient();
  1619. return $client->invokeMethod(0,"setFileEncoding",array($enc));
  1620. }
  1621. function java_instanceof_internal($ob,$clazz) {
  1622. if(!$ob instanceof java_JavaType) throw new java_IllegalArgumentException($ob);
  1623. if(!$clazz instanceof java_JavaType) throw new java_IllegalArgumentException($clazz);
  1624. $client=__javaproxy_Client_getClient();
  1625. return $client->invokeMethod(0,"instanceOf",array($ob,$clazz));
  1626. }
  1627. function java_instanceof($ob,$clazz) {
  1628. return java_instanceof_internal($ob,$clazz);
  1629. }
  1630. function java_cast_internal($object,$type) {
  1631. if(!$object instanceof java_JavaType) {
  1632. switch($type[0]) {
  1633. case 'S': case 's':
  1634. return (string)$object;
  1635. case 'B': case 'b':
  1636. return (boolean)$object;
  1637. case 'L': case 'I': case 'l': case 'i':
  1638. return (integer)$object;
  1639. case 'D': case 'd': case 'F': case 'f':
  1640. return (float) $object;
  1641. case 'N': case 'n':
  1642. return null;
  1643. case 'A': case 'a':
  1644. return (array)$object;
  1645. case 'O': case 'o':
  1646. return (object)$object;
  1647. }
  1648. }
  1649. return $object->__cast($type);
  1650. }
  1651. function java_cast($object,$type) {
  1652. return java_cast_internal($object,$type);
  1653. }
  1654. function java_require($arg) {
  1655. trigger_error('java_require() not supported anymore. Please use <a href="http://php-java-bridge.sourceforge.net/pjb/webapp.php>tomcat or jee hot deployment</a> instead',E_USER_WARNING);
  1656. }
  1657. function java_get_lifetime ()
  1658. {
  1659. $session_max_lifetime=ini_get("session.gc_maxlifetime");
  1660. return $session_max_lifetime ? (int)$session_max_lifetime : 1440;
  1661. }
  1662. function java_session_array($args) {
  1663. $client=__javaproxy_Client_getClient();
  1664. if(!isset($args[0])) $args[0]=null;
  1665. if(!isset($args[1]))
  1666. $args[1]=0;
  1667. elseif ($args[1]===true)
  1668. $args[1]=1;
  1669. else
  1670. $args[1]=2;
  1671. if(!isset($args[2])) {
  1672. $args[2]=java_get_lifetime ();
  1673. }
  1674. return $client->getSession($args);
  1675. }
  1676. function java_session() {
  1677. return java_session_array(func_get_args());
  1678. }
  1679. function java_server_name() {
  1680. try {
  1681. $client=__javaproxy_Client_getClient();
  1682. return $client->getServerName();
  1683. } catch (java_ConnectException $ex) {
  1684. return null;
  1685. }
  1686. }
  1687. function java_context() {
  1688. $client=__javaproxy_Client_getClient();
  1689. return $client->getContext();
  1690. }
  1691. function java_closure_array($args) {
  1692. if(isset($args[2]) && ((!($args[2] instanceof java_JavaType))&&!is_array($args[2])))
  1693. throw new java_IllegalArgumentException($args[2]);
  1694. $client=__javaproxy_Client_getClient();
  1695. $args[0]=isset($args[0]) ? $client->globalRef->add($args[0]) : 0;
  1696. $client->protocol->invokeBegin(0,"makeClosure");
  1697. $n=count($args);
  1698. $client->protocol->writeULong($args[0]);
  1699. for($i=1; $i<$n; $i++) {
  1700. $client->writeArg($args[$i]);
  1701. }
  1702. $client->protocol->invokeEnd();
  1703. $val=$client->getResult();
  1704. return $val;
  1705. }
  1706. function java_closure() {
  1707. return java_closure_array(func_get_args());
  1708. }
  1709. function java_begin_document() {
  1710. }
  1711. function java_end_document() {
  1712. }
  1713. class java_JavaProxy implements java_JavaType {
  1714. public $__serialID,$__java;
  1715. public $__signature;
  1716. public $__client;
  1717. public $__tempGlobalRef;
  1718. function java_JavaProxy($java,$signature){
  1719. $this->__java=$java;
  1720. $this->__signature=$signature;
  1721. $this->__client=__javaproxy_Client_getClient();
  1722. }
  1723. function __cast($type) {
  1724. return $this->__client->cast($this,$type);
  1725. }
  1726. function __sleep() {
  1727. $args=array($this,java_get_lifetime());
  1728. $this->__serialID=$this->__client->invokeMethod(0,"serialize",$args);
  1729. $this->__tempGlobalRef=$this->__client->globalRef;
  1730. return array("__serialID","__tempGlobalRef");
  1731. }
  1732. function __wakeup() {
  1733. $args=array($this->__serialID,java_get_lifetime());
  1734. $this->__client=__javaproxy_Client_getClient();
  1735. if($this->__tempGlobalRef)
  1736. $this->__client->globalRef=$this->__tempGlobalRef;
  1737. $this->__tempGlobalRef=null;
  1738. $this->__java=$this->__client->invokeMethod(0,"deserialize",$args);
  1739. }
  1740. function __destruct() {
  1741. if(isset($this->__client))
  1742. $this->__client->unref($this->__java);
  1743. }
  1744. function __get($key) {
  1745. return $this->__client->getProperty($this->__java,$key);
  1746. }
  1747. function __set($key,$val) {
  1748. $this->__client->setProperty($this->__java,$key,$val);
  1749. }
  1750. function __call($method,$args) {
  1751. return $this->__client->invokeMethod($this->__java,$method,$args);
  1752. }
  1753. function __toString() {
  1754. try {
  1755. return $this->__client->invokeMethod(0,"ObjectToString",array($this));
  1756. } catch (JavaException $ex) {
  1757. trigger_error("Exception in Java::__toString(): ". java_truncate((string)$ex),E_USER_WARNING);
  1758. return "";
  1759. }
  1760. }
  1761. }
  1762. class java_objectIterator implements Iterator {
  1763. private $var;
  1764. function java_ObjectIterator($javaProxy) {
  1765. $this->var=java_cast ($javaProxy,"A");
  1766. }
  1767. function rewind() {
  1768. reset($this->var);
  1769. }
  1770. function valid() {
  1771. return $this->current() !==false;
  1772. }
  1773. function next() {
  1774. return next($this->var);
  1775. }
  1776. function key() {
  1777. return key($this->var);
  1778. }
  1779. function current() {
  1780. return current($this->var);
  1781. }
  1782. }
  1783. class java_IteratorProxy extends java_JavaProxy implements IteratorAggregate {
  1784. function getIterator() {
  1785. return new java_ObjectIterator($this);
  1786. }
  1787. }
  1788. class java_ArrayProxy extends java_IteratorProxy implements ArrayAccess {
  1789. function offsetExists($idx) {
  1790. $ar=array($this,$idx);
  1791. return $this->__client->invokeMethod(0,"offsetExists",$ar);
  1792. }
  1793. function offsetGet($idx) {
  1794. $ar=array($this,$idx);
  1795. return $this->__client->invokeMethod(0,"offsetGet",$ar);
  1796. }
  1797. function offsetSet($idx,$val) {
  1798. $ar=array($this,$idx,$val);
  1799. return $this->__client->invokeMethod(0,"offsetSet",$ar);
  1800. }
  1801. function offsetUnset($idx) {
  1802. $ar=array($this,$idx);
  1803. return $this->__client->invokeMethod(0,"offsetUnset",$ar);
  1804. }
  1805. }
  1806. class java_ExceptionProxy extends java_JavaProxy {
  1807. function __toExceptionString($trace) {
  1808. $args=array($this,$trace);
  1809. return $this->__client->invokeMethod(0,"ObjectToString",$args);
  1810. }
  1811. }
  1812. abstract class java_AbstractJava implements IteratorAggregate,ArrayAccess,java_JavaType {
  1813. public $__client;
  1814. public $__delegate;
  1815. public $__serialID;
  1816. public $__factory;
  1817. public $__java,$__signature;
  1818. public $__cancelProxyCreationTag;
  1819. function __createDelegate() {
  1820. $proxy=$this->__delegate=
  1821. $this->__factory->create($this->__java,$this->__signature);
  1822. $this->__java=$proxy->__java;
  1823. $this->__signature=$proxy->__signature;
  1824. }
  1825. function __cast($type) {
  1826. if(!isset($this->__delegate)) $this->__createDelegate();
  1827. return $this->__delegate->__cast($type);
  1828. }
  1829. function __sleep() {
  1830. if(!isset($this->__delegate)) $this->__createDelegate();
  1831. $this->__delegate->__sleep();
  1832. return array("__delegate");
  1833. }
  1834. function __wakeup() {
  1835. if(!isset($this->__delegate)) $this->__createDelegate();
  1836. $this->__delegate->__wakeup();
  1837. $this->__java=$this->__delegate->__java;
  1838. $this->__client=$this->__delegate->__client;
  1839. }
  1840. function __get($key) {
  1841. if(!isset($this->__delegate)) $this->__createDelegate();
  1842. return $this->__delegate->__get($key);
  1843. }
  1844. function __set($key,$val) {
  1845. if(!isset($this->__delegate)) $this->__createDelegate();
  1846. $this->__delegate->__set($key,$val);
  1847. }
  1848. function __call($method,$args) {
  1849. if(!isset($this->__delegate)) $this->__createDelegate();
  1850. return $this->__delegate->__call($method,$args);
  1851. }
  1852. function __toString() {
  1853. if(!isset($this->__delegate)) $this->__createDelegate();
  1854. return $this->__delegate->__toString();
  1855. }
  1856. function getIterator() {
  1857. if(!isset($this->__delegate)) $this->__createDelegate();
  1858. if(func_num_args()==0) return $this->__delegate->getIterator();
  1859. $args=func_get_args(); return $this->__call("getIterator",$args);
  1860. }
  1861. function offsetExists($idx) {
  1862. if(!isset($this->__delegate)) $this->__createDelegate();
  1863. if(func_num_args()==1) return $this->__delegate->offsetExists($idx);
  1864. $args=func_get_args(); return $this->__call("offsetExists",$args);
  1865. }
  1866. function offsetGet($idx) {
  1867. if(!isset($this->__delegate)) $this->__createDelegate();
  1868. if(func_num_args()==1) return $this->__delegate->offsetGet($idx);
  1869. $args=func_get_args(); return $this->__call("offsetGet",$args);
  1870. }
  1871. function offsetSet($idx,$val) {
  1872. if(!isset($this->__delegate)) $this->__createDelegate();
  1873. if(func_num_args()==2) return $this->__delegate->offsetSet($idx,$val);
  1874. $args=func_get_args(); return $this->__call("offsetSet",$args);
  1875. }
  1876. function offsetUnset($idx) {
  1877. if(!isset($this->__delegate)) $this->__createDelegate();
  1878. if(func_num_args()==1) return $this->__delegate->offsetUnset($idx);
  1879. $args=func_get_args(); return $this->__call("offsetUnset",$args);
  1880. }
  1881. }
  1882. class Java extends java_AbstractJava {
  1883. function Java() {
  1884. $client=$this->__client=__javaproxy_Client_getClient();
  1885. $args=func_get_args();
  1886. $name=array_shift($args);
  1887. if(is_array($name)) {$args=$name; $name=array_shift($args);}
  1888. $sig="&{$this->__signature}@{$name}";
  1889. $len=count($args);
  1890. $args2=array();
  1891. for($i=0; $i<$len; $i++) {
  1892. switch(gettype($val=$args[$i])) {
  1893. case 'boolean': array_push($args2,$val); $sig.='@b'; break;
  1894. case 'integer': array_push($args2,$val); $sig.='@i'; break;
  1895. case 'double': array_push($args2,$val); $sig.='@d'; break;
  1896. case 'string': array_push($args2,htmlspecialchars($val,ENT_COMPAT)); $sig.='@s'; break;
  1897. case 'array':$sig="~INVALID"; break;
  1898. case 'object':
  1899. if($val instanceof java_JavaType) {
  1900. array_push($args2,$val->__java);
  1901. $sig.="@o{$val->__signature}";
  1902. }
  1903. else {
  1904. $sig="~INVALID";
  1905. }
  1906. break;
  1907. case 'resource': array_push($args2,$val); $sig.='@r'; break;
  1908. case 'NULL': array_push($args2,$val); $sig.='@N'; break;
  1909. case 'unknown type': array_push($args2,$val); $sig.='@u'; break;
  1910. default: throw new java_IllegalArgumentException($val);
  1911. }
  1912. }
  1913. if(array_key_exists($sig,$client->methodCache)) {
  1914. $cacheEntry=&$client->methodCache[$sig];
  1915. $client->sendBuffer.=$client->preparedToSendBuffer;
  1916. if(strlen($client->sendBuffer)>=JAVA_SEND_SIZE) {
  1917. if($client->protocol->handler->write($client->sendBuffer)<=0)
  1918. throw new java_IllegalStateException("Connection out of sync,check backend log for details.");
  1919. $client->sendBuffer=null;
  1920. }
  1921. $client->preparedToSendBuffer=vsprintf($cacheEntry->fmt,$args2);
  1922. $this->__java=++$client->asyncCtx;
  1923. $this->__factory=$cacheEntry->factory;
  1924. $this->__signature=$cacheEntry->signature;
  1925. $this->__cancelProxyCreationTag=++$client->cancelProxyCreationTag;
  1926. } else {
  1927. $client->currentCacheKey=$sig;
  1928. $delegate=$this->__delegate=$client->createObject($name,$args);
  1929. $this->__java=$delegate->__java;
  1930. $this->__signature=$delegate->__signature;
  1931. }
  1932. }
  1933. function __destruct() {
  1934. if(!isset($this->__client)) return;
  1935. $client=$this->__client;
  1936. $preparedToSendBuffer=&$client->preparedToSendBuffer;
  1937. if($preparedToSendBuffer &&
  1938. $client->cancelProxyCreationTag==$this->__cancelProxyCreationTag) {
  1939. $preparedToSendBuffer[6]="3";
  1940. $client->sendBuffer.=$preparedToSendBuffer;
  1941. $preparedToSendBuffer=null;
  1942. $client->asyncCtx -=1;
  1943. } else {
  1944. if(!isset($this->__delegate)) {
  1945. $client->unref($this->__java);
  1946. }
  1947. }
  1948. }
  1949. function __call($method,$args) {
  1950. $client=$this->__client;
  1951. $sig="@{$this->__signature}@$method";
  1952. $len=count($args);
  1953. $args2=array($this->__java);
  1954. for($i=0; $i<$len; $i++) {
  1955. switch(gettype($val=$args[$i])) {
  1956. case 'boolean': array_push($args2,$val); $sig.='@b'; break;
  1957. case 'integer': array_push($args2,$val); $sig.='@i'; break;
  1958. case 'double': array_push($args2,$val); $sig.='@d'; break;
  1959. case 'string': array_push($args2,htmlspecialchars($val,ENT_COMPAT)); $sig.='@s'; break;
  1960. case 'array':$sig="~INVALID"; break;
  1961. case 'object':
  1962. if($val instanceof java_JavaType) {
  1963. array_push($args2,$val->__java);
  1964. $sig.="@o{$val->__signature}";
  1965. }
  1966. else {
  1967. $sig="~INVALID";
  1968. }
  1969. break;
  1970. case 'resource': array_push($args2,$val); $sig.='@r'; break;
  1971. case 'NULL': array_push($args2,$val); $sig.='@N'; break;
  1972. case 'unknown type': array_push($args2,$val); $sig.='@u'; break;
  1973. default: throw new java_IllegalArgumentException($val);
  1974. }
  1975. }
  1976. if(array_key_exists($sig,$client->methodCache)) {
  1977. $cacheEntry=&$client->methodCache[$sig];
  1978. $client->sendBuffer.=$client->preparedToSendBuffer;
  1979. if(strlen($client->sendBuffer)>=JAVA_SEND_SIZE) {
  1980. if($client->protocol->handler->write($client->sendBuffer)<=0)
  1981. throw new java_IllegalStateException("Out of sync. Check backend log for details.");
  1982. $client->sendBuffer=null;
  1983. }
  1984. $client->preparedToSendBuffer=vsprintf($cacheEntry->fmt,$args2);
  1985. if($cacheEntry->resultVoid) {
  1986. $client->cancelProxyCreationTag +=1;
  1987. return null;
  1988. } else {
  1989. $result=clone($client->cachedJavaPrototype);
  1990. $result->__factory=$cacheEntry->factory;
  1991. $result->__java=++$client->asyncCtx;
  1992. $result->__signature=$cacheEntry->signature;
  1993. $result->__cancelProxyCreationTag=++$client->cancelProxyCreationTag;
  1994. return $result;
  1995. }
  1996. } else {
  1997. $client->currentCacheKey=$sig;
  1998. $retval=parent::__call($method,$args);
  1999. return $retval;
  2000. }
  2001. }
  2002. }
  2003. class java_InternalJava extends Java {
  2004. function java_InternalJava($proxy) {
  2005. $this->__delegate=$proxy;
  2006. $this->__java=$proxy->__java;
  2007. $this->__signature=$proxy->__signature;
  2008. $this->__client=$proxy->__client;
  2009. }
  2010. }
  2011. class java_class extends Java {
  2012. function java_class() {
  2013. $this->__client=__javaproxy_Client_getClient();
  2014. $args=func_get_args();
  2015. $name=array_shift($args);
  2016. if(is_array($name)) { $args=$name; $name=array_shift($args); }
  2017. $delegate=$this->__delegate=$this->__client->referenceObject($name,$args);
  2018. $this->__java=$delegate->__java;
  2019. $this->__signature=$delegate->__signature;
  2020. }
  2021. }
  2022. class JavaClass extends java_class{}
  2023. class java_exception extends Exception implements java_JavaType {
  2024. public $__serialID,$__java,$__client;
  2025. public $__delegate;
  2026. public $__signature;
  2027. public $__hasDeclaredExceptions;
  2028. function java_exception() {
  2029. $this->__client=__javaproxy_Client_getClient();
  2030. $args=func_get_args();
  2031. $name=array_shift($args);
  2032. if(is_array($name)) { $args=$name; $name=array_shift($args); }
  2033. if (count($args)==0)
  2034. Exception::__construct($name);
  2035. else
  2036. Exception::__construct($args[0]);
  2037. $delegate=$this->__delegate=$this->__client->createObject($name,$args);
  2038. $this->__java=$delegate->__java;
  2039. $this->__signature=$delegate->__signature;
  2040. $this->__hasDeclaredExceptions='T';
  2041. }
  2042. function __cast($type) {
  2043. return $this->__delegate->__cast($type);
  2044. }
  2045. function __sleep() {
  2046. $this->__delegate->__sleep();
  2047. return array("__delegate");
  2048. }
  2049. function __wakeup() {
  2050. $this->__delegate->__wakeup();
  2051. $this->__java=$this->__delegate->__java;
  2052. $this->__client=$this->__delegate->__client;
  2053. }
  2054. function __get($key) {
  2055. return $this->__delegate->__get($key);
  2056. }
  2057. function __set($key,$val) {
  2058. $this->__delegate->__set($key,$val);
  2059. }
  2060. function __call($method,$args) {
  2061. return $this->__delegate->__call($method,$args);
  2062. }
  2063. function __toString() {
  2064. return $this->__delegate->__toExceptionString($this->getTraceAsString());
  2065. }
  2066. }
  2067. class JavaException extends java_exception {}
  2068. class java_InternalException extends JavaException {
  2069. function java_InternalException($proxy,$exception) {
  2070. $this->__delegate=$proxy;
  2071. $this->__java=$proxy->__java;
  2072. $this->__signature=$proxy->__signature;
  2073. $this->__client=$proxy->__client;
  2074. $this->__hasDeclaredExceptions=$exception;
  2075. }
  2076. }
  2077. class java_JavaProxyProxy extends Java {
  2078. function java_JavaProxyProxy($client) {
  2079. $this->__client=$client;
  2080. }
  2081. }
  2082. }
  2083. ?>