PageRenderTime 72ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/HadoopWebClient/Java.inc

https://github.com/aaronyc/HadoopSaaS
PHP | 2084 lines | 2074 code | 1 blank | 9 comment | 269 complexity | 71f80a7c1659a09ace6a5eae3bcac219 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  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-rc1");
  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. static $cache=null;
  627. if (!is_null($cache)) {
  628. trigger_error("java_session() should be called once at the beginning of the script",E_USER_WARNING);
  629. return $cache;
  630. }
  631. return $cache=$this->invokeMethod(0,"getSession",$args);
  632. }
  633. function getServerName() {
  634. static $cache=null;
  635. if (!is_null($cache)) return $cache;
  636. return $cache=$this->protocol->getServerName();
  637. }
  638. }
  639. function java_shutdown() {
  640. global $java_initialized;
  641. if (!$java_initialized) return;
  642. if (session_id()) session_write_close();
  643. $client=__javaproxy_Client_getClient();
  644. if (!isset($client->protocol) || $client->inArgs) return;
  645. if ($client->preparedToSendBuffer)
  646. $client->sendBuffer.=$client->preparedToSendBuffer;
  647. $client->sendBuffer.=$client->protocol->getKeepAlive();
  648. $client->protocol->flush();
  649. $client->protocol->keepAlive();
  650. }
  651. register_shutdown_function("java_shutdown");
  652. class java_GlobalRef {
  653. public $map;
  654. function java_GlobalRef() {
  655. $this->map=array();
  656. }
  657. function add($object) {
  658. if(is_null($object)) return 0;
  659. return array_push($this->map,$object);
  660. }
  661. function get($id) {
  662. if(!$id) return 0;
  663. return $this->map[--$id];
  664. }
  665. }
  666. class java_NativeParser {
  667. public $parser,$handler;
  668. public $level,$event;
  669. public $buf;
  670. function java_NativeParser($handler) {
  671. $this->handler=$handler;
  672. $this->parser=xml_parser_create();
  673. xml_parser_set_option($this->parser,XML_OPTION_CASE_FOLDING,0);
  674. xml_set_object($this->parser,$this);
  675. xml_set_element_handler($this->parser,"begin","end");
  676. xml_parse($this->parser,"<F>");
  677. $this->level=0;
  678. }
  679. function begin($parser,$name,$param) {
  680. $this->event=true;
  681. switch($name) {
  682. case 'X': case 'A': $this->level+=1;
  683. }
  684. $this->handler->begin($name,$param);
  685. }
  686. function end($parser,$name) {
  687. $this->handler->end($name);
  688. switch($name) {
  689. case 'X': case 'A': $this->level-=1;
  690. }
  691. }
  692. function getData($str) {
  693. return base64_decode($str);
  694. }
  695. function parse() {
  696. do {
  697. $this->event=false;
  698. $buf=$this->buf=$this->handler->read(JAVA_RECV_SIZE);
  699. $len=strlen($buf);
  700. if(!xml_parse($this->parser,$buf,$len==0)) {
  701. $this->handler->protocol->handler->shutdownBrokenConnection(
  702. sprintf("protocol error: %s,%s at col %d. Check the back end log for OutOfMemoryErrors.",
  703. $buf,
  704. xml_error_string(xml_get_error_code($this->parser)),
  705. xml_get_current_column_number($this->parser)));
  706. }
  707. } while(!$this->event || $this->level>0);
  708. }
  709. function parserError() {
  710. $this->handler->protocol->handler->shutdownBrokenConnection(
  711. sprintf("protocol error: %s. Check the back end log for details.",$this->buf));
  712. }
  713. }
  714. class java_Parser {
  715. public $parser;
  716. function java_Parser($handler) {
  717. if(function_exists("xml_parser_create")) {
  718. $this->parser=new java_NativeParser($handler);
  719. $handler->RUNTIME["PARSER"]="NATIVE";
  720. } else {
  721. $this->parser=new java_SimpleParser($handler);
  722. $handler->RUNTIME["PARSER"]="SIMPLE";
  723. }
  724. }
  725. function parse() {
  726. $this->parser->parse();
  727. }
  728. function getData($str) {
  729. return $this->parser->getData($str);
  730. }
  731. function parserError() {
  732. $this->parser->parserError();
  733. }
  734. }
  735. function java_getHeader($name,$array) {
  736. if (array_key_exists($name,$array)) return $array[$name];
  737. $name="HTTP_$name";
  738. if (array_key_exists($name,$array)) return $array[$name];
  739. return null;
  740. }
  741. function java_checkCliSapi() {
  742. $sapi=substr(php_sapi_name(),0,3);
  743. return ((($sapi=='cgi') && !get_cfg_var("java.session")) || ($sapi=='cli'));
  744. }
  745. function java_getCompatibilityOption($client) {
  746. static $compatibility=null;
  747. if ($compatibility) return $compatibility;
  748. $compatibility=$client->RUNTIME["PARSER"]=="NATIVE"
  749. ? (0103-JAVA_PREFER_VALUES)
  750. : (0100+JAVA_PREFER_VALUES);
  751. if(is_int(JAVA_LOG_LEVEL)) {
  752. $compatibility |=128 | (7 & JAVA_LOG_LEVEL)<<2;
  753. }
  754. $compatibility=chr ($compatibility);
  755. return $compatibility;
  756. }
  757. class java_EmptyChannel {
  758. protected $handler;
  759. private $res;
  760. function java_EmptyChannel($handler) {
  761. $this->handler=$handler;
  762. }
  763. function shutdownBrokenConnection () {}
  764. function fwrite($data) {
  765. return $this->handler->fwrite($data);
  766. }
  767. function fread($size) {
  768. return $this->handler->fread($size);
  769. }
  770. function getKeepAliveA() {
  771. return "<F p=\"A\" />";
  772. }
  773. function getKeepAliveE() {
  774. return "<F p=\"E\" />";
  775. }
  776. function getKeepAlive() {
  777. return $this->getKeepAliveE();
  778. }
  779. function error() {
  780. trigger_error("An unchecked exception occured during script execution. Please check the server log files for details.",E_USER_ERROR);
  781. }
  782. function checkA($peer) {
  783. $val=$this->res[6];
  784. if ($val !='A') fclose($peer);
  785. if ($val !='A' && $val !='E') {
  786. $this->error();
  787. }
  788. }
  789. function checkE() {
  790. $val=$this->res[6];
  791. if ($val !='E') {
  792. $this->error();
  793. }
  794. }
  795. function keepAliveS() {
  796. $this->res=$this->fread(10);
  797. }
  798. function keepAliveSC() {
  799. $this->res=$this->fread(10);
  800. $this->fwrite("");
  801. $this->fread(JAVA_RECV_SIZE);
  802. }
  803. function keepAliveH() {
  804. $this->res=$this->handler->read(10);
  805. }
  806. function keepAlive() {
  807. $this->keepAliveH();
  808. $this->checkE();
  809. }
  810. }
  811. abstract class java_SocketChannel extends java_EmptyChannel {
  812. public $peer,$host;
  813. function java_SocketChannel($peer,$host) {
  814. $this->peer=$peer;
  815. $this->host=$host;
  816. }
  817. function fwrite($data) {
  818. return fwrite($this->peer,$data);
  819. }
  820. function fread($size) {
  821. return fread($this->peer,$size);
  822. }
  823. function shutdownBrokenConnection () {
  824. fclose($this->peer);
  825. }
  826. }
  827. class java_SocketChannelP extends java_SocketChannel {
  828. function getKeepAlive() {return $this->getKeepAliveA();}
  829. function keepAlive() { $this->keepAliveS(); $this->checkA($this->peer); }
  830. }
  831. class java_ChunkedSocketChannel extends java_SocketChannel {
  832. function fwrite($data) {
  833. $len=dechex(strlen($data));
  834. return fwrite($this->peer,"${len}\r\n${data}\r\n");
  835. }
  836. function fread($size) {
  837. $length=hexdec(fgets($this->peer,JAVA_RECV_SIZE));
  838. $data="";
  839. while ($length > 0) {
  840. $str=fread($this->peer,$length);
  841. if (feof ($this->peer)) return null;
  842. $length -=strlen($str);
  843. $data .=$str;
  844. }
  845. fgets($this->peer,3);
  846. return $data;
  847. }
  848. function keepAlive() { $this->keepAliveSC(); $this->checkE(); fclose ($this->peer); }
  849. }
  850. class java_SocketHandler {
  851. public $protocol,$channel;
  852. function java_SocketHandler($protocol,$channel) {
  853. $this->protocol=$protocol;
  854. $this->channel=$channel;
  855. }
  856. function write($data) {
  857. return $this->channel->fwrite($data);
  858. }
  859. function fwrite($data) {return $this->write($data);}
  860. function read($size) {
  861. return $this->channel->fread($size);
  862. }
  863. function fread($size) {return $this->read($size);}
  864. function redirect() {}
  865. function getKeepAlive() {
  866. return $this->channel->getKeepAlive();
  867. }
  868. function keepAlive() {
  869. $this->channel->keepAlive();
  870. }
  871. function dieWithBrokenConnection($msg) {
  872. unset($this->protocol->client->protocol);
  873. trigger_error ($msg?$msg:"unknown error: please see back end log for details",E_USER_ERROR);
  874. }
  875. function shutdownBrokenConnection ($msg) {
  876. $this->channel->shutdownBrokenConnection();
  877. $this->dieWithBrokenConnection($msg);
  878. }
  879. }
  880. class java_SimpleHttpHandler extends java_SocketHandler {
  881. public $headers,$cookies;
  882. public $context,$ssl,$port;
  883. public $host;
  884. function createChannel() {
  885. $channelName=java_getHeader("X_JAVABRIDGE_REDIRECT",$_SERVER);
  886. $context=java_getHeader("X_JAVABRIDGE_CONTEXT",$_SERVER);
  887. $len=strlen($context);
  888. $len0=java_getCompatibilityOption($this->protocol->client);
  889. $len1=chr($len&0xFF); $len>>=8;
  890. $len2=chr($len&0xFF);
  891. $this->channel=new java_EmptyChannel($this);
  892. $this->channel=$this->getChannel($channelName);
  893. $this->protocol->socketHandler=new java_SocketHandler($this->protocol,$this->channel);
  894. $this->protocol->write("\177${len0}${len1}${len2}${context}");
  895. $this->context=sprintf("X_JAVABRIDGE_CONTEXT: %s\r\n",$context);
  896. $this->protocol->handler=$this->protocol->socketHandler;
  897. $this->protocol->handler->write($this->protocol->client->sendBuffer)
  898. or $this->protocol->handler->shutdownBrokenConnection("Broken local connection handle");
  899. $this->protocol->client->sendBuffer=null;
  900. $this->protocol->handler->read(1)
  901. or $this->protocol->handler->shutdownBrokenConnection("Broken local connection handle");
  902. }
  903. function java_SimpleHttpHandler($protocol,$ssl,$host,$port) {
  904. $this->cookies=array();
  905. $this->protocol=$protocol;
  906. $this->ssl=$ssl;
  907. $this->host=$host;
  908. $this->port=$port;
  909. $this->createChannel();
  910. }
  911. function getCookies() {
  912. $str="";
  913. $first=true;
  914. foreach($_COOKIE as $k=> $v) {
  915. $str .=($first ? "Cookie: $k=$v":"; $k=$v");
  916. $first=false;
  917. }
  918. if(!$first) $str .="\r\n";
  919. return $str;
  920. }
  921. function getContextFromCgiEnvironment() {
  922. $ctx=java_getHeader('X_JAVABRIDGE_CONTEXT',$_SERVER);
  923. return $ctx;
  924. }
  925. function getContext() {
  926. static $context=null;
  927. if($context) return $context;
  928. $ctx=$this->getContextFromCgiEnvironment();
  929. $context="";
  930. if($ctx) {
  931. $context=sprintf("X_JAVABRIDGE_CONTEXT: %s\r\n",$ctx);
  932. }
  933. return $context;
  934. }
  935. function getWebAppInternal() {
  936. $context=$this->protocol->webContext;
  937. if(isset($context)) return $context;
  938. return (JAVA_SERVLET=="User" &&
  939. array_key_exists('PHP_SELF',$_SERVER) &&
  940. array_key_exists('HTTP_HOST',$_SERVER))
  941. ? $_SERVER['PHP_SELF']."javabridge"
  942. : null;
  943. }
  944. function getWebApp() {
  945. $context=$this->getWebAppInternal();
  946. if(is_null($context)) $context=JAVA_SERVLET;
  947. if(is_null($context) || $context[0]!="/")
  948. $context="/JavaBridge/JavaBridge.phpjavabridge";
  949. return $context;
  950. }
  951. function write($data) {
  952. return $this->protocol->socketHandler->write($data);
  953. }
  954. function doSetCookie($key,$val,$path) {
  955. $path=trim($path);
  956. $webapp=$this->getWebAppInternal(); if(!$webapp) $path="/";
  957. setcookie($key,$val,0,$path);
  958. }
  959. function read($size) {
  960. return $this->protocol->socketHandler->read($size);
  961. }
  962. function getChannel($channelName) {
  963. $errstr=null; $errno=null;
  964. $peer=pfsockopen($this->host,$channelName,$errno,$errstr,20);
  965. if (!$peer) throw new java_IllegalStateException("No ContextServer for {$this->host}:{$channelName}. Error: $errstr ($errno)\n");
  966. stream_set_timeout($peer,-1);
  967. return new java_SocketChannelP($peer,$this->host);
  968. }
  969. function keepAlive() {
  970. parent::keepAlive();
  971. }
  972. function redirect() {}
  973. }
  974. class java_SimpleHttpTunnelHandler extends java_SimpleHttpHandler {
  975. public $socket;
  976. protected $hasContentLength=false;
  977. function createSimpleChannel () {
  978. $this->channel=new java_EmptyChannel($this);
  979. }
  980. function createChannel() {
  981. $this->createSimpleChannel();
  982. }
  983. function shutdownBrokenConnection ($msg) {
  984. fclose($this->socket);
  985. $this->dieWithBrokenConnection($msg);
  986. }
  987. function checkSocket($socket,&$errno,&$errstr) {
  988. if (!$socket) {
  989. $msg="Could not connect to the JEE server {$this->ssl}{$this->host}:{$this->port}. Please start it.";
  990. $msg.=java_checkCliSapi()
  991. ?" Or define('JAVA_HOSTS',9267); define('JAVA_SERVLET',false); before including 'Java.inc' and try again. Error message: $errstr ($errno)\n"
  992. :" Error message: $errstr ($errno)\n";
  993. throw new java_ConnectException($msg);
  994. }
  995. }
  996. function open() {
  997. $errno=null; $errstr=null;
  998. $socket=fsockopen("{$this->ssl}{$this->host}",$this->port,$errno,$errstr,20);
  999. $this->checkSocket($socket,$errno,$errstr);
  1000. stream_set_timeout($socket,-1);
  1001. $this->socket=$socket;
  1002. }
  1003. function fread($size) {
  1004. $length=hexdec(fgets($this->socket,JAVA_RECV_SIZE));
  1005. $data="";
  1006. while ($length > 0) {
  1007. $str=fread($this->socket,$length);
  1008. if (feof ($this->socket)) return null;
  1009. $length -=strlen($str);
  1010. $data .=$str;
  1011. }
  1012. fgets($this->socket,3);
  1013. return $data;
  1014. }
  1015. function fwrite($data) {
  1016. $len=dechex(strlen($data));
  1017. return fwrite($this->socket,"${len}\r\n${data}\r\n");
  1018. }
  1019. function close() {
  1020. fwrite($this->socket,"0\r\n\r\n");
  1021. fgets($this->socket,JAVA_RECV_SIZE);
  1022. fgets($this->socket,3);
  1023. fclose($this->socket);
  1024. }
  1025. function java_SimpleHttpTunnelHandler($protocol,$ssl,$host,$port) {
  1026. parent::java_SimpleHttpHandler($protocol,$ssl,$host,$port);
  1027. $this->open();
  1028. }
  1029. function read($size) {
  1030. if(is_null($this->headers)) $this->parseHeaders();
  1031. if (isset($this->headers["http_error"])) {
  1032. if (isset($this->headers["transfer_chunked"])) {
  1033. $str=$this->fread(JAVA_RECV_SIZE);
  1034. } elseif (isset($this->headers['content_length'])) {
  1035. $len=$this->headers['content_length'];
  1036. for($str=fread($this->socket,$len); strlen($str)<$len; $str.=fread($this->socket,$len-strlen($str)))
  1037. if (feof ($this->socket)) break;
  1038. } else {
  1039. $str=fread($this->socket,JAVA_RECV_SIZE);
  1040. }
  1041. $this->shutdownBrokenConnection($str);
  1042. }
  1043. return $this->fread(JAVA_RECV_SIZE);
  1044. }
  1045. function getBodyFor ($compat,$data) {
  1046. $len=dechex(2+strlen($data));
  1047. 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";
  1048. }
  1049. function write($data) {
  1050. $compat=java_getCompatibilityOption($this->protocol->client);
  1051. $this->headers=null;
  1052. $socket=$this->socket;
  1053. $webapp=$this->getWebApp();
  1054. $cookies=$this->getCookies();
  1055. $context=$this->getContext();
  1056. $res="PUT ";
  1057. $res .=$webapp;
  1058. $res .=" HTTP/1.1\r\n";
  1059. $res .="Host: {$this->host}:{$this->port}\r\n";
  1060. $res .=$context;
  1061. $res .=$cookies;
  1062. $res .=$this->getBodyFor($compat,$data);
  1063. $count=fwrite($socket,$res) or $this->shutdownBrokenConnection("Broken connection handle");
  1064. fflush($socket) or $this->shutdownBrokenConnection("Broken connection handle");
  1065. return $count;
  1066. }
  1067. function parseHeaders() {
  1068. $this->headers=array();
  1069. $line=trim(fgets($this->socket,JAVA_RECV_SIZE));
  1070. $ar=explode (" ",$line);
  1071. $code=((int)$ar[1]);
  1072. if ($code !=200) $this->headers["http_error"]=$code;
  1073. while (($str=trim(fgets($this->socket,JAVA_RECV_SIZE)))) {
  1074. if($str[0]=='X') {
  1075. if(!strncasecmp("X_JAVABRIDGE_REDIRECT",$str,21)) {
  1076. $this->headers["redirect"]=trim(substr($str,22));
  1077. } else if(!strncasecmp("X_JAVABRIDGE_CONTEXT",$str,20)) {
  1078. $this->headers["context"]=trim(substr($str,21));
  1079. }
  1080. } else if($str[0]=='S') {
  1081. if(!strncasecmp("SET-COOKIE",$str,10)) {
  1082. $str=substr($str,12);
  1083. $this->cookies[]=$str;
  1084. $ar=explode(";",$str);
  1085. $cookie=explode("=",$ar[0]);
  1086. $path="";
  1087. if(isset($ar[1])) $p=explode("=",$ar[1]);
  1088. if(isset($p)) $path=$p[1];
  1089. $this->doSetCookie($cookie[0],$cookie[1],$path);
  1090. }
  1091. } else if($str[0]=='C') {
  1092. if(!strncasecmp("CONTENT-LENGTH",$str,14)) {
  1093. $this->headers["content_length"]=trim(substr($str,15));
  1094. $this->hasContentLength=true;
  1095. } else if(!strncasecmp("CONNECTION",$str,10) && !strncasecmp("close",trim(substr($str,11)),5)) {
  1096. $this->headers["connection_close"]=true;
  1097. }
  1098. } else if($str[0]=='T') {
  1099. if(!strncasecmp("TRANSFER-ENCODING",$str,17) && !strncasecmp("chunked",trim(substr($str,18)),7)) {
  1100. $this->headers["transfer_chunked"]=true;
  1101. }
  1102. }
  1103. }
  1104. }
  1105. function getSimpleChannel() {
  1106. return new java_ChunkedSocketChannel($this->socket,$this->protocol,$this->host);
  1107. }
  1108. function redirect() {
  1109. $this->isRedirect=isset($this->headers["redirect"]);
  1110. if ($this->isRedirect)
  1111. $channelName=$this->headers["redirect"];
  1112. $context=$this->headers["context"];
  1113. $len=strlen($context);
  1114. $len0=chr(0xFF);
  1115. $len1=chr($len&0xFF); $len>>=8;
  1116. $len2=chr($len&0xFF);
  1117. if ($this->isRedirect) {
  1118. $this->protocol->socketHandler=new java_SocketHandler($this->protocol,$this->getChannel($channelName));
  1119. $this->protocol->write("\177${len0}${len1}${len2}${context}");
  1120. $this->context=sprintf("X_JAVABRIDGE_CONTEXT: %s\r\n",$context);
  1121. $this->close ();
  1122. $this->protocol->handler=$this->protocol->socketHandler;
  1123. $this->protocol->handler->write($this->protocol->client->sendBuffer)
  1124. or $this->protocol->handler->shutdownBrokenConnection("Broken local connection handle");
  1125. $this->protocol->client->sendBuffer=null;
  1126. $this->protocol->handler->read(1)
  1127. or $this->protocol->handler->shutdownBrokenConnection("Broken local connection handle");
  1128. } else {
  1129. $this->protocol->handler=$this->protocol->socketHandler=new java_SocketHandler($this->protocol,$this->getSimpleChannel());
  1130. }
  1131. }
  1132. }
  1133. class java_HttpTunnelHandler extends java_SimpleHttpTunnelHandler {
  1134. function fread($size) {
  1135. if ($this->hasContentLength)
  1136. return fread($this->socket,$this->headers["content_length"]);
  1137. else
  1138. return parent::fread($size);
  1139. }
  1140. function fwrite($data) {
  1141. if ($this->hasContentLength)
  1142. return fwrite($this->socket,$data);
  1143. else
  1144. return parent::fwrite($data);
  1145. }
  1146. function close() {
  1147. if ($this->hasContentLength) {
  1148. fwrite($this->socket,"0\r\n\r\n");
  1149. fclose($this->socket);
  1150. } else {
  1151. parent::fclose($this->socket);
  1152. }
  1153. }
  1154. }
  1155. class java_Protocol {
  1156. public $client;
  1157. public $webContext;
  1158. public $serverName;
  1159. function getOverrideHosts() {
  1160. if(array_key_exists('X_JAVABRIDGE_OVERRIDE_HOSTS',$_ENV)) {
  1161. $override=$_ENV['X_JAVABRIDGE_OVERRIDE_HOSTS'];
  1162. if(!is_null($override) && $override!='/') return $override;
  1163. }
  1164. return
  1165. java_getHeader('X_JAVABRIDGE_OVERRIDE_HOSTS_REDIRECT',$_SERVER);
  1166. }
  1167. static function getHost() {
  1168. static $host=null;
  1169. if(is_null($host)) {
  1170. $hosts=explode(";",JAVA_HOSTS);
  1171. $host=explode(":",$hosts[0]);
  1172. while(count ($host) < 3) array_unshift($host,"");
  1173. if (substr($host[1],0,2)=="//") $host[1]=substr($host[1],2);
  1174. }
  1175. return $host;
  1176. }
  1177. function createHttpHandler() {
  1178. $overrideHosts=$this->getOverrideHosts();
  1179. $ssl="";
  1180. if($overrideHosts) {
  1181. $s=$overrideHosts;
  1182. if((strlen($s)>2) && ($s[1]==':')) {
  1183. if($s[0]=='s')
  1184. $ssl="ssl://";
  1185. $s=substr($s,2);
  1186. }
  1187. $webCtx=strpos($s,"//");
  1188. if($webCtx)
  1189. $host=substr($s,0,$webCtx);
  1190. else
  1191. $host=$s;
  1192. $idx=strpos($host,':');
  1193. if($idx) {
  1194. if($webCtx)
  1195. $port=substr($host,$idx+1,$webCtx);
  1196. else
  1197. $port=substr($host,$idx+1);
  1198. $host=substr($host,0,$idx);
  1199. } else {
  1200. $port="8080";
  1201. }
  1202. if($webCtx) $webCtx=substr($s,$webCtx+1);
  1203. $this->webContext=$webCtx;
  1204. } else {
  1205. $hostVec=java_Protocol::getHost();
  1206. if ($ssl=$hostVec[0]) $ssl .="://";
  1207. $host=$hostVec[1];
  1208. $port=$hostVec[2];
  1209. }
  1210. $this->serverName="${ssl}${host}:$port";
  1211. if ((array_key_exists("X_JAVABRIDGE_REDIRECT",$_SERVER)) ||
  1212. (array_key_exists("HTTP_X_JAVABRIDGE_REDIRECT",$_SERVER)))
  1213. return new java_SimpleHttpHandler($this,$ssl,$host,$port);
  1214. return new java_HttpTunnelHandler($this,$ssl,$host,$port);
  1215. }
  1216. function createSimpleHandler($name,$again=true) {
  1217. $channelName=$name;
  1218. $errno=null; $errstr=null;
  1219. if(is_numeric($channelName)) {
  1220. $peer=@pfsockopen($host="127.0.0.1",$channelName,$errno,$errstr,5);
  1221. } else {
  1222. $type=$channelName[0];
  1223. list($host,$channelName)=explode(":",$channelName);
  1224. $peer=pfsockopen($host,$channelName,$errno,$errstr,20);
  1225. if (!$peer)
  1226. throw new java_ConnectException("No Java server at $host:$channelName. Error message: $errstr ($errno)");
  1227. }
  1228. if (!$peer) {
  1229. $java=file_exists(ini_get("extension_dir")."/JavaBridge.jar")?ini_get("extension_dir")."/JavaBridge.jar":(java_get_base()."/JavaBridge.jar");
  1230. if (!file_exists($java))
  1231. 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.");
  1232. $java_cmd="java -Dphp.java.bridge.daemon=true -jar \"${java}\" INET_LOCAL:$channelName 0";
  1233. if (!$again)
  1234. throw new java_ConnectException("No Java back end! Please run it with: $java_cmd. Error message: $errstr ($errno)");
  1235. if (!java_checkCliSapi())
  1236. 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);
  1237. system ($java_cmd);
  1238. return $this->createSimpleHandler($name,false);
  1239. }
  1240. stream_set_timeout($peer,-1);
  1241. $handler=new java_SocketHandler($this,new java_SocketChannelP($peer,$host));
  1242. $compatibility=java_getCompatibilityOption($this->client);
  1243. $this->write("\177$compatibility");
  1244. $this->serverName="127.0.0.1:$channelName";
  1245. return $handler;
  1246. }
  1247. function java_get_simple_channel() {
  1248. return (JAVA_HOSTS&&(!JAVA_SERVLET||(JAVA_SERVLET=="Off"))) ? JAVA_HOSTS : null;
  1249. }
  1250. function createHandler() {
  1251. if(!java_getHeader('X_JAVABRIDGE_OVERRIDE_HOSTS',$_SERVER)&&
  1252. ((function_exists("java_get_default_channel")&&($defaultChannel=java_get_default_channel())) ||
  1253. ($defaultChannel=$this->java_get_simple_channel())) ) {
  1254. return $this->createSimpleHandler($defaultChannel);
  1255. } else {
  1256. return $this->createHttpHandler();
  1257. }
  1258. }
  1259. function java_Protocol ($client) {
  1260. $this->client=$client;
  1261. $this->handler=$this->createHandler();
  1262. }
  1263. function redirect() {
  1264. $this->handler->redirect();
  1265. }
  1266. function read($size) {
  1267. return $this->handler->read($size);
  1268. }
  1269. function sendData() {
  1270. $this->handler->write($this->client->sendBuffer);
  1271. $this->client->sendBuffer=null;
  1272. }
  1273. function flush() {
  1274. $this->sendData();
  1275. }
  1276. function getKeepAlive() {
  1277. return $this->handler->getKeepAlive();
  1278. }
  1279. function keepAlive() {
  1280. $this->handler->keepAlive();
  1281. }
  1282. function handle() {
  1283. $this->client->handleRequests();
  1284. }
  1285. function write($data) {
  1286. $this->client->sendBuffer.=$data;
  1287. }
  1288. function finish() {
  1289. $this->flush();
  1290. $this->handle();
  1291. $this->redirect();
  1292. }
  1293. function referenceBegin($name) {
  1294. $this->client->sendBuffer.=$this->client->preparedToSendBuffer;
  1295. $this->client->preparedToSendBuffer=null;
  1296. $signature=sprintf("<H p=\"1\" v=\"%s\">",$name);
  1297. $this->write($signature);
  1298. $signature[6]="2";
  1299. $this->client->currentArgumentsFormat=$signature;
  1300. }
  1301. function referenceEnd() {
  1302. $this->client->currentArgumentsFormat.=$format="</H>";
  1303. $this->write($format);
  1304. $this->finish();
  1305. $this->client->currentCacheKey=null;
  1306. }
  1307. function createObjectBegin($name) {
  1308. $this->client->sendBuffer.=$this->client->preparedToSendBuffer;
  1309. $this->client->preparedToSendBuffer=null;
  1310. $signature=sprintf("<K p=\"1\" v=\"%s\">",$name);
  1311. $this->write($signature);
  1312. $signature[6]="2";
  1313. $this->client->currentArgumentsFormat=$signature;
  1314. }
  1315. function createObjectEnd() {
  1316. $this->client->currentArgumentsFormat.=$format="</K>";
  1317. $this->write($format);
  1318. $this->finish();
  1319. $this->client->currentCacheKey=null;
  1320. }
  1321. function propertyAccessBegin($object,$method) {
  1322. $this->client->sendBuffer.=$this->client->preparedToSendBuffer;
  1323. $this->client->preparedToSendBuffer=null;
  1324. $this->write(sprintf("<G p=\"1\" v=\"%x\" m=\"%s\">",$object,$method));
  1325. $this->client->currentArgumentsFormat="<G p=\"2\" v=\"%x\" m=\"${method}\">";
  1326. }
  1327. function propertyAccessEnd() {
  1328. $this->client->currentArgumentsFormat.=$format="</G>";
  1329. $this->write($format);
  1330. $this->finish();
  1331. $this->client->currentCacheKey=null;
  1332. }
  1333. function invokeBegin($object,$method) {
  1334. $this->client->sendBuffer.=$this->client->preparedToSendBuffer;
  1335. $this->client->preparedToSendBuffer=null;
  1336. $this->write(sprintf("<Y p=\"1\" v=\"%x\" m=\"%s\">",$object,$method));
  1337. $this->client->currentArgumentsFormat="<Y p=\"2\" v=\"%x\" m=\"${method}\">";
  1338. }
  1339. function invokeEnd() {
  1340. $this->client->currentArgumentsFormat.=$format="</Y>";
  1341. $this->write($format);
  1342. $this->finish();
  1343. $this->client->currentCacheKey=null;
  1344. }
  1345. function resultBegin() {
  1346. $this->client->sendBuffer.=$this->client->preparedToSendBuffer;
  1347. $this->client->preparedToSendBuffer=null;
  1348. $this->write("<R>");
  1349. }
  1350. function resultEnd() {
  1351. $this->client->currentCacheKey=null;
  1352. $this->write("</R>");
  1353. $this->flush();
  1354. }
  1355. function writeString($name) {
  1356. $this->client->currentArgumentsFormat.=$format="<S v=\"%s\"/>";
  1357. $this->write(sprintf($format,htmlspecialchars($name,ENT_COMPAT)));
  1358. }
  1359. function writeBoolean($boolean) {
  1360. $this->client->currentArgumentsFormat.=$format="<T v=\"%s\"/>";
  1361. $this->write(sprintf($format,$boolean));
  1362. }
  1363. function writeLong($l) {
  1364. $this->client->currentArgumentsFormat.="<J v=\"%d\"/>";
  1365. if($l<0) {
  1366. $this->write(sprintf("<L v=\"%x\" p=\"A\"/>",-$l));
  1367. } else {
  1368. $this->write(sprintf("<L v=\"%x\" p=\"O\"/>",$l));
  1369. }
  1370. }
  1371. function writeULong($l) {
  1372. $this->client->currentArgumentsFormat.=$format="<L v=\"%x\" p=\"O\"/>";
  1373. $this->write(sprintf($format,$l));
  1374. }
  1375. function writeDouble($d) {
  1376. $this->client->currentArgumentsFormat.=$format="<D v=\"%.14e\"/>";
  1377. $this->write(sprintf($format,$d));
  1378. }
  1379. function writeObject($object) {
  1380. $this->client->currentArgumentsFormat.=$format="<O v=\"%x\"/>";
  1381. $this->write(sprintf($format,$object));
  1382. }
  1383. function writeException($object,$str) {
  1384. $this->write(sprintf("<E v=\"%x\" m=\"%s\"/>",$object,htmlspecialchars($str,ENT_COMPAT)));
  1385. }
  1386. function writeCompositeBegin_a() {
  1387. $this->write("<X t=\"A\">");
  1388. }
  1389. function writeCompositeBegin_h() {
  1390. $this->write("<X t=\"H\">");
  1391. }
  1392. function writeCompositeEnd() {
  1393. $this->write("</X>");
  1394. }
  1395. function writePairBegin_s($key) {
  1396. $this->write(sprintf("<P t=\"S\" v=\"%s\">",htmlspecialchars($key,ENT_COMPAT)));
  1397. }
  1398. function writePairBegin_n($key) {
  1399. $this->write(sprintf("<P t=\"N\" v=\"%x\">",$key));
  1400. }
  1401. function writePairBegin() {
  1402. $this->write("<P>");
  1403. }
  1404. function writePairEnd() {
  1405. $this->write("</P>");
  1406. }
  1407. function writeUnref($object) {
  1408. $this->client->sendBuffer.=$this->client->preparedToSendBuffer;
  1409. $this->client->preparedToSendBuffer=null;
  1410. $this->write(sprintf("<U v=\"%x\"/>",$object));
  1411. }
  1412. function getServerName() {
  1413. return $this->serverName;
  1414. }
  1415. }
  1416. class java_ParserString {
  1417. public $string,$off,$length;
  1418. function toString() {
  1419. return $this->getString();
  1420. }
  1421. function getString() {
  1422. return substr($this->string,$this->off,$this->length);
  1423. }
  1424. }
  1425. class java_ParserTag {
  1426. public $n,$strings;
  1427. function java_ParserTag() {
  1428. $this->strings=array();
  1429. $this->n=0;
  1430. }
  1431. }
  1432. class java_SimpleParser {
  1433. public $SLEN=256;
  1434. public $handler;
  1435. public $tag,$buf,$len,$s;
  1436. public $type;
  1437. function java_SimpleParser($handler) {
  1438. $this->handler=$handler;
  1439. $this->tag=array(new java_ParserTag(),new java_ParserTag(),new java_ParserTag());
  1440. $this->len=$this->SLEN;
  1441. $this->s=str_repeat(" ",$this->SLEN);
  1442. $this->type=$this->VOJD;
  1443. }
  1444. public $BEGIN=0,$KEY=1,$VAL=2,$ENTITY=3,$VOJD=5,$END=6;
  1445. public $level=0,$eor=0; public $in_dquote,$eot=false;
  1446. public $pos=0,$c=0,$i=0,$i0=0,$e;
  1447. function RESET() {
  1448. $this->type=$this->VOJD;
  1449. $this->level=0;
  1450. $this->eor=0;
  1451. $this->in_dquote=false;
  1452. $this->i=0;
  1453. $this->i0=0;
  1454. }
  1455. function APPEND($c) {
  1456. if($this->i>=$this->len-1) {
  1457. $this->s=str_repeat($this->s,2);
  1458. $this->len*=2;
  1459. }
  1460. $this->s[$this->i++]=$c;
  1461. }
  1462. function CALL_BEGIN() {
  1463. $pt=&$this->tag[1]->strings;
  1464. $st=&$this->tag[2]->strings;
  1465. $t=&$this->tag[0]->strings[0];
  1466. $name=$t->string[$t->off];
  1467. $n=$this->tag[2]->n;
  1468. $ar=array();
  1469. for($i=0; $i<$n; $i++) {
  1470. $ar[$pt[$i]->getString()]=$st[$i]->getString();
  1471. }
  1472. $this->handler->begin($name,$ar);
  1473. }
  1474. function CALL_END() {
  1475. $t=&$this->tag[0]->strings[0];
  1476. $name=$t->string[$t->off];
  1477. $this->handler->end($name);
  1478. }
  1479. function PUSH($t) {
  1480. $str=&$this->tag[$t]->strings;
  1481. $n=&$this->tag[$t]->n;
  1482. $this->s[$this->i]='|';
  1483. if(!isset($str[$n])){$h=$this->handler; $str[$n]=$h->createParserString();}
  1484. $str[$n]->string=&$this->s;
  1485. $str[$n]->off=$this->i0;
  1486. $str[$n]->length=$this->i-$this->i0;
  1487. ++$this->tag[$t]->n;
  1488. $this->APPEND('|');
  1489. $this->i0=$this->i;
  1490. }
  1491. function parse() {
  1492. while($this->eor==0) {
  1493. if($this->c>=$this->pos) {
  1494. $this->buf=$this->handler->read(JAVA_RECV_SIZE);
  1495. if(is_null($this->buf) || strlen($this->buf)==0)
  1496. $this->handler->protocol->handler->shutdownBrokenConnection("protocol error. Check the back end log for OutOfMemoryErrors.");
  1497. $this->pos=strlen($this->buf);
  1498. if($this->pos==0) break;
  1499. $this->c=0;
  1500. }
  1501. switch(($ch=$this->buf[$this->c]))
  1502. {
  1503. case '<': if($this->in_dquote) {$this->APPEND($ch); break;}
  1504. $this->level+=1;
  1505. $this->type=$this->BEGIN;
  1506. break;
  1507. case '\t': case '\f': case '\n': case '\r': case ' ': if($this->in_dquote) {$this->APPEND($ch); break;}
  1508. if($this->type==$this->BEGIN) {
  1509. $this->PUSH($this->type);
  1510. $this->type=$this->KEY;
  1511. }
  1512. break;
  1513. case '=': if($this->in_dquote) {$this->APPEND($ch); break;}
  1514. $this->PUSH($this->type);
  1515. $this->type=$this->VAL;
  1516. break;
  1517. case '/': if($this->in_dquote) {$this->APPEND($ch); break;}
  1518. if($this->type==$this->BEGIN) { $this->type=$this->END; $this->level-=1; }
  1519. $this->level-=1;
  1520. $this->eot=true;
  1521. break;
  1522. case '>': if($this->in_dquote) {$this->APPEND($ch); break;}
  1523. if($this->type==$this->END){
  1524. $this->PUSH($this->BEGIN);
  1525. $this->CALL_END();
  1526. } else {
  1527. if($this->type==$this->VAL) $this->PUSH($this->type);
  1528. $this->CALL_BEGIN();
  1529. }
  1530. $this->tag[0]->n=$this->tag[1]->n=$this->tag[2]->n=0; $this->i0=$this->i=0;
  1531. $this->type=$this->VOJD;
  1532. if($this->level==0) $this->eor=1;
  1533. break;
  1534. case ';':
  1535. if($this->type==$this->ENTITY) {
  1536. switch ($this->s[$this->e+1]) {
  1537. case 'l': $this->s[$this->e]='<'; $this->i=$this->e+1; break;
  1538. case 'g': $this->s[$this->e]='>'; $this->i=$this->e+1; break;
  1539. case 'a': $this->s[$this->e]=($this->s[$this->e+2]=='m'?'&':'\''); $this->i=$this->e+1; break;
  1540. case 'q': $this->s[$this->e]='"'; $this->i=$this->e+1; break;
  1541. default: $this->APPEND($ch);
  1542. }
  1543. $this->type=$this->VAL;
  1544. } else {
  1545. $this->APPEND($ch);
  1546. }
  1547. break;
  1548. case '&':
  1549. $this->type=$this->ENTITY;
  1550. $this->e=$this->i;
  1551. $this->APPEND($ch);
  1552. break;
  1553. case '"':
  1554. $this->in_dquote=!$this->in_dquote;
  1555. if(!$this->in_dquote && $this->type==$this->VAL) {
  1556. $this->PUSH($this->type);
  1557. $this->type=$this->KEY;
  1558. }
  1559. break;
  1560. default:
  1561. $this->APPEND($ch);
  1562. }
  1563. $this->c+=1;
  1564. }
  1565. $this->RESET();
  1566. }
  1567. function getData($str) {
  1568. return $str;
  1569. }
  1570. function parserError() {
  1571. $this->handler->protocol->handler->shutdownBrokenConnection(
  1572. sprintf("protocol error: %s. Check the back end log for details.",$this->s));
  1573. }
  1574. }
  1575. interface java_JavaType {};
  1576. $java_initialized=false;
  1577. function __javaproxy_Client_getClient() {
  1578. static $client=null;
  1579. if(!is_null($client)) return $client;
  1580. if (function_exists("java_create_client")) $client=java_create_client();
  1581. else {
  1582. global $java_initialized;
  1583. $client=new java_Client();
  1584. $java_initialized=true;
  1585. }
  1586. return $client;
  1587. }
  1588. function java_last_exception_get() {
  1589. $client=__javaproxy_Client_getClient();
  1590. return $client->invokeMethod(0,"getLastException",array());
  1591. }
  1592. function java_last_exception_clear() {
  1593. $client=__javaproxy_Client_getClient();
  1594. $client->invokeMethod(0,"clearLastException",array());
  1595. }
  1596. function java_values_internal($object) {
  1597. if(!$object instanceof java_JavaType) return $object;
  1598. $client=__javaproxy_Client_getClient();
  1599. return $client->invokeMethod(0,"getValues",array($object));
  1600. }
  1601. function java_invoke($object,$method,$args) {
  1602. $client=__javaproxy_Client_getClient();
  1603. $id=($object==null) ? 0 : $object->__java;
  1604. return $client->invokeMethod($id,$method,$args);
  1605. }
  1606. function java_unwrap ($object) {
  1607. if(!$object instanceof java_JavaType) throw new java_IllegalArgumentException($object);
  1608. $client=__javaproxy_Client_getClient();
  1609. return $client->globalRef->get($client->invokeMethod(0,"unwrapClosure",array($object)));
  1610. }
  1611. function java_values($object) {
  1612. return java_values_internal($object);
  1613. }
  1614. function java_inspect_internal($object) {
  1615. if(!$object instanceof java_JavaType) throw new java_IllegalArgumentException($object);
  1616. $client=__javaproxy_Client_getClient();
  1617. return $client->invokeMethod(0,"inspect",array($object));
  1618. }
  1619. function java_inspect($object) {
  1620. return java_inspect_internal($object);
  1621. }
  1622. function java_set_file_encoding($enc) {
  1623. $client=__javaproxy_Client_getClient();
  1624. return $client->invokeMethod(0,"setFileEncoding",array($enc));
  1625. }
  1626. function java_instanceof_internal($ob,$clazz) {
  1627. if(!$ob instanceof java_JavaType) throw new java_IllegalArgumentException($ob);
  1628. if(!$clazz instanceof java_JavaType) throw new java_IllegalArgumentException($clazz);
  1629. $client=__javaproxy_Client_getClient();
  1630. return $client->invokeMethod(0,"instanceOf",array($ob,$clazz));
  1631. }
  1632. function java_instanceof($ob,$clazz) {
  1633. return java_instanceof_internal($ob,$clazz);
  1634. }
  1635. function java_cast_internal($object,$type) {
  1636. if(!$object instanceof java_JavaType) {
  1637. switch($type[0]) {
  1638. case 'S': case 's':
  1639. return (string)$object;
  1640. case 'B': case 'b':
  1641. return (boolean)$object;
  1642. case 'L': case 'I': case 'l': case 'i':
  1643. return (integer)$object;
  1644. case 'D': case 'd': case 'F': case 'f':
  1645. return (float) $object;
  1646. case 'N': case 'n':
  1647. return null;
  1648. case 'A': case 'a':
  1649. return (array)$object;
  1650. case 'O': case 'o':
  1651. return (object)$object;
  1652. }
  1653. }
  1654. return $object->__cast($type);
  1655. }
  1656. function java_cast($object,$type) {
  1657. return java_cast_internal($object,$type);
  1658. }
  1659. function java_require($arg) {
  1660. 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);
  1661. }
  1662. function java_get_lifetime ()
  1663. {
  1664. $session_max_lifetime=ini_get("session.gc_maxlifetime");
  1665. return $session_max_lifetime ? (int)$session_max_lifetime : 1440;
  1666. }
  1667. function java_session_array($args) {
  1668. $client=__javaproxy_Client_getClient();
  1669. if(!isset($args[0])) $args[0]=null;
  1670. if(!isset($args[1])) $args[1]=false;
  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(

Large files files are truncated, but you can click here to view the full file