-
Notifications
You must be signed in to change notification settings - Fork 143
/
StatefulSessionContainer.java
3355 lines (2867 loc) · 136 KB
/
StatefulSessionContainer.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) 2021, 2023 Contributors to the Eclipse Foundation
* Copyright (c) 1997, 2020 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.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.ejb.containers;
import com.sun.appserv.util.cache.CacheListener;
import com.sun.ejb.ComponentContext;
import com.sun.ejb.Container;
import com.sun.ejb.EJBUtils;
import com.sun.ejb.EjbInvocation;
import com.sun.ejb.InvocationInfo;
import com.sun.ejb.MethodLockInfo;
import com.sun.ejb.base.stats.HAStatefulSessionStoreMonitor;
import com.sun.ejb.base.stats.StatefulSessionStoreMonitor;
import com.sun.ejb.containers.EJBContextImpl.BeanState;
import com.sun.ejb.containers.util.cache.LruSessionCache;
import com.sun.ejb.monitoring.probes.EjbCacheProbeProvider;
import com.sun.ejb.monitoring.stats.EjbCacheStatsProvider;
import com.sun.ejb.monitoring.stats.EjbMonitoringStatsProvider;
import com.sun.ejb.monitoring.stats.EjbMonitoringUtils;
import com.sun.ejb.monitoring.stats.StatefulSessionBeanStatsProvider;
import com.sun.ejb.spi.container.SFSBContainerCallback;
import com.sun.ejb.spi.container.StatefulEJBContext;
import com.sun.ejb.spi.sfsb.util.SFSBUUIDUtil;
import com.sun.ejb.spi.sfsb.util.SFSBVersionManager;
import com.sun.enterprise.admin.monitor.callflow.ComponentType;
import com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper;
import com.sun.enterprise.container.common.impl.EntityManagerWrapper;
import com.sun.enterprise.container.common.impl.PhysicalEntityManagerWrapper;
import com.sun.enterprise.container.common.spi.util.IndirectlySerializable;
import com.sun.enterprise.container.common.spi.util.SerializableObjectFactory;
import com.sun.enterprise.deployment.EntityManagerReferenceDescriptor;
import com.sun.enterprise.deployment.LifecycleCallbackDescriptor;
import com.sun.enterprise.deployment.LifecycleCallbackDescriptor.CallbackType;
import com.sun.enterprise.deployment.MethodDescriptor;
import com.sun.enterprise.security.SecurityManager;
import com.sun.enterprise.transaction.api.JavaEETransaction;
import com.sun.enterprise.util.Utility;
import com.sun.enterprise.util.io.FileUtils;
import jakarta.ejb.ConcurrentAccessException;
import jakarta.ejb.ConcurrentAccessTimeoutException;
import jakarta.ejb.CreateException;
import jakarta.ejb.EJBException;
import jakarta.ejb.EJBHome;
import jakarta.ejb.EJBLocalHome;
import jakarta.ejb.EJBObject;
import jakarta.ejb.IllegalLoopbackException;
import jakarta.ejb.NoSuchObjectLocalException;
import jakarta.ejb.RemoveException;
import jakarta.ejb.SessionBean;
import jakarta.ejb.SessionSynchronization;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceContextType;
import jakarta.persistence.SynchronizationType;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.InaccessibleObjectException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.glassfish.api.invocation.ComponentInvocation;
import org.glassfish.api.invocation.ComponentInvocation.ComponentInvocationType;
import org.glassfish.ejb.LogFacade;
import org.glassfish.ejb.deployment.descriptor.EjbDescriptor;
import org.glassfish.ejb.deployment.descriptor.EjbRemovalInfo;
import org.glassfish.ejb.deployment.descriptor.EjbSessionDescriptor;
import org.glassfish.ejb.deployment.descriptor.runtime.CheckpointAtEndOfMethodDescriptor;
import org.glassfish.ejb.deployment.descriptor.runtime.IASEjbExtraDescriptors;
import org.glassfish.flashlight.provider.ProbeProviderFactory;
import org.glassfish.ha.store.api.BackingStore;
import org.glassfish.ha.store.api.BackingStoreException;
import org.glassfish.ha.store.util.SimpleMetadata;
import org.glassfish.logging.annotation.LogMessageInfo;
import static com.sun.ejb.codegen.AsmSerializableBeanGenerator.getGeneratedSerializableClassName;
import static jakarta.persistence.SynchronizationType.SYNCHRONIZED;
/**
* This class provides container functionality specific to stateful
* SessionBeans.
* At deployment time, one instance of the StatefulSessionContainer is created
* for each stateful SessionBean type (i.e. deployment descriptor) in a JAR.
* <p/>
* The 5 states of a Stateful EJB (an EJB can be in only 1 state at a time):
* 1. PASSIVE : has been passivated
* 2. READY : ready for invocations, no transaction in progress
* 3. INVOKING : processing an invocation
* 4. INCOMPLETE_TX : ready for invocations, transaction in progress
* 5. DESTROYED : does not exist
*
* @author Mahesh Kannan
*/
public final class StatefulSessionContainer
extends BaseContainer
implements CacheListener, SFSBContainerCallback {
private static final Logger _logger = LogFacade.getLogger();
@LogMessageInfo(
message = "[SFSBContainer] Exception while initializing SessionSynchronization methods",
level = "WARNING")
private static final String EXCEPTION_WHILE_INITIALIZING_SESSION_SYNCHRONIZATION = "AS-EJB-00012";
@LogMessageInfo(
message = "[SFSBContainer] Exception while loading checkpoint info",
level = "WARNING")
private static final String EXCEPTION_WHILE_LOADING_CHECKPOINT = "AS-EJB-00013";
@LogMessageInfo(
message = "Exception creating ejb object : [{0}]",
level = "WARNING")
private static final String CREATE_EJBOBJECT_EXCEPTION = "AS-EJB-00014";
@LogMessageInfo(
message = "Exception creating ejb local object [{0}]",
level = "WARNING")
private static final String CREATE_EJBLOCALOBJECT_EXCEPTION = "AS-EJB-00015";
@LogMessageInfo(
message = "Couldn't update timestamp for: [{0}]; Exception: [{1}]",
level = "WARNING")
private static final String COULDNT_UPDATE_TIMESTAMP_FOR_EXCEPTION = "AS-EJB-00016";
@LogMessageInfo(
message = "Cannot register bean for checkpointing",
level = "WARNING")
private static final String CANNOT_REGISTER_BEAN_FOR_CHECKPOINTING = "AS-EJB-00017";
@LogMessageInfo(
message = "Error during checkpoint ([{0}]. Key: [{1}]) [{2}]",
level = "WARNING")
private static final String ERROR_DURING_CHECKPOINT_3PARAMs = "AS-EJB-00018";
@LogMessageInfo(
message = "sfsb checkpoint error. Name: [{0}]",
level = "WARNING")
private static final String SFSB_CHECKPOINT_ERROR_NAME = "AS-EJB-00019";
@LogMessageInfo(
message = "sfsb checkpoint error. Key: [{0}]",
level = "WARNING")
private static final String SFSB_CHECKPOINT_ERROR_KEY = "AS-EJB-00020";
@LogMessageInfo(
message = "Exception in afterCompletion : [{0}]",
level = "INFO")
private static final String AFTER_COMPLETION_EXCEPTION = "AS-EJB-00021";
@LogMessageInfo(
message = "1. passivateEJB() returning because containerState: [{0}]",
level = "WARNING")
private static final String PASSIVATE_EJB_RETURNING_BECAUSE_CONTAINER_STATE = "AS-EJB-00022";
@LogMessageInfo(
message = "Extended EM not serializable. Exception: [{0}]",
level = "WARNING")
private static final String EXTENDED_EM_NOT_SERIALIZABLE = "AS-EJB-00023";
@LogMessageInfo(
message = "Error during passivation: [{0}]; [{1}]",
level = "WARNING")
private static final String ERROR_DURING_PASSIVATION = "AS-EJB-00024";
@LogMessageInfo(
message = "Error during passivation of [{0}]",
level = "WARNING")
private static final String PASSIVATION_ERROR_1PARAM = "AS-EJB-00025";
@LogMessageInfo(
message = "sfsb passivation error. Key: [{0}]",
level = "WARNING")
private static final String SFSB_PASSIVATION_ERROR_1PARAM = "AS-EJB-00026";
@LogMessageInfo(
message = "Error during Stateful Session Bean activation for key [{0}]",
level = "SEVERE",
cause = "A problem occurred while the container was activating a stateful session bean. " +
"One possible cause is that the bean code threw a system exception from its ejbActivate method.",
action = "Check the stack trace to see whether the exception was thrown from the ejbActivate method " +
"and if so double-check the application code to determine what caused the exception.")
private static final String SFSB_ACTIVATION_ERROR = "AS-EJB-00028";
@LogMessageInfo(
message = "[{0}]: Error during backingStore.shutdown()",
level = "WARNING")
private static final String ERROR_DURING_BACKING_STORE_SHUTDOWN = "AS-EJB-00029";
@LogMessageInfo(
message = "[{0}]: Error during onShutdown()",
level = "WARNING")
private static final String ERROR_DURING_ON_SHUTDOWN = "AS-EJB-00030";
@LogMessageInfo(
message = "[{0}]: Error while undeploying ctx. Key: [{1}]",
level = "WARNING")
private static final String ERROR_WHILE_UNDEPLOYING_CTX_KEY = "AS-EJB-00031";
@LogMessageInfo(
message = "Cannot add idle bean cleanup task",
level = "WARNING")
private static final String ADD_CLEANUP_TASK_ERROR = "AS-EJB-00032";
@LogMessageInfo(
message = "Got exception during removeExpiredSessions (but the reaper thread is still alive)",
level = "WARNING")
private static final String GOT_EXCEPTION_DURING_REMOVE_EXPIRED_SESSIONS = "AS-EJB-00033";
@LogMessageInfo(
message = "Error during checkpoint(, but session not destroyed)",
level = "WARNING")
private static final String ERROR_DURING_CHECKPOINT_SESSION_ALIVE = "AS-EJB-00034";
@LogMessageInfo(
message = "Error during checkpoint",
level = "WARNING")
private static final String ERROR_DURING_CHECKPOINT = "AS-EJB-00035";
@LogMessageInfo(
message = "Cache is shutting down, {0} stateful session beans will not be restored after restarting " +
"since passivation is disabled",
level = "INFO")
private static final String SFSB_NOT_RESTORED_AFTER_RESTART = "AS-EJB-00050";
@LogMessageInfo(
message = "Exception in backingStore.size()",
level = "WARNING")
private static final String ERROR_WHILE_BACKSTORE_SIZE_ACCESS = "AS-EJB-00063";
// We do not want too many ORB task for passivation
public static final int MIN_PASSIVATION_BATCH_COUNT = 8;
private final static long CONCURRENCY_NOT_ALLOWED = 0;
private final static long BLOCK_INDEFINITELY = -1;
private final ArrayList passivationCandidates = new ArrayList();
private final Object asyncTaskSemaphore = new Object();
private int asyncTaskCount = 0;
private int asyncCummTaskCount = 0;
private int passivationBatchCount
= MIN_PASSIVATION_BATCH_COUNT;
private int containerTrimCount = 0;
private LruSessionCache sessionBeanCache;
private BackingStore<Serializable, SimpleMetadata> backingStore;
private SFSBUUIDUtil<Object> uuidGenerator;
private final ArrayList scheduledTimerTasks = new ArrayList();
private int statMethodReadyCount = 0;
private final String ejbName;
private boolean isHAEnabled;
private int removalGracePeriodInSeconds;
private final InvocationInfo postConstructInvInfo;
private final InvocationInfo preDestroyInvInfo;
private final InvocationInfo postActivateInvInfo;
private final InvocationInfo prePassivateInvInfo;
private StatefulSessionStoreMonitor sfsbStoreMonitor;
private final String traceInfoPrefix;
private SFSBVersionManager sfsbVersionManager;
private Method afterBeginMethod;
private Method beforeCompletionMethod;
private Method afterCompletionMethod;
private final boolean isPassivationCapable;
/**
* Cache for keeping ref count for shared extended entity manager.
* The key in this map is the physical entity manager
*/
private static final Map<EntityManager, EEMRefInfo> extendedEMReferenceCountMap = new HashMap<>();
private static final Map<EEMRefInfoKey, EntityManager> eemKey2EEMMap = new HashMap<>();
/**
* This constructor is called from the JarManager when a Jar is deployed.
*
* @throws Exception on error
*/
public StatefulSessionContainer(EjbDescriptor desc, ClassLoader loader, SecurityManager sm) throws Exception {
this(ContainerType.STATEFUL, desc, loader, sm);
}
public StatefulSessionContainer(ContainerType conType, EjbDescriptor desc, ClassLoader loader, SecurityManager sm)
throws Exception {
super(conType, desc, loader, sm);
super.createCallFlowAgent(ComponentType.SFSB);
this.ejbName = desc.getName();
this.traceInfoPrefix = "sfsb-" + ejbName + ": ";
postConstructInvInfo = getLifecycleCallbackInvInfo(ejbDescriptor.getPostConstructDescriptors());
preDestroyInvInfo = getLifecycleCallbackInvInfo(ejbDescriptor.getPreDestroyDescriptors());
EjbSessionDescriptor sfulDesc = (EjbSessionDescriptor) ejbDescriptor;
postActivateInvInfo = getLifecycleCallbackInvInfo(sfulDesc.getPostActivateDescriptors());
prePassivateInvInfo = getLifecycleCallbackInvInfo(sfulDesc.getPrePassivateDescriptors());
isPassivationCapable = sfulDesc.isPassivationCapable();
}
@Override
public boolean isPassivationCapable() {
return isPassivationCapable;
}
private InvocationInfo getLifecycleCallbackInvInfo(Set<LifecycleCallbackDescriptor> lifecycleCallbackDescriptors)
throws Exception {
InvocationInfo inv = new InvocationInfo();
inv.ejbName = ejbDescriptor.getName();
inv.methodIntf = MethodDescriptor.LIFECYCLE_CALLBACK;
inv.txAttr = getTxAttrForLifecycleCallback(lifecycleCallbackDescriptors, -1, TX_NOT_SUPPORTED, TX_REQUIRES_NEW);
return inv;
}
@Override
protected void initializeHome() throws Exception {
super.initializeHome();
initSessionSyncMethods();
loadCheckpointInfo();
registerMonitorableComponents();
}
private void initSessionSyncMethods() throws Exception {
if (SessionSynchronization.class.isAssignableFrom(ejbClass)) {
try {
afterBeginMethod = ejbClass.getMethod("afterBegin");
beforeCompletionMethod = ejbClass.getMethod("beforeCompletion");
afterCompletionMethod = ejbClass.getMethod("afterCompletion", Boolean.TYPE);
} catch (Exception e) {
_logger.log(Level.WARNING, EXCEPTION_WHILE_INITIALIZING_SESSION_SYNCHRONIZATION, e);
}
} else {
EjbSessionDescriptor sessionDesc = (EjbSessionDescriptor) ejbDescriptor;
MethodDescriptor afterBeginMethodDesc = sessionDesc.getAfterBeginMethod();
if (afterBeginMethodDesc != null) {
afterBeginMethod = afterBeginMethodDesc.getDeclaredMethod(sessionDesc);
processSessionSynchMethod(afterBeginMethod);
}
MethodDescriptor beforeCompletionMethodDesc = sessionDesc.getBeforeCompletionMethod();
if (beforeCompletionMethodDesc != null) {
beforeCompletionMethod = beforeCompletionMethodDesc.getDeclaredMethod(sessionDesc);
processSessionSynchMethod(beforeCompletionMethod);
}
MethodDescriptor afterCompletionMethodDesc = sessionDesc.getAfterCompletionMethod();
if (afterCompletionMethodDesc != null) {
afterCompletionMethod = afterCompletionMethodDesc.getDeclaredMethod(sessionDesc);
if (afterCompletionMethod == null) {
afterCompletionMethod = afterCompletionMethodDesc.getDeclaredMethod(sessionDesc,
new Class[] {Boolean.TYPE});
}
processSessionSynchMethod(afterCompletionMethod);
}
}
}
private void processSessionSynchMethod(Method sessionSynchMethod) throws Exception {
final Method methodAccessible = sessionSynchMethod;
// SessionSynch method defined through annotation or ejb-jar.xml
// can have any access modifier so make sure we have permission
// to invoke it.
PrivilegedExceptionAction<Void> action = () -> {
if (!methodAccessible.trySetAccessible()) {
throw new InaccessibleObjectException("Unable to make accessible: " + methodAccessible);
}
return null;
};
AccessController.doPrivileged(action);
}
// Called before invoking a bean with no Tx or with a new Tx.
// Check if the bean is associated with an unfinished tx.
@Override
protected void checkUnfinishedTx(Transaction prevTx, EjbInvocation inv) {
try {
if (inv.invocationInfo.isBusinessMethod && prevTx != null
&& prevTx.getStatus() != Status.STATUS_NO_TRANSACTION) {
// An unfinished tx exists for the bean.
// so we cannot invoke the bean with no Tx or a new Tx.
throw new IllegalStateException("Bean is associated with a different unfinished transaction");
}
} catch (SystemException ex) {
_logger.log(Level.FINE, "Exception in checkUnfinishedTx", ex);
throw new EJBException(ex);
}
}
protected void loadCheckpointInfo() {
try {
if (isHAEnabled) {
Iterator<InvocationInfo> iter = invocationInfoMap.values().iterator();
while (iter.hasNext()) {
InvocationInfo info = iter.next();
info.checkpointEnabled = false;
MethodDescriptor md = new MethodDescriptor(info.method, info.methodIntf);
IASEjbExtraDescriptors extraDesc = ejbDescriptor.getIASEjbExtraDescriptors();
if (extraDesc != null) {
CheckpointAtEndOfMethodDescriptor cpDesc = extraDesc.getCheckpointAtEndOfMethodDescriptor();
if (cpDesc != null) {
info.checkpointEnabled = cpDesc.isCheckpointEnabledFor(md);
}
}
if (info.checkpointEnabled) {
_logger.log(Level.FINE, "[SFSBContainer] {0} MARKED for end-of-method-checkpoint", info.method);
}
}
}
} catch (Exception ex) {
_logger.log(Level.WARNING, EXCEPTION_WHILE_LOADING_CHECKPOINT, ex);
}
}
@Override
protected void registerMonitorableComponents() {
registerEjbCacheProbeProvider();
super.registerMonitorableComponents();
cacheProbeListener = new EjbCacheStatsProvider(sessionBeanCache, getContainerId(), containerInfo.appName,
containerInfo.modName, containerInfo.ejbName);
cacheProbeListener.register();
if (isHAEnabled) {
sfsbStoreMonitor = new HAStatefulSessionStoreMonitor();
} else {
sfsbStoreMonitor = new StatefulSessionStoreMonitor();
}
sessionBeanCache.setStatefulSessionStoreMonitor(sfsbStoreMonitor);
_logger.log(Level.FINE, "[SFSBContainer] registered monitorable");
}
private void registerEjbCacheProbeProvider() {
try {
final String applicationName = ejbDescriptor.getApplication().isVirtual() ? null
: ejbDescriptor.getApplication().getRegistrationName();
final String moduleName;
if (applicationName == null) {
moduleName = ejbDescriptor.getApplication().getRegistrationName();
} else {
final String archiveuri = ejbDescriptor.getEjbBundleDescriptor().getModuleDescriptor().getArchiveUri();
moduleName = FileUtils.makeFriendlyFilename(archiveuri);
}
final String ejbNameFromDescriptor = ejbDescriptor.getName();
final ProbeProviderFactory probeFactory = ejbContainerUtilImpl.getProbeProviderFactory();
final String invokerId = EjbMonitoringUtils.getInvokerId(applicationName, moduleName, ejbNameFromDescriptor);
cacheProbeNotifier = probeFactory.getProbeProvider(EjbCacheProbeProvider.class, invokerId);
_logger.log(Level.FINE, "Got ProbeProvider: {0}", cacheProbeNotifier.getClass().getName());
} catch (Exception ex) {
cacheProbeNotifier = new EjbCacheProbeProvider();
_logger.log(Level.FINE, "Error getting the EjbCacheProbeProvider");
}
}
public String getMonitorAttributeValues() {
StringBuilder sbuf = new StringBuilder();
sbuf.append(" { asyncTaskCount=").append(asyncTaskCount)
.append("; asyncCummTaskCount=").append(asyncCummTaskCount)
.append("; passivationBatchCount=").append(passivationBatchCount)
.append("; passivationQSz=").append(passivationCandidates.size())
.append("; trimEventCount=").append(containerTrimCount)
.append(" }");
return sbuf.toString();
}
@Override
protected EjbMonitoringStatsProvider getMonitoringStatsProvider(String appName, String modName, String ejbName) {
StatefulSessionBeanStatsProvider statsProvider = new StatefulSessionBeanStatsProvider(this, getContainerId(),
appName, modName, ejbName);
try {
statsProvider.setPassiveCount(backingStore.size());
} catch (BackingStoreException e) {
_logger.log(Level.WARNING, ERROR_WHILE_BACKSTORE_SIZE_ACCESS, e);
}
return statsProvider;
}
private static String convertCtxStateToString(SessionContextImpl sc) {
switch (sc.getState()) {
case PASSIVATED:
return "PASSIVE";
case READY:
return "READY";
case INVOKING:
return "INVOKING";
case INCOMPLETE_TX:
return "INCOMPLETE_TX";
case DESTROYED:
return "DESTROYED";
default:
return "UNKNOWN-STATE";
}
}
@Override
protected boolean isIdentical(EJBObjectImpl ejbo, EJBObject other) throws RemoteException {
if (other == ejbo.getStub()) {
return true;
}
try {
// other may be a stub for a remote object.
return getProtocolManager().isIdentical(ejbo.getStub(), other);
} catch (Exception ex) {
_logger.log(Level.FINE, "Exception while getting stub for ejb", ex);
throw new RemoteException("Error during isIdentical.", ex);
}
}
/**
* This is called from the generated "HelloEJBHomeImpl" create method
* via EJBHomeImpl.createEJBObject.
* <p>
* Note: for stateful beans, the HelloEJBHomeImpl.create calls
* ejbCreate on the new bean after createEJBObject() returns.
* Return the EJBObject for the bean.
*/
@Override
protected EJBObjectImpl createEJBObjectImpl() throws CreateException, RemoteException {
try {
SessionContextImpl context = createBeanInstance();
EJBObjectImpl ejbObjImpl = createEJBObjectImpl(context);
afterInstanceCreation(context);
return ejbObjImpl;
} catch (Exception ex) {
_logger.log(Level.WARNING, CREATE_EJBOBJECT_EXCEPTION, new Object[] {ejbDescriptor.getName(), ex});
if (ex instanceof EJBException) {
throw (EJBException) ex;
}
CreateException ce = new CreateException("ERROR creating stateful SessionBean");
ce.initCause(ex);
throw ce;
}
}
@Override
protected EJBObjectImpl createRemoteBusinessObjectImpl() throws CreateException, RemoteException {
try {
SessionContextImpl context = createBeanInstance();
EJBObjectImpl ejbBusinessObjImpl = createRemoteBusinessObjectImpl(context);
afterInstanceCreation(context);
return ejbBusinessObjImpl;
} catch (Exception ex) {
_logger.log(Level.WARNING, CREATE_EJBOBJECT_EXCEPTION, new Object[] {ejbDescriptor.getName(), ex});
if (ex instanceof EJBException) {
throw (EJBException) ex;
}
CreateException ce = new CreateException("ERROR creating stateful SessionBean");
ce.initCause(ex);
throw ce;
}
}
/**
* This is called from the generated "HelloEJBLocalHomeImpl" create method
* via EJBLocalHomeImpl.createEJBObject.
* <p>
* Note: for stateful beans, the HelloEJBLocalHomeImpl.create calls
* ejbCreate on the new bean after createEJBLocalObjectImpl() returns.
* Return the EJBLocalObject for the bean.
*/
@Override
protected EJBLocalObjectImpl createEJBLocalObjectImpl() throws CreateException {
try {
SessionContextImpl context = createBeanInstance();
EJBLocalObjectImpl localObjImpl = createEJBLocalObjectImpl(context);
afterInstanceCreation(context);
return localObjImpl;
} catch (Exception ex) {
_logger.log(Level.WARNING, CREATE_EJBLOCALOBJECT_EXCEPTION, new Object[] {ejbDescriptor.getName(), ex});
if (ex instanceof EJBException) {
throw (EJBException) ex;
}
CreateException ce = new CreateException("ERROR creating stateful SessionBean");
ce.initCause(ex);
throw ce;
}
}
/**
* Internal creation event for Local Business view of SFSB
*/
@Override
EJBLocalObjectImpl createEJBLocalBusinessObjectImpl(boolean localBeanView) throws CreateException {
try {
SessionContextImpl context = createBeanInstance();
EJBLocalObjectImpl localBusinessObjImpl = localBeanView ? createOptionalEJBLocalBusinessObjectImpl(context)
: createEJBLocalBusinessObjectImpl(context);
afterInstanceCreation(context);
return localBusinessObjImpl;
} catch (Exception ex) {
_logger.log(Level.WARNING, CREATE_EJBLOCALOBJECT_EXCEPTION, new Object[] {ejbDescriptor.getName(), ex});
if (ex instanceof EJBException) {
throw (EJBException) ex;
}
CreateException ce = new CreateException("ERROR creating stateful SessionBean");
ce.initCause(ex);
throw ce;
}
}
@Override
protected EJBContextImpl _constructEJBContextImpl(Object instance) {
return new SessionContextImpl(instance, this);
}
@Override
protected Object _constructEJBInstance() throws Exception {
if (sfsbSerializedClass == null) {
return ejbClass.getDeclaredConstructor().newInstance();
}
return sfsbSerializedClass.getDeclaredConstructor().newInstance();
}
@Override
protected boolean suspendTransaction(EjbInvocation inv) throws Exception {
SessionContextImpl sc = (SessionContextImpl) inv.context;
return !inv.invocationInfo.isBusinessMethod && !sc.getInLifeCycleCallback();
}
@Override
protected boolean resumeTransaction(EjbInvocation inv) throws Exception {
SessionContextImpl sc = (SessionContextImpl) inv.context;
return !inv.invocationInfo.isBusinessMethod && !sc.getInLifeCycleCallback();
}
/**
* Create a new Session Bean and set Session Context.
*/
private SessionContextImpl createBeanInstance() throws Exception {
EjbInvocation ejbInv = null;
try {
SessionContextImpl context = (SessionContextImpl) createEjbInstanceAndContext();
Object ejb = context.getEJB();
Object sessionKey = uuidGenerator.createSessionKey();
createExtendedEMs(context, sessionKey);
// Need to do preInvoke because setSessionContext can access JNDI
ejbInv = super.createEjbInvocation(ejb, context);
invocationManager.preInvoke(ejbInv);
// setSessionContext will be called without a Tx as required
// by the spec, because the EJBHome.create would have been called
// after the container suspended any client Tx.
// setSessionContext is also called before createEJBObject because
// the bean is not allowed to do EJBContext.getEJBObject here
if (ejb instanceof SessionBean) {
((SessionBean) ejb).setSessionContext(context);
}
// Perform injection right after where setSessionContext
// would be called. This is important since injection methods
// have the same "operations allowed" permissions as
// setSessionContext.
injectEjbInstance(context);
// Set the timestamp before inserting into bean store, else
// Recycler might go crazy and remove this bean!
context.touch();
// Add the EJB into the session store
// and get the instanceKey for this EJB instance.
// XXX The store operation could be avoided for local-only beans.
sessionBeanCache.put(sessionKey, context);
context.setInstanceKey(sessionKey);
_logger.log(Level.FINE, "[SFSBContainer] Created session: {0}", sessionKey);
return context;
} catch (Exception ex) {
throw ex;
} catch (Throwable t) {
EJBException ejbEx = new EJBException();
ejbEx.initCause(t);
throw ejbEx;
} finally {
if (ejbInv != null) {
invocationManager.postInvoke(ejbInv);
}
}
}
private void createExtendedEMs(SessionContextImpl ctx, Object sessionKey) {
Set<EntityManagerReferenceDescriptor> emRefs = ejbDescriptor.getEntityManagerReferenceDescriptors();
Iterator<EntityManagerReferenceDescriptor> iter = emRefs.iterator();
Set<EEMRefInfo> eemRefInfos = new HashSet<>();
while (iter.hasNext()) {
EntityManagerReferenceDescriptor refDesc = iter.next();
if (refDesc.getPersistenceContextType() == PersistenceContextType.EXTENDED) {
String unitName = refDesc.getUnitName();
EntityManagerFactory emf = EntityManagerFactoryWrapper.lookupEntityManagerFactory(
ComponentInvocation.ComponentInvocationType.EJB_INVOCATION, unitName, ejbDescriptor);
if (emf != null) {
PhysicalEntityManagerWrapper physicalEntityManagerWrapper = findExtendedEMFromInvList(emf);
if (physicalEntityManagerWrapper == null) {
// We did not find an extended EM that we can inherit from. Create one
try {
EntityManager em = emf.createEntityManager(refDesc.getSynchronizationType(),
refDesc.getProperties());
physicalEntityManagerWrapper = new PhysicalEntityManagerWrapper(em,
refDesc.getSynchronizationType());
} catch (Throwable th) {
EJBException ejbEx = new EJBException("Couldn't create EntityManager for" + " refName: "
+ refDesc.getName() + "; unitname: " + unitName);
ejbEx.initCause(th);
throw ejbEx;
}
} else {
// We found an extended EM we can inherit from. Validate that sync type matches
if (physicalEntityManagerWrapper.getSynchronizationType() != refDesc.getSynchronizationType()) {
throw new EJBException(
"The current invocation inherits a persistence context of synchronization type '"
+ physicalEntityManagerWrapper.getSynchronizationType()
+ "' where as it references a persistence context of synchronization type '"
+ refDesc.getSynchronizationType() + "' refName: " + refDesc.getName()
+ " unitName: " + unitName);
}
}
String emRefName = refDesc.getName();
long containerID = this.getContainerId();
EEMRefInfo refInfo = null;
synchronized (extendedEMReferenceCountMap) {
refInfo = extendedEMReferenceCountMap.get(physicalEntityManagerWrapper.getEM());
if (refInfo != null) {
refInfo.refCount++;
} else {
refInfo = new EEMRefInfo(emRefName, refDesc.getUnitName(), refDesc.getSynchronizationType(),
containerID, sessionKey, physicalEntityManagerWrapper.getEM(), emf);
refInfo.refCount = 1;
extendedEMReferenceCountMap.put(physicalEntityManagerWrapper.getEM(), refInfo);
eemKey2EEMMap.put(refInfo.getKey(), refInfo.getEntityManager());
}
}
ctx.addExtendedEntityManagerMapping(emf, refInfo);
eemRefInfos.add(refInfo);
} else {
throw new EJBException("EMF is null. Couldn't get extended EntityManager for"
+ " refName: " + refDesc.getName()
+ "; unitname: " + unitName);
}
}
}
if (!eemRefInfos.isEmpty()) {
ctx.setEEMRefInfos(eemRefInfos);
}
}
private PhysicalEntityManagerWrapper findExtendedEMFromInvList(EntityManagerFactory emf) {
ComponentInvocation compInv = invocationManager.getCurrentInvocation();
if (compInv != null) {
if (compInv.getInvocationType() == ComponentInvocation.ComponentInvocationType.EJB_INVOCATION) {
EjbInvocation ejbInv = (EjbInvocation) compInv;
if (ejbInv.context instanceof SessionContextImpl) {
SessionContextImpl ctxImpl = (SessionContextImpl) ejbInv.context;
if (ctxImpl.container instanceof StatefulSessionContainer) {
return ctxImpl.getExtendedEntityManager(emf);
}
}
}
}
return null;
}
@Override
public EntityManager lookupExtendedEntityManager(EntityManagerFactory emf) {
PhysicalEntityManagerWrapper physicalEntityManagerWrapper = findExtendedEMFromInvList(emf);
return physicalEntityManagerWrapper == null ? null : physicalEntityManagerWrapper.getEM();
}
private void afterInstanceCreation(SessionContextImpl context) throws Exception {
context.setState(BeanState.READY);
EjbInvocation ejbInv = null;
boolean inTx = false;
try {
// Need to do preInvoke because setSessionContext can access JNDI
ejbInv = super.createEjbInvocation(context.getEJB(), context);
invocationManager.preInvoke(ejbInv);
// PostConstruct must be called after state set to something other than CREATED
inTx = callLifecycleCallbackInTxIfUsed(ejbInv, context, postConstructInvInfo, CallbackType.POST_CONSTRUCT);
} catch (Throwable t) {
EJBException ejbEx = new EJBException();
ejbEx.initCause(t);
throw ejbEx;
} finally {
if (ejbInv != null) {
try {
invocationManager.postInvoke(ejbInv);
if (inTx) {
// Call directly to report exception
postInvokeTx(ejbInv);
}
} catch (Exception pie) {
if (ejbInv.exception != null) {
_logger.log(Level.FINE, "Exception during SFSB startup postInvoke ", pie);
} else {
ejbInv.exception = pie;
CreateException creEx = new CreateException(
"Initialization failed for Stateful Session Bean " + ejbDescriptor.getName());
creEx.initCause(pie);
throw creEx;
}
} finally {
context.setInLifeCycleCallback(false);
}
}
}
ejbProbeNotifier.ejbBeanCreatedEvent(getContainerId(),
containerInfo.appName, containerInfo.modName,
containerInfo.ejbName);
incrementMethodReadyStat();
}
// called from createEJBObject and activateEJB and createEJBLocalObjectImpl
private EJBLocalObjectImpl createEJBLocalObjectImpl(SessionContextImpl context) throws Exception {
if (context.getEJBLocalObjectImpl() != null) {
return context.getEJBLocalObjectImpl();
}
// create EJBLocalObject
EJBLocalObjectImpl localObjImpl = instantiateEJBLocalObjectImpl(context.getInstanceKey());
// introduce context and EJBLocalObject to each other
context.setEJBLocalObjectImpl(localObjImpl);
localObjImpl.setContext(context);
if (hasLocalBusinessView) {
createEJBLocalBusinessObjectImpl(context);
}
if (hasOptionalLocalBusinessView) {
createOptionalEJBLocalBusinessObjectImpl(context);
}
if (hasRemoteHomeView) {
// enable remote invocations too
createEJBObjectImpl(context);
}
if (hasRemoteBusinessView) {
createRemoteBusinessObjectImpl(context);
}
return localObjImpl;
}
private EJBLocalObjectImpl createEJBLocalBusinessObjectImpl(SessionContextImpl context) throws Exception {
if (context.getEJBLocalBusinessObjectImpl() != null) {
return context.getEJBLocalBusinessObjectImpl();
}
EJBLocalObjectImpl localBusinessObjImpl = instantiateEJBLocalBusinessObjectImpl();
context.setEJBLocalBusinessObjectImpl(localBusinessObjImpl);
localBusinessObjImpl.setContext(context);
localBusinessObjImpl.setKey(context.getInstanceKey());
if (hasOptionalLocalBusinessView) {
createOptionalEJBLocalBusinessObjectImpl(context);
}
if (hasLocalHomeView) {
createEJBLocalObjectImpl(context);
}
if (hasRemoteHomeView) {
// enable remote invocations too
createEJBObjectImpl(context);
}
if (hasRemoteBusinessView) {
createRemoteBusinessObjectImpl(context);
}
return localBusinessObjImpl;
}
private EJBLocalObjectImpl createOptionalEJBLocalBusinessObjectImpl(SessionContextImpl context) throws Exception {
if (context.getOptionalEJBLocalBusinessObjectImpl() != null) {
return context.getOptionalEJBLocalBusinessObjectImpl();
}
EJBLocalObjectImpl optionalLocalBusinessObjImpl = instantiateOptionalEJBLocalBusinessObjectImpl();
context.setOptionalEJBLocalBusinessObjectImpl(optionalLocalBusinessObjImpl);
optionalLocalBusinessObjImpl.setContext(context);
optionalLocalBusinessObjImpl.setKey(context.getInstanceKey());
if (hasLocalBusinessView) {
createEJBLocalBusinessObjectImpl(context);
}
if (hasLocalHomeView) {
createEJBLocalObjectImpl(context);
}
if (hasRemoteHomeView) {
// enable remote invocations too
createEJBObjectImpl(context);
}
if (hasRemoteBusinessView) {
createRemoteBusinessObjectImpl(context);
}
return optionalLocalBusinessObjImpl;
}
// called from createEJBObject and activateEJB and createEJBLocalObjectImpl
private EJBObjectImpl createEJBObjectImpl(SessionContextImpl context) throws Exception {
if (context.getEJBObjectImpl() != null) {
return context.getEJBObjectImpl();
}
// create EJBObject and associate it with the key
Object sessionKey = context.getInstanceKey();
EJBObjectImpl ejbObjImpl = instantiateEJBObjectImpl(null, sessionKey);
// introduce context and EJBObject to each other
context.setEJBObjectImpl(ejbObjImpl);
ejbObjImpl.setContext(context);
// connect the EJBObject to the ProtocolManager
// (creates the client-side stub too)
byte[] sessionOID = uuidGenerator.keyToByteArray(sessionKey);
EJBObject ejbStub = (EJBObject) remoteHomeRefFactory.createRemoteReference(sessionOID);
context.setEJBStub(ejbStub);
ejbObjImpl.setStub(ejbStub);