JBoss Source Code Analysis (ZZ)

xiaoxiao2021-03-06  115

JBoss is a very excellent J2EE Application Server to study its source code helps us better understand the various technologies of J2EE. This series is analyzed from four aspects of the JBoss source code: 1.EJB Container implementation 2.Transaction implementation 3.Persistence mapping 4.client to the server-only INVOCATION ----------------- ------------------------------------------------Firstly 1 point: EJB Container implementation. 1.1 EJB POOL We know that EJB Container will maintain an EJB pool, sharing between multiple clients, avoiding the overhead of destroying objects frequently. Let's look at Jboss achieve Pool: EJB points EntityBean, MDB, Stateless / Stateful Session Bean, and the corresponding Jboss also have EntityInstancePool, MessageDrivenInstancePool, StatefulSessionInstancePool, StatelessSessionInstancePool Let's start with a common base class AbstractInstancePool four classes. looks: class AbstractInstancePool implements the interface InstancePool, this interface has the following methods: EnterpriseContext get () throws Exception; void free (EnterpriseContext ctx); void discard (EnterpriseContext ctx); int getCurrentSize (); public int getMaxSize (); -------------------------------------------------- ----------------- First, the EnterpriseContext is explained. EnterpriseContext's role is to link specific EJB Instance and its metadata. This class is: Public Abstract Class EnterpriseContext, there are 4 subclasses, EntityEnterpriseContext, MessageNenerPriseContext, StateEternalNterpriseContext, StatelessSessionNterpriseContext. There correspond to four types of EJBs, respectively. There are several important member variables in EnterpriseContext. / ** The ejb instance * / Object instance; / ** the contacter using this context * / container con; // Container This class is JBoss to represent the class that provides Transaction, Security, Pool, etc., let's return. Will say anything.

/ ** Only StatelessSession Beans Have No ID, Stateful and Entity Do * / Object ID; / ** THE Transaction Associated; // Transaction, We will say later. // Constructors ----- ------------------------------------------- Public EnterpriseContext (Object Instance Container con) {this.instance = instance; this.con = con;} public contact instance;} public container getContainer () {return con;} public void setid (Object id) {this.id = id;} public Object getId () {return id;} public void setTransaction (Transaction transaction) {this.transaction = transaction;} public Transaction getTransaction () {return transaction;} / ** * Get the EJBContext object * / public abstract EjbContext getEjbContext (); // Remove Javax.eb.ejbContext by subclass, Note that this EJBContext is a Context that the EJB specification is required to provide EJB, which doesn't matter with JBOSS you EnterpriseContext. / ** @ in i i = 0; public void lock () {locked ;} public void unlock ()} public void unlock ()} public void unlock ()} public void unlock ()} public void unlock () {locked -; {RETURN LOCKED! = 0;} // Lock This member variable indicates that there is no one in this ejb installation. // This variable is used to give Reentrance, as well as canpassviate. / ** * Before Reusing this context We clear it of previous State Called * by pool.free () * No EJB Instance and Transaction Information * Clear this information when it returns Pool.

