forked from micw/php-java-bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaBridge.java
More file actions
1957 lines (1852 loc) · 69.6 KB
/
Copy pathJavaBridge.java
File metadata and controls
1957 lines (1852 loc) · 69.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-*- mode: Java; tab-width:8 -*-*/
package php.java.bridge;
/*
* Copyright (C) 2003-2007 Jost Boekemeier and others.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* This is the main interface of the PHP/Java Bridge. It
* contains utility methods which can be used by clients.
* @author Sam Ruby (methods coerce and select)
* @author Kai Londenberg
* @author Jost Boekemeier
* @see php.java.bridge.Standalone
* @see php.java.servlet.PhpJavaServlet
*/
public class JavaBridge implements Runnable {
/**
* For PHP4's last_exception_get.
*/
public Throwable lastException = null;
protected Throwable lastAsyncException; // reported by end_document()
// array of objects in use in the current script
GlobalRef globalRef=new GlobalRef();
static HashMap sessionHash = new HashMap();
/**
* For internal use only. The input stream for the current channel.
*/
public InputStream in;
/**
* For internal use only. The output stream for the current channel.
*/
public OutputStream out;
/**
* For internal use only. The request log level.
*/
public int logLevel = Util.logLevel;
/**
* Return the log level:
* <br>
* 0: log off <br>
* 1: log fatal <br>
* 2: log messages/exceptions <br>
* 3: log verbose <br>
* 4: log debug <br>
* 5: log method invocations
* @return The request log level.
*/
public int getLogLevel() {
return logLevel;
}
/**
* Handle requests from the InputStream, write the responses to OutputStream
* @param in the InputStream
* @param out the OutputStream
* @param logger the default logger can be obtained via <code>getServletContext().getAttribute(ContextLoaderListener.LOGGER)</code>
* @throws IOException
* @deprecated
* Example:
* <blockquote>
* <code>
* protected void doPut (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { <br>
* IContextFactory ctx = new RemoteHttpServletContextFactory(this, getServletContext(), req, req, resr);<br>
* res.setHeader("X_JAVABRIDGE_CONTEXT", ctx.getId());<br>
* res.setHeader("Pragma", "no-cache");<br>
* res.setHeader("Cache-Control", "no-cache");<br>
* try { ctx.getBridge().handleRequests(req.getInputStream(), res.getOutputStream(), myLogge); } finally { ctx.destroy(); }<br>
* }
* </code>
* </blockquote>
*/
public void handleRequests (InputStream in, OutputStream out, ILogger logger) throws IOException {
handleRequests(in, out);
}
/**
* Handle requests from the InputStream, write the responses to OutputStream
* @param in the InputStream
* @param out the OutputStream
* @throws IOException
* Example:
* <blockquote>
* <code>
* protected void doPut (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { <br>
* IContextFactory ctx = new RemoteHttpServletContextFactory(this, getServletContext(), req, req, resr);<br>
* res.setHeader("X_JAVABRIDGE_CONTEXT", ctx.getId());<br>
* res.setHeader("Pragma", "no-cache");<br>
* res.setHeader("Cache-Control", "no-cache");<br>
* try { ctx.getBridge().handleRequests(req.getInputStream(), res.getOutputStream(), myLogge); } finally { ctx.destroy(); }<br>
* }
* </code>
* </blockquote>
*/
public void handleRequests (InputStream in, OutputStream out) throws IOException {
this.request = new Request(this);
this.in = in;
this.out = out;
if(this.request.init(this.in, this.out)) {
this.request.handleRequests();
}
else {
Util.warn("handleHttpConnection init failed");
}
}
/**
* For internal use only. The current request (if any)
*
*/
public Request request;
// false if we detect that setAccessible is not possible
boolean canModifySecurityPermission = true;
private MethodCache methodCache = new MethodCache();
private ConstructorCache constructorCache = new ConstructorCache();
StringCache stringCache = new StringCache(this);
/** For internal use only. */
private IJavaBridgeFactory sessionFactory;
/**
* Return the session/jsr223 factory associated with this bridge
* @return The session/jsr223 factory
*/
public IJavaBridgeFactory getFactory() {
if(sessionFactory==null) throw new NullPointerException("session factory");
return sessionFactory;
}
Options options;
/**
* Returns the connection options
* @return The Options.
*/
public Options getOptions() {
return options;
}
/**
* Communication with client in a new thread
*/
public void run() {
try {
logDebug("START: JavaBridge.run()");
request = new Request(this);
try {
if(!request.init(in, out)) return;
} catch (Throwable e) {
printStackTrace(e);
return;
}
try {
request.handleRequests();
} catch (Exception e) {
printStackTrace(e);
}
globalRef=null;
logDebug("END: JavaBridge.run()");
} catch (Exception t) {
printStackTrace(t);
} finally {
if(in!=null) try {in.close();} catch (IOException e1) {printStackTrace(e1);}
if(out!=null) try {out.close();} catch (IOException e2) {printStackTrace(e2);}
sessionFactory.destroy();
}
}
/**
* Create a new server socket and return it.
* @param sockname the socket name
* @return the server socket
* @throws IOException
*/
public static ISocketFactory bind(String sockname) throws IOException {
return Standalone.bind(Util.logLevel, sockname);
}
/**
* Global init. Redirects System.out and System.err to the server
* log file(s) or to System.err and creates and opens the
* communcation channel. Note: Do not write anything to
* System.out, this stream is connected with a pipe which waits
* for the channel name.
* @param s an array of [socketname, level, logFile]
*/
public static void init(String s[]) {
(new Standalone()).init(s);
}
// called by Standalone.init()
static void initLog(String socket, int logLevel, String s[]) {
String logFile=null, rawLogFile=null;
if(logLevel==-1) logLevel = Util.DEFAULT_LOG_LEVEL;
Util.logLevel = logLevel;
try {
try {
rawLogFile=logFile=s.length>0?"":Util.DEFAULT_LOG_FILE;
if(s.length>2) {
rawLogFile=logFile=s[2];
if(Util.setConfiguredLogger(logFile))
logFile=null; // when log4j is used, System.out and System.err are not redirected
else
Util.setDefaultLogger(new FileLogger()); // use specified log file
if(Util.logLevel>3) System.err.println(Util.EXTENSION_NAME+" log: " + rawLogFile);
}
}catch (Throwable t) {
t.printStackTrace();
}
Util.redirectOutput( logFile);
Util.logMessage("VM : " + Util.VM_NAME);
if(Util.VERSION != null)
Util.logMessage(Util.EXTENSION_NAME+ " version : " + Util.VERSION);
Util.logMessage("logFile : " + rawLogFile);
Util.logMessage("default logLevel : " + Util.logLevel);
Util.logMessage("socket : " + socket);
Util.logMessage("java.ext.dirs : " + System.getProperty("java.ext.dirs"));
Util.logMessage("php.java.bridge.base: " + Util.JAVABRIDGE_BASE);
Util.logMessage("thread pool size : " + Util.THREAD_POOL_MAX_SIZE);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
// called by Standalone.init()
static void init(ISocketFactory socket, int logLevel, String s[]) {
try {
AppThreadPool pool = Util.createThreadPool(Util.EXTENSION_NAME+"ThreadPool");
try {
String policy = System.getProperty("java.security.policy");
String base = Util.JAVABRIDGE_BASE;
if(policy!=null && base!=null) {
SecurityManager manager = new php.java.bridge.JavaBridgeSecurityManager();
System.setSecurityManager(manager);
Util.logMessage(Util.EXTENSION_NAME + " policy base : " + base);
Util.logMessage(Util.EXTENSION_NAME + " security policy : " + policy);
}
} catch(Exception e) {
Util.logMessage("Cannot install security manager: " + e);
}
Util.logDebug("Starting to accept Socket connections");
while(true) {
Socket sock = socket.accept();
Util.logDebug("Socket connection accepted");
JavaBridge bridge = new SessionFactory().getBridge();
bridge.in = sock.getInputStream();
bridge.out = sock.getOutputStream();
if(pool!=null) {
Util.logDebug("Starting bridge thread from thread pool");
pool.start(bridge); // Uses thread pool
} else {
Util.logDebug("Starting new bridge thread");
Thread t = new Util.Thread(bridge);
t.start();
}
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
/**
* Start the PHP/Java Bridge. <br>
* Example:<br>
* <code>java -Djava.awt.headless=true -jar JavaBridge.jar INET:9656 5 /var/log/php-java-bridge.log</code><br>
* Note: Do not write anything to System.out, this
* stream is connected with a pipe which waits for the channel name.
* @param s an array of [socketname, level, logFile]
* Use Standalone.main()
* @see php.java.bridge.Standalone#main(String[])
*/
public static void main(String s[]) {
Standalone.main(s);
}
/**
* Print a stack trace to the log file.
* @param t the throwable
*/
public void printStackTrace(Throwable t) {
if(logLevel > 0)
if ((t instanceof Error) || logLevel > 1) {
Util.getLogger().printStackTrace(t);
}
}
private String getId() {
return Integer.toHexString(System.identityHashCode(this))+"@"+Integer.toHexString(System.identityHashCode(Thread.currentThread()));
}
/**
* Write a debug message
* @param msg The message
*/
public void logDebug(String msg) {
if(logLevel>3) Util.println(4, getId() + " " + msg);
}
/**
* Write a fatal message
* @param msg The message
*/
public void logFatal(String msg) {
if(logLevel>0) Util.println(1, getId() + " " + msg);
}
/**
* Write an error message.
* @param msg The message
*/
public void logError(String msg) {
if(logLevel>1) Util.println(2, getId() + " " + msg);
}
/**
* Write a notice.
* @param msg The message
*/
public void logMessage(String msg) {
if(logLevel>2) Util.println(3, getId() + " " + msg);
}
/**
* Write a warning.
* @param msg The warning.
*/
public void warn(String msg) {
if(logLevel>0) Util.warn(getId() + " " + msg);
}
void setException(Response response, Throwable e, String method, Object obj, String name, Object args[], Class params[], boolean hasDeclaredExceptions) {
if (e instanceof InvocationTargetException) {
Throwable t = ((InvocationTargetException)e).getTargetException();
if (t!=null) e=t;
if (logLevel>3 || (!options.preferValues() && !hasDeclaredExceptions)) printStackTrace(e);
} else {
printStackTrace(e);
}
StringBuffer buf=new StringBuffer(method);
buf.append(" failed: ");
if(obj!=null) {
buf.append("[");
Util.appendShortObject(obj, buf);
buf.append("]->");
} else {
buf.append("new ");
}
buf.append(name);
String arguments = Util.argsToString(args, params);
if(arguments.length()>0) {
buf.append("(");
Util.appendArgs(args, params, buf);
buf.append(")");
}
buf.append(".");
buf.append(" Cause: ");
buf.append(String.valueOf(e));
buf.append(" VM: ");
buf.append(Util.VM_NAME);
lastException = new Exception(buf.toString(), e);
StackTraceElement[] trace = e.getStackTrace();
if(trace!=null) lastException.setStackTrace(trace);
response.setResultException(lastException, hasDeclaredExceptions);
}
private Exception getUnresolvedExternalReferenceException(Throwable e, String what) {
return new ClassNotFoundException("Unresolved external reference: "+ e+ ". -- " +
"Unable to "+what+", see the README section \"Java platform issues\" " +
"for details and DO NOT REPORT THIS PROBLEM TO THE PHP/Java Bridge MAILING LIST!", e);
}
/**
* Create an new instance of a given class, to be called by clients.
* @param name The class name
* @param createInstance true if we should create an instance, false otherwise
* @param args The argument array
* @param response The response writer
*/
public void CreateObject(String name, boolean createInstance,
Object args[], Response response) {
Class params[] = null;
LinkedList candidates = new LinkedList();
LinkedList matches = new LinkedList();
boolean hasDeclaredExceptions = true;
try {
Constructor selected = null;
ConstructorCache.Entry entry = null;
Class clazz = Util.classForName(name);
if(createInstance) {
entry = constructorCache.getEntry(name, args);
selected = constructorCache.get(entry);
if(selected==null) {
Constructor cons[] = clazz.getConstructors();
for (int i=0; i<cons.length; i++) {
candidates.add(cons[i]);
if (cons[i].getParameterTypes().length == args.length) {
matches.add(cons[i]);
}
}
selected = (Constructor)select(matches, args);
if(selected!=null) constructorCache.put(entry, selected);
}
}
if (selected == null) {
if (args.length > 0) {
throw createInstance?
(Exception)new InstantiationException("No matching constructor found. " + "Candidates: " + String.valueOf(candidates)):
(Exception)new JavaBridgeIllegalArgumentException("ReferenceClass must be called w/o arguments; either write new JavaClass(\""+name+"\") or new Java(\""+name+"\", args...).");
} else {
// for classes which have no visible constructor, return the class
// useful for classes like java.lang.System and java.util.Calendar.
if(createInstance && logLevel>2) {
logMessage("No visible constructor found in: "+ name +", returning the class instead of an instance; this may not be what you want. Please correct this error or please use the function java(\""+name+"\") instead.");
}
response.setResultClass(clazz);
return;
}
}
Object coercedArgs[] = coerce(params=entry.getParameterTypes(selected), args, response);
// If we have a logLevel of 5 or above, do very detailed invocation logging
hasDeclaredExceptions = selected.getExceptionTypes().length!=0;
if (this.logLevel>4) {
Object result = selected.newInstance(coercedArgs);
logInvoke(result, name, coercedArgs);
response.setResult(result, clazz, hasDeclaredExceptions);
} else {
response.setResult(selected.newInstance(coercedArgs), clazz, hasDeclaredExceptions);
}
} catch (Throwable e) {
Throwable e1 = e;
if(e1 instanceof InvocationTargetException) e1 = ((InvocationTargetException)e1).getTargetException();
if(e1 instanceof Request.AbortException) {throw (Request.AbortException)e1;}
if(e1 instanceof OutOfMemoryError) {
Util.logFatal("OutOfMemoryError");
throw (OutOfMemoryError)e1; // abort
}
if(e1 instanceof NoClassDefFoundError) {
e = getUnresolvedExternalReferenceException(e1, "call constructor");
}
setException(response, e, createInstance?"CreateInstance":"ReferenceClass", null, name, args, params, hasDeclaredExceptions);
}
}
private static final Iterator EMPTY_ITERATOR = (new LinkedList()).iterator();
//
// Select the best match from a list of methods
//
private int weight(Class param, Class arg, Object phpArrayValue) {
int w = 0;
if (param.isAssignableFrom(arg)) {
for (Class c=arg; (c=c.getSuperclass()) != null; ) {
if (!param.isAssignableFrom(c)) {
break;
}
w+=16; // prefer more specific arg, for
// example AbstractMap hashMap
// over Object hashMap.
}
} else if (param == java.lang.String.class) {
if (!(String.class.isAssignableFrom(arg)) && !(PhpString.class.isAssignableFrom(arg)))
if(byte[].class.isAssignableFrom(arg))
w+=32;
else
w+=8000; // conversion to string is always possible
} else if (param.isArray()) {
if(PhpString.class.isAssignableFrom(arg)) {
Class c=param.getComponentType();
if(c == byte.class)
w+=32;
else
w+=9999;
} else if(arg == PhpArray.class) {
Iterator iterator = phpArrayValue == null ? EMPTY_ITERATOR : ((Map)phpArrayValue).values().iterator();
if(iterator.hasNext()) {
Object elem = iterator.next();
Class ptype = param.getComponentType(), atype = elem.getClass();
if (ptype!=atype) {
w+=(ptype==Object.class?10:8200)+weight(ptype, atype, null);
}
}
} else if(arg.isArray()) {
Class ptype = param.getComponentType(), atype = arg.getComponentType();
if (ptype!=atype) {
w+=(ptype==Object.class?10:8200)+weight(ptype, atype, null);
}
}
else w+=9999;
} else if ((java.util.Collection.class).isAssignableFrom(param)) {
if (java.util.Map.class.isAssignableFrom(arg)) w+=8100; // conversion to Collection is always possible
else if (!(PhpArray.class.isAssignableFrom(arg))) w+=9999;
} else if (param.isPrimitive()) {
Class c=param;
if (Number.class.isAssignableFrom(arg)) {
if(Double.class.isAssignableFrom(arg)) {
if (c==Float.TYPE) w+=1;
else if (c==Double.TYPE) w+=0;
else w+=256;
} else {
if (c==Boolean.TYPE) w+=5;
else if (c==Character.TYPE) w+=4;
else if (c==Byte.TYPE) w+=3;
else if (c==Short.TYPE) w+=2;
else if (c==Integer.TYPE) w+=1;
else if (c==Long.TYPE) w+=0;
else w+=256;
}
} else if (Boolean.class.isAssignableFrom(arg)) {
if (c!=Boolean.TYPE) w+=9999;
} else if (Character.class.isAssignableFrom(arg)) {
if (c!=Character.TYPE) w+=9999;
} else if ((String.class.isAssignableFrom(arg))||(PhpString.class.isAssignableFrom(arg))) {
w+=64;
} else {
w+=9999;
}
} else if(Number.class.isAssignableFrom(param)) {
if(param==Float.class || param==Double.class) {
if(!(Double.class.isAssignableFrom(arg))) w+=9999;
} else if(!(PhpExactNumber.class.isAssignableFrom(arg))) w+=9999;
} else {
w+=9999;
}
if(logLevel>4) logDebug("weight " + param + " " + arg + ": " +w);
return w;
}
private Object select(LinkedList methods, Object args[]) {
if (methods.size() == 1) return methods.getFirst();
Object similar = null, selected = null;
int best = Integer.MAX_VALUE;
int n = 0;
for (Iterator e = methods.iterator(); e.hasNext(); n++) {
Object element = e.next();
int w=0;
Class parms[] = (element instanceof Method) ?
((Method)element).getParameterTypes() :
((Constructor)element).getParameterTypes();
for (int i=0; i<parms.length; i++) {
Object arg = args[i];
if (arg!=null)
w+=weight(parms[i], arg.getClass(), arg);
}
if (w < best) {
if (w == 0) {
if(logLevel>4) logDebug("Selected: " + element + " " + w);
return element;
}
best = w;
selected = element;
if(logLevel>2) {
similar = null;
if(logLevel>4) logDebug("best: " + selected + " " + w);
}
} else {
if(logLevel>2) {
if(w==best) similar = element;
if(logLevel>4) logDebug("skip: " + element + " " + w);
}
}
}
if(logLevel>2 && similar!=null) {
StringBuffer buf = new StringBuffer();
for(int i=0; i<args.length; i++) {
Util.appendParam(args[i], buf);
}
logMessage("Portability warning: " + selected + " and " + similar + " both match " + buf.toString());
}
if(logLevel>4) logDebug("Selected: " + selected + " " + best);
return selected;
}
private Object o[] = new Object[1];
private Class c[] = new Class[1];
Object coerce(Class param, Object arg, Response response) {
o[0]=arg; c[0]=param;
return coerce(c, o, response)[0];
}
//
// Coerce arguments when possible to conform to the argument list.
// Java's reflection will automatically do widening conversions,
// unfortunately PHP only supports wide formats, so to be practical
// some (possibly lossy) conversions are required.
//
Object[] coerce(Class parms[], Object args[], Response response) {
Object arg;
Object result[] = args;
int size = 0;
for (int i=0; i<args.length; i++) {
if((arg=args[i]) == null) continue;
if(parms[i]==String.class) {
if (arg instanceof PhpString)
result[i] = ((PhpString)arg).getString();
else
result[i] = arg.toString();
} else if (arg instanceof PhpString || arg instanceof String) {
if(!parms[i].isArray()) {
Class c = parms[i];
String s = (arg instanceof String) ? (String) arg : ((PhpString)arg).getString();
result[i] = s;
try {
if (c == Boolean.TYPE) result[i]=new Boolean(s);
else if (c == Byte.TYPE) result[i]=new Byte(s);
else if (c == Short.TYPE) result[i]=new Short(s);
else if (c == Integer.TYPE) result[i]=new Integer(s);
else if (c == Float.TYPE) result[i]=new Float(s);
else if (c == Double.TYPE) result[i]=new Double(s);
else if (c == Long.TYPE) result[i]=new Long(s);
else if (c == Character.TYPE && s.length()>0)
result[i]=new Character(s.charAt(0));
} catch (NumberFormatException n) {
printStackTrace(n);
// oh well, we tried!
}
} else {
result[i]=((PhpString)arg).getBytes();
}
} else if (arg instanceof Number) {
if (parms[i].isPrimitive()) {
Class c = parms[i];
Number n = (Number)arg;
if (c == Boolean.TYPE) result[i]=new Boolean(0.0!=n.floatValue());
else if (c == Byte.TYPE) result[i]=new Byte(n.byteValue());
else if (c == Short.TYPE) result[i]=new Short(n.shortValue());
else if (c == Integer.TYPE) result[i]=new Integer(n.intValue());
else if (c == Float.TYPE) result[i]=new Float(n.floatValue());
else if (c == Double.TYPE) result[i]=new Double(n.doubleValue());
else if (c == Long.TYPE && !(n instanceof Long))
result[i]=new Long(n.longValue());
} else {
if(arg.getClass()==PhpExactNumber.class) {
{
Class c = parms[i];
if(c.isAssignableFrom(Integer.class)) {
result[i] = new Integer(((Number)arg).intValue());
} else {
result[i] = new Long(((Number)arg).longValue());
}
}
}
}
} else if (arg instanceof PhpArray) {
if(parms[i].isArray()) {
Map.Entry e = null;
Object tempArray = null;
PhpArray ht = null;
Class targetType = parms[i].getComponentType();
try {
ht = (PhpArray)arg;
size = ht.arraySize();
// flatten hash into an array
targetType = parms[i].getComponentType();
tempArray = Array.newInstance(targetType, size);
} catch (Exception ex) {
//logError("Could not create array from Map: " + objectDebugDescription(arg) + ". Cause: " + ex);
throw new JavaBridgeIllegalArgumentException("Could not create array from Map: " + firstChars(arg), ex);
}
try {
for (Iterator ii = ht.entrySet().iterator(); ii.hasNext(); ) {
e = (Entry) ii.next();
Array.set(tempArray, ((Number)(e.getKey())).intValue(), coerce(targetType, e.getValue(), response));
}
result[i]=tempArray;
} catch (Exception ex) {
//logError("Could not create array of type: " + targetType + ", size: " + size + ", " + " failed entry at: " + e + ", from Map: " + objectDebugDescription(arg) + ". Cause: " + ex);
throw new JavaBridgeIllegalArgumentException("Could not create array of type: " + targetType + ", size: " + size + ", " + " failed entry at: " + e, ex);
}
} else if ((java.util.Collection.class).isAssignableFrom(parms[i])) {
try {
Map m = (Map)arg;
Collection c = m.values();
if(!parms[i].isInstance(c))
try { // could be a concrete class, for example LinkedList.
Collection collection = (Collection) parms[i].newInstance();
collection.addAll(c);
c=collection;
} catch (Exception e) { // it was an interface, try some concrete class
try { c = new ArrayList(c); } catch (Exception ex) {/*we've tried*/}
}
result[i]=c;
} catch (Exception ex) {
//logError("Could not create Collection from Map: " +objectDebugDescription(arg) + ". Cause: " + ex);
throw new JavaBridgeIllegalArgumentException("Could not create Collection from Map: " + firstChars(arg), ex);
}
} else if ((java.util.Hashtable.class).isAssignableFrom(parms[i])) {
try {
Map ht = (Map)arg;
Hashtable res;
res = (Hashtable)parms[i].newInstance();
res.putAll(ht);
result[i]=res;
} catch (Exception ex) {
logError("Could not create Hashtable from Map: " +objectDebugDescription(arg) + ". Cause: " + ex);
throw new JavaBridgeIllegalArgumentException("Could not create Hashtable from Map: " + firstChars(arg), ex);
}
} else if ((java.util.Map.class).isAssignableFrom(parms[i])) {
result[i]=arg;
} else if(arg instanceof PhpString) {
result[i] = ((PhpString)arg).getString(); // always prefer strings over byte[]
}
}
}
return result;
}
static abstract class FindMatchingInterface {
JavaBridge bridge;
String name;
Object args[];
boolean ignoreCase;
public FindMatchingInterface (JavaBridge bridge, String name, Object args[], boolean ignoreCase) {
this.bridge=bridge;
this.name=name;
this.args=args;
this.ignoreCase=ignoreCase;
}
abstract Class findMatchingInterface(Class jclass);
public boolean checkAccessible(AccessibleObject o) {return true;}
}
static final FindMatchingInterfaceVoid MATCH_VOID_ICASE = new FindMatchingInterfaceVoid(true);
static final FindMatchingInterfaceVoid MATCH_VOID_CASE = new FindMatchingInterfaceVoid(false);
static class FindMatchingInterfaceVoid extends FindMatchingInterface {
public FindMatchingInterfaceVoid(boolean b) { super(null, null, null, b); }
Class findMatchingInterface(Class jclass) {
return jclass;
}
public boolean checkAccessible(AccessibleObject o) {
if(!o.isAccessible()) {
try {
o.setAccessible(true);
} catch (java.lang.SecurityException ex) {
return false;
}
}
return true;
}
}
static class FindMatchingInterfaceForInvoke extends FindMatchingInterface {
protected FindMatchingInterfaceForInvoke(JavaBridge bridge, String name, Object args[], boolean ignoreCase) {
super(bridge, name, args, ignoreCase);
}
public static FindMatchingInterface getInstance(JavaBridge bridge, String name, Object args[], boolean ignoreCase, boolean canModifySecurityPermission) {
if(canModifySecurityPermission) return ignoreCase?MATCH_VOID_ICASE : MATCH_VOID_CASE;
else return new FindMatchingInterfaceForInvoke(bridge, name, args, ignoreCase);
}
Class findMatchingInterface(Class jclass) {
if(jclass==null) return jclass;
if(bridge.logLevel>3)
if(bridge.logLevel>3)bridge.logDebug("searching for matching interface for Invoke for class " + jclass);
while (!Modifier.isPublic(jclass.getModifiers())) {
// OK, some joker gave us an instance of a non-public class
// This often occurs in the case of enumerators
// Substitute the matching first public interface in its place,
// and barring that, try the superclass
Class interfaces[] = jclass.getInterfaces();
Class superclass = jclass.getSuperclass();
for (int i=interfaces.length; i-->0;) {
if (Modifier.isPublic(interfaces[i].getModifiers())) {
jclass=interfaces[i];
Method methods[] = jclass.getMethods();
for (int j=0; j<methods.length; j++) {
String nm = methods[j].getName();
boolean eq = ignoreCase ? nm.equalsIgnoreCase(name) : nm.equals(name);
if (eq && (methods[j].getParameterTypes().length == args.length)) {
if(bridge.logLevel>3) bridge.logDebug("matching interface for Invoke: " + jclass);
return jclass;
}
}
}
}
jclass = superclass;
}
if(bridge.logLevel>3) bridge.logDebug("interface for Invoke: " + jclass);
return jclass;
}
}
static class FindMatchingInterfaceForGetSetProp extends FindMatchingInterface {
protected FindMatchingInterfaceForGetSetProp(JavaBridge bridge, String name, Object args[], boolean ignoreCase) {
super(bridge, name, args, ignoreCase);
}
public static FindMatchingInterface getInstance(JavaBridge bridge, String name, Object args[], boolean ignoreCase, boolean canModifySecurityPermission) {
if(canModifySecurityPermission) return ignoreCase?MATCH_VOID_ICASE : MATCH_VOID_CASE;
else return new FindMatchingInterfaceForGetSetProp(bridge, name, args, ignoreCase);
}
Class findMatchingInterface(Class jclass) {
if(jclass==null) return jclass;
if(bridge.logLevel>3)
if(bridge.logLevel>3)bridge.logDebug("searching for matching interface for GetSetProp for class "+ jclass);
while (!Modifier.isPublic(jclass.getModifiers())) {
// OK, some joker gave us an instance of a non-public class
// This often occurs in the case of enumerators
// Substitute the matching first public interface in its place,
// and barring that, try the superclass
Class interfaces[] = jclass.getInterfaces();
Class superclass = jclass.getSuperclass();
for (int i=interfaces.length; i-->0;) {
if (Modifier.isPublic(interfaces[i].getModifiers())) {
jclass=interfaces[i];
Field jfields[] = jclass.getFields();
for (int j=0; j<jfields.length; j++) {
String nm = jfields[j].getName();
boolean eq = ignoreCase ? nm.equalsIgnoreCase(name) : nm.equals(name);
if (eq) {
if(bridge.logLevel>3) bridge.logDebug("matching interface for GetSetProp: "+ jclass);
return jclass;
}
}
}
}
jclass = superclass;
}
if(bridge.logLevel>3) bridge.logDebug("interface for GetSetProp: "+ jclass);
return jclass;
}
}
private static ClassIterator getClassClassIterator(Class clazz) {
if(clazz==Class.class) return new MetaClassIterator();
return new ClassClassIterator();
}
private static abstract class ClassIterator {
Object object;
Class current;
FindMatchingInterface match;
public static ClassIterator getInstance(Object object, FindMatchingInterface match) {
ClassIterator c;
if(object instanceof Class)
c = getClassClassIterator((Class)object);
else
c = new ObjectClassIterator();
c.match = match;
c.object = object;
c.current = null;
return c;
}
public abstract Class getNext();
public abstract boolean checkAccessible(AccessibleObject o);
public abstract boolean isVisible(int modifier);
}
static class ObjectClassIterator extends ClassIterator {
private Class next() {
if (current == null) return current = object.getClass();
return null;
}
public Class getNext() {
return match.findMatchingInterface(next());
}
public boolean checkAccessible(AccessibleObject o) {
return match.checkAccessible(o);
}
public boolean isVisible(int modifier) { return true; }
}
static class ClassClassIterator extends ClassIterator {
boolean hasNext=false;
private Class next() {
// check the class first, then the class class.
if(current == null) { hasNext = true; return current = (Class)object;}
if(hasNext) { hasNext = false; return object.getClass();}
return null;
}
public Class getNext() {
return next();
}
public boolean checkAccessible(AccessibleObject o) {
return true;
}
public boolean isVisible(int modifier) {
// all members of the class class or only static members of the class
return !hasNext || ((modifier&Modifier.STATIC)!=0);
}
}
static class MetaClassIterator extends ClassIterator {
private Class next() {
// The ClassClass has the ClassClass as its class
if(current == null) { return current = (Class)object;}
return null;
}
public Class getNext() {
return next();
}
public boolean checkAccessible(AccessibleObject o) {
return true;
}
public boolean isVisible(int modifier) {
return true;
}
}
private static void logInvoke(Object obj, String method, Object args[]) {
String dmsg = "\nInvoking "+objectDebugDescription(obj)+"."+method+"(";
for (int t =0;t<args.length;t++) {
if (t>0) dmsg +=",";
dmsg += objectDebugDescription(args[t]);
}
dmsg += ");\n";
Util.logDebug(dmsg);
}
private static void logResult(Object obj) {
String dmsg = "\nResult "+objectDebugDescription(obj) + "\n";
Util.logDebug(dmsg);
}
/**
* Invoke a method on a given object, to be called by clients.
* @param object The object
* @param method The method of the object
* @param args The argument array
* @param response The response writer
* @throws NullPointerException If the object was null
*/
public void Invoke
(Object object, String method, Object args[], Response response)
{
Class jclass;
boolean again;
Object coercedArgs[] = null;
Class params[] = null;
LinkedList candidates = new LinkedList();
LinkedList matches = new LinkedList();
Method selected = null;
boolean hasDeclaredExceptions = true;
try {
if(object==null) {object = Request.PHPNULL;throw new NullPointerException("cannot call \""+method+"()\" on a Java null object. A previous Java call has returned a null value, use java_is_null($jvalue) to check.");}
/* PR1616498: Do not use Util.getClass(): if object is a class, we must pass the class class.