forked from micw/php-java-bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtil.java
More file actions
1559 lines (1422 loc) · 49.6 KB
/
Copy pathUtil.java
File metadata and controls
1559 lines (1422 loc) · 49.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
*
* 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.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Vector;
import java.util.Map.Entry;
import php.java.bridge.http.FCGIConnectionPool;
/**
* Miscellaneous functions.
* @author jostb
*
*/
public final class Util {
static {
initGlobals();
}
/**
* Script engines are started from this pool.
* Use pool.destroy() to destroy the thread pool upon JVM or servlet shutdown
*/
public static final ThreadPool PHP_SCRIPT_ENGINE_THREAD_POOL = new ThreadPool("JavaBridgeStandaloneScriptEngineProxy", Integer.parseInt(Util.THREAD_POOL_MAX_SIZE)) {
protected Delegate createDelegate(String name) {
Delegate d = super.createDelegate(name);
d.setDaemon(true);
return d;
}
};
/**
* Only for internal use. The library standalone ScriptEngine FastCGI connection pool, if any
*/
public static FCGIConnectionPool fcgiConnectionPool;
/** Used by the watchdog. After MAX_WAIT (default 1500ms) the ContextRunner times out. Raise this value if you want to debug the bridge.
* See also system property <code>php.java.bridge.max_wait</code>
*/
public static int MAX_WAIT;
/** The java/Java.inc code */
public static Class JAVA_INC;
/** The java/Java.inc code */
public static Class PHPDEBUGGER_PHP;
/** The java/JavaProxy.php code */
public static Class JAVA_PROXY;
/** The launcher.sh code */
public static Class LAUNCHER_UNIX;
/** The launcher.exe code */
public static Class LAUNCHER_WINDOWS, LAUNCHER_WINDOWS2, LAUNCHER_WINDOWS3, LAUNCHER_WINDOWS4;
/** Only for internal use */
public static final byte HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/** True if /bin/sh exists, false otherwise */
public static final boolean USE_SH_WRAPPER = new File("/bin/sh").exists();
/** The PHP argument allow_url_include=On, passed to all JSR223 script engines */
public static final String[] ALLOW_URL_INCLUDE = {"-d", "allow_url_include=On"};
/** Used to re-direct back to the current VM */
public static final String X_JAVABRIDGE_OVERRIDE_HOSTS = "X_JAVABRIDGE_OVERRIDE_HOSTS";
/** The standard Context ID used by the ContextFactory */
public static final String X_JAVABRIDGE_CONTEXT = "X_JAVABRIDGE_CONTEXT";
public static final String X_JAVABRIDGE_OVERRIDE_HOSTS_REDIRECT = "X_JAVABRIDGE_OVERRIDE_HOSTS_REDIRECT";
public static final String X_JAVABRIDGE_REDIRECT = "X_JAVABRIDGE_REDIRECT";
public static final String X_JAVABRIDGE_INCLUDE = "X_JAVABRIDGE_INCLUDE";
public static final String X_JAVABRIDGE_INCLUDE_ONLY = "X_JAVABRIDGE_INCLUDE_ONLY";
private Util() {}
/**
* Only for internal use. Use Util.getLogger() instread.
*
* A bridge which uses log4j or the default logger.
*
*/
public static class Logger implements ILogger {
protected ChainsawLogger clogger = null;
protected ILogger logger;
/**
* Use chainsaw, if available or a default logger.
*
*/
public Logger() {
logger = new FileLogger(); // log to logStream
}
/**
* Use chainsaw, if available.
* @param logger The specified logger.
*/
public Logger(ILogger logger) {
this(!DEFAULT_LOG_FILE_SET, logger);
}
public Logger(boolean useChainsaw, ILogger logger) {
if (useChainsaw)
try {this.clogger = ChainsawLogger.createChainsawLogger();} catch (Throwable t) {
if(Util.logLevel>5) t.printStackTrace();
this.logger = logger;
} else {
this.logger = logger;
}
}
private ILogger getLogger() {
if(logger==null) return logger=new FileLogger();
return logger;
}
/**{@inheritDoc}*/
public void printStackTrace(Throwable t) {
if (clogger==null) logger.printStackTrace(t);
else
try {
clogger.printStackTrace(t);
} catch (Exception e) {
clogger=null;
getLogger().printStackTrace(t);
}
}
/**{@inheritDoc}*/
public void log(int level, String msg) {
if(clogger==null) logger.log(level, msg);
else
try {
clogger.log(level, msg);
} catch (Exception e) {
clogger=null;
getLogger().log(level, msg);
}
}
/**{@inheritDoc}*/
public void warn(String msg) {
if(clogger==null) logger.warn(msg);
else
try {
clogger.warn(msg);
} catch (Exception e) {
clogger=null;
getLogger().warn(msg);
}
}
}
/**
* The default PHP arguments. Can be passed via -Dphp.java.bridge.php_exec_args=list of urlencoded strings separated by space
* Default: "-d display_errors=Off -d log_errors=On -d java.persistent_servlet_connections=On"
*/
private static String[] PHP_ARGS;
private static String DEFAULT_PHP_ARGS;
/**
* The default CGI locations: <code>"/usr/bin/php-cgi"</code>, <code>"c:/Program Files/PHP/php-cgi.exe</code>
*/
public static String DEFAULT_CGI_LOCATIONS[];
/**
* ASCII encoding
*/
public static final String ASCII = "ASCII";
/**
* UTF8 encoding
*/
public static final String UTF8 = "UTF-8";
/**
* DEFAULT currently UTF-8, will be changed when most OS support and use UTF-16.
*/
public static final String DEFAULT_ENCODING = "UTF-8";
/**
* The default buffer size
*/
public static final int BUF_SIZE = 8192;
/** Environment entries which should NOT be passed to PHP. For example PHPRC, which is set by some broken PHP installers */
public static List ENVIRONMENT_BLACKLIST;
/**
* A map containing environment values not in ENVIRONMENT_BLACKLIST. At least:
* "PATH", "LD_LIBRARY_PATH", "LD_ASSUME_KERNEL", "USER", "TMP", "TEMP", "HOME", "HOMEPATH", "LANG", "TZ", "OS"
* They can be set with e.g.: <code>java -DPATH="$PATH" -DHOME="$HOME" -jar JavaBridge.jar</code> or
* <code>java -DPATH="%PATH%" -jar JavaBridge.jar</code>.
*/
public static HashMap COMMON_ENVIRONMENT;
/**
* The default extension directories. If one of the directories
* "/usr/share/java/ext", "/usr/java/packages/lib/ext" contains
* java libraries, the bridge loads these libraries automatically.
* Useful if you have non-pure java libraries (=libraries which
* use the Java Native Interface to load native dll's or shared
* libraries).
*/
public static final String DEFAULT_EXT_DIRS[] = { "/usr/share/java/ext", "/usr/java/packages/lib/ext" };
/** Set to true if the VM is gcj, false otherwise */
public static final boolean IS_GNU_JAVA = checkVM();
/**
* The name of the extension, usually "JavaBridge" or "MonoBridge"
*/
public static String EXTENSION_NAME;
/**
* The max. number of threads in the thread pool. Default is 20.
* @see System property <code>php.java.bridge.threads</code>
*/
public static String THREAD_POOL_MAX_SIZE;
/**
* The default log level, java.log_level from php.ini
* overrides. Default is 3, if started via java -jar
* JavaBridge.jar or 2, if started as a sub-process of Apache/IIS.
* @see System property <code>php.java.bridge.default_log_level</code>
*/
public static int DEFAULT_LOG_LEVEL;
/**
* Backlog for TCP and unix domain connections.
*/
public static final int BACKLOG = 20;
/** Only for internal use */
public static final Object[] ZERO_ARG = new Object[0];
/** Only for internal use */
public static final Class[] ZERO_PARAM = new Class[0];
/** Only for internal use */
public static final byte[] RN = Util.toBytes("\r\n");
public static File TMPDIR;
/** The name of the VM, for example "1.4.2@http://java.sun.com/" or "1.4.2@http://gcc.gnu.org/java/".*/
public static String VM_NAME;
/**
* Set to true, if the Java VM has been started with -Dphp.java.bridge.promiscuous=true;
*/
public static boolean JAVABRIDGE_PROMISCUOUS;
/**
* The default log file. Default is stderr, if started as a
* sub-process of Apache/IIS or <code>EXTENSION_NAME</code>.log,
* if started via java -jar JavaBridge.jar.
* @see System property <code>php.java.bridge.default_log_file</code>
*/
public static String DEFAULT_LOG_FILE;
private static boolean DEFAULT_LOG_FILE_SET;
/** The base directory of the PHP/Java Bridge. Usually /usr/php/modules/ or $HOME */
public static String JAVABRIDGE_BASE;
private static String getProperty(Properties p, String key, String defaultValue) {
String s = null;
if(p!=null) s = p.getProperty(key);
if(s==null) s = System.getProperty("php.java.bridge." + String.valueOf(key).toLowerCase());
if(s==null) s = defaultValue;
return s;
}
/** Only for internal use */
public static String VERSION;
/** Only for internal use */
public static String osArch;
/** Only for internal use */
public static String osName;
/** Only for internal use */
public static String PHP_EXEC;
/** Only for internal use */
public static File HOME_DIR;
private static String sessionSavePath;
private static void initGlobals() {
try {
JAVA_INC = Class.forName("php.java.bridge.JavaInc");
} catch (Exception e) {/*ignore*/}
try {
PHPDEBUGGER_PHP = Class.forName("php.java.bridge.PhpDebuggerPHP");
} catch (Exception e) {/*ignore*/}
try {
JAVA_PROXY = Class.forName("php.java.bridge.JavaProxy");
} catch (Exception e) {/*ignore*/}
try {
LAUNCHER_UNIX = Class.forName("php.java.bridge.LauncherUnix");
} catch (Exception e) {/*ignore*/}
try {
LAUNCHER_WINDOWS = Class.forName("php.java.bridge.LauncherWindows");
LAUNCHER_WINDOWS2 = Class.forName("php.java.bridge.LauncherWindows2");
LAUNCHER_WINDOWS3 = Class.forName("php.java.bridge.LauncherWindows3");
LAUNCHER_WINDOWS4 = Class.forName("php.java.bridge.LauncherWindows4");
} catch (Exception e) {/*ignore*/}
Properties p = new Properties();
try {
InputStream in = Util.class.getResourceAsStream("global.properties");
p.load(in);
VERSION = p.getProperty("BACKEND_VERSION");
} catch (Throwable t) {
VERSION = "unknown";
//t.printStackTrace();
};
ENVIRONMENT_BLACKLIST = getEnvironmentBlacklist(p);
COMMON_ENVIRONMENT = getCommonEnvironment(ENVIRONMENT_BLACKLIST);
DEFAULT_CGI_LOCATIONS = new String[] {"/usr/bin/php-cgi", "c:/Program Files/PHP/php-cgi.exe"};
try {
if (!new File(DEFAULT_CGI_LOCATIONS[0]).exists() && !new File(DEFAULT_CGI_LOCATIONS[0]).exists())
try {
File filePath = null;
boolean found = false;
String path = (String)COMMON_ENVIRONMENT.get("PATH");
StringTokenizer tok = new StringTokenizer(path, File.pathSeparator);
while(tok.hasMoreTokens()) {
String s = tok.nextToken();
if ((filePath = new File(s, "php-cgi.exe")).exists()) { found = true; break; }
if ((filePath = new File(s, "php-cgi")).exists()) { found = true; break; }
}
if (!found) found = ((filePath = new File("/usr/php/bin/php-cgi")).exists());
if (!found) {
String programFiles = (String)COMMON_ENVIRONMENT.get("ProgramFiles");
if (programFiles!=null)
found = ((filePath = new File(programFiles+"\\PHP\\php-cgi.exe")).exists());
}
if (found)
DEFAULT_CGI_LOCATIONS = new String[] {filePath.getCanonicalPath(), DEFAULT_CGI_LOCATIONS[0], DEFAULT_CGI_LOCATIONS[1]};
} catch (Exception e) { /*ignore*/ }
} catch (Throwable xe) {/*ignore*/}
try {
MAX_WAIT = Integer.parseInt(getProperty(p, "php.java.bridge.max_wait", "15000"));
} catch (Exception e) {
MAX_WAIT = 15000;
}
try {
HOME_DIR = new File(System.getProperty("user.home"));
} catch (Exception e) {
HOME_DIR = null;
}
try {
JAVABRIDGE_BASE = getProperty(p, "php.java.bridge.base", System.getProperty("user.home"));
} catch (Exception e) {
JAVABRIDGE_BASE=".";
}
try {
VM_NAME = "unknown";
VM_NAME = System.getProperty("java.version")+"@" + System.getProperty("java.vendor.url");
} catch (Exception e) {/*ignore*/}
try {
JAVABRIDGE_PROMISCUOUS = false;
JAVABRIDGE_PROMISCUOUS = getProperty(p, "php.java.bridge.promiscuous", "false").toLowerCase().equals("true");
} catch (Exception e) {/*ignore*/}
try {
THREAD_POOL_MAX_SIZE = "20";
THREAD_POOL_MAX_SIZE = getProperty(p, "THREADS", "20");
} catch (Throwable t) {
//t.printStackTrace();
};
// resolve java.io.tmpdir for windows; PHP doesn't like dos short file names like foo~1\bar~2\...
TMPDIR = new File(System.getProperty("java.io.tmpdir", "/tmp"));
if (!TMPDIR.exists() || !TMPDIR.isDirectory()) TMPDIR = null;
sessionSavePath = null;
if (TMPDIR != null) try {TMPDIR = TMPDIR.getCanonicalFile(); } catch (IOException ex) {/*ignore*/}
if (TMPDIR != null) {
sessionSavePath = TMPDIR.getPath();
}
DEFAULT_PHP_ARGS = "-d java.session=On -d display_errors=Off -d log_errors=On -d java.persistent_servlet_connections=On";
try {
String str = getProperty(p, "PHP_EXEC_ARGS", DEFAULT_PHP_ARGS);
String[] args = str.split(" ");
for (int i=0; i<args.length; i++) {
try {
args[i] = java.net.URLDecoder.decode(args[i], UTF8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
PHP_ARGS = args;
} catch (Throwable t) {
//t.printStackTrace();
};
try {
EXTENSION_NAME = "JavaBridge";
EXTENSION_NAME = getProperty(p, "EXTENSION_DISPLAY_NAME", "JavaBridge");
} catch (Throwable t) {
//t.printStackTrace();
};
try {
PHP_EXEC = getProperty(p, "PHP_EXEC", null);
} catch (Throwable t) {
//t.printStackTrace();
}
try {
String s = getProperty(p, "DEFAULT_LOG_LEVEL", "3");
DEFAULT_LOG_LEVEL = Integer.parseInt(s);
Util.logLevel=Util.DEFAULT_LOG_LEVEL; /* java.log_level in php.ini overrides */
} catch (Throwable t) {/*ignore*/}
try {
DEFAULT_LOG_FILE_SET = false;
DEFAULT_LOG_FILE = getProperty(p, "DEFAULT_LOG_FILE", Util.EXTENSION_NAME+".log");
DEFAULT_LOG_FILE_SET = System.getProperty("php.java.bridge.default_log_file") != null;
} catch (Throwable t) {/*ignore*/}
String separator = "/-+.,;: ";
try {
String val = System.getProperty("os.arch").toLowerCase();
StringTokenizer t = new StringTokenizer(val, separator);
osArch = t.nextToken();
} catch (Throwable t) {/*ignore*/}
if(osArch==null) osArch="unknown";
try {
String val = System.getProperty("os.name").toLowerCase();
StringTokenizer t = new StringTokenizer(val, separator);
osName = t.nextToken();
} catch (Throwable t) {/*ignore*/}
if(osName==null) osName="unknown";
}
/**
* The logStream, defaults to System.err
*/
static PrintStream logStream;
private static ILogger defaultLogger = new Logger(new FileLogger());
/**
* The loglevel:<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
*/
public static int logLevel;
/**
* print a message on a given log level
* @param level The log level
* @param msg The message
*/
public static void println(int level, String msg) {
getLogger().log(level, msg);
}
/**
* Display a warning if logLevel >= 1
* @param msg The warn message
*/
public static void warn(String msg) {
if(logLevel<=0) return;
getLogger().warn(msg);
}
/**
* Display a stack trace if logLevel >= 1
* @param t The Throwable
*/
public static void printStackTrace(Throwable t) {
getLogger().printStackTrace(t);
}
/**
* Display a debug message
* @param msg The message
*/
public static void logDebug(String msg) {
if(logLevel>3) println(4, msg);
}
/**
* Display a fatal error
* @param msg The error
*/
public static void logFatal(String msg) {
if(logLevel>0) println(1, msg);
}
/**
* Display an error or an exception
* @param msg The error or the exception
*/
public static void logError(String msg) {
if(logLevel>1) println(2, msg);
}
/**
* Display a message
* @param msg The message
*/
public static void logMessage(String msg) {
if(logLevel>2) println(3, msg);
}
/**
* Return the class name
* @param obj The object
* @return The class name
*/
public static String getClassName(Object obj) {
if(obj==null) return "null";
Class c = getClass(obj);
String name = c.getName();
if(name.startsWith("[")) name = "array_of_"+name.substring(1);
return name;
}
/**
* Return the short class name
* @param obj The object
* @return The class name
*/
public static String getShortClassName(Object obj) {
String name = getClassName(obj);
int idx = name.lastIndexOf('.');
if(idx!=-1)
name = name.substring(idx+1);
return name;
}
/**
* Return the short class name
* @param clazz The class
* @return The class name
*/
public static String getShortName(Class clazz) {
String name = clazz.getName();
if(name.startsWith("[")) name = "array_of_"+name.substring(1);
int idx = name.lastIndexOf('.');
if(idx!=-1)
name = name.substring(idx+1);
return name;
}
/**
* Return the class or the object, if obj is already a class.
* @param obj The object
* @return Either obj or the class of obj.
*/
public static Class getClass(Object obj) {
if(obj==null) return null;
return obj instanceof Class?(Class)obj:obj.getClass();
}
/**
* Append an object to a StringBuffer
* @param obj The object
* @param buf The StringBuffer
*/
public static void appendObject(Object obj, StringBuffer buf) {
if(obj==null) { buf.append("null"); return; }
if(obj instanceof Class) {
if(((Class)obj).isInterface())
buf.append("[i:");
else
buf.append("[c:");
} else {
buf.append("[o:");
}
buf.append(getShortClassName(obj));
buf.append("]:");
buf.append("\"");
buf.append(Util.stringValueOf(obj));
buf.append("\"");
}
/**
* Append a stack trace to buf.
* @param throwable The throwable object
* @param trace The trace from PHP
* @param buf The current buffer.
*/
public static void appendTrace(Throwable throwable, String trace, StringBuffer buf) {
buf.append(" at:\n");
StackTraceElement stack[] = throwable.getStackTrace();
int top=stack.length;
for(int i=0; i<top; i++) {
buf.append("#-");
buf.append(top-i);
buf.append(" ");
buf.append(stack[i].toString());
buf.append("\n");
}
buf.append(trace);
}
/**
* Append a parameter object to a StringBuffer
* @param obj The object
* @param buf The StringBuffer
*/
public static void appendShortObject(Object obj, StringBuffer buf) {
if(obj==null) { buf.append("null"); return; }
if(obj instanceof Class) {
if(((Class)obj).isInterface())
buf.append("[i:");
else
buf.append("[c:");
} else {
buf.append("[o:");
}
buf.append(getShortClassName(obj));
buf.append("]");
}
/**
* Append a function parameter to a StringBuffer
* @param c The parameter
* @param buf The StringBuffer
*/
public static void appendParam(Class c, StringBuffer buf) {
if(c.isInterface())
buf.append("(i:");
else if (c==java.lang.Class.class)
buf.append("(c:");
else
buf.append("(o:");
buf.append(getShortClassName(c));
buf.append(")");
}
/**
* Append a function parameter to a StringBuffer
* @param obj The parameter object
* @param buf The StringBuffer
*/
public static void appendParam(Object obj, StringBuffer buf) {
if(obj instanceof Class) {
Class c = (Class)obj;
if(c.isInterface())
buf.append("(i:");
else
buf.append("(c:");
}
else
buf.append("(o:");
buf.append(getShortClassName(obj));
buf.append(")");
}
/**
* Return function arguments and their types as a String
* @param args The args
* @param params The associated types
* @return A new string
*/
public static String argsToString(Object args[], Class[] params) {
StringBuffer buffer = new StringBuffer("");
appendArgs(args, params, buffer);
return buffer.toString();
}
/**
* Append function arguments and their types to a StringBuffer
* @param args The args
* @param params The associated types
* @param buf The StringBuffer
*/
public static void appendArgs(Object args[], Class[] params, StringBuffer buf) {
if(args!=null) {
for(int i=0; i<args.length; i++) {
if(params!=null) {
appendParam(params[i], buf);
}
appendShortObject(args[i], buf);
if(i+1<args.length) buf.append(", ");
}
}
}
/**
* Locale-independent getBytes(), uses ASCII encoding
* @param s The String
* @return The ASCII encoded bytes
*/
public static byte[] toBytes(String s) {
try {
return s.getBytes(ASCII);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return s.getBytes();
}
}
/**
* Create a string array from a hashtable.
* @param h The hashtable
* @return The String
* @throws NullPointerException
*/
public static String[] hashToStringArray(Map h) {
Vector v = new Vector();
Iterator e = h.keySet().iterator();
while (e.hasNext()) {
String k = e.next().toString();
v.add(k + "=" + h.get(k));
}
String[] strArr = new String[v.size()];
v.copyInto(strArr);
return strArr;
}
/**
* Sets the fall back logger, used when no thread-local logger exists. The default logger is initialized with: <code>new Logger(new FileLogger())</code>.
* @param logger the logger
* @see #logDebug
*/
public static synchronized void setDefaultLogger(ILogger logger) {
Util.defaultLogger = logger;
}
/**
* @return Returns the logger.
*/
public static ILogger getLogger() {
return defaultLogger;
}
/**
* Returns the string "127.0.0.1". If the system property "php.java.bridge.promiscuous" is "true",
* the real host address is returned.
* @return The host address as a string.
*/
public static String getHostAddress(boolean promiscuous) {
String addr = "127.0.0.1";
try {
if(JAVABRIDGE_PROMISCUOUS || promiscuous)
addr = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {/*ignore*/}
return addr;
}
/**
* Checks if the cgi binary buf-<os.arch>-<os.name>.sh or buf-<os.arch>-<os.name>.exe or buf-<os.arch>-<os.name> exists.
* @param php the php binary or null
* @return The full name or null.
*/
public static String[] checkCgiBinary(String php) {
File location;
File phpFile = new File(php);
String path = phpFile.getParent();
String file = phpFile.getName();
StringBuffer buf = new StringBuffer();
if (path != null) {
buf.append(path);
buf.append(File.separatorChar);
}
buf.append(osArch);
buf.append("-");
buf.append(osName);
buf.append(File.separatorChar);
buf.append(file);
if (USE_SH_WRAPPER) {
location = new File(buf.toString() + ".sh");
if(Util.logLevel>3) Util.logDebug("trying: " + location);
if(location.exists()) return new String[] {"/bin/sh", location.getAbsolutePath()};
} else {
location = new File(buf.toString() + ".exe");
if(Util.logLevel>3) Util.logDebug("trying: " + location);
if(location.exists()) return new String[] {location.getAbsolutePath()};
}
location = new File(buf.toString());
if(Util.logLevel>3) Util.logDebug("trying: " + location);
if(location.exists()) return new String[] {location.getAbsolutePath()};
return null;
}
/**
* Returns s if s contains "PHP Fatal error:";
* @param s The error string
* @return The fatal error or null
*/
public static String checkError(String s) {
// Is there a better way to check for a fatal error?
return (s.startsWith("PHP") && (s.indexOf("error:")>-1)) ? s : null;
}
/**
* Convenience daemon thread class
*/
public static class Thread extends java.lang.Thread {
/**Create a new thread */
public Thread() {
super();
initThread();
}
/**Create a new thread
* @param name */
public Thread(String name) {
super(name);
initThread();
}
/**Create a new thread
* @param target */
public Thread(Runnable target) {
super(target);
initThread();
}
/**Create a new thread
* @param group
* @param target */
public Thread(ThreadGroup group, Runnable target) {
super(group, target);
initThread();
}
/**Create a new thread
* @param group
* @param name */
public Thread(ThreadGroup group, String name) {
super(group, name);
initThread();
}
/**Create a new thread
* @param target
* @param name */
public Thread(Runnable target, String name) {
super(target, name);
initThread();
}
/**Create a new thread
* @param group
* @param target
* @param name */
public Thread(ThreadGroup group, Runnable target, String name) {
super(group, target, name);
initThread();
}
/**Create a new thread
* @param group
* @param target
* @param name
* @param stackSize */
public Thread(ThreadGroup group, Runnable target, String name, long stackSize) {
super(group, target, name, stackSize);
initThread();
}
private void initThread() {
setDaemon(true);
}
}
/**
* Starts a CGI process and returns the process handle.
*/
public static class Process extends java.lang.Process {
protected java.lang.Process proc;
private String[] args;
private File homeDir;
private Map env;
private boolean tryOtherLocations;
private boolean preferSystemPhp;
private boolean isOldPhpVersion = false; // php < 5.3
private boolean includeJava;
private String cgiDir;
private String pearDir;
private String webInfDir;
private String getQuoted(String key, String val) {
if (isOldPhpVersion) return key+val;
StringBuffer buf = new StringBuffer(key);
buf.append("'");
buf.append(val);
buf.append("'");
return buf.toString();
}
/**
* Return args + PHP_ARGS
* @param args The prefix
* @param includeJava The option php_include_java
* @param cgiDir The WEB-INF/cgi directory
* @param pearDir The WEB-INF/pear directory
* @param webInfDir The WEB-INF directory
* @return args with PHP_ARGS appended
*/
private String[] getPhpArgs(String[] args, boolean includeJava, String cgiDir, String pearDir, String webInfDir) {
String[] allArgs = new String[args.length+PHP_ARGS.length+((sessionSavePath!=null)?2:0)+(includeJava?1:0)+(cgiDir!=null?2:0)+(pearDir!=null?2:0)+(webInfDir!=null?2:0)];
int i=0;
for(i=0; i<args.length; i++) {
allArgs[i]=args[i];
}
if (sessionSavePath!=null) {
allArgs[i++] = "-d";
allArgs[i++] = getQuoted("session.save_path=", sessionSavePath);
}
if (cgiDir!=null) {
File extDir = new File(cgiDir, Util.osArch+"-"+Util.osName);
try {
cgiDir = extDir.getCanonicalPath();
} catch (IOException e) {
Util.printStackTrace(e);
cgiDir = extDir.getAbsolutePath();
}
allArgs[i++] = "-d";
allArgs[i++] = getQuoted("java.os_arch_dir=",cgiDir);
}
if (pearDir!=null) {
allArgs[i++] = "-d";
allArgs[i++] = getQuoted("java.pear_dir=",pearDir);
}
if (webInfDir!=null) {
allArgs[i++] = "-d";
allArgs[i++] = getQuoted("java.web_inf_dir=",webInfDir);
}
if (includeJava) allArgs[i++] = "-C"; // don't chdir, we'll do it
for(int j=0; j<PHP_ARGS.length; j++) {
allArgs[i++]=PHP_ARGS[j];
}
return allArgs;
}
protected String[] quoteArgs(String[] s) {
// quote all args for windows
if (!USE_SH_WRAPPER)
for(int j=0; j<s.length; j++)
if(s[j]!=null) s[j] = "\""+s[j]+"\"";
return s;
}
protected boolean testPhp(String[] php, String[] args) {
Runtime rt = Runtime.getRuntime();
String[] s = quoteArgs(getTestArgumentArray(php, args));
byte[] buf = new byte[BUF_SIZE];
int c, result, errCode;
InputStream in = null;
OutputStream out = null;
InputStream err = null;
try {
proc = rt.exec(s, hashToStringArray(env), homeDir);
in = proc.getInputStream();
err = proc.getErrorStream();
out = proc.getOutputStream();
out.close();
out = null;
while((c=err.read(buf))>0)
Util.logError(new String(buf, 0, c, ASCII));