KickJava   Java API By Example, From Geeks To Geeks.

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


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.util.*;
26 import java.security.Identity JavaDoc;
27 import java.security.Principal JavaDoc;
28 import java.lang.reflect.Method JavaDoc;
29
30 import java.lang.ref.*;
31
32 import javax.ejb.*;
33 import javax.transaction.*;
34
35 import com.sun.ejb.*;
36 import com.sun.enterprise.*;
37 import com.sun.enterprise.util.LocalStringManagerImpl;
38 import com.sun.enterprise.resource.ResourceHandle;
39 import com.sun.enterprise.deployment.EjbDescriptor;
40 import com.sun.enterprise.deployment.RoleReference;
41
42 import com.sun.ejb.containers.util.cache.CacheEntry;
43
44 import java.util.logging.*;
45 import com.sun.logging.*;
46 import javax.naming.Context JavaDoc;
47 import javax.naming.InitialContext JavaDoc;
48
49 /**
50  * Implementation of javax.ejb.EJBContext for the J2EE Reference Implementation.
51  *
52  */

53
54 public abstract class EJBContextImpl
55     implements EJBContext, ComponentContext, java.io.Serializable JavaDoc
56 {
57     private static Logger _logger;
58     static {
59         _logger=LogDomains.getLogger(LogDomains.EJB_LOGGER);
60     }
61     
62     private static LocalStringManagerImpl localStrings =
63     new LocalStringManagerImpl(EJBContextImpl.class);
64     protected static int NOT_INITIALIZED = -999; // not initialized state
65

66     private Object JavaDoc ejb;
67     
68     // These are all transient to prevent serialization during passivation
69
// Note: all these will be initialized to default values during
70
// deserialization.
71
transient protected BaseContainer container;
72     
73     transient protected Transaction transaction = null;
74     transient private Context JavaDoc initialContext = null;
75     transient private ArrayList resources;
76     transient private int concInvokeCount = 0;
77     
78     // the EJBObject's client-side RMI stub
79
transient protected EJBObject ejbStub=null;
80     transient protected EJBObjectImpl ejbObjectImpl;
81
82     transient protected EJBObjectImpl ejbRemoteBusinessObjectImpl;
83
84     transient protected EJBLocalObjectImpl ejbLocalObjectImpl;
85     transient protected EJBLocalObjectImpl ejbLocalBusinessObjectImpl;
86     
87     transient private long lastTimeUsed;
88     transient protected int state;
89     
90     // true if the bean exposes a RemoteHome/Remote view
91
// (not 3.0 business view)
92
protected final boolean isRemoteInterfaceSupported;
93
94     // true if the bean exposes a LocalHome/Localview
95
// (not 3.0 business view)
96
protected final boolean isLocalInterfaceSupported;
97
98     // can't/doesn't set the context to DESTROYED until after calling ejbRemove
99
// but it needs a way to know if bean is being removed. Standardizing
100
// on the DESTROYED state doesn't help, since often times the container
101
// can't/doesn't set the context to DESTROYED until after calling ejbRemove
102
transient protected boolean inEjbRemove;
103     
104     private Object JavaDoc[] interceptorInstances;
105     
106     EJBContextImpl(Object JavaDoc ejb, BaseContainer container) {
107         this.ejb = ejb;
108         this.container = container;
109         state = NOT_INITIALIZED;
110         inEjbRemove = false;
111
112         isRemoteInterfaceSupported = container.isRemoteInterfaceSupported();
113         isLocalInterfaceSupported = container.isLocalInterfaceSupported();
114     }
115     
116     public Transaction getTransaction() {
117         return transaction;
118     }
119     
120     public void setTransaction(Transaction tr) {
121         transaction = tr;
122     }
123     
124     void setEJBStub(EJBObject ejbStub) {
125         this.ejbStub = ejbStub;
126     }
127     
128     void setEJBLocalObjectImpl(EJBLocalObjectImpl localObjectImpl) {
129         this.ejbLocalObjectImpl = localObjectImpl;
130     }
131
132     void setEJBLocalBusinessObjectImpl(EJBLocalObjectImpl localBusObjectImpl) {
133         this.ejbLocalBusinessObjectImpl = localBusObjectImpl;
134     }
135
136     
137     void setEJBObjectImpl(EJBObjectImpl ejbo) {
138         this.ejbObjectImpl = ejbo;
139     }
140     
141     EJBObjectImpl getEJBObjectImpl() {
142         return ejbObjectImpl;
143     }
144     
145     void setEJBRemoteBusinessObjectImpl(EJBObjectImpl ejbo) {
146         this.ejbRemoteBusinessObjectImpl = ejbo;
147     }
148
149     EJBObjectImpl getEJBRemoteBusinessObjectImpl() {
150         return this.ejbRemoteBusinessObjectImpl;
151     }
152
153     EJBLocalObjectImpl getEJBLocalObjectImpl() {
154         return ejbLocalObjectImpl;
155     }
156
157     EJBLocalObjectImpl getEJBLocalBusinessObjectImpl() {
158         return ejbLocalBusinessObjectImpl;
159     }
160     
161     void setContainer(BaseContainer container) {
162         this.container = container;
163     }
164     
165     void setState(int s) {
166         state = s;
167     }
168
169     boolean isTimedObject() {
170         return container.isTimedObject();
171     }
172
173     int getState() {
174         return state;
175     }
176     
177     void setInEjbRemove(boolean beingRemoved) {
178         inEjbRemove = beingRemoved;
179     }
180     
181     boolean isInEjbRemove() {
182         return inEjbRemove;
183     }
184     
185     /**
186      * Returns true if this context has NOT progressed past its initial
187      * state. The point at which this happens is container-specific.
188      */

189     boolean isUnitialized() {
190         return (state == NOT_INITIALIZED);
191     }
192     
193     public long getLastTimeUsed() {
194         return lastTimeUsed;
195     }
196     
197     void setSoftRef(SoftReference softRef) {
198     }
199     
200     void setHardRef(Object JavaDoc referent) {
201     }
202     
203     void touch() {
204         lastTimeUsed = System.currentTimeMillis();
205     }
206     
207     
208     
209     /**************************************************************************
210     The following are implementations of ComponentContext methods.
211      **************************************************************************/

212     
213     /**
214      *
215      */

216     public Object JavaDoc getEJB() {
217         return ejb;
218     }
219     
220     
221     public Container getContainer() {
222         return container;
223     }
224     
225     /**
226      * Register a resource opened by the EJB instance
227      * associated with this Context.
228      */

229     public void registerResource(ResourceHandle h) {
230         if ( resources == null )
231             resources = new ArrayList();
232         resources.add(h);
233     }
234     
235     /**
236      * Unregister a resource from this Context.
237      */

238     public void unregisterResource(ResourceHandle h) {
239         if ( resources == null )
240             resources = new ArrayList();
241         resources.remove(h);
242     }
243
244     /**
245      * Get all the resources associated with the context
246      */

247     public List getResourceList() {
248         if (resources == null)
249             resources = new ArrayList(0);
250         return resources;
251     }
252     
253     
254     /**
255      * Get the number of concurrent invocations on this bean
256      * (could happen with re-entrant bean).
257      * Used by TM.
258      */

259     public int getConcurrentInvokeCount() {
260         return concInvokeCount;
261     }
262     
263     /**
264      * Increment the number of concurrent invocations on this bean
265      * (could happen with re-entrant bean).
266      * Used by TM.
267      */

268     public synchronized void incrementConcurrentInvokeCount() {
269         concInvokeCount++;
270     }
271     
272     /**
273      * Decrement the number of concurrent invocations on this bean
274      * (could happen with re-entrant bean).
275      * Used by TM.
276      */

277     public synchronized void decrementConcurrentInvokeCount() {
278         concInvokeCount--;
279     }
280     
281     /**************************************************************************
282     The following are implementations of EJBContext methods.
283      **************************************************************************/

284     
285     /**
286      * This is a SessionContext/EntityContext method.
287      */

288     public EJBObject getEJBObject()
289         throws IllegalStateException JavaDoc
290     {
291         if (ejbStub == null) {
292             throw new IllegalStateException JavaDoc("EJBObject not available");
293         }
294
295         return ejbStub;
296     }
297     
298     /**
299      * This is a SessionContext/EntityContext method.
300      */

301     public EJBLocalObject getEJBLocalObject()
302         throws IllegalStateException JavaDoc
303     {
304         if ( ejbLocalObjectImpl == null ) {
305             throw new IllegalStateException JavaDoc("EJBLocalObject not available");
306         }
307         
308         // Have to convert EJBLocalObjectImpl to the client-view of
309
// EJBLocalObject
310
return (EJBLocalObject) ejbLocalObjectImpl.getClientObject();
311     }
312     
313     /**
314      *
315      */

316     public EJBHome getEJBHome() {
317         if (! isRemoteInterfaceSupported) {
318             throw new IllegalStateException JavaDoc("EJBHome not available");
319         }
320
321         return container.getEJBHomeStub();
322     }
323     
324     
325     /**
326      *
327      */

328     public EJBLocalHome getEJBLocalHome() {
329         if (! isLocalInterfaceSupported) {
330             throw new IllegalStateException JavaDoc("EJBLocalHome not available");
331         }
332
333         return container.getEJBLocalHome();
334     }
335     
336     
337     /**
338      *
339      */

340     public Properties getEnvironment() {
341         // This is deprecated, see EJB2.0 section 20.6.
342
return container.getEnvironmentProperties();
343     }
344     
345     /**
346      * @deprecated
347      */

348     public Identity JavaDoc getCallerIdentity() {
349         // This method is deprecated.
350
// see EJB2.0 section 21.2.5
351
throw new RuntimeException JavaDoc(
352         "getCallerIdentity() is deprecated, please use getCallerPrincipal().");
353     }
354
355
356     public Object JavaDoc lookup(String JavaDoc name) {
357         Object JavaDoc o = null;
358
359         if( name == null ) {
360             throw new IllegalArgumentException JavaDoc("Argument is null");
361         }
362         try {
363             if( initialContext == null ) {
364                 initialContext = new InitialContext JavaDoc();
365             }
366             // name is relative to the private component namespace
367
o = initialContext.lookup("java:comp/env/" + name);
368         } catch(Exception JavaDoc e) {
369             throw new IllegalArgumentException JavaDoc(e);
370         }
371         return o;
372     }
373     
374     /**
375      *
376      */

377     public Principal JavaDoc getCallerPrincipal() {
378
379         checkAccessToCallerSecurity();
380
381         com.sun.enterprise.SecurityManager sm = container.getSecurityManager();
382         return sm.getCallerPrincipal();
383     }
384     
385     
386     /**
387      * @deprecated
388      */

389     public boolean isCallerInRole(Identity JavaDoc identity) {
390         // THis method is deprecated.
391
// This implementation is as in EJB2.0 section 21.2.5
392
return isCallerInRole(identity.getName());
393     }
394     
395     
396     /**
397      *
398      */

399     public boolean isCallerInRole(String JavaDoc roleRef) {
400         if ( roleRef == null )
401             throw new IllegalArgumentException JavaDoc("Argument is null");
402
403         checkAccessToCallerSecurity();
404         
405         EjbDescriptor ejbd = container.getEjbDescriptor();
406         RoleReference rr = ejbd.getRoleReferenceByName(roleRef);
407         
408         if ( rr == null ) {
409             throw new IllegalArgumentException JavaDoc(
410                 "No mapping available for role reference " + roleRef);
411         }
412         
413         com.sun.enterprise.SecurityManager sm = container.getSecurityManager();
414     return sm.isCallerInRole(roleRef);
415     }
416     
417     /**
418      * Overridden in containers that allow access to isCallerInRole() and
419      * getCallerPrincipal()
420      */

421     protected void checkAccessToCallerSecurity()
422         throws IllegalStateException JavaDoc
423     {
424         throw new IllegalStateException JavaDoc("Operation not allowed");
425     }
426     
427     /**
428      *
429      */

430     public UserTransaction getUserTransaction()
431         throws IllegalStateException JavaDoc
432     {
433         throw new IllegalStateException JavaDoc("Operation not allowed");
434     }
435     
436     /**
437      *
438      */

439     public void setRollbackOnly()
440         throws IllegalStateException JavaDoc
441     {
442         if ( state == NOT_INITIALIZED )
443             throw new IllegalStateException JavaDoc("EJB not in READY state");
444         
445         // EJB2.0 section 7.5.2: only EJBs with container managed transactions
446
// can use this method.
447
if ( container.isBeanManagedTx() )
448             throw new IllegalStateException JavaDoc(
449                 "Illegal operation for bean-managed transactions");
450         
451         J2EETransactionManager tm = Switch.getSwitch().getTransactionManager();
452         
453         try {
454             if ( tm.getStatus() == Status.STATUS_NO_TRANSACTION ) {
455                 // EJB might be in a non-business method (for SessionBeans)
456
// or afterCompletion.
457
// OR this was a NotSupported/Never/Supports
458
// EJB which was invoked without a global transaction.
459
// In that case the JDBC connection would have autoCommit=true
460
// so the container doesnt have to do anything.
461
throw new IllegalStateException JavaDoc("No transaction context.");
462             }
463             
464             checkActivatePassivate();
465             
466             tm.setRollbackOnly();
467             
468         } catch (Exception JavaDoc ex) {
469             IllegalStateException JavaDoc illEx = new IllegalStateException JavaDoc(ex.toString());
470             illEx.initCause(ex);
471             throw illEx;
472         }
473     }
474     
475     /**
476      *
477      */

478     public boolean getRollbackOnly()
479         throws IllegalStateException JavaDoc
480     {
481         if ( state == NOT_INITIALIZED )
482             throw new IllegalStateException JavaDoc("EJB not in READY state");
483         
484         // EJB2.0 section 7.5.2: only EJBs with container managed transactions
485
// can use this method.
486
if ( container.isBeanManagedTx() )
487             throw new IllegalStateException JavaDoc(
488                 "Illegal operation for bean-managed transactions");
489         
490         J2EETransactionManager tm = Switch.getSwitch().getTransactionManager();
491         
492         try {
493             int status = tm.getStatus();
494             if ( status == Status.STATUS_NO_TRANSACTION ) {
495                 // EJB which was invoked without a global transaction.
496
throw new IllegalStateException JavaDoc("No transaction context.");
497             }
498             
499             checkActivatePassivate();
500             
501             if ( status == Status.STATUS_MARKED_ROLLBACK
502             || status == Status.STATUS_ROLLEDBACK
503             || status == Status.STATUS_ROLLING_BACK )
504                 return true;
505             else
506                 return false;
507         } catch (Exception JavaDoc ex) {
508             _logger.log(Level.FINE, "Exception in method getRollbackOnly()",
509                 ex);
510             IllegalStateException JavaDoc illEx = new IllegalStateException JavaDoc(ex.toString());
511             illEx.initCause(ex);
512             throw illEx;
513         }
514     }
515     
516     /**************************************************************************
517     The following are EJBContextImpl-specific methods.
518      **************************************************************************/

519     void setInterceptorInstances(Object JavaDoc[] instances) {
520         this.interceptorInstances = instances;
521     }
522     
523     public Object JavaDoc[] getInterceptorInstances() {
524         return this.interceptorInstances;
525     }
526     
527     /**
528      * The EJB spec makes a distinction between access to the TimerService
529      * object itself (via EJBContext.getTimerService) and access to the
530      * methods on TimerService, Timer, and TimerHandle. The latter case
531      * is covered by this check. It is overridden in the applicable concrete
532      * context impl subclasses.
533      */

534     public void checkTimerServiceMethodAccess()
535         throws IllegalStateException JavaDoc
536     {
537         throw new IllegalStateException JavaDoc("EJB Timer Service method calls " +
538         "cannot be called in this context");
539     }
540     
541     // Throw exception if EJB is in ejbActivate/Passivate
542
protected void checkActivatePassivate()
543         throws IllegalStateException JavaDoc
544     {
545         if( inActivatePassivate() ) {
546             throw new IllegalStateException JavaDoc("Operation not allowed.");
547         }
548         
549     }
550     
551     protected boolean inActivatePassivate() {
552         return inActivatePassivate(
553             container.invocationManager.getCurrentInvocation());
554     }
555
556     protected boolean inActivatePassivate(ComponentInvocation inv) {
557         boolean inActivatePassivate = false;
558         if ( inv instanceof Invocation ) {
559             Method JavaDoc currentMethod = ((Invocation)inv).method;
560             inActivatePassivate = (currentMethod != null)
561                 ? (currentMethod.getName().equals("ejbActivate") ||
562                    currentMethod.getName().equals("ejbPassivate")
563                   )
564                 : false;
565         }
566         return inActivatePassivate;
567     }
568     
569     /**
570      * Called after this context is freed up.
571      */

572     void deleteAllReferences() {
573         ejb = null;
574         container = null;
575         transaction = null;
576         resources = null;
577         ejbStub = null;
578         ejbObjectImpl = null;
579         ejbRemoteBusinessObjectImpl = null;
580         ejbLocalObjectImpl = null;
581         ejbLocalBusinessObjectImpl = null;
582     }
583     
584 }
585
Popular Tags