-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
OgnlRuntime.java
4126 lines (3651 loc) · 164 KB
/
OgnlRuntime.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
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
// --------------------------------------------------------------------------
// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Drew Davidson nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// --------------------------------------------------------------------------
package ognl;
import ognl.enhance.ExpressionCompiler;
import ognl.enhance.OgnlExpressionCompiler;
import ognl.internal.ClassCache;
import ognl.internal.ClassCacheImpl;
import ognl.security.OgnlSecurityManagerFactory;
import ognl.security.UserMethod;
import java.beans.*;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Utility class used by internal OGNL API to do various things like:
*
* <ul>
* <li>Handles majority of reflection logic / caching. </li>
* <li>Utility methods for casting strings / various numeric types used by {@link OgnlExpressionCompiler}.</li>
* <li>Core runtime configuration point for setting/using global {@link TypeConverter} / {@link OgnlExpressionCompiler} /
* {@link NullHandler} instances / etc.. </li>
* </ul>
*
* @author Luke Blanshard (blanshlu@netscape.net)
* @author Drew Davidson (drew@ognl.org)
*/
public class OgnlRuntime {
/**
* Constant expression used to indicate that a given method / property couldn't be found
* during reflection operations.
*/
public static final Object NotFound = new Object();
public static final List NotFoundList = new ArrayList();
public static final Map NotFoundMap = new HashMap();
public static final Object[] NoArguments = new Object[]{};
public static final Class[] NoArgumentTypes = new Class[]{};
/**
* Token returned by TypeConverter for no conversion possible
*/
public static final Object NoConversionPossible = "ognl.NoConversionPossible";
/**
* Not an indexed property
*/
public static int INDEXED_PROPERTY_NONE = 0;
/**
* JavaBeans IndexedProperty
*/
public static int INDEXED_PROPERTY_INT = 1;
/**
* OGNL ObjectIndexedProperty
*/
public static int INDEXED_PROPERTY_OBJECT = 2;
/**
* Constant string representation of null string.
*/
public static final String NULL_STRING = "" + null;
/**
* Java beans standard set method prefix.
*/
private static final String SET_PREFIX = "set";
/**
* Java beans standard get method prefix.
*/
private static final String GET_PREFIX = "get";
/**
* Java beans standard is<Foo> boolean getter prefix.
*/
private static final String IS_PREFIX = "is";
/**
* Prefix padding for hexadecimal numbers to HEX_LENGTH.
*/
private static final Map HEX_PADDING = new HashMap();
private static final int HEX_LENGTH = 8;
/**
* Returned by <CODE>getUniqueDescriptor()</CODE> when the object is <CODE>null</CODE>.
*/
private static final String NULL_OBJECT_STRING = "<null>";
/**
* Used to store the result of determining if current jvm is 1.5 language compatible.
*/
private static boolean _jdk15 = false;
private static boolean _jdkChecked = false;
/**
* Control usage of JDK9+ access handler using the JVM option:
* -Dognl.UseJDK9PlusAccessHandler=true
* -Dognl.UseJDK9PlusAccessHandler=false
*
* Note: Set to "true" to allow the new JDK9 and later behaviour, <b>provided a newer JDK9+
* is detected</b>. By default the standard pre-JDK9 AccessHandler will be used even when
* running on JDK9+, so users must "opt-in" in order to enable the alternate JDK9+ AccessHandler.
* Using the JDK9PlusAccessHandler <b>may</b> avoid / mask JDK9+ warnings of the form:
* "WARNING: Illegal reflective access by ognl.OgnlRuntime"
* or provide an alternative when running in environments set with "--illegal-access=deny".
*
* Note: The default behaviour is to use the standard pre-JDK9 access handler.
* Using the "false" value has the same effect as omitting the option completely.
*
* Warning: Users are <b>strongly advised</b> to review their code and confirm they really
* need the AccessHandler modifying access levels, looking at alternatives to avoid that need.
*/
static final String USE_JDK9PLUS_ACESS_HANDLER = "ognl.UseJDK9PlusAccessHandler";
/**
* Control usage of "stricter" invocation processing by invokeMethod() using the JVM options:
* -Dognl.UseStricterInvocation=true
* -Dognl.UseStricterInvocation=false
*
* Note: Using the "true" value has the same effect as omitting the option completely.
* The default behaviour is to use the "stricter" invocation processing.
* Using the "false" value reverts to the older "less strict" invocation processing
* (in the event the "stricter" processing causes issues for existing applications).
*/
static final String USE_STRICTER_INVOCATION = "ognl.UseStricterInvocation";
/**
* Hold environment flag state associated with USE_JDK9PLUS_ACESS_HANDLER.
* Default: false (if not set)
*/
private static final boolean _useJDK9PlusAccessHandler;
static {
boolean initialFlagState = false;
try {
final String propertyString = System.getProperty(USE_JDK9PLUS_ACESS_HANDLER);
if (propertyString != null && propertyString.length() > 0) {
initialFlagState = Boolean.parseBoolean(propertyString);
}
} catch (Exception ex) {
// Unavailable (SecurityException, etc.)
}
_useJDK9PlusAccessHandler = initialFlagState;
}
/**
* Hold environment flag state associated with USE_STRICTER_INVOCATION.
* Default: true (if not set)
*/
private static final boolean _useStricterInvocation;
static {
boolean initialFlagState = true;
try {
final String propertyString = System.getProperty(USE_STRICTER_INVOCATION);
if (propertyString != null && propertyString.length() > 0) {
initialFlagState = Boolean.parseBoolean(propertyString);
}
} catch (Exception ex) {
// Unavailable (SecurityException, etc.)
}
_useStricterInvocation = initialFlagState;
}
/*
* Attempt to detect the system-reported Major Java Version (e.g. 5, 7, 11).
*/
private static final int _majorJavaVersion = detectMajorJavaVersion();
private static final boolean _jdk9Plus = _majorJavaVersion >= 9;
/*
* Assign an accessibility modification mechanism, based on Major Java Version and Java option flag
* flag {@link OgnlRuntime#USE_JDK9PLUS_ACESS_HANDLER}.
*
* Note: Will use the standard Pre-JDK9 accessibility modification mechanism unless OGNL is running
* on JDK9+ and the Java option flag has also been set true.
*/
private static final AccessibleObjectHandler _accessibleObjectHandler;
static {
_accessibleObjectHandler = usingJDK9PlusAccessHandler() ? AccessibleObjectHandlerJDK9Plus.createHandler() :
AccessibleObjectHandlerPreJDK9.createHandler();
}
/**
* Private references for use in blocking direct invocation by invokeMethod().
*/
private static final Method SYS_CONSOLE_REF;
private static final Method SYS_EXIT_REF;
private static final Method AO_SETACCESSIBLE_REF;
private static final Method AO_SETACCESSIBLE_ARR_REF;
/**
* Initialize the Method references used for blocking usage within invokeMethod().
*/
static {
Method setAccessibleMethod = null;
Method setAccessibleMethodArray = null;
Method systemExitMethod = null;
Method systemConsoleMethod = null;
try {
setAccessibleMethod = AccessibleObject.class.getMethod("setAccessible", new Class<?>[]{boolean.class});
} catch (NoSuchMethodException nsme) {
// Should not happen. To debug, uncomment the next line.
//throw new IllegalStateException("OgnlRuntime initialization missing setAccessible method", nsme);
} catch (SecurityException se) {
// May be blocked by existing SecurityManager. To debug, uncomment the next line.
//throw new SecurityException("OgnlRuntime initialization cannot access setAccessible method", se);
} finally {
AO_SETACCESSIBLE_REF = setAccessibleMethod;
}
try {
setAccessibleMethodArray = AccessibleObject.class.getMethod("setAccessible", new Class<?>[]{AccessibleObject[].class, boolean.class});
} catch (NoSuchMethodException nsme) {
// Should not happen. To debug, uncomment the next line.
//throw new IllegalStateException("OgnlRuntime initialization missing setAccessible method", nsme);
} catch (SecurityException se) {
// May be blocked by existing SecurityManager. To debug, uncomment the next line.
//throw new SecurityException("OgnlRuntime initialization cannot access setAccessible method", se);
} finally {
AO_SETACCESSIBLE_ARR_REF = setAccessibleMethodArray;
}
try {
systemExitMethod = System.class.getMethod("exit", new Class<?>[]{int.class});
} catch (NoSuchMethodException nsme) {
// Should not happen. To debug, uncomment the next line.
//throw new IllegalStateException("OgnlRuntime initialization missing exit method", nsme);
} catch (SecurityException se) {
// May be blocked by existing SecurityManager. To debug, uncomment the next line.
//throw new SecurityException("OgnlRuntime initialization cannot access exit method", se);
} finally {
SYS_EXIT_REF = systemExitMethod;
}
try {
systemConsoleMethod = System.class.getMethod("console", new Class<?>[]{}); // Not available in JDK 1.5 or earlier
} catch (NoSuchMethodException nsme) {
// May happen for JDK 1.5 and earlier. To debug, uncomment the next line.
//throw new IllegalStateException("OgnlRuntime initialization missing console method", nsme);
} catch (SecurityException se) {
// May be blocked by existing SecurityManager. To debug, uncomment the next line.
//throw new SecurityException("OgnlRuntime initialization cannot access console method", se);
} finally {
SYS_CONSOLE_REF = systemConsoleMethod;
}
}
/**
* Control usage of the OGNL Security Manager using the JVM option:
* -Dognl.security.manager=true (or any non-null value other than 'disable')
*
* Omit '-Dognl.security.manager=' or nullify the property to disable the feature.
*
* To forcibly disable the feature (only possible at OGNL Library initialization, use the option:
* -Dognl.security.manager=forceDisableOnInit
*
* Users that have their own Security Manager implementations and no intention to use the OGNL SecurityManager
* sandbox may choose to use the 'forceDisableOnInit' flag option for performance reasons (avoiding overhead
* involving the system property security checks - when that feature will not be used).
*/
static final String OGNL_SECURITY_MANAGER = "ognl.security.manager";
static final String OGNL_SM_FORCE_DISABLE_ON_INIT = "forceDisableOnInit";
/**
* Hold environment flag state associated with OGNL_SECURITY_MANAGER. See
* {@link OgnlRuntime#OGNL_SECURITY_MANAGER} for more details.
* Default: false (if not set).
*/
private static final boolean _disableOgnlSecurityManagerOnInit;
static {
boolean initialFlagState = false;
try {
final String propertyString = System.getProperty(OGNL_SECURITY_MANAGER);
if (propertyString != null && propertyString.length() > 0) {
initialFlagState = OGNL_SM_FORCE_DISABLE_ON_INIT.equalsIgnoreCase(propertyString);
}
} catch (Exception ex) {
// Unavailable (SecurityException, etc.)
}
_disableOgnlSecurityManagerOnInit = initialFlagState;
}
/**
* Allow users to revert to the old "first match" lookup for getters/setters by OGNL using the JVM options:
* -Dognl.UseFirstMatchGetSetLookup=true
* -Dognl.UseFirstMatchGetSetLookup=false
*
* Note: Using the "false" value has the same effect as omitting the option completely.
* The default behaviour is to use the "best match" lookup for getters/setters.
* Using the "true" value reverts to the older "first match" lookup for getters/setters
* (in the event the "best match" processing causes issues for existing applications).
*/
static final String USE_FIRSTMATCH_GETSET_LOOKUP = "ognl.UseFirstMatchGetSetLookup";
/**
* Hold environment flag state associated with USE_FIRSTMATCH_GETSET_LOOKUP.
* Default: false (if not set)
*/
private static final boolean _useFirstMatchGetSetLookup;
static {
boolean initialFlagState = false;
try {
final String propertyString = System.getProperty(USE_FIRSTMATCH_GETSET_LOOKUP);
if (propertyString != null && propertyString.length() > 0) {
initialFlagState = Boolean.parseBoolean(propertyString);
}
} catch (Exception ex) {
// Unavailable (SecurityException, etc.)
}
_useFirstMatchGetSetLookup = initialFlagState;
}
static final ClassCache _methodAccessors = new ClassCacheImpl();
static final ClassCache _propertyAccessors = new ClassCacheImpl();
static final ClassCache _elementsAccessors = new ClassCacheImpl();
static final ClassCache _nullHandlers = new ClassCacheImpl();
static final ClassCache _propertyDescriptorCache = new ClassCacheImpl();
static final ClassCache _constructorCache = new ClassCacheImpl();
static final ClassCache _staticMethodCache = new ClassCacheImpl();
static final ClassCache _instanceMethodCache = new ClassCacheImpl();
static final ClassCache _invokePermissionCache = new ClassCacheImpl();
static final ClassCache _fieldCache = new ClassCacheImpl();
static final List _superclasses = new ArrayList(); /* Used by fieldCache lookup */
static final ClassCache[] _declaredMethods = new ClassCache[]{new ClassCacheImpl(), new ClassCacheImpl()};
static final Map _primitiveTypes = new HashMap(101);
static final ClassCache _primitiveDefaults = new ClassCacheImpl();
static final Map _methodParameterTypesCache = new HashMap(101);
static final Map _genericMethodParameterTypesCache = new HashMap(101);
static final Map _ctorParameterTypesCache = new HashMap(101);
static SecurityManager _securityManager = System.getSecurityManager();
static final EvaluationPool _evaluationPool = new EvaluationPool();
static final ObjectArrayPool _objectArrayPool = new ObjectArrayPool();
static final Map<Method, Boolean> _methodAccessCache = new ConcurrentHashMap<Method, Boolean>();
static final Map<Method, Boolean> _methodPermCache = new ConcurrentHashMap<Method, Boolean>();
static final ClassPropertyMethodCache cacheSetMethod = new ClassPropertyMethodCache();
static final ClassPropertyMethodCache cacheGetMethod = new ClassPropertyMethodCache();
static ClassCacheInspector _cacheInspector;
/**
* Expression compiler used by {@link Ognl#compileExpression(OgnlContext, Object, String)} calls.
*/
private static OgnlExpressionCompiler _compiler;
/**
* Lazy loading of Javassist library
*/
static {
try {
Class.forName("javassist.ClassPool");
_compiler = new ExpressionCompiler();
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Javassist library is missing in classpath! Please add missed dependency!",e);
} catch (RuntimeException rt) {
throw new IllegalStateException("Javassist library cannot be loaded, is it restricted by runtime environment?");
}
}
private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
private static IdentityHashMap PRIMITIVE_WRAPPER_CLASSES = new IdentityHashMap();
/**
* Used to provide primitive type equivalent conversions into and out of
* native / object types.
*/
static {
PRIMITIVE_WRAPPER_CLASSES.put(Boolean.TYPE, Boolean.class);
PRIMITIVE_WRAPPER_CLASSES.put(Boolean.class, Boolean.TYPE);
PRIMITIVE_WRAPPER_CLASSES.put(Byte.TYPE, Byte.class);
PRIMITIVE_WRAPPER_CLASSES.put(Byte.class, Byte.TYPE);
PRIMITIVE_WRAPPER_CLASSES.put(Character.TYPE, Character.class);
PRIMITIVE_WRAPPER_CLASSES.put(Character.class, Character.TYPE);
PRIMITIVE_WRAPPER_CLASSES.put(Short.TYPE, Short.class);
PRIMITIVE_WRAPPER_CLASSES.put(Short.class, Short.TYPE);
PRIMITIVE_WRAPPER_CLASSES.put(Integer.TYPE, Integer.class);
PRIMITIVE_WRAPPER_CLASSES.put(Integer.class, Integer.TYPE);
PRIMITIVE_WRAPPER_CLASSES.put(Long.TYPE, Long.class);
PRIMITIVE_WRAPPER_CLASSES.put(Long.class, Long.TYPE);
PRIMITIVE_WRAPPER_CLASSES.put(Float.TYPE, Float.class);
PRIMITIVE_WRAPPER_CLASSES.put(Float.class, Float.TYPE);
PRIMITIVE_WRAPPER_CLASSES.put(Double.TYPE, Double.class);
PRIMITIVE_WRAPPER_CLASSES.put(Double.class, Double.TYPE);
}
private static final Map NUMERIC_CASTS = new HashMap();
/**
* Constant strings for casting different primitive types.
*/
static {
NUMERIC_CASTS.put(Double.class, "(double)");
NUMERIC_CASTS.put(Float.class, "(float)");
NUMERIC_CASTS.put(Integer.class, "(int)");
NUMERIC_CASTS.put(Long.class, "(long)");
NUMERIC_CASTS.put(BigDecimal.class, "(double)");
NUMERIC_CASTS.put(BigInteger.class, "");
}
private static final Map NUMERIC_VALUES = new HashMap();
/**
* Constant strings for getting the primitive value of different
* native types on the generic {@link Number} object interface. (or the less
* generic BigDecimal/BigInteger types)
*/
static {
NUMERIC_VALUES.put(Double.class, "doubleValue()");
NUMERIC_VALUES.put(Float.class, "floatValue()");
NUMERIC_VALUES.put(Integer.class, "intValue()");
NUMERIC_VALUES.put(Long.class, "longValue()");
NUMERIC_VALUES.put(Short.class, "shortValue()");
NUMERIC_VALUES.put(Byte.class, "byteValue()");
NUMERIC_VALUES.put(BigDecimal.class, "doubleValue()");
NUMERIC_VALUES.put(BigInteger.class, "doubleValue()");
NUMERIC_VALUES.put(Boolean.class, "booleanValue()");
}
private static final Map NUMERIC_LITERALS = new HashMap();
/**
* Numeric primitive literal string expressions.
*/
static {
NUMERIC_LITERALS.put(Integer.class, "");
NUMERIC_LITERALS.put(Integer.TYPE, "");
NUMERIC_LITERALS.put(Long.class, "l");
NUMERIC_LITERALS.put(Long.TYPE, "l");
NUMERIC_LITERALS.put(BigInteger.class, "d");
NUMERIC_LITERALS.put(Float.class, "f");
NUMERIC_LITERALS.put(Float.TYPE, "f");
NUMERIC_LITERALS.put(Double.class, "d");
NUMERIC_LITERALS.put(Double.TYPE, "d");
NUMERIC_LITERALS.put(BigInteger.class, "d");
NUMERIC_LITERALS.put(BigDecimal.class, "d");
}
private static final Map NUMERIC_DEFAULTS = new HashMap();
static {
NUMERIC_DEFAULTS.put(Boolean.class, Boolean.FALSE);
NUMERIC_DEFAULTS.put(Byte.class, new Byte((byte) 0));
NUMERIC_DEFAULTS.put(Short.class, new Short((short) 0));
NUMERIC_DEFAULTS.put(Character.class, new Character((char) 0));
NUMERIC_DEFAULTS.put(Integer.class, new Integer(0));
NUMERIC_DEFAULTS.put(Long.class, new Long(0L));
NUMERIC_DEFAULTS.put(Float.class, new Float(0.0f));
NUMERIC_DEFAULTS.put(Double.class, new Double(0.0));
NUMERIC_DEFAULTS.put(BigInteger.class, new BigInteger("0"));
NUMERIC_DEFAULTS.put(BigDecimal.class, new BigDecimal(0.0));
}
static {
PropertyAccessor p = new ArrayPropertyAccessor();
setPropertyAccessor(Object.class, new ObjectPropertyAccessor());
setPropertyAccessor(byte[].class, p);
setPropertyAccessor(short[].class, p);
setPropertyAccessor(char[].class, p);
setPropertyAccessor(int[].class, p);
setPropertyAccessor(long[].class, p);
setPropertyAccessor(float[].class, p);
setPropertyAccessor(double[].class, p);
setPropertyAccessor(Object[].class, p);
setPropertyAccessor(List.class, new ListPropertyAccessor());
setPropertyAccessor(Map.class, new MapPropertyAccessor());
setPropertyAccessor(Set.class, new SetPropertyAccessor());
setPropertyAccessor(Iterator.class, new IteratorPropertyAccessor());
setPropertyAccessor(Enumeration.class, new EnumerationPropertyAccessor());
ElementsAccessor e = new ArrayElementsAccessor();
setElementsAccessor(Object.class, new ObjectElementsAccessor());
setElementsAccessor(byte[].class, e);
setElementsAccessor(short[].class, e);
setElementsAccessor(char[].class, e);
setElementsAccessor(int[].class, e);
setElementsAccessor(long[].class, e);
setElementsAccessor(float[].class, e);
setElementsAccessor(double[].class, e);
setElementsAccessor(Object[].class, e);
setElementsAccessor(Collection.class, new CollectionElementsAccessor());
setElementsAccessor(Map.class, new MapElementsAccessor());
setElementsAccessor(Iterator.class, new IteratorElementsAccessor());
setElementsAccessor(Enumeration.class, new EnumerationElementsAccessor());
setElementsAccessor(Number.class, new NumberElementsAccessor());
NullHandler nh = new ObjectNullHandler();
setNullHandler(Object.class, nh);
setNullHandler(byte[].class, nh);
setNullHandler(short[].class, nh);
setNullHandler(char[].class, nh);
setNullHandler(int[].class, nh);
setNullHandler(long[].class, nh);
setNullHandler(float[].class, nh);
setNullHandler(double[].class, nh);
setNullHandler(Object[].class, nh);
MethodAccessor ma = new ObjectMethodAccessor();
setMethodAccessor(Object.class, ma);
setMethodAccessor(byte[].class, ma);
setMethodAccessor(short[].class, ma);
setMethodAccessor(char[].class, ma);
setMethodAccessor(int[].class, ma);
setMethodAccessor(long[].class, ma);
setMethodAccessor(float[].class, ma);
setMethodAccessor(double[].class, ma);
setMethodAccessor(Object[].class, ma);
_primitiveTypes.put("boolean", Boolean.TYPE);
_primitiveTypes.put("byte", Byte.TYPE);
_primitiveTypes.put("short", Short.TYPE);
_primitiveTypes.put("char", Character.TYPE);
_primitiveTypes.put("int", Integer.TYPE);
_primitiveTypes.put("long", Long.TYPE);
_primitiveTypes.put("float", Float.TYPE);
_primitiveTypes.put("double", Double.TYPE);
_primitiveDefaults.put(Boolean.TYPE, Boolean.FALSE);
_primitiveDefaults.put(Boolean.class, Boolean.FALSE);
_primitiveDefaults.put(Byte.TYPE, new Byte((byte) 0));
_primitiveDefaults.put(Byte.class, new Byte((byte) 0));
_primitiveDefaults.put(Short.TYPE, new Short((short) 0));
_primitiveDefaults.put(Short.class, new Short((short) 0));
_primitiveDefaults.put(Character.TYPE, new Character((char) 0));
_primitiveDefaults.put(Integer.TYPE, new Integer(0));
_primitiveDefaults.put(Long.TYPE, new Long(0L));
_primitiveDefaults.put(Float.TYPE, new Float(0.0f));
_primitiveDefaults.put(Double.TYPE, new Double(0.0));
_primitiveDefaults.put(BigInteger.class, new BigInteger("0"));
_primitiveDefaults.put(BigDecimal.class, new BigDecimal(0.0));
}
/**
* Clears all of the cached reflection information normally used
* to improve the speed of expressions that operate on the same classes
* or are executed multiple times.
*
* <p>
* <strong>Warning:</strong> Calling this too often can be a huge performance
* drain on your expressions - use with care.
* </p>
*/
public static void clearCache()
{
synchronized(_methodParameterTypesCache) {
_methodParameterTypesCache.clear();
}
synchronized(_ctorParameterTypesCache) {
_ctorParameterTypesCache.clear();
}
synchronized(_propertyDescriptorCache) {
_propertyDescriptorCache.clear();
}
synchronized(_constructorCache) {
_constructorCache.clear();
}
synchronized(_staticMethodCache) {
_staticMethodCache.clear();
}
synchronized(_instanceMethodCache) {
_instanceMethodCache.clear();
}
synchronized(_invokePermissionCache) {
_invokePermissionCache.clear();
}
synchronized(_fieldCache) {
_fieldCache.clear();
_superclasses.clear(); // Used by fieldCache lookup (synchronized on _fieldCache).
}
synchronized(_declaredMethods[0]) {
_declaredMethods[0].clear();
}
synchronized(_declaredMethods[1]) {
_declaredMethods[1].clear();
}
_methodAccessCache.clear();
_methodPermCache.clear();
}
/**
* Clears some additional caches used by OgnlRuntime. The existing {@link OgnlRuntime#clearCache()}
* clears the standard reflection-related caches, but some applications may have need to clear
* the additional caches as well.
*
* Clearing the additional caches may have greater impact than the {@link OgnlRuntime#clearCache()}
* method so it should only be used when the normal cache clear is insufficient.
*
* <p>
* <strong>Warning:</strong> Calling this method too often can be a huge performance
* drain on your expressions - use with care.
* </p>
*
* @since 3.1.25
*/
public static void clearAdditionalCache()
{
cacheSetMethod.clear();
cacheGetMethod.clear();
synchronized(_genericMethodParameterTypesCache) {
_genericMethodParameterTypesCache.clear();
}
}
/**
* Checks if the current jvm is java language >= 1.5 compatible.
*
* @return True if jdk15 features are present.
*/
public static boolean isJdk15()
{
if (_jdkChecked)
return _jdk15;
try
{
Class.forName("java.lang.annotation.Annotation");
_jdk15 = true;
} catch (Exception e) { /* ignore */ }
_jdkChecked = true;
return _jdk15;
}
/**
* Get the Major Java Version detected by OGNL.
*
* @return Detected Major Java Version, or 5 (minimum supported version for OGNL) if unable to detect.
*/
public static int getMajorJavaVersion() {
return _majorJavaVersion;
}
/**
* Check if the detected Major Java Version is 9 or higher (JDK 9+).
*
* @return Return true if the Detected Major Java version is 9 or higher, otherwise false.
*/
public static boolean isJdk9Plus() {
return _jdk9Plus;
}
public static String getNumericValueGetter(Class type)
{
return (String) NUMERIC_VALUES.get(type);
}
public static Class getPrimitiveWrapperClass(Class primitiveClass)
{
return (Class) PRIMITIVE_WRAPPER_CLASSES.get(primitiveClass);
}
public static String getNumericCast(Class type)
{
return (String) NUMERIC_CASTS.get(type);
}
public static String getNumericLiteral(Class type)
{
return (String) NUMERIC_LITERALS.get(type);
}
public static void setCompiler(OgnlExpressionCompiler compiler)
{
_compiler = compiler;
}
public static OgnlExpressionCompiler getCompiler()
{
return _compiler;
}
public static void compileExpression(OgnlContext context, Node expression, Object root)
throws Exception
{
_compiler.compileExpression(context, expression, root);
}
/**
* Gets the "target" class of an object for looking up accessors that are registered on the
* target. If the object is a Class object this will return the Class itself, else it will
* return object's getClass() result.
*
* @param o the Object from which to retrieve its Class.
* @return the Class of o.
*/
public static Class getTargetClass(Object o)
{
return (o == null) ? null : ((o instanceof Class) ? (Class) o : o.getClass());
}
/**
* Returns the base name (the class name without the package name prepended) of the object
* given.
*
* @param o the Object from which to retrieve its base classname.
* @return the base classname of o's Class.
*/
public static String getBaseName(Object o)
{
return (o == null) ? null : getClassBaseName(o.getClass());
}
/**
* Returns the base name (the class name without the package name prepended) of the class given.
*
* @param c the Class from which to retrieve its name.
* @return the base classname of c.
*/
public static String getClassBaseName(Class c)
{
String s = c.getName();
return s.substring(s.lastIndexOf('.') + 1);
}
public static String getClassName(Object o, boolean fullyQualified)
{
if (!(o instanceof Class))
{
o = o.getClass();
}
return getClassName((Class) o, fullyQualified);
}
public static String getClassName(Class c, boolean fullyQualified)
{
return fullyQualified ? c.getName() : getClassBaseName(c);
}
/**
* Returns the package name of the object's class.
*
* @param o the Object from which to retrieve its Class package name.
* @return the package name of o's Class.
*/
public static String getPackageName(Object o)
{
return (o == null) ? null : getClassPackageName(o.getClass());
}
/**
* Returns the package name of the class given.
*
* @param c the Class from which to retrieve its package name.
* @return the package name of c.
*/
public static String getClassPackageName(Class c)
{
String s = c.getName();
int i = s.lastIndexOf('.');
return (i < 0) ? null : s.substring(0, i);
}
/**
* Returns a "pointer" string in the usual format for these things - 0x<hex digits>.
*
* @param num the int to convert into a "pointer" string in hex format.
* @return the String representing num as a "pointer" string in hex format.
*/
public static String getPointerString(int num)
{
StringBuffer result = new StringBuffer();
String hex = Integer.toHexString(num), pad;
Integer l = new Integer(hex.length());
// result.append(HEX_PREFIX);
if ((pad = (String) HEX_PADDING.get(l)) == null) {
StringBuffer pb = new StringBuffer();
for (int i = hex.length(); i < HEX_LENGTH; i++) {
pb.append('0');
}
pad = new String(pb);
HEX_PADDING.put(l, pad);
}
result.append(pad);
result.append(hex);
return new String(result);
}
/**
* Returns a "pointer" string in the usual format for these things - 0x<hex digits> for the
* object given. This will always return a unique value for each object.
*
* @param o the Object to convert into a "pointer" string in hex format.
* @return the String representing o as a "pointer" string in hex format.
*/
public static String getPointerString(Object o)
{
return getPointerString((o == null) ? 0 : System.identityHashCode(o));
}
/**
* Returns a unique descriptor string that includes the object's class and a unique integer
* identifier. If fullyQualified is true then the class name will be fully qualified to include
* the package name, else it will be just the class' base name.
*
* @param object the Object for which a unique descriptor string is desired.
* @param fullyQualified true if the descriptor string is fully-qualified (package name), false for just the Class' base name.
* @return the unique descriptor String for the object, qualified as per fullyQualified parameter.
*/
public static String getUniqueDescriptor(Object object, boolean fullyQualified)
{
StringBuffer result = new StringBuffer();
if (object != null) {
if (object instanceof Proxy) {
Class interfaceClass = object.getClass().getInterfaces()[0];
result.append(getClassName(interfaceClass, fullyQualified));
result.append('^');
object = Proxy.getInvocationHandler(object);
}
result.append(getClassName(object, fullyQualified));
result.append('@');
result.append(getPointerString(object));
} else {
result.append(NULL_OBJECT_STRING);
}
return new String(result);
}
/**
* Returns a unique descriptor string that includes the object's class' base name and a unique
* integer identifier.
*
* @param object the Object for which a unique descriptor string is desired.
* @return the unique descriptor String for the object, NOT fully-qualified.
*/
public static String getUniqueDescriptor(Object object)
{
return getUniqueDescriptor(object, false);
}
/**
* Utility to convert a List into an Object[] array. If the list is zero elements this will
* return a constant array; toArray() on List always returns a new object and this is wasteful
* for our purposes.
*
* @param list the List to convert into an Object array.
* @return the array of Objects from the list.
*/
public static Object[] toArray(List list)
{
Object[] result;
int size = list.size();
if (size == 0) {
result = NoArguments;
} else {
result = getObjectArrayPool().create(list.size());
for (int i = 0; i < size; i++) {
result[i] = list.get(i);
}
}
return result;
}
/**
* Returns the parameter types of the given method.
*
* @param m the Method whose parameter types are being queried.
* @return the array of Class elements representing m's parameters. May be null if m does not utilize parameters.
*/
public static Class[] getParameterTypes(Method m)
{
synchronized (_methodParameterTypesCache)
{
Class[] result;
if ((result = (Class[]) _methodParameterTypesCache.get(m)) == null)
{
_methodParameterTypesCache.put(m, result = m.getParameterTypes());
}
return result;
}
}
/**
* Finds the appropriate parameter types for the given {@link Method} and
* {@link Class} instance of the type the method is associated with. Correctly
* finds generic types if running in >= 1.5 jre as well.
*
* @param type The class type the method is being executed against.
* @param m The method to find types for.
* @return Array of parameter types for the given method.
*/
public static Class[] findParameterTypes(Class type, Method m)
{
Type[] genTypes = m.getGenericParameterTypes();
Class[] types = new Class[genTypes.length];;
boolean noGenericParameter = true;
for (int i=0; i < genTypes.length; i++)
{
if (Class.class.isInstance(genTypes[i]))
{
types[i] = (Class) genTypes[i];
continue;
}
noGenericParameter = false;
break;
}
if (noGenericParameter)
{
return types;
}
if (type == null || !isJdk15())
{
return getParameterTypes(m);
}
final Type typeGenericSuperclass = type.getGenericSuperclass();
if (typeGenericSuperclass == null
|| !ParameterizedType.class.isInstance(typeGenericSuperclass)
|| m.getDeclaringClass().getTypeParameters() == null)
{
return getParameterTypes(m);
}
if ((types = (Class[]) _genericMethodParameterTypesCache.get(m)) != null)
{
ParameterizedType genericSuperclass = (ParameterizedType) typeGenericSuperclass;
if (Arrays.equals(types, genericSuperclass.getActualTypeArguments())) {
return types;
}
}
ParameterizedType param = (ParameterizedType)typeGenericSuperclass;
TypeVariable[] declaredTypes = m.getDeclaringClass().getTypeParameters();
types = new Class[genTypes.length];
for (int i=0; i < genTypes.length; i++)
{
TypeVariable paramType = null;
if (TypeVariable.class.isInstance(genTypes[i]))
{
paramType = (TypeVariable)genTypes[i];
} else if (GenericArrayType.class.isInstance(genTypes[i]))
{
paramType = (TypeVariable) ((GenericArrayType)genTypes[i]).getGenericComponentType();
}
else if (ParameterizedType.class.isInstance(genTypes[i]))
{
types[i] = (Class) ((ParameterizedType) genTypes[i]).getRawType();
continue;
} else if (Class.class.isInstance(genTypes[i]))
{
types[i] = (Class) genTypes[i];
continue;
}
Class resolved = resolveType(param, paramType, declaredTypes);
if (resolved != null)