/
Sys.java
625 lines (544 loc) · 20.2 KB
/
Sys.java
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
//
// Copyright (c) 2006, Brian Frank and Andy Frank
// Licensed under the Academic Free License version 3.0
//
// History:
// 2 Dec 05 Brian Frank Creation
//
package fan.sys;
import java.lang.ref.*;
import java.io.File;
import java.util.Iterator;
import java.lang.management.*;
import fanx.fcode.*;
import fanx.util.*;
/**
* Sys provides static access to the system's environment and initializes
* key data structures in a specific order in its static initializer.
*/
public final class Sys
{
//////////////////////////////////////////////////////////////////////////
// Fields (loaded before type constants)
//////////////////////////////////////////////////////////////////////////
/** Env.os constant */
public static final String os = initOs();
/** Env.arch constant */
public static final String arch = initArch();
/** Env.platform constant */
public static final String platform = os + "-" + arch;
/** Booting from only a JAR distribution? */
public static final boolean isJarDist = initIsJarDist();
/** BootEnv.homeDir */
public static final File homeDir = initHomeDir();
/** {BootEnv.homeDir}/lib/fan/ */
public static final File podsDir = initPodsDir();
/** {BootEnv.homeDir}/lib/fan/sys.pod */
public static final Pod sysPod = initSysPod();
//////////////////////////////////////////////////////////////////////////
// Java Version
//////////////////////////////////////////////////////////////////////////
public static int JAVA_1_5 = 5;
public static int JAVA_1_6 = 6;
public static int JAVA_1_7 = 7;
public static int JAVA_1_8 = 8;
/** Java version as single integer (e.g. 8, 9). This is the way Java9+
* specifies the version now. */
public static int javaVersion = initJavaVersion();
//////////////////////////////////////////////////////////////////////////
// Fields (type constants)
//////////////////////////////////////////////////////////////////////////
// the Eve of all types
public static final Type ObjType = initType("Obj");
// basic primitives
public static final Type NumType = initType("Num");
public static final Type EnumType = initType("Enum");
public static final Type FacetType = initType("Facet");
public static final Type BoolType = initType("Bool");
public static final Type DurationType = initType("Duration");
public static final Type FuncType = initType("Func");
public static final Type IntType = initType("Int");
public static final Type DecimalType = initType("Decimal");
public static final Type FloatType = initType("Float");
public static final Type ListType = initType("List");
public static final Type MapType = initType("Map");
public static final Type MonthType = initType("Month");
public static final Type PodType = initType("Pod");
public static final Type RangeType = initType("Range");
public static final Type StrType = initType("Str");
public static final Type StrBufType = initType("StrBuf");
public static final Type TestType = initType("Test");
public static final Type DateTimeType = initType("DateTime");
public static final Type DateType = initType("Date");
public static final Type TimeType = initType("Time");
public static final Type TimeZoneType = initType("TimeZone");
public static final Type TypeType = initType("Type");
public static final Type WeekdayType = initType("Weekday");
public static final Type ThisType = initType("This");
public static final Type VoidType = initType("Void");
public static final Type EnvType = initType("Env");
public static final Type BootEnvType = initType("BootEnv");
public static final Type JarDistEnvType = initType("JarDistEnv");
// reflection
public static final Type SlotType = initType("Slot");
public static final Type FieldType = initType("Field");
public static final Type MethodType = initType("Method");
public static final Type ParamType = initType("Param");
// IO
public static final Type CharsetType = initType("Charset");
public static final Type EndianType = initType("Endian");
public static final Type InStreamType = initType("InStream");
public static final Type SysInStreamType = initType("SysInStream");
public static final Type OutStreamType = initType("OutStream");
public static final Type SysOutStreamType = initType("SysOutStream");
public static final Type FileType = initType("File");
public static final Type LocalFileType = initType("LocalFile");
public static final Type ZipEntryFileType = initType("ZipEntryFile");
public static final Type MemFileType = initType("MemFile");
public static final Type PathFileType = initType("PathFile");
public static final Type BufType = initType("Buf");
public static final Type MemBufType = initType("MemBuf");
public static final Type ConstBufType = initType("ConstBuf");
public static final Type FileBufType = initType("FileBuf");
public static final Type NioBufType = initType("NioBuf");
public static final Type UriType = initType("Uri");
public static final Type ZipType = initType("Zip");
public static final Type ClassLoaderFileType = initType("ClassLoaderFile");
public static final Type FileStoreType = initType("FileStore");
public static final Type LocalFileStoreType = initType("LocalFileStore");
// utils
public static final Type DependType = initType("Depend");
public static final Type LogType = initType("Log");
public static final Type LogLevelType = initType("LogLevel");
public static final Type LogRecType = initType("LogRec");
public static final Type LocaleType = initType("Locale");
public static final Type MimeTypeType = initType("MimeType");
public static final Type ProcessType = initType("Process");
public static final Type RegexType = initType("Regex");
public static final Type RegexMatcherType = initType("RegexMatcher");
public static final Type ServiceType = initType("Service");
public static final Type VersionType = initType("Version");
public static final Type UnitType = initType("Unit");
public static final Type UnsafeType = initType("Unsafe");
public static final Type UuidType = initType("Uuid");
// uri schemes
public static final Type UriSchemeType = initType("UriScheme");
public static final Type FanSchemeType = initType("FanScheme");
public static final Type FileSchemeType = initType("FileScheme");
// facets
public static final Type TransientType = initType("Transient");
public static final Type SerializableType = initType("Serializable");
public static final Type JsType = initType("Js");
public static final Type NoDocType = initType("NoDoc");
public static final Type DeprecatedType = initType("Deprecated");
public static final Type OperatorType = initType("Operator");
public static final Type FacetMetaType = initType("FacetMeta");
// exceptions
public static final Type ErrType = initType("Err");
public static final Type ArgErrType = initType("ArgErr");
public static final Type CancelledErrType = initType("CancelledErr");
public static final Type CastErrType = initType("CastErr");
public static final Type ConstErrType = initType("ConstErr");
public static final Type FieldNotSetErrType = initType("FieldNotSetErr");
public static final Type IOErrType = initType("IOErr");
public static final Type IndexErrType = initType("IndexErr");
public static final Type InterruptedErrType = initType("InterruptedErr");
public static final Type NameErrType = initType("NameErr");
public static final Type NotImmutableErrType = initType("NotImmutableErr");
public static final Type NullErrType = initType("NullErr");
public static final Type ParseErrType = initType("ParseErr");
public static final Type ReadonlyErrType = initType("ReadonlyErr");
public static final Type TestErrType = initType("TestErr");
public static final Type TimeoutErrType = initType("TimeoutErr");
public static final Type UnknownKeyErrType = initType("UnknownKeyErr");
public static final Type UnknownPodErrType = initType("UnknownPodErr");
public static final Type UnknownServiceErrType = initType("UnknownServiceErr");
public static final Type UnknownSlotErrType = initType("UnknownSlotErr");
public static final Type UnknownFacetErrType = initType("UnknownFacetErr");
public static final Type UnknownTypeErrType = initType("UnknownTypeErr");
public static final Type UnresolvedErrType = initType("UnresolvedErr");
public static final Type UnsupportedErrType = initType("UnsupportedErr");
// generic parameter types used with generic types List, Map, and Method
static final ClassType[] genericParamTypes = new ClassType[256];
public static final ClassType AType = initGeneric('A');
public static final ClassType BType = initGeneric('B');
public static final ClassType CType = initGeneric('C');
public static final ClassType DType = initGeneric('D');
public static final ClassType EType = initGeneric('E');
public static final ClassType FType = initGeneric('F');
public static final ClassType GType = initGeneric('G');
public static final ClassType HType = initGeneric('H');
public static final ClassType KType = initGeneric('K');
public static final ClassType LType = initGeneric('L');
public static final ClassType MType = initGeneric('M');
public static final ClassType RType = initGeneric('R');
public static final ClassType VType = initGeneric('V');
static { initGenericParamTypes(); }
//////////////////////////////////////////////////////////////////////////
// Fields (loaded after type constants)
//////////////////////////////////////////////////////////////////////////
/** Empty Str:Obj? map */
public static final Map emptyStrObjMap = initEmptyStrMap(ObjType.toNullable());
/** Empty Str:Str map */
public static final Map emptyStrStrMap = initEmptyStrMap(StrType);
/** Empty Str:Type map */
public static final Map emptyStrTypeMap = initEmptyStrMap(TypeType);
/** Bootstrap environment */
public static final BootEnv bootEnv = new BootEnv();
static Env curEnv = bootEnv;
/** {BootEnv.homeDir}/etc/sys/config.props */
public static final Map sysConfig = initSysConfig();
/** Config prop used to generating debug attributes in bytecode */
public static final boolean debug = sysConfigBool("debug", false);
/** Config prop used to determine max stack trace */
public static final int errTraceMaxDepth = sysConfigInt("errTraceMaxDepth", 25);
/** Absolute boot time */
public static final DateTime bootDateTime = initBootDateTime();
/** Relative boot time */
public static final Duration bootDuration = initBootDuration();
/** Current environment - do this after sys fully booted */
static
{
initEnv();
initEnvClassPath();
}
//////////////////////////////////////////////////////////////////////////
// Platform Init
//////////////////////////////////////////////////////////////////////////
private static String initOs()
{
try
{
String os = System.getProperty("os.name", "unknown");
os = sanitize(os);
if (os.contains("win")) return "win32";
if (os.contains("mac")) return "macosx";
if (os.contains("sunos")) return "solaris";
return os;
}
catch (Throwable e)
{
throw initFail("os", e);
}
}
private static String initArch()
{
try
{
String arch = System.getProperty("os.arch", "unknown");
arch = sanitize(arch);
if (arch.contains("i386")) return "x86";
if (arch.contains("amd64")) return "x86_64";
return arch;
}
catch (Throwable e)
{
throw initFail("arch", e);
}
}
private static String sanitize(String s)
{
StringBuilder buf = new StringBuilder();
for (int i=0; i<s.length(); ++i)
{
int c = s.charAt(i);
if (c == '_') { buf.append((char)c); continue; }
if ('a' <= c && c <= 'z') { buf.append((char)c); continue; }
if ('0' <= c && c <= '9') { buf.append((char)c); continue; }
if ('A' <= c && c <= 'Z') { buf.append((char)(c | 0x20)); continue; }
// skip it
}
return buf.toString();
}
//////////////////////////////////////////////////////////////////////////
// Init isJarDist
//////////////////////////////////////////////////////////////////////////
private static boolean initIsJarDist()
{
return System.getProperty("fan.jardist", "false").equals("true");
}
//////////////////////////////////////////////////////////////////////////
// Dir Init
//////////////////////////////////////////////////////////////////////////
private static File initHomeDir()
{
try
{
return sysPropToDir("fan.home", "FAN_HOME", null);
}
catch (Throwable e)
{
throw initFail("homeDir", e);
}
}
private static File initPodsDir()
{
try
{
return new File(homeDir, "lib" + File.separator + "fan");
}
catch (Throwable e)
{
throw initFail("podsDir", e);
}
}
private static File sysPropToDir(String propKey, String envKey, String def)
{
// lookup system property
String val = System.getProperty(propKey);
// fallback to environment variable
if (val == null)
val = System.getenv(envKey);
if (val == null)
val = System.getenv(FanStr.lower(envKey));
// fallback to def if provides
if (val == null && def != null)
val = def;
// if still not found then we're toast
if (val == null)
throw new RuntimeException("Missing " + propKey + " system property or " + envKey + " env var");
// check that val ends in trailing newline
if (!val.endsWith("/")) val += "/";
// map to java.io.File and check that it is a valid directory
File f = new File(val);
if (!f.exists() || !f.isDirectory())
throw new RuntimeException("Invalid " + propKey + " dir: " + f);
return f;
}
//////////////////////////////////////////////////////////////////////////
// Init Sys Pod
//////////////////////////////////////////////////////////////////////////
static Pod initSysPod()
{
try
{
return Pod.doFind("sys", true, null, null);
}
catch (Throwable e)
{
throw initFail("sysPod", e);
}
}
//////////////////////////////////////////////////////////////////////////
// Init Java Version
//////////////////////////////////////////////////////////////////////////
static int initJavaVersion()
{
String s = null;
try
{
s = System.getProperty("java.vm.specification.version", "1.5");
// Java 1.8 and earlier uses 1.x for version. Get 'x'
if (s.startsWith("1.")) s = s.substring(2,3);
return Integer.parseInt(s);
}
catch (Throwable e)
{
throw initFail("javaVersion: " + s, e);
}
}
//////////////////////////////////////////////////////////////////////////
// Init Types
//////////////////////////////////////////////////////////////////////////
static Type initType(String name)
{
try
{
return sysPod.type(name, true);
}
catch (Throwable e)
{
throw initFail("type " + name, e);
}
}
private static ClassType initGeneric(int ch)
{
String name = String.valueOf((char)ch);
try
{
return genericParamTypes[ch] = new ClassType(sysPod, name, 0, null);
}
catch (Throwable e)
{
throw initFail("generic " + name, e);
}
}
private static void initGenericParamTypes()
{
List noMixins = new List(TypeType, 0).ro();
for (int i=0; i<genericParamTypes.length; ++i)
{
ClassType gp = genericParamTypes[i];
if (gp == null) continue;
gp.base = ObjType;
gp.mixins = noMixins;
}
}
public static Type genericParamType(String name)
{
if (name.length() == 1 && name.charAt(0) < genericParamTypes.length)
return genericParamTypes[name.charAt(0)];
else
return null;
}
//////////////////////////////////////////////////////////////////////////
// Init Env
//////////////////////////////////////////////////////////////////////////
private static void initEnv()
{
try
{
// if running from JAR, we have to use special JarDistEnv
if (isJarDist)
{
curEnv = JarDistEnv.make();
return;
}
// check FAN_ENV environment variable
String var = (String)Env.cur().vars().get("FAN_ENV");
if (var != null)
{
curEnv = (Env)Type.find(var).make();
return;
}
// lookup up from current directory to find "fan.props" file
File dir = new File(".").getCanonicalFile();
while (dir != null)
{
File fanFile = new File(dir, "fan.props");
if (fanFile.exists())
{
curEnv = (Env)Type.find("util::PathEnv").method("makeProps").call(new LocalFile(fanFile));
return;
}
dir = dir.getParentFile();
}
}
catch (Exception e)
{
initWarn("curEnv", e);
}
}
private static void initEnvClassPath()
{
try
{
// add environment's work dir to classpath
LocalFile homeDir = (LocalFile)curEnv.homeDir();
LocalFile workDir = (LocalFile)curEnv.workDir();
if (!homeDir.equals(workDir))
FanClassLoader.extClassLoader.addFanDir(workDir.file);
}
catch (Exception e)
{
initWarn("envClassPath", e);
}
}
//////////////////////////////////////////////////////////////////////////
// Empty Maps
//////////////////////////////////////////////////////////////////////////
private static Map initEmptyStrMap(Type v)
{
try
{
return (Map)new Map(StrType, v).toImmutable();
}
catch (Exception e)
{
throw initFail("emptyStrMap", e);
}
}
//////////////////////////////////////////////////////////////////////////
// Sys Config
//////////////////////////////////////////////////////////////////////////
private static Map initSysConfig()
{
try
{
String sep = java.io.File.separator;
LocalFile f = new LocalFile(new java.io.File(homeDir, "etc" + sep + "sys" + sep + "config.props"));
if (f.exists())
{
try
{
return f.readProps();
}
catch (Exception e)
{
System.out.println("ERROR: Invalid props file: " + f);
System.out.println(" " + e);
}
}
}
catch (Throwable e)
{
throw initFail("sysConfig", e);
}
return emptyStrStrMap;
}
static String sysConfig(String name)
{
// first try system property
String s = System.getenv("FAN_" + name.toUpperCase());
if (s != null) return s;
// fallback to etc/sys/config.props
return (String)sysConfig.get(name);
}
static boolean sysConfigBool(String name, boolean def)
{
String val = sysConfig(name);
if (val != null) return val.equals("true");
return def;
}
static int sysConfigInt(String name, int def)
{
try
{
String val = sysConfig(name);
if (val != null) return Integer.parseInt(val);
}
catch (Exception e) {}
return def;
}
//////////////////////////////////////////////////////////////////////////
// Boot Times
//////////////////////////////////////////////////////////////////////////
private static Duration initBootDuration()
{
try
{
return Duration.now();
}
catch (Throwable e)
{
throw initFail("bootDuration", e);
}
}
private static DateTime initBootDateTime()
{
try
{
return DateTime.now();
}
catch (Throwable e)
{
throw initFail("bootDuration", e);
}
}
//////////////////////////////////////////////////////////////////////////
// Utils
//////////////////////////////////////////////////////////////////////////
private static void initWarn(String field, Throwable e)
{
System.out.println("WARN: cannot init Sys." + field);
e.printStackTrace();
}
private static RuntimeException initFail(String field, Throwable e)
{
System.out.println("ERROR: cannot init Sys." + field);
e.printStackTrace();
throw new RuntimeException("Cannot boot fan: " + e.toString());
}
/** Force sys class to load */
public static void boot() {}
}