/
SDOHelperContext.java
1540 lines (1438 loc) · 66.3 KB
/
SDOHelperContext.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, 2024 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0,
* or the Eclipse Distribution License v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
// Contributors:
// Oracle - initial API and implementation from Oracle TopLink
// dmccann - Nov. 7/2008 - Added delegate key logic from AbstractHelperDelegator
// Dmitry Kornilov - 2014/11/25 - ApplicationAccessWLS fixed to reflect changes in WLS
package org.eclipse.persistence.sdo.helper;
import java.io.File;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.AttributeChangeNotification;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.Notification;
import javax.management.NotificationFilterSupport;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.eclipse.persistence.exceptions.SDOException;
import org.eclipse.persistence.internal.helper.Helper;
import org.eclipse.persistence.internal.identitymaps.CacheIdentityMap;
import org.eclipse.persistence.internal.identitymaps.CacheKey;
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
import org.eclipse.persistence.internal.security.PrivilegedGetMethod;
import org.eclipse.persistence.sdo.SDOResolvable;
import org.eclipse.persistence.sdo.SDOSystemProperties;
import org.eclipse.persistence.sdo.helper.delegates.SDODataFactoryDelegate;
import org.eclipse.persistence.sdo.helper.delegates.SDOTypeHelperDelegate;
import org.eclipse.persistence.sdo.helper.delegates.SDOTypeHelperDelegate.SDOWrapperTypeId;
import org.eclipse.persistence.sdo.helper.delegates.SDOXMLHelperDelegate;
import org.eclipse.persistence.sdo.helper.delegates.SDOXSDHelperDelegate;
import org.eclipse.persistence.sdo.types.SDOWrapperType;
import commonj.sdo.Type;
import commonj.sdo.helper.CopyHelper;
import commonj.sdo.helper.DataFactory;
import commonj.sdo.helper.DataHelper;
import commonj.sdo.helper.EqualityHelper;
import commonj.sdo.helper.HelperContext;
import commonj.sdo.helper.TypeHelper;
import commonj.sdo.helper.XMLHelper;
import commonj.sdo.helper.XSDHelper;
import commonj.sdo.impl.ExternalizableDelegator;
/**
* <b>Purpose:</b>
* <ul>
* <li>This class represents a local HelperContext. The global
* HelperContext can be accessed as HelperProvider.getDefaultContext().</li>
* </ul>
* <b>Responsibilities:</b>
* <ul>
* <li>Provide access to instances of helper objects.</li>
* <li>Provide an OSGi compatible HelperContext (when the constructor that takes
* a ClassLoader is used).</li>
* </ul>
*
* @since Oracle TopLink 11.1.1.0.0
*/
public class SDOHelperContext implements HelperContext {
private static final Logger LOGGER = Logger.getLogger(SDOHelperContext.class.getName());
protected CopyHelper copyHelper;
protected DataFactory dataFactory;
protected DataHelper dataHelper;
protected EqualityHelper equalityHelper;
protected XMLHelper xmlHelper;
protected TypeHelper typeHelper;
protected XSDHelper xsdHelper;
private String identifier;
private Map<String, Object> properties;
private boolean isStrictTypeCheckingEnabled = PrivilegedAccessHelper.getSystemPropertyBoolean(
SDOSystemProperties.SDO_STRICT_TYPE_CHECKING_PROPERTY_NAME, true);
/**
* Property controls strictness of {@link Type#getInstanceClass()} type checking.
*
* <p>
* See {@link #isStrictTypeCheckingEnabled()} for more details.
* By this property, the initial value can be changed.
* Default value is <code>true</code>.
* </p>
*
* @deprecated Use {@link org.eclipse.persistence.sdo.SDOSystemProperties#SDO_STRICT_TYPE_CHECKING_PROPERTY_NAME}.
*/
@Deprecated(since = "4.0", forRemoval = true)
public static final String STRICT_TYPE_CHECKING_PROPERTY_NAME = SDOSystemProperties.SDO_STRICT_TYPE_CHECKING_PROPERTY_NAME;
private static int helperContextsMaxSize = Integer.parseInt(PrivilegedAccessHelper.getSystemProperty(SDOSystemProperties.SDO_HELPER_CONTEXTS_MAX_SIZE, "1000000"));
// Each application will have its own helper context - it is assumed that application
// names/loaders are unique within each active server instance
private static ConcurrentHashMap<Object, CacheIdentityMap> helperContexts = new ConcurrentHashMap<>();
// Each application will have a Map of alias' to identifiers
private static ConcurrentHashMap<Object, ConcurrentHashMap<String, String>> aliasMap = new ConcurrentHashMap<>();
// Each application could have separate HelperContextResolver
private static final ConcurrentHashMap<Object, HelperContextResolver> HELPER_CONTEXT_RESOLVERS = new ConcurrentHashMap<>();
// allow users to set their own classloader to context map pairs
private static WeakHashMap<ClassLoader, WeakHashMap<String, WeakReference<HelperContext>>> userSetHelperContexts = new WeakHashMap<>();
// keep a map of application names to application class loaders to handle redeploy
private static ConcurrentHashMap<String, ClassLoader> appNameToClassLoaderMap = new ConcurrentHashMap<>();
// keep a map of application name to the wrapper types for that application
private static final ConcurrentHashMap<String,Map<SDOWrapperTypeId,SDOWrapperType>> SDO_WRAPPER_TYPES = new ConcurrentHashMap<>();
// Application server identifiers
private static String WLS_CLASSLOADER_NAME = "weblogic";
private static String WAS_CLASSLOADER_NAME = "com.ibm.ws";
private static String JBOSS_CLASSLOADER_NAME = "jboss";
private static String GLOBAL_HELPER_IDENTIFIER = "";
private static final int WLS_IDENTIFIER = 0;
private static final int JBOSS_IDENTIFIER = 1;
// Common
private static final int COUNTER_LIMIT = 20;
// For WebLogic
private static volatile ApplicationAccessWLS applicationAccessWLS = null;
private static MBeanServer wlsMBeanServer = null;
private static ObjectName wlsThreadPoolRuntime = null;
private static final String WLS_ENV_CONTEXT_LOOKUP = "java:comp/env/jmx/runtime";
private static final String WLS_CONTEXT_LOOKUP = "java:comp/jmx/runtime";
private static final String WLS_RUNTIME_SERVICE = "RuntimeService";
private static final String WLS_SERVICE_KEY = "com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean";
private static final String WLS_APP_RUNTIMES = "ApplicationRuntimes";
private static final String WLS_SERVER_RUNTIME = "ServerRuntime";
private static final String WLS_THREADPOOL_RUNTIME = "ThreadPoolRuntime";
private static final String WLS_EXECUTE_THREAD = "ExecuteThread";
private static final String WLS_MBEAN_SERVER = "MBeanServer";
private static final String WLS_EXECUTE_THREAD_GET_METHOD_NAME = "getExecuteThread";
private static final String WLS_APPLICATION_NAME = "ApplicationName";
private static final String WLS_APPLICATION_VERSION = "ApplicationVersion";
private static final String WLS_APPLICATION_NAME_GET_METHOD_NAME = "getApplicationName";
private static final String WLS_ACTIVE_VERSION_STATE = "ActiveVersionState";
private static final Class<?>[] WLS_PARAMETER_TYPES = {};
// For WebSphere
private static final String WAS_NEWLINE = "\n";
private static final String WAS_APP_COLON = "[app:";
private static final String WAS_CLOSE_BRACKET = "]";
// For JBoss
private static MBeanServer jbossMBeanServer = null;
private static String JBOSS_SERVICE_CONTROLLER = "jboss.system:service=ServiceController";
private static String JBOSS_TYPE_STOP = "org.jboss.system.ServiceMBean.stop";
private static String JBOSS_ID_KEY = "id";
private static final String JBOSS_DEFAULT_DOMAIN_NAME = "jboss";
private static final String JBOSS_VFSZIP = "vfszip:";
private static final String JBOSS_VFSFILE = "vfsfile:";
private static final String JBOSS_EAR = ".ear";
private static final String JBOSS_JAR = ".jar";
private static final String JBOSS_WAR = ".war";
private static final int JBOSS_VFSZIP_OFFSET = JBOSS_VFSZIP.length();
private static final int JBOSS_VFSFILE_OFFSET = JBOSS_VFSFILE.length();
private static final int JBOSS_EAR_OFFSET = JBOSS_EAR.length();
private static final int JBOSS_TRIM_COUNT = 2; // for stripping off the remaining '/}' chars
// allow users to provide application info
private static ApplicationResolver appResolver;
private static boolean isAppResolverSet = false;
/**
* Default strategy for HelperContext creation.
* Singleton.
*/
private static final HelperContextResolver DEFAULT_HCR = new DefaultHelperContextResolver();
/**
* ADVANCED:
* Used to set an ApplicationResolver instance that will be used to retrieve
* info pertaining to a given application, such as the application name, in
* the case where our logic fails.
*
* This method can be called once and only once per active server instance.
*
* @param aResolver the ApplicationResolver instance that will be used to retrieve
* info pertaining to a given application. Note that null is
* considered a valid set operation.
* @throws SDOException if more than one call is made to this method
* in an active server instance.
*/
public static void setApplicationResolver(ApplicationResolver aResolver) {
// we only allow one set operation per running server instance
if (isApplicationResolverSet()) {
throw SDOException.attemptToResetApplicationResolver();
}
appResolver = aResolver;
isAppResolverSet = true;
}
/**
* Indicates if a call to setApplicationResolver has been made.
*
* @return true if a prior call to setApplicationResolver has
* been made, false otherwise
*/
public static boolean isApplicationResolverSet() {
return isAppResolverSet;
}
/**
* Create a local HelperContext. The current thread's context ClassLoader
* will be used to find static instance classes. In OSGi environments the
* construct that takes a ClassLoader parameter should be used instead.
*/
public SDOHelperContext() {
this(Thread.currentThread().getContextClassLoader());
}
/**
* Create a local HelperContext with the given identifier. The current
* thread's context ClassLoader will be used to find static instance
* classes. In OSGi environments the construct that takes a ClassLoader
* parameter should be used instead.
*
* @param identifier The unique label for this HelperContext.
*/
public SDOHelperContext(String identifier) {
this(identifier, Thread.currentThread().getContextClassLoader());
}
/**
* Create a local HelperContext. This constructor should be used in OSGi
* environments.
*
* @param aClassLoader This class loader will be used to find static
* instance classes.
*/
public SDOHelperContext(ClassLoader aClassLoader) {
super();
this.identifier = GLOBAL_HELPER_IDENTIFIER;
initialize(aClassLoader);
}
/**
* Create a local HelperContext with the given identifier. This constructor
* should be used in OSGi environments.
*
* @param identifier The unique label for this HelperContext.
* @param aClassLoader This class loader will be used to find static
* instance classes.
*/
public SDOHelperContext(String identifier, ClassLoader aClassLoader) {
super();
this.identifier = identifier;
initialize(aClassLoader);
}
/**
* The underlying helpers for this instance will be instantiated
* in this method.
*
* @param aClassLoader
*/
protected void initialize(ClassLoader aClassLoader) {
copyHelper = new SDOCopyHelper(this);
dataFactory = new SDODataFactoryDelegate(this);
dataHelper = new SDODataHelper(this);
equalityHelper = new SDOEqualityHelper(this);
xmlHelper = new SDOXMLHelperDelegate(this, aClassLoader);
typeHelper = new SDOTypeHelperDelegate(this);
xsdHelper = new SDOXSDHelperDelegate(this);
}
/**
* Reset the Type,XML and XSD helper instances.
*/
public void reset() {
((SDOTypeHelper)getTypeHelper()).reset();
((SDOXMLHelper)getXMLHelper()).reset();
((SDOXSDHelper)getXSDHelper()).reset();
}
/**
* Return the CopyHelper instance for this helper context.
*/
@Override
public CopyHelper getCopyHelper() {
return copyHelper;
}
/**
* Return the DataFactory instance for this helper context.
*/
@Override
public DataFactory getDataFactory() {
return dataFactory;
}
/**
* Return the DataHelper instance for this helper context.
*/
@Override
public DataHelper getDataHelper() {
return dataHelper;
}
/**
* Return the EqualityHelper instance for this helper context.
*/
@Override
public EqualityHelper getEqualityHelper() {
return equalityHelper;
}
/**
* Return the TypeHelper instance for this helper context.
*/
@Override
public TypeHelper getTypeHelper() {
return typeHelper;
}
/**
* Return the XMLHelper instance for this helper context.
*/
@Override
public XMLHelper getXMLHelper() {
return xmlHelper;
}
/**
* Return the XSDHelper instance for this helper context.
*/
@Override
public XSDHelper getXSDHelper() {
return xsdHelper;
}
/**
* Create and return a new ExternalizableDelegator.Resolvable instance based
* on this helper context.
*
* @return
*/
public ExternalizableDelegator.Resolvable createResolvable() {
return new SDOResolvable(this);
}
/**
* Create and return a new ExternalizableDelegator.Resolvable instance based
* on this helper context and a given target.
*
* @param target
* @return
*/
public ExternalizableDelegator.Resolvable createResolvable(Object target) {
return new SDOResolvable(target, this);
}
/**
* INTERNAL:
* Put a ClassLoader/HelperContext key/value pair in the Thread HelperContext
* map. If Thread.currentThread().getContextClassLoader() == key during
* getHelperContext() call then the HelperContext (value) will be returned.
* This method will overwrite an existing entry in the map with the same
* ClassLoader key.
*
* @param key class loader
* @param value helper context
*/
public static void putHelperContext(ClassLoader key, HelperContext value) {
if (key == null || value == null) {
return;
}
WeakHashMap<String, WeakReference<HelperContext>> currentMap = userSetHelperContexts.get(key);
if(currentMap == null) {
currentMap = new WeakHashMap<>();
userSetHelperContexts.put(key, currentMap);
}
currentMap.put(((SDOHelperContext) value).getIdentifier(), new WeakReference(value));
}
/**
* INTERNAL:
* Retrieve the HelperContext for a given ClassLoader from the Thread
* HelperContext map.
*
* @param key class loader
* @return HelperContext for the given key if key exists in the map, otherwise null
*/
private static HelperContext getUserSetHelperContext(String identifier, ClassLoader key) {
if (key == null) {
return null;
}
WeakHashMap<String, WeakReference<HelperContext>> currentMap = userSetHelperContexts.get(key);
if(currentMap == null) {
return null;
}
WeakReference<HelperContext> ref = currentMap.get(identifier);
if(ref == null) {
return null;
}
return ref.get();
}
/**
* INTERNAL:
* Remove a ClassLoader/HelperContext key/value pair from the Thread
* HelperContext map. If there are multiple local helper contexts associated
* with this ClassLoader, they will all be removed from the map.
*
* @param key class loader
*/
public static void removeHelperContext(ClassLoader key) {
if (key == null) {
return;
}
userSetHelperContexts.remove(key);
}
/**
* INTERNAL
* @param identifier the specific identifier of the HelperContext to be removed. "" for a Global helper
* @param key the ClassLoader associated with the HelperContext to be removed
*/
public static void removeHelperContext(String identifier, ClassLoader key) {
if(key == null) {
return;
}
WeakHashMap<String, WeakReference<HelperContext>> currentMap = userSetHelperContexts.get(key);
if(currentMap != null) {
currentMap.remove(identifier);
}
}
/**
* INTERNAL:
* Return the helper context for a given key. The key will either
* be a ClassLoader or a String (representing an application name).
* A new context will be created and put in the map if none exists
* for the given key.
*
* The key is assumed to be non-null - getDelegateKey should always
* return either a string representing the application name (for WLS,
* WAS and JBoss if available) or a class loader. This is relevant
* since 'putIfAbsent' will throw a null pointer exception if the
* key is null.
*/
public static HelperContext getHelperContext() {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
// check the map for contextClassLoader and return it if it exists
HelperContext hCtx = getUserSetHelperContext(GLOBAL_HELPER_IDENTIFIER, contextClassLoader);
if (hCtx != null) {
return hCtx;
}
return getHelperContext(GLOBAL_HELPER_IDENTIFIER);
}
/**
* Return the local helper context associated with the given identifier, or
* create one if it does not already exist. If identifier is an alias, the
* value associated with it in the alias Map will be used as the identifier
* value.
*
* @param identifier the identifier or alias to use for lookup/creation
* @return HelperContext associated with identifier, or a new HelperContext
* keyed on identifier if none eixsts
*/
public static HelperContext getHelperContext(String identifier) {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
return getHelperContext(identifier, contextClassLoader);
}
/**
* Return the local helper context with the given identifier, or create
* one if it does not already exist.
*/
public static HelperContext getHelperContext(String identifier, ClassLoader classLoader) {
// if identifier is an alias, we need the actual id value
ConcurrentMap<String, String> aliasEntries = getAliasMap();
if (aliasEntries.containsKey(identifier)) {
identifier = aliasEntries.get(identifier);
}
HelperContext helperContext = getUserSetHelperContext(identifier, classLoader);
if (helperContext != null) {
return helperContext;
}
CacheIdentityMap contextMap = getContextMap();
helperContext = (HelperContext)contextMap.get(identifier);
if (null == helperContext) {
LOGGER.fine("helperContext not found.");
helperContext = getHelperContextResolver().getHelperContext(identifier, classLoader);
HelperContext existingContext = (HelperContext)contextMap.get(identifier);
if (existingContext != null) {
LOGGER.fine(String.format("contextMap already has context for id: %s. Existing one will be used.", identifier));
helperContext = existingContext;
} else {
contextMap.put(identifier, helperContext, false, 0);
}
}
return helperContext;
}
/**
* Returns the map of helper contexts, keyed on Identifier, for the current application
* @return
*/
static CacheIdentityMap getContextMap() {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
String classLoaderName = contextClassLoader.getClass().getName();
// get a MapKeyLookupResult instance based on the context loader
MapKeyLookupResult hCtxMapKey = getContextMapKey(contextClassLoader, classLoaderName);
// at this point we will have a loader and possibly an application name
String appName = hCtxMapKey.getApplicationName();
ClassLoader appLoader = hCtxMapKey.getLoader();
// we will use the application name as the map key if set; otherwise we use the loader
Object contextMapKey = appName != null ? appName : appLoader;
CacheIdentityMap contextMap = helperContexts.get(contextMapKey);
// handle possible redeploy
// the following block only applies to WAS - hence the loader name check
if (contextMap != null && appName != null && classLoaderName.contains(WAS_CLASSLOADER_NAME)) {
// at this point there is an existing entry in the map - if the context is keyed
// on application name we need to check to see if a redeployment occurred; in
// that case the app names will match, but the class loaders will not
ClassLoader currentAppLoader = appNameToClassLoaderMap.get(appName);
if (currentAppLoader != null && currentAppLoader != appLoader) {
// concurrency - use remove(key, value) to ensure we don't remove a newly added entry
appNameToClassLoaderMap.remove(appName, currentAppLoader);
helperContexts.remove(appName, contextMap);
contextMap = null;
}
}
// may need to add a new entry
if (null == contextMap) {
contextMap = new CacheIdentityMap(helperContextsMaxSize, null, null, false);
// use putIfAbsent to avoid concurrent entries in the map
CacheIdentityMap existingMap = helperContexts.putIfAbsent(contextMapKey, contextMap);
if (existingMap != null) {
// if a new entry was just added, use it instead of the one we just created
contextMap = existingMap;
} else if (appName != null) {
// add an appName/appLoader pair to the appNameToClassLoader map
appNameToClassLoaderMap.put(appName, appLoader);
if (classLoaderName.contains(WLS_CLASSLOADER_NAME)) {
// add a loader/context pair to the helperContexts map to handle case where appName
// is no longer available, but the loader from a previous lookup is being used
helperContexts.put(appLoader, contextMap);
// add a notification listener to handle redeploy
addWLSNotificationListener(appName);
} else if (classLoaderName.contains(JBOSS_CLASSLOADER_NAME)) {
// add a notification listener to handle redeploy - the listener will only be added once
addJBossNotificationListener();
}
}
}
return contextMap;
}
/**
* Replaces the provided helper context in the map of identifiers to
* helper contexts for this application. ctx.getIdentifier() will be
* used to obtain the identifier value. If identifier is a key in the
* the alias Map, i.e. was previously set as alias, the corresponding
* entry will be removed from the alias Map.
*
* @param ctx the HelperContext to be added to the context Map for
* the current application
*/
public static void putHelperContext(HelperContext ctx) {
String identifier = ((SDOHelperContext) ctx).getIdentifier();
if (GLOBAL_HELPER_IDENTIFIER.equals(identifier)) {
// The global HelperContext cannot be replaced
return;
}
getContextMap().put(identifier, ctx, false, 0);
// identifier may have been an alias at one point
getAliasMap().remove(identifier);
}
/**
* ADVANCED:
* Remove the HelperContext for the application associated with a
* given key, if it exists in the map.
*/
private static void resetHelperContext(String key) {
// remove entry from helperContext map
boolean successHc = removeAppFromMap(helperContexts, key, false);
// remove app's helperContextResolver
boolean successHcr = removeAppFromMap(HELPER_CONTEXT_RESOLVERS, key, true);
if (LOGGER.isLoggable(Level.WARNING) && !successHc && !successHcr) {
LOGGER.warning("No entries found in maps for application:" + key);
}
// remove the appName entry in the appNameToClassLoader map
appNameToClassLoaderMap.remove(key);
// remove static SDOWrapperType instances bound to this application
SDO_WRAPPER_TYPES.remove(key);
// remove the alias map for this app
aliasMap.remove(key);
}
/**
* Trying to remove entry for a given app the provided map.
*
* @param map from which app value should be removed
* @param appName application name
* @param removeDefaultClassloader whether to try removing the default classloader
* @return true if any removal took place
*/
private static boolean removeAppFromMap(Map map, String appName, boolean removeDefaultClassloader) {
boolean result = map.remove(appName) != null;
// there may be a loader/context pair to remove
ClassLoader appLoader = appNameToClassLoaderMap.get(appName);
if (appLoader != null) {
result = result | map.remove(appLoader) != null;
} else if (removeDefaultClassloader) {
// try with Thread ContextClassLoader
result = result | map.remove(Thread.currentThread().getContextClassLoader()) != null;
}
return result;
}
/**
* INTERNAL:
* Return the key to be used for Map lookups based in the current thread's
* context loader. The returned value will be the application name (if
* available) or the context loader.
*
*/
private static Object getMapKey() {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
String classLoaderName = contextClassLoader.getClass().getName();
// get a MapKeyLookupResult instance based on the context loader
MapKeyLookupResult hCtxMapKey = getContextMapKey(contextClassLoader, classLoaderName);
// at this point we will have a loader and possibly an application name
String appName = hCtxMapKey.getApplicationName();
ClassLoader appLoader = hCtxMapKey.getLoader();
// we will use the application name as the map key if set; otherwise we use the loader
return appName != null ? appName : appLoader;
}
/**
* Bug #506919
* Retrieves the application name for current {@link ClassLoader}.
*
* @param classLoader the ClassLoader to use for searching application name
* @return the application name
*/
private static String getApplicationName(ClassLoader classLoader) {
String classLoaderName = classLoader.getClass().getName();
// get a MapKeyLookupResult instance based on the context loader
MapKeyLookupResult hCtxMapKey = getContextMapKey(classLoader, classLoaderName);
// at this point we will have a loader and possibly an application name
String applicationName = hCtxMapKey.getApplicationName();
return applicationName != null? applicationName : "DEFAULT";
}
/**
* INTERNAL:
* This method will return the MapKeyLookupResult instance to be used to
* store/retrieve the global helper context for a given application.
*
* @return MapKeyLookupResult wrapping the application name for WebLogic and WebSphere, the archive file
* name for JBoss - if available; otherwise a MapKeyLookupResult
* wrapping Thread.currentThread().getContextClassLoader()
*/
private static MapKeyLookupResult getContextMapKey(ClassLoader classLoader, String classLoaderName) {
// Helper contexts in WebLogic server will be keyed on application name if available
if (classLoaderName.contains(WLS_CLASSLOADER_NAME)) {
if (null == applicationAccessWLS) {
synchronized (SDOHelperContext.class) {
if (applicationAccessWLS == null) {
applicationAccessWLS = new ApplicationAccessWLS();
}
}
}
Object appName = applicationAccessWLS.getApplicationName(classLoader);
if (appName != null) {
return new MapKeyLookupResult(appName.toString(), classLoader);
}
Object executeThread = getExecuteThread();
if (executeThread != null) {
try {
Method getMethod = PrivilegedAccessHelper.getPublicMethod(executeThread.getClass(), WLS_APPLICATION_NAME_GET_METHOD_NAME, WLS_PARAMETER_TYPES, false);
appName = PrivilegedAccessHelper.invokeMethod(getMethod, executeThread);
} catch (Exception e) {
throw SDOException.errorInvokingWLSMethodReflectively(WLS_APPLICATION_NAME_GET_METHOD_NAME, WLS_EXECUTE_THREAD, e);
}
}
// if ExecuteThread is null or doesn't return the app name, attempt
// to use the user-set ApplicationResolver (if set)
if (appName == null && appResolver != null) {
appName = appResolver.getApplicationName();
}
// use the application name if set, otherwise key on the class loader
if (appName != null) {
return new MapKeyLookupResult(appName.toString(), classLoader);
}
// couldn't get the application name, so default to the context loader
return new MapKeyLookupResult(classLoader);
}
// Helper contexts in WebSphere server will be keyed on application name if available
if (classLoaderName.contains(WAS_CLASSLOADER_NAME)) {
return getContextMapKeyForWAS(classLoader);
}
// Helper contexts in JBoss server will be keyed on archive file name if available
if (classLoaderName.contains(JBOSS_CLASSLOADER_NAME)) {
return getContextMapKeyForJBoss(classLoader);
}
// at this point we will default to the context loader
return new MapKeyLookupResult(classLoader);
}
/**
* Lazy load the WebLogic MBeanServer instance.
*
* @return
*/
private static MBeanServer getWLSMBeanServer() {
if (wlsMBeanServer == null) {
Context weblogicContext = null;
try {
weblogicContext = new InitialContext();
try {
// The lookup string used depends on the context from which this class is being
// accessed, i.e. servlet, EJB, etc. Try java:comp/env lookup
wlsMBeanServer = (MBeanServer) weblogicContext.lookup(WLS_ENV_CONTEXT_LOOKUP);
} catch (NamingException e) {
// Lookup failed - try java:comp
try {
wlsMBeanServer = (MBeanServer) weblogicContext.lookup(WLS_CONTEXT_LOOKUP);
} catch (NamingException ne) {
throw SDOException.errorPerformingWLSLookup(WLS_MBEAN_SERVER, ne);
}
}
} catch (NamingException nex) {
throw SDOException.errorCreatingWLSInitialContext(nex);
}
}
return wlsMBeanServer;
}
/**
* INTERNAL:
* This convenience method will look up a WebLogic execute thread from the runtime
* MBean tree. The execute thread contains application information. This code
* will use the name of the current thread to lookup the corresponding ExecuteThread.
* The ExecuteThread will allow us to obtain the application name (and version, etc).
*
* @return application name or null if the name cannot be obtained
*/
private static Object getExecuteThread() {
if (getWLSMBeanServer() != null) {
// Lazy load the ThreadPoolRuntime instance
if (wlsThreadPoolRuntime == null) {
ObjectName service = null;
ObjectName serverRuntime = null;
try {
service = new ObjectName(WLS_SERVICE_KEY);
} catch (Exception x) {
throw SDOException.errorGettingWLSObjectName(WLS_RUNTIME_SERVICE + " [" + WLS_SERVICE_KEY + "]", x);
}
try {
serverRuntime = (ObjectName) wlsMBeanServer.getAttribute(service, WLS_SERVER_RUNTIME);
} catch (Exception x) {
throw SDOException.errorGettingWLSObjectName(WLS_SERVER_RUNTIME, x);
}
try {
wlsThreadPoolRuntime = (ObjectName) wlsMBeanServer.getAttribute(serverRuntime, WLS_THREADPOOL_RUNTIME);
} catch (Exception x) {
throw SDOException.errorGettingWLSObjectName(WLS_THREADPOOL_RUNTIME, x);
}
}
try {
return wlsMBeanServer.invoke(wlsThreadPoolRuntime, WLS_EXECUTE_THREAD_GET_METHOD_NAME, new Object[] { Thread.currentThread().getName() }, new String[] { String.class.getName() });
} catch (Exception x) {
throw SDOException.errorInvokingWLSMethodReflectively(WLS_EXECUTE_THREAD_GET_METHOD_NAME, WLS_THREADPOOL_RUNTIME, x);
}
}
return null;
}
/**
* INTERNAL:
* Adds a notification listener to the ApplicationRuntimeMBean instance with "ApplicationName"
* attribute equals to 'mapKey.applicationName'. The listener will handle application
* re-deployment.
*
* If any errors occur, we will fail silently, i.e. the listener will not be added.
*
* This method should only be called when running in an active WLS instance.
*
* @param applicationName
*/
private static void addWLSNotificationListener(String applicationName) {
try {
if (getWLSMBeanServer() != null) {
ObjectName service = new ObjectName(WLS_SERVICE_KEY);
ObjectName serverRuntime = (ObjectName) wlsMBeanServer.getAttribute(service, WLS_SERVER_RUNTIME);
ObjectName[] appRuntimes = (ObjectName[]) wlsMBeanServer.getAttribute(serverRuntime, WLS_APP_RUNTIMES);
for (int i=0; i < appRuntimes.length; i++) {
try {
ObjectName appRuntime = appRuntimes[i];
Object appName = wlsMBeanServer.getAttribute(appRuntime, WLS_APPLICATION_NAME);
Object appVersion = wlsMBeanServer.getAttribute(appRuntime, WLS_APPLICATION_VERSION);
String appIdentifier = null;
if (appName != null) {
if (appVersion != null) {
appIdentifier = appName + "#" + appVersion;
} else {
appIdentifier = appName.toString();
}
if (appIdentifier != null && appIdentifier.equals(applicationName)) {
wlsMBeanServer.addNotificationListener(appRuntime, new MyNotificationListener(applicationName, WLS_IDENTIFIER), null, null);
break;
}
}
} catch (Exception ex) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Failed to retrieve application name in runtime " + appRuntimes[i].toString() + ":\n" + Helper.printStackTraceToString(ex));
}
}
}
}
} catch (Exception x) {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.warning("Failed to add notification listener for application " + applicationName + ":\n" + Helper.printStackTraceToString(x));
}
}
}
/**
* INTERNAL:
* The listener will handle application re-deployment. If any errors occur, we will
* fail silently, i.e. the listener will not be added. Since we cannot register for
* notifications for a particular application, and hence recieve notifications for
* all apps that are redeployed, we only add the listener once - each time we receive
* notification we will check the map and remove the corresponding entry if it exists.
*
* This method should only be called when running in an active JBoss instance.
*
*/
private static void addJBossNotificationListener() {
if (jbossMBeanServer == null) {
List<MBeanServer> mbeanServers = MBeanServerFactory.findMBeanServer(null);
for (MBeanServer server : mbeanServers) {
if (server.getDefaultDomain().equals(JBOSS_DEFAULT_DOMAIN_NAME)) {
jbossMBeanServer = server;
try {
jbossMBeanServer.addNotificationListener(new ObjectName(JBOSS_SERVICE_CONTROLLER), new MyNotificationListener(JBOSS_IDENTIFIER), new MyNotificationFilter(), null);
} catch (Exception e) {}
break;
}
}
}
}
/**
* Getter for HelperContextResolver
* @return actual strategy
*/
public static HelperContextResolver getHelperContextResolver() {
Object key = getMapKey();
HelperContextResolver result = HELPER_CONTEXT_RESOLVERS.get(key);
if (result == null) {
result = DEFAULT_HCR;
HELPER_CONTEXT_RESOLVERS.putIfAbsent(key, result);
}
return result;
}
/**
* Method allows dynamically change HelperContext creation strategy.
*
* @param helperContextResolver on this object {@link HelperContextResolver#getHelperContext(String, ClassLoader)} will be called.
* If it is null - then default strategy will be set.
*/
public static void setHelperContextResolver(Object helperContextResolver) {
Object key = getMapKey();
if (helperContextResolver == null)
HELPER_CONTEXT_RESOLVERS.put(key, DEFAULT_HCR);
else
HELPER_CONTEXT_RESOLVERS.put(key, new ReflectionHelperContextResolver(helperContextResolver));
}
/**
* Method allows dynamically change HelperContext creation strategy.
*
* @param helperContextResolver strategy to be used. If it is null - then default strategy will be set.
*/
public static void setHelperContextResolver(HelperContextResolver helperContextResolver) {
Object key = getMapKey();
if (helperContextResolver == null)
HELPER_CONTEXT_RESOLVERS.put(key, DEFAULT_HCR);
else
HELPER_CONTEXT_RESOLVERS.put(key, helperContextResolver);
}
/**
* Removes HelperContextResolver for the current application.
* Application is resolved based on applicationName or classLoader.
*/
public static void removeHelerContextResolver() {
HELPER_CONTEXT_RESOLVERS.remove(getMapKey());
}
/**
* INTERNAL:
* This class will be handed in as a parameter when adding a JBoss notification listener.
* The purpose of this class is to restrict notifications to "stop", i.e. we don't
* care about "destroy", "start" etc.
*
*/
static class MyNotificationFilter extends NotificationFilterSupport {
MyNotificationFilter() {
super.enableType(JBOSS_TYPE_STOP);
}
}
/**
* INTERNAL:
* Inner class used to catch application re-deployment. Upon notification of this event,
* the helper context for the given application will be removed from the helper context
* to application map. This method will also remove the corresponding entry in the
* application name to application loader map if necessary.
*
* For WebLogic, 'appName' will be set; we will regester a listener for each application
* name we key a context on, and will only receive a notification if a particular app
* is redeployed. Upon notification we will remove the context entry for 'appName'.
*
* For JBoss, 'appName' will not be set; we will only register the listener once,
* and each time we're notified of an application redeployment, we will reset the
* associated helper context if one exists.
*
*/
private static class MyNotificationListener implements NotificationListener {
int server;
String appName;
/**
* This is the default constructor - typically used when running in an
* actove JBoss instance.
*
* @param server
*/
public MyNotificationListener(int server) {
this.server = server;
}
/**
* This constructor will set 'appName' - typically used when running in
* an active WebLogic instance.
*
* @param appName
* @param server
*/
public MyNotificationListener(String appName, int server) {
this.server = server;
this.appName = appName;
}
@Override
public void handleNotification(Notification notification, Object handback) {
switch (server) {
case 0: { // handle WebLogic notification
if (notification instanceof AttributeChangeNotification acn) {
if (acn.getAttributeName().equals(WLS_ACTIVE_VERSION_STATE)) {
if (acn.getNewValue().equals(0)) {
resetHelperContext(appName);
}
}
}
break;
}
case 1: { // handle JBoss notification
// assumes 'user data' is an ObjectName containing an 'id' property which indicates the archive file name
appName = getApplicationNameFromJBossClassLoader(((ObjectName) notification.getUserData()).getKeyProperty(JBOSS_ID_KEY));
// we receive notifications for all service stops in JBoss; only call reset if necessary
if (helperContexts.containsKey(appName)) {
resetHelperContext(appName);