KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > ejb > containers > SessionContextImpl


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.ejb.containers;
24
25 import java.lang.reflect.Method JavaDoc;
26
27 import java.util.Map JavaDoc;
28 import java.util.Set JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.HashSet JavaDoc;
31 import java.util.Collection JavaDoc;
32
33 import javax.ejb.*;
34 import javax.transaction.UserTransaction JavaDoc;
35 import javax.xml.rpc.handler.MessageContext JavaDoc;
36
37 import javax.persistence.EntityManagerFactory;
38 import javax.persistence.EntityManager;
39
40 import com.sun.ejb.*;
41 import com.sun.enterprise.*;
42 import com.sun.enterprise.deployment.EjbSessionDescriptor;
43 import com.sun.enterprise.deployment.EjbDescriptor;
44
45 import com.sun.ejb.spi.container.StatefulEJBContext;
46
47 /**
48  * Implementation of EJBContext for SessionBeans
49  *
50  * @author Mahesh Kannan
51  */

52
53 public final class SessionContextImpl
54     extends EJBContextImpl
55     implements SessionContext, StatefulEJBContext
56 {
57     private Object JavaDoc instanceKey;
58     private boolean completedTxStatus;
59     private boolean afterCompletionDelayed=false;
60     private boolean committing=false;
61     private boolean inAfterCompletion=false;
62     private boolean isStateless = false;
63     private boolean isStateful = false;
64
65     private boolean existsInSessionStore = false;
66     private transient int refCount = 0;
67
68     private boolean txCheckpointDelayed;
69     private String JavaDoc ejbName;
70     private long lastPersistedAt;
71
72     // Map of entity managers with extended persistence context
73
// for this stateful session bean.
74
private Map JavaDoc<EntityManagerFactory, EntityManager> extendedEntityManagerMap;
75
76     private Set JavaDoc<EntityManagerFactory> emfsRegisteredWithTx;
77
78     SessionContextImpl(Object JavaDoc ejb, BaseContainer container) {
79         super(ejb, container);
80         EjbSessionDescriptor sessionDesc =
81             (EjbSessionDescriptor) getContainer().getEjbDescriptor();
82         isStateless = sessionDesc.isStateless();
83         isStateful = sessionDesc.isStateful();
84
85     this.ejbName = sessionDesc.getName();
86     }
87
88     public String JavaDoc toString() {
89     return ejbName + "; id: " + instanceKey;
90     }
91
92     public Map JavaDoc<EntityManagerFactory, EntityManager>
93         getExtendedEntityManagerMap() {
94         if( extendedEntityManagerMap == null ) {
95             extendedEntityManagerMap =
96                 new HashMap JavaDoc<EntityManagerFactory, EntityManager>();
97         }
98         return extendedEntityManagerMap;
99     }
100
101     public void addExtendedEntityManagerMapping(EntityManagerFactory emf,
102                                                 EntityManager em) {
103         getExtendedEntityManagerMap().put(emf, em);
104     }
105
106     public EntityManager getExtendedEntityManager(EntityManagerFactory emf) {
107         return getExtendedEntityManagerMap().get(emf);
108     }
109
110     public Collection JavaDoc<EntityManager> getExtendedEntityManagers() {
111         return getExtendedEntityManagerMap().values();
112     }
113
114     private Set JavaDoc<EntityManagerFactory> getEmfsRegisteredWithTx() {
115         if( emfsRegisteredWithTx == null ) {
116             emfsRegisteredWithTx = new HashSet JavaDoc<EntityManagerFactory>();
117         }
118         return emfsRegisteredWithTx;
119     }
120
121     public void setEmfRegisteredWithTx(EntityManagerFactory emf, boolean flag)
122     {
123         if( flag ) {
124             getEmfsRegisteredWithTx().add(emf);
125         } else {
126             getEmfsRegisteredWithTx().remove(emf);
127         }
128     }
129
130     public boolean isEmfRegisteredWithTx(EntityManagerFactory emf) {
131         return getEmfsRegisteredWithTx().contains(emf);
132     }
133
134     public TimerService getTimerService() throws IllegalStateException JavaDoc {
135         if( isStateful ) {
136             throw new IllegalStateException JavaDoc
137                 ("EJBTimer Service is not accessible to Stateful Session ejbs");
138         }
139
140         // Instance key is first set between after setSessionContext and
141
// before ejbCreate
142
if ( instanceKey == null ) {
143             throw new IllegalStateException JavaDoc("Operation not allowed");
144         }
145
146         ContainerFactoryImpl cf = (ContainerFactoryImpl)
147         Switch.getSwitch().getContainerFactory();
148         EJBTimerService timerService = cf.getEJBTimerService();
149         if( timerService == null ) {
150             throw new EJBException("EJB Timer service not available");
151         }
152
153         return new EJBTimerServiceWrapper(timerService, this);
154     }
155     
156     public UserTransaction JavaDoc getUserTransaction()
157         throws IllegalStateException JavaDoc
158     {
159         // The state check ensures that an exception is thrown if this
160
// was called from setSession/EntityContext. The instance key check
161
// ensures that an exception is not thrown if this was called
162
// from a stateless SessionBean's ejbCreate.
163
if ( (state == NOT_INITIALIZED) && (instanceKey == null) )
164             throw new IllegalStateException JavaDoc("Operation not allowed");
165         
166         return ((BaseContainer)getContainer()).getUserTransaction();
167     }
168     
169     public MessageContext JavaDoc getMessageContext() {
170         if( isStateless ) {
171             Switch theSwitch = Switch.getSwitch();
172             InvocationManager invManager = theSwitch.getInvocationManager();
173             try {
174                 ComponentInvocation inv = invManager.getCurrentInvocation();
175                     
176                 if( (inv != null) && isWebServiceInvocation(inv) ) {
177                     return ((Invocation)inv).messageContext;
178                 } else {
179                     throw new IllegalStateException JavaDoc("Attempt to access " +
180                        "MessageContext outside of a web service invocation");
181                 }
182             } catch(Exception JavaDoc e) {
183                 IllegalStateException JavaDoc ise = new IllegalStateException JavaDoc();
184                 ise.initCause(e);
185                 throw ise;
186             }
187         } else {
188             throw new IllegalStateException JavaDoc
189                 ("Attempt to access MessageContext from stateful session ejb");
190         }
191     }
192
193     public <T> T getBusinessObject(Class JavaDoc<T> businessInterface)
194         throws IllegalStateException JavaDoc
195     {
196
197         // getBusinessObject not allowed for Stateless/Stateful beans
198
// until after dependency injection
199
if ( instanceKey == null ) {
200             throw new IllegalStateException JavaDoc("Operation not allowed");
201         }
202
203         T businessObject = null;
204
205         EjbDescriptor ejbDesc = container.getEjbDescriptor();
206
207         if( businessInterface != null ) {
208             String JavaDoc intfName = businessInterface.getName();
209             
210             if( (ejbLocalBusinessObjectImpl != null) &&
211                 ejbDesc.getLocalBusinessClassNames().contains(intfName) ) {
212
213                 // Get proxy corresponding to this business interface.
214
businessObject = (T) ejbLocalBusinessObjectImpl
215                     .getClientObject(intfName);
216
217             } else if( (ejbRemoteBusinessObjectImpl != null) &&
218                    ejbDesc.getRemoteBusinessClassNames().contains(intfName)) {
219
220                 // Create a new client object from the stub for this
221
// business interface.
222
String JavaDoc generatedIntf =
223                     EJBUtils.getGeneratedRemoteIntfName(intfName);
224
225                 java.rmi.Remote JavaDoc stub =
226                     ejbRemoteBusinessObjectImpl.getStub(generatedIntf);
227
228                 try {
229                     businessObject = (T) EJBUtils.createRemoteBusinessObject
230                         (container.getClassLoader(), intfName, stub);
231                 } catch(Exception JavaDoc e) {
232
233                     IllegalStateException JavaDoc ise = new IllegalStateException JavaDoc
234                         ("Error creating remote business object for " +
235                          intfName);
236                     ise.initCause(e);
237                     throw ise;
238                 }
239             }
240         }
241         
242         if( businessObject == null ) {
243             throw new IllegalStateException JavaDoc("Invalid business interface : " +
244                 businessInterface + " for ejb " + ejbDesc.getName());
245         }
246         
247         return businessObject;
248     }
249
250     public Class JavaDoc getInvokedBusinessInterface()
251         throws IllegalStateException JavaDoc
252     {
253
254         Switch theSwitch = Switch.getSwitch();
255         InvocationManager invManager = theSwitch.getInvocationManager();
256
257         Class JavaDoc businessInterface = null;
258
259         try {
260             ComponentInvocation inv = invManager.getCurrentInvocation();
261             
262             if( (inv != null) && (inv instanceof Invocation) ) {
263                 Invocation invocation = (Invocation) inv;
264                 if( invocation.isBusinessInterface ) {
265                     businessInterface = invocation.clientInterface;
266                 }
267             }
268         } catch(Exception JavaDoc e) {
269             IllegalStateException JavaDoc ise = new IllegalStateException JavaDoc();
270             ise.initCause(e);
271             throw ise;
272         }
273
274         if( businessInterface == null ) {
275             throw new IllegalStateException JavaDoc("Attempt to call " +
276                "getInvokedBusinessInterface outside the scope of a business " +
277                                             "method");
278         }
279
280         return businessInterface;
281     }
282     
283     protected void checkAccessToCallerSecurity()
284         throws IllegalStateException JavaDoc
285     {
286         
287         if( isStateless ) {
288             // This covers constructor, setSessionContext, ejbCreate,
289
// and ejbRemove. NOTE : For stateless session beans,
290
// instances don't move past NOT_INITIALIZED until after ejbCreate.
291
if( (state == NOT_INITIALIZED) || inEjbRemove ) {
292                 throw new IllegalStateException JavaDoc("Operation not allowed");
293             }
294         } else {
295             // This covers constructor and setSessionContext.
296
// For stateful session beans, instances move past
297
// NOT_INITIALIZED after setSessionContext.
298
if( state == NOT_INITIALIZED ) {
299                 throw new IllegalStateException JavaDoc("Operation not allowed");
300             }
301         }
302         
303     }
304     
305     
306     public void checkTimerServiceMethodAccess()
307         throws IllegalStateException JavaDoc
308     {
309         // checks that only apply to stateful session beans
310
ComponentInvocation compInv = getCurrentComponentInvocation();
311         if (isStateful) {
312             if (
313             inStatefulSessionEjbCreate(compInv) ||
314             inActivatePassivate(compInv) ||
315             inAfterCompletion ) {
316                 throw new IllegalStateException JavaDoc
317                 ("EJB Timer methods for stateful session beans cannot be " +
318                 " called in this context");
319             }
320         }
321         
322         // checks that apply to both stateful AND stateless
323
if ( (state == NOT_INITIALIZED) || inEjbRemove ) {
324             throw new IllegalStateException JavaDoc
325             ("EJB Timer method calls cannot be called in this context");
326         }
327     }
328     
329     public Object JavaDoc getInstanceKey() {
330         return instanceKey;
331     }
332     
333     public void setInstanceKey(Object JavaDoc instanceKey) {
334         this.instanceKey = instanceKey;
335     }
336     
337     
338     boolean getCompletedTxStatus() {
339         return completedTxStatus;
340     }
341     
342     void setCompletedTxStatus(boolean s) {
343         this.completedTxStatus = s;
344     }
345     
346     boolean isAfterCompletionDelayed() {
347         return afterCompletionDelayed;
348     }
349     
350     void setAfterCompletionDelayed(boolean s) {
351         this.afterCompletionDelayed = s;
352     }
353     
354     boolean isTxCompleting() {
355         return committing;
356     }
357     
358     void setTxCompleting(boolean s) {
359         this.committing = s;
360     }
361     
362     void setInAfterCompletion(boolean flag) {
363         inAfterCompletion = flag;
364     }
365
366     private ComponentInvocation getCurrentComponentInvocation() {
367         BaseContainer container = (BaseContainer) getContainer();
368         return container.invocationManager.getCurrentInvocation();
369     }
370     
371     private boolean isWebServiceInvocation(ComponentInvocation inv) {
372         return (inv instanceof Invocation) && ((Invocation)inv).isWebService;
373     }
374     
375     // Used to check if stateful session bean is in ejbCreate.
376
// Since bean goes to READY state before ejbCreate is called by
377
// EJBHomeImpl and EJBLocalHomeImpl, we can't rely on getState()
378
// being NOT_INITIALIZED for operations matrix checks.
379
private boolean inStatefulSessionEjbCreate(ComponentInvocation inv) {
380         boolean inEjbCreate = false;
381         if ( inv instanceof Invocation ) {
382             Class JavaDoc clientIntf = ((Invocation)inv).clientInterface;
383             // If call came through a home/local-home, this can only be a
384
// create call.
385
inEjbCreate = ((Invocation)inv).isHome &&
386                 (javax.ejb.EJBHome JavaDoc.class.isAssignableFrom(clientIntf) ||
387                  javax.ejb.EJBLocalHome JavaDoc.class.isAssignableFrom(clientIntf));
388         }
389         return inEjbCreate;
390     }
391     
392     void setTxCheckpointDelayed(boolean val) {
393     this.txCheckpointDelayed = val;
394     }
395
396     boolean isTxCheckpointDelayed() {
397     return this.txCheckpointDelayed;
398     }
399
400     long getLastPersistedAt() {
401     return lastPersistedAt;
402     }
403
404     void setLastPersistedAt(long val) {
405     this.lastPersistedAt = val;
406     }
407
408     /*************************************************************************/
409     /************ Implementation of StatefulEJBContext ***********************/
410     /*************************************************************************/
411
412     public long getLastAccessTime() {
413         return getLastTimeUsed();
414     }
415
416     public boolean canBePassivated() {
417         return ((state == StatefulSessionContainer.READY)
418             && (! hasExtendedPC()));
419     }
420     
421     public boolean hasExtendedPC() {
422         return (this.getExtendedEntityManagerMap().size() != 0);
423     }
424
425     public SessionContext getSessionContext() {
426         return this;
427     }
428
429     public boolean existsInStore() {
430         return existsInSessionStore ;
431     }
432
433     public void setExistsInStore(boolean val) {
434         this.existsInSessionStore = val;
435     }
436
437     public final void incrementRefCount() {
438         refCount++;
439     }
440
441     public final void decrementRefCount() {
442         refCount--;
443     }
444
445     public final int getRefCount() {
446         return refCount;
447     }
448
449 }
450
Popular Tags