* / public void clear () {this.id = null; this.locked = 0; this.transaction = null;} // --------------------- -------------------------------------------------- -------------- Protected Boolean IscontainerManagedtx () {beanmetadata MD = (beanmetadata) Con. GetBeanMetadata (); return md.iscontainerManageDTX ();} // Corresponding to the associated Container Metadata, determined whether cmt. // Note that CON is a Container member variable, can not be connected, connection general abbreviation is conn, // I am confused at the beginning :) // beanmetadata These metadata subclasses are from XML The Metadata constructed in the configuration, // is not mysterious. This class has two INNER CLASS, EJBCONTEXTIMPL IMPLEments EJBCONTEXT, UserTransaction IMPLEments Utertransaction. EjbContextImpl, etc. explain the Container, and the next section is said to be said by UserTransaction. Now let's look at a few subclasses EnterpriseContext: First look at the analogy member variables of several sub-categories: EntityEnterpriseContext: private EJBObject ejbObject; private EJBLocalObject ejbLocalObject; private EntityContext ctx; StatefulSessionEnterpriseContext private EJBObject ejbObject; private EJBLocalObject ejbLocalObject; private SessionContext ctx; StatelessSessionEnterpriseContext EJBObject ejbObject; EJBLocalObject ejbLocalObject; SessionContext ctx; MessageDrivenEnterpriseContext: private MessageDrivenContext ctx; in addition it seems there is no corresponding MDB EJBObject / EJBLocalObject, all the others have learned :) EJB knows, syntactically EJB instance is implements EntityBean / SessionBean / MessageDrivenBean (three interface have a common interface: public interface EnterpriseBean extends Serializable, EnterpriseBean a Marker interface inside nothing, it seems, like Serializable interface, only instructions to achieve it is EJB and EntityBean / SessionBean / MessageDrivenBean have correspondence. Void ejbactivate () throws ejbexception, remoteexception; void ejbload () throws ejbexception, RemoteException; some methods need to be implemented.

(Although it is often empty implementation :), a lot of things made by the container) so that EJBOBJECT / EJBLOCALOBJECT is not directly implemented in grammar, representing the Remote / Local interface exposed to EJB Instance. Since these EJB Instances do these interfaces directly, how these interfaces are associated with the specific EJB Instance, and we will know when the Container class is known. -------------------------------------------------- -------------------------------- EnterpriseContext Sub-class EntityEnterpriseContext constructor PUBLIC EntityEnterpriseContext (Object Instance, Container Con) throws RemoteException {super (instance, con); ctx = new entryxTextImpl (); // This is the subclass of EJBContextImpl, no rising :) (EntityBean) .SetentityContext (ctx); // Take a look, original set ... Context is what ejbcreate (), ejbel (), ejbactive (), what is called here? Next, we slowly find it, this can be spread around :)} // The three lines of the three lines of the other subclasses are also true, it is similar.

For StatelessSessionEnterpriseContext and MessageDrivenEnterpriseContext, it is immediately Method ejbCreate = instance.getClass () getMethod (/ "ejbCreate /", new Class [0]);. EjbCreate.invoke (instance, new Object [0]); // See It comes to ejbcreate :), for StatelessSessionBean, come up with Ejbcreate () ~ Next to see the point: For EnterpriseContext, there is public abstract void discard () throws remoteException; for MessageDriven ... Public void throws RemoteException {((MessageDrivenBean) instance) .ejbRemove ();} for StatelessSession the public void discard () throws RemoteException {((SessionBean) instance) .ejbRemove ();} for the StatefulSession ... public void discard () throws RemoteException {// Do nothing} for Entity .... public void discard () throws RemoteException {((EntityBean) instance) .unsetEntityContext ();} // discard is void discard in the AbstractInstancePool (EnterpriseContext ctx); call / ** * Discard an anonymous instance instance after invocation. * This is caled if the instance surhaps due to some * exception being thrown from it. * * @Param ctx The context to discard * / public void discard (EnterpriseContext ctx) {ctx.discard ();} AbstractInstancePool there is a free method:. public void free (EnterpriseContext ctx) {ctx.clear (); // remember just clear ctx Drop, Transaction, etc., return to pool, ready to reput? // discard is an error when an error occurs, so Discard off, //, and // corresponding to get () FREE method is just returning EnterpriseContext to pool.} ------------- -------------------------------------------------- ------------------- Specially for Stateful .... context has functions with EJB Instance / ** * during activation of stateful session beans we replace the instance * by the One read from the file. * / public void setInstance (object instance) {this.instance = instance; (sessionbean) .SetSessionContext (CTX);

} Note ... Context Of the four, only Stateful ... Context signature public class StatefulSessionEnterpriseContext extends EnterpriseContext implements Serializable more than a implements Serializable, (the other is not), this is to support Activation / Passviation, Passviation when the EJB INSTANCE is written in the file. Two such methods private void writeObject (ObjectOutputStream out) in the StatefulSessionEnterpriseContext throws IOException, ClassNotFoundException {// do nothing} private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException {// do nothing} // description of the time sequence StatefulSessionEnterpriseContext It does not need to be written in itself, only the corresponding EJB Instance needs to be written. Now let's see the source code of AbstractInstancePool, because there are too many content, it is not explained in detail. First look at Abstract ... pool's create (Object Instance) function Hotmia ~ Abstract ... pool // protected ------------------------- ---------------------------- Protected Abstract EnterpriseContext Create (Object Instance) throws Exception; Entity ... pool protected enterpriseContext Create (Object Instance) throws Exception {Return New EntityEnterpriseContext (Instance, getContainer ());} Other three Pool is similar.

Look back Abstract..Pool / ** The pool data structure * / protected EnterpriseContext [] pool; protected int currentIndex = -1; / ** The maximum number of instances allowed in the pool * / protected int maxSize = 30; / ** the minimum size of the pool * / protected int minSize = 0; / ** determine if we reuse EnterpriseContext objects ie if we actually do pooling * / protected reclaim = false boolean; // for MDB and StatelessSessionBean, this variable is set To true, // for mdb, we * do * pool // for SLSB, We * do * pool OK, now look at Pool's highlights, get () / free (EnterpriseContext CTX) function (EnterpriseContext CTX) Over, no longer repeat) These functions are also interfaces to implement in Interface Instancepool :) Gossip less, come and see code ~~ protected boyan minsizeinitialized = false; / ** * get an instance helness Identity. * Can be buy by finders, create-methods, and activation * * @return Context / w instance * @exception RemoteException * / public EnterpriseContext get () {// pool inside there Take out stuff synchronized (pool) {if (currentIndex> -1) {EnterpriseContext CTX = pool [currentIndex]; pool [currentIndex -] = null ; Return ctx;}} // initialize a small fixed size of instance at startup if (minSizeInitialized!) {MinSizeInitialized = true;. Synchronized (pool) {for (int i = 0; i

CTX;}}} For Entity ... pool, he OverWrite FREE / ** * RETURN An Instance to the Free Pool. RESET State * * Called in 3 Cases: *

*

Done with finder method * removed * passidated *

* @Param CTX * / Public Void Free (EnterpriseContext CTX) {// i t ac a i () = null) {Return; = null SUPER.FREE (CTX);} --------------------------------------- ------------ And Stateful .... Pool's Free method Overwrite's abstract ... Pool, public synchronized void free (EnterpriseContext CTX) {discard (ctx); // Simply discard No ~} The rest of the next copy, first preview 2 system: 1.Abstractinstancecache, EntityInstanceCache and StatefulSessionInstanceCache subclasses. For Entity, use its PrimaryKey to make Cache's key, for Stateful, JBoss will also pay each instance a unique calibration value to do CacheKey. Abstract ... cache is combined with Abstract ... pool, get good Performance. 2.Public Abstract Class Container, there are 4 subclasses of EntityContainer, MessageDrivencontainer, Stateful / StatelessSessionContainer, used to provide services such as Transaction / Security / Pool for EJB Instance. // look at its member variables, you can probably guess / ** This is the TransactionManager * / protected TransactionManager tm; / ** This is the SecurityManager * / protected AuthenticationManager sm; / ** This is the instancepool that is to Be buy * / protected instancepool instancepool;

Start talking Container, I have said that Container has 4 seed classes, respectively corresponds to the four types of EJB. A Container is a distributed place for all Container Plugins (Note 2), the Container Plugins can get Metadata from Container and When other Container Plugins.ejb deployment, create the corresponding container.container basically don't do too much, the main delegate gives Plugins.

OK, let's take a look at the member variable of Container: / ** * this is the new metadata. it incdude information from Both EJB-JAR AND * JBOSS.XML The metadata for the application can be booksed Trough * metadata.getApplicationMetadata () * / protected BeanMetaData metaData; / ** This is the EnterpriseBean class * / protected class beanClass; / ** This is the Home interface class * / protected class homeInterface; / ** This is the Remote interface class * / protected class remoteInterface; / ** The local home interface class * / protected class localHomeInterface; / ** The local inteface class * / protected class localInterface; / ** This is the TransactionManager * / protected TransactionManager tm; / ** This is the SecurityManager * / protected AuthenticationManager sm; / ** This is the realm mapping * / protected RealmMapping rm; / ** This is the bean lock manager that is to be used * / protected BeanLockManager lockManager; / ** This is the application that this container is a part Of * / protected ejbmodule ejbmodule; // ejbmodule as a Module deployed by a unit, such as an ejb-jar is a module, / * This EJB-JAR may have multiple ENTITYBEAN, SessionBean, so for each EntityBean, SessionBean has a corresponding Container, and these Dongdong shared one ejbModule. * / / ** * Returns a new instance of the bean class or a subclass of the bean class. * This factory style method is speciffically used by a container to supply * an implementation of the abstract accessors in EJB2.0, but could be * usefull in other situations This method should ALWAYS be used instead * of getBeanClass () newInstance ();.. * * @return the new instance * * @see java.lang.Class # newInstance * / public Object createBeanClassInstance () THROWS EXCEPTION {Return getBeanclass (). newinstance ();} public class getbeanclass () {return beanclass;

} Note EntityContainer overwrite's method: / ** * Returns a new instance of the bean class or a subclass of the bean class. * If this is 1.x CMP, SIMPLY RETURN A NEW Instance of the bean class. * If this is 2.x cmp, return a subclass that provides an implementation * of the abstract accessors. * * @see java.lang.Class # newInstance * * @return The new instance. * / public Object createBeanClassInstance () throws Exception {return persistenceManager .createBeanClassInstance ();} where persistenceManager declared: / ** This is the persistence manager for this container * / protected EntityPersistenceManager persistenceManager; // persitenceManager and PersistenceStore we will explain in part 3. Now give a rough impression: BMPPersistenceManager achieve public Object createBeanClassInstance () throws Exception {return con.getBeanClass () newInstance ();.} CMPPersistenceManager achieve EntityPersistenceStore store; public Object createBeanClassInstance () throws Exception {return store.createBeanClassInstance ();} -------------------------------------------------- ----------------- OK, let's take a look at how Containe handles the invocation of the client. Everything is in the following functions public object invoke (Invocation MI); // invocation represents some member variables in the call // invocation of the Client side, indicating the Method, // Args, Transaction Information, Principle / Credential, which is to call. And other information.

/ ** Maps for MarshalledInvocation mapping * / protected Map marshalledInvocationMapping = new HashMap (); public Object invoke (Invocation mi) throws Exception {Thread currentThread = Thread.currentThread (); ClassLoader callerClassLoader = currentThread.getContextClassLoader (); // save the original the classloader, finally recovered in Method m = null; Object type = null; try {currentThread.setContextClassLoader (this.classLoader); (Note 3) // Check against home, remote, localHome, local, getHome, // getRemote, getLocalHome, getLocal type = mi.getType (); if (type == InvocationType.REMOTE || type == InvocationType.LOCAL) {if (mi instanceof MarshalledInvocation) {((MarshalledInvocation) mi) .setMethodMap (marshalledInvocationMapping);} return internalInvoke (mi);} else if (type == InvocationType.HOME || type == InvocationType.LOCALHOME) {if (mi instanceof MarshalledInvocation) {((MarshalledInvocation) mi) .setMethodMap (marshalledInvocationMapping); return internalInvokeHome (mi); } else {throw new MBeaneXception (New Ill) EGALARGUMENTEXCEPTION (/// "Unknown Invocation Type: ///" type));}} Finally {CurrentThread.setContextClassLoader (CallerclassLoader);}} ------------------ ---------------------------------------------- MarshalledInvocation is Invocation Frames, representatives that can pass from the client to Server, INVOCATION PUBLIC CLASS INVOCATION ... PUBLIC CLASS MARSHALLEDINVOCATION EXTENDS INVOCATION IMPLEments Java.io.Externalizable, invocation is delivered between the calling chain (Interceptor chain, Note 4) in the Server side. --- -------------------------------------------------- - OK, slightly breathing, then look at the two INTERNAL INVOKEs, all is Abstract, implement Public Abstract Object INTERINVOKEHOME (Invocation MI) throughword;

Public Abstract Object InternalInvoke (Invocation Mi) THROWS EXCEPTION; as for specific implementation, To be conitue pull :) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ------------------------ Note 1: ContainerPlugin can be placed in the stuff in the container. Interface interface ContainerPlugin: void setContainer (Container con); there InstancePool, InstanceCache, EJBProxyFactory / LocalProxyFactory, EntityPersistenceManager / EntityPersistenceStore Plugin etc. Note 2: metadata information describing the deployment, such as ejb-jar.xml, describes what is EntityBean stuff, what Dongdong is sessionbean, session is BMP / CMP, etc. Note 3: Member Variables of Container Protected ClassLoader ClassLoader; uses to Load this CONTAINER's classes and resources to set up a Container ClassLoader because it makes EJB RE-deployable. (JBoss schedule DEPLOY directory, if ejb change REDEPLOY, if the EJB is deleted, undeploy) Note 4: JBoss will create an interceptor chain, the Invocation passes the chain. For example, there is an EntityInterceptor, SecurityInterceptor, Transaction Interceptor, a set, one set, each interceptor handles some processing for the current Invocation, such as check permissions, things, etc., then pass to the next interceptor process (this is Filter and Pipe mode, it is also AOP pull ~, others say that JBoss This interceptor is implemented to the AOP dialect especially :). All interceptor is now Object Invokehome (Invocation MI) "and Object Invoke (Invocation MI) Throws Exception; in its own invoke, after all Interceptor, call the next one. See AbstractInterceptor default implementation: public abstract class AbstractInterceptor implements Interceptor public Object invokeHome (final Invocation mi) throws Exception {// do sth return getNext () invokeHome (mi);..} Public Object invoke (final Invocation mi) throws Exception {// do sth. Return getNext (). Invoke (mi);} The method of calling the EJB Instance in the final reach of the EJB Instance after the heavy interceptor.

In fact, very simple to achieve: public Object internalInvokeHome (Invocation mi) throws Exception {return getInterceptor () invokeHome (mi);.} Public Object internalInvoke (Invocation mi) throws Exception {// Invoke through interceptors return getInterceptor () invoke (mi). ;} public Interceptor getInterceptor () {return interceptor;} protected Interceptor interceptor; // this is the first of a chain Interceptor Container established here invoking ~ look at void addInterceptor (Interceptor in); this function Interceptor last chain then hang a Interceptor public void addInterceptor (Interceptor in) {if (interceptor == null) {interceptor = in;} else {Interceptor current = interceptor; while (! current.getNext () = null) {current = current.getNext ( ); current.setnext (in);}} -------------------------------------- ---------------------------------- The included Pool and cache / ** this is the instance cache for This Container * / protected instancecache instancecache; / ** this is the instancepool That is to be used * / protected instancepool instancepool; / ** this is the instancepool That Is To BE Used * / protected instancepool instancepool; ------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------- .instanceCache = ic; ic.setContainer (this);} public InstanceCache getInstanceCache () {return instanceCache;} public void setInstancePool (InstancePool ip) {if (ip == null) throw new IllegalArgumentException (/// "null pool // / "); this.instancepool = IP; ip.setcontainer (this);} -------------------------------- --------------------------------------- OK, let us see Container What did EJB Instance have been made, what is the way?

There is also how to call EJB Instance. This is important 2 map / ** * THESE ARE THE MAPPINGS BETWEEN THESE ARE THE MAPPINGS BETWEEN The Home Interface Methods and The * Container Methods. * All Home Maps are available here * / protected map homemapping = new Hashmap (); / ** * THESE ARE The mappings Between The Remote / local interface methods and the * bean methods. * All EJBOBJECT methods maps are available here * / protected map beanmapping = new hashmap (); ------ -------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Here you will see what he calls your EJB Instance {public Object Invokehome (Invocation MI) throws exception {// invoke and handle exception method mimethod = mi.getMethod (); method m = (Method) HomeMapping. GET (MIMETHOD); if (M.GetDeclaringClass (). Equals (entityContainer.class) {Try {Return M.Invoke (EntityContainer.This, New Object [] {mi});} Catch (Exception E) {RethRow e);}} else // Home method {Try {RE Turn M.Invoke ((EnterpriseContext) mi.getenterpriseContext ()). getInstance (), mi.getarguments ();} catCh (Exception E) {Rethrow (e);}} // We will never get this far, but the compiler does not know that throw new org.jboss.util.UnreachableStatementException ();} public Object invoke (Invocation mi) throws Exception {// Get method Method miMethod = mi.getMethod (); Method m = (Method) beanMapping .get (mimethod); if (m == null) {string msg = /// "Invalid Invocation, Check Your Deployment Packaging ///" /// ", Method = ///" MIMETHOD; throw new EJBEXCEPTION (msg);

} // Select instance to invoke (container or bean) if (m.getDeclaringClass (). Equals (EntityContainer.class)) {// Invoke and handle exceptions try {return m.invoke (EntityContainer.this, new Object [] { Mi});} catch (e) {Rethrow (e);}} else {// invoke and handle exceptions try {return m.invoke ((EnterpriseContext) mi.geTenterpriseContext ()). GetInstance (), MI. Getarguments ());} catch (e) {Rethrow (e);}} // we will never get this far, but the compiler does not know That thrtio new org.jboss.util.unreachablestatementException ();}} / / Can be seen that two MAPs have been mapped, and the key of the MAP is the method of the EJB Instance method you want to call, the method implemented by the actual implementation may be the method implemented by EJB Instance itself, or the container is implemented ( For example, the Abstract Get / SET method in the CMP can only be implemented. From here, it can also be seen, JBoss mainly saves method mapping to handle the call request of EJBObject / EJBLOCALOBJECT, and some other J2EE AS ​​is dynamically generated EJBOBJECT / EjblocalObject and your EJB Instance are implemented (while JBoss generates a stuff in CMP2.0, nor is the subclass of EJB Instance).

OK, basically understand the principle of Container, let's see some of the initialization operation of the bottom Container consider a service, JBoss calls several functions related to Service when deploy / undeploy / redeploy: protected void createService () throws Exception {} protected void startService () throws Exception {} protected void stopService () throws Exception {} protected void destroyService () throws Exception {} let's look from the EntityContainer: protected void createService () throws Exception {// Associate thread with classloader ClassLoader oldCl = Thread.currentThread () getContextClassLoader ();. Thread.currentThread () setContextClassLoader (getClassLoader ());. try {// Acquire classes from CL // get Home / Remote from the metadata Class if (metaData ! .getHome () = null) homeInterface = classLoader.loadClass (metaData.getHome ());! if (metaData.getRemote () = null) remoteInterface = classLoader.loadClass (metaData.getRemote ()); // Call default init // Call the CreateService in the Container, let's look back in super.createservice (); // Establish the two Method mapping mapp setupbeanmapping (); setuPhomApping (); // map the interfaces to long setupmarsh alledInvocationMapping (); // Initialize pool instancePool.create (); // Try to register the instance pool as an MBean try {ObjectName containerName = super.getJmxName (); Hashtable props = containerName.getKeyPropertyList (); props.put (/ // "Plugin ///", /// "pool ///"); ObjectName PoolName = New ObjectName (Container.getDomain (); Server.RegisterMbean (Instancepool, poolname);} catch {log.debug (// "failed to register cache as mbean ///////////////////////init instance (); // try to register the instance cache as an mbean try {Objectname ContainerName = super.getjmxname (); HashTable Props =

Containername.getKeyPropertyList (); Props.put (/// "plugin ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Instancecache, cachename);} catch (throwable t) {log.debug (// "failed to register cache as mbean ////////////////////////////////> it.hasNext ();) {String invokerBinding = (String) it.next (); EJBProxyFactory ci = (EJBProxyFactory) proxyFactories.get (invokerBinding); ci.create ();} // Init persistence persistenceManager.create (); // initialize the interceptor by calling the chain interceptor in = interceptor; while (in! = Null); in.create (); in.getnext ();} readonly = ((EntityMetadata) metaData) .isReadOnly ();} finally {// Reset classloader Thread.currentThread () setContextClassLoader (oldCl);.}} protected void startService () throws Exception {// Associate thread with classloader ClassLoader oldCl = Thread.currentThread (). GetContextClassLoader (); thread.cur . RentThread () setContextClassLoader (getClassLoader ()); try {// Call default start super.startService ();. // Start container invokers for (Iterator it = proxyFactories.keySet () iterator (); it.hasNext (); ) {String invokerBinding = (String) it.next (); EJBProxyFactory ci = (EJBProxyFactory) proxyFactories.get (invokerBinding); ci.start ();} // Start instance cache instanceCache.start (); // Start persistence persistenceManager .Start (); // Start the instance pool instancepool.start (); // start all interceptors in the chain interceptor in = interceptor; while (in! = null) {in.start (); in = in.GetNext );

}} Finally {// Reset classloader Thread.currentThread () setContextClassLoader (oldCl);.}} Protected void stopService () throws Exception {// Associate thread with classloader ClassLoader oldCl = Thread.currentThread () getContextClassLoader ();. Thread. currentThread () setContextClassLoader (getClassLoader ());.. try {// Stop items in reverse order from start // This assures that CachedConnectionInterceptor will get removed // from in between this and the pm before the pm is stopped // Stop all interceptors in the chain Interceptor in = interceptor; while (in = null!) {in.stop (); in = in.getNext ();} // Stop the instance pool instancePool.stop (); // Stop persistence persistenceManager. STOP (); // stop instance cache instancecache.stop (); // stop container invoker for (iTerator it = proxyfactories.keyset (). iterator (); it.hasnext ();) {String Invokerbinding = (string) IT .next (); ejbProxyFactory Ci = (ejbProxyFactory) proxyFactories.get (invokerbinding); ci.stop ();} // call default stop super.sto pService ();} finally {// Reset classloader Thread.currentThread () setContextClassLoader (oldCl);.}} protected void destroyService () throws Exception {// Associate thread with classloader ClassLoader oldCl = Thread.currentThread () getContextClassLoader (). ; Thread.currentThread () setContextClassLoader (getClassLoader ());. try {// Destroy container invoker for (Iterator it = proxyFactories.keySet () iterator ();. it.hasNext ();) {String invokerBinding = (String) it.next (); EJBProxyFactory ci = (EJBProxyFactory) proxyFactories.get (invokerBinding); ci.destroy ();} // Destroy instance cache instanceCache.destroy (); instanceCache.setContainer (null); try {ObjectName containerName = super .GetjmxName ();

Hashtable props = containername.getKeyPropertyList (); Props.Put (// "plugin ////////" cache ///////////////////////////////////////////////////// "Cache /////////////////////-" .unregisterMBean (cacheName);} catch (Throwable ignore) {} // Destroy persistence persistenceManager.destroy (); persistenceManager.setContainer (null); // Destroy the pool instancePool.destroy (); instancePool.setContainer (null); try {ObjectName containerName = super.getJmxName (); Hashtable props = containerName.getKeyPropertyList (); props.put (/// "plugin ///", /// "pool ///"); ObjectName poolName = new ObjectName ( containerName.getDomain (), props); server.unregisterMBean (poolName);} catch (Throwable ignore) {} // Destroy all the interceptors in the chain Interceptor in = interceptor;! while (in = null) {in.destroy ( ); in.setContainer (null); in = in.getNext ();} MarshalledInvocation.removeHashes (homeInterface); MarshalledInvocation.removeHashes (remoteInterface); // Call default destroy super.destroyService ();} finally {/ RESET CLASLOADER THREAD.CURRENTTHREAD (). SetContextClassLoader (OLDCL);}} ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------- Protected void setupbeamapping () throws Exception {try {i (remoteinterface! = null) {Method [] M = remoteInterface.getMethods (); setupBeanMappingImpl (m, ///"javax.ejb.EJBObject/// ");} if (localInterface = null!) {Method [] m = localInterface.getMethods (); setupBeanMappingImpl (m, /// "javax.ejb.ejblocalobject///// ");}} catch (Exception E) {// Ditch The Half Built mappings homemapping.clear (); beanmapping.clear (); throw e;

}} private void setupbeanmappingIMPL (Method [] M, String INTFNAME) THROWS Exception {for (int i = 0; i

.GetDeclaringClass (). getname (). Equals (intFName)) {// Implement by bean beanmapping.put (m, beanclass.getMethod (m.getname (), m.getParameterTypes ());} else {// importMented By Container BeanMapping.Put (M, getClass (). getMethod (M.GetName (), new class [] {invocation.class});}}} private void setuPhomAppingIMPL (Method [] M, String FinderName, String Append) Throws Exception {// adrian BROCK: This SHOULD Go AWAY WHEN We Don /// 't support ejb1x boolean ISEJB1X = metadata.GetApplicationMetadata (). ISEJB1X (); for (int i = 0; i 0 0 sPpercase () methodname.substring (1 ); homeMapping.put (m, beanClass.getMethod (ejbHomeMethodName, m.getParameterTypes ())); continue;} catch (NoSuchMethodException ignore) {} // just go on with other types of methods // Implemented by container (in both Cases) IF (MethodName.StartSwith (/// "Find //////// homemappin G.Put (M, this.getClass (). getMethod (FinderName, New class [] {invocation.class});} else if (MethodName.Equals (//////// ") || (ISEJB1X == false && methodname.startswith (/// "CREATE / / /")))))) {homemapping.put (m, this.getclass (). getMethod (/// "create //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////- ] {Invocation.class}); beanmapping.put (m, this.getClass (). GetMethod (// "postcreate ///" append, new class [] {invocation.class});} else { homeMapping.put (m, this.getClass () getMethod (methodName append, new Class [] {Invocation.class}).);}} catch (NoSuchMethodException e) {throw new NoSuchMethodException (/// "Could not find matching Method for /// "

m);}}} protected (}} protected)}} protected (}) ()}}} protected ()}} protected ()}} protected ()}} protected ()}} protected ()}}}}} /// "Home ///");} if (localhomeinterface! = Null) {method [] m = localhomeinterface.getMethods (); setuphomemappingImpl (m, /// "findlocal ////////" Localhome /// ");} // special methods // get the one on handle (get the class class handleclass = class.forname (///" javax.ejb.handle ///// "); // Get THE Methods (There Is Only One) Method [] HandleMethods = Handleclass.getMethods (); // Just To Make Sure Let /// 's Iterate for (INT J = 0; J {

// Get Only the One Called Handle.GeteJBObject

IF (HandleMethods [J] .GetName (). Equals (/// "getjbobject ///////////////////////////////////////>))))

{

// map it in the home stuff

Homemapping.put (HandleMethods [J],

THIS.GETCLASS (). getMethod (/// "getjbobject /////",

NEW class [] {invocation.class});

}

}

}

Catch (Exception E)

{

// Ditch the Half Built mapings

Homemapping.clear ();

Beanmapping.clear ();

Throw e;

}

}

转载请注明原文地址:https://www.9cbs.com/read-99742.html

New Post(0)