Introduction to Aspect-Oriented Programming Martin Giese Chalmers University of Technology Göteborg, Sweden AOP Course 2003 – p.1/36 Motivation AOP Course 2003 – p.2/36 Motivation XML parsing in Apache Tomcat: ➠ All in one class. AOP Course 2003 – p.3/36 Motivation (cont.) URL pattern matching in Apache Tomcat: ➠ All in two classes. AOP Course 2003 – p.4/36 Motivation (cont.) Logging in Apache Tomcat: ➠ Something in almost every class. AOP Course 2003 – p.5/36 dularized Motivation (cont.) problems like… expiration is not modularized Session Expiration in Apachesession Tomcat: ApplicationSession /================================================================= * *TheApacheSoftwareLicense,Version1.1 *re Co sp eyrrv ie gh dt.(c) 1999 The Apache Software Foundation. All rs ight * Redistribution and use in source and binary forms, with orthow ui t *m are odifimet: cation,arepermittedprovidedthatthefollowingcotn io dnis * 1. Redistributions of source code must retain the above co ight pyr * notice,thislistofconditionsandthefollowingdiscle r .aim *2.nR oe td ii cs et ,rt ih bi us tiloinsstionfbcionnad ri ytf ior nm sm au ns dttr hepf rol dl uc oe witnhgedaibsocvle p ra yri cgm h oti n * distribution. thedocumentationand/orothermaterialsprovidedwiththe * 3. The end- user documentation included with the redistribution, if * any ", Th mi ust pr io nd cu lc ut de in tc hl eufdo el sls oo wf it nw gaacknowlegement redevelopedby:the * AlterA np aatce he lyS,of tthwi ar seac Fk on uonwd la et gi eo me nnt(httpm :a /y /wa wp wp .eaapracihne.tohreg/s)o.f"tware * ifandwhereversuchthirditself, party acknowlegements normallyappear. * 4. The names "The Jakarta Project", "Tomcat", and "Apachetw Sa orf e * Foundation"mustnotbeusedtoendorseorpromoteprodsuct derived * per fm ri os msio tn h, ispls eo af st ewacroenta wc ittha op ua tche p@ ra ip oa rchw er .i ot rt ge .n permission. Forr ittew n *5.Productsderivedfromthissoftwaremaynotbecalled"che" Apa * permins os riomn ayof"t Ah pa ech Aep"aca hpepeGarouipn.their names without prior we nritt * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR I E DMPL * WO AFRRAM NET RC IHE AN ST, ABIL IIN TY CLUD AN IDNG,FIT BNU ES TSNOFT ORLIA MITP EAD RTIC TU O LA ,RTHPE URPI OS M EPLIAE RE D WAR TIES RAN *D II TSCC LO AN IT MR EI DB.UTI ON RSNO BEEV LE IN AT BLSEHA FL OL RT AH NE YA DP IA RC EH CE T,SO IF NT DW IA RR EE CTF,OU IND CA IT DA O R L ,I EO NN T *L SI PM EI CT IA EL D,TO E, XEP MR PO LC AU RR YE ,MO ER NTCON FSS EU QB US ET NI TT IU AL TEDG AO MO AD GE SSOR (IS NE CR LV UI DC IE NS G; ,L B N O F TO US TS *UOSR NE,T AO N DR Y ATTA T( H ,I EN OC RL YU PDR OIO FNF GILT INS AE; BGILL O II R GTEY B N, U CE SI WH N OERTSHSO ET RIHN EI T RN E WI RS R CE O U) N PTRA IAR OCIN TS) ,INHG SOTWRI E INV CE TA RNLY CY E L D IA I O AT U BYS W T I A ,A N D *SUCH OF THE DAMAGE. USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSI T YBILIO F *================================================================= *i Tn hd ii svs io df ut aw lasre onco bn es hi as lt fsoo fftv ho elA up na tc ah re yS cof ntw ra ir be utF iou nn sda mt ad ie onb .ym yF m oo a rr n e *<i hn tf tp o: r/ m/ aw tw iw o. nap oa nch te h. eor Ag p/ a> c. heSoftwareFoundation,pleasesee *[Additionalnotices,ifrequiredbypriorlicensingcondit s ]ion * / packageorg.apache.tomcat.session; importorg.apache.tomcat.core.*; importo ja r va g.. io apach. * ; e.tomcat.util.StringManager ; immpp or otr ja tvjaa .n vea t.*u;til.*; importjavax.servleett..htt*p.* ;; /** *Coreimplementationofanapplicationlevelsession *@authorrJJaamseosnDHuu nn ct ae nr D[ av ji cdhs@oenn [g.sd uu nn.c] cao n@ meng.sun.]com *@a/ uthorJamesTodd[gonzo@eng.sun.com] publicclassApplicationSessimo pl nements HttpSession { privateStringManager = s m privSatt ri en Hg aM sa hn tab gl ee r.getv Manlau gers("o =rgn .H a ep a waschet.a to ( ) ; bml ca et.session " ) ; privvaatt ee SS te rr iv ne griSde;ssion serverSession ; privatel Cong tc er xe ta ctoinotneTx it m; e = System.currentTimeMil();; lis privatelionn gthisAccessTime TiT me; i ln a ta sc tt Ai cv ceI sn st ee drval= crec 1 ; are tat iionn ime privateboolean valid = true; Appli Cc oa nti eoxntSceosnstieox nt () S{ tring i d , ServerSession serverSession, thhis i.sse .rcve ornSe tsesi xotn=co= s netre ve xrt Se ;ssion; this.id = id; this.inactiveInterval = context.getSessionTimeOut( ) ; if(this.inactiveInterval *= ! 1 =){60; } } ServerSession getServerSession ( ) { } returnserverSession; /** * Ca iln le adctbi yvico tnc ita en xst bedweha el ntwriet qh ua es ct cor cd om ie nsgly i. n so that accessa n d es * / void/ a/ cc sestslea d( s) t{accessedtothisAccessTime asitwillbeleftover /a/sf l tA rcocm es tsh ed e=pretv hiisA ocu ce ssa sTcim cee ;ss thisAccessTime = System.currentTimeMillis( ) ; } validate(); voidvalidate(){ // i f(ii fnawcetih va ev Ie nte ar nva il n!= acti1v)e{interval,checktoseeifw eeexceeded 'v it i n( i tn h tt i) s( IS ny ts et re vm a.lc=urrentTimeMillis()- lastAccessed ) / 1000; if(thisInterval> inactiveInterval ) { } invalidate(); } } //HTTPSESSIONIMPLEMENTATIONMETHODS public fS(tvra il ng id){getId () { } elr setu{ rnid; Stringm s g = sm.getString("applicationSession.session.ise" ) ; } throw new IllegalStateException(msg ) ; } publiifc(lvoanlgigde )t {CreationT( i) me { } elr seet{urncreationT; ime Stringm s g = sm.getString("applicationSession.session.ise" ) ; } throw new IllegalStateException(msg ) ; } /** * *@de/ precated publicHttpSessionContext getSessionContext ( ) { } return neSw essionContextImpl( ) ; publiclonggetLastAccessedT( ) { ime if(vraeltiudr )n {lastAcces; sed } elS setr{ingm s g = sm.getString("applicationSession.session.ise" ) ; throw new IllegalStateException(msg ) ; } } publicvos iedrivn ev ra Sl es is di ao tn e.(r)e{ moveApplicationSession(context) ; //removeeverythinginthesession En w huimlee rateinou ( nme. nu hm a=svMaolr ues E. lk eemyes (n( )t )s ; { r Se tmr oi ve nVg alu nea (m na eme) S ; =tri (ng)enum.nextElement(); } } valid = false; publicboolean isNew(){ if(!St varlid) ng{m s g = sm.getString("applicationSession.session.ise" ) ; throw new IllegalStateException(msg ) ; } if(r th eitsu Ac rc net sr sT uiem; e = creationTime){ } elr setu {rnfalse; } } / **@ *deprecated * / publsi et cAvto ti ri dbpuu te t(V namle, uv ea( lu Se t)r ;n ia nmge,Objectvalue){ } publif ic(v !ov iad li sd) et{Attribute(Strn ianmge,Objectvalue){ Stringm s g = sm.getString("applicationSession.session.ise" ) ; } throw new IllegalStateException(msg ) ; if (name == null) { Shr t t owrine n wgm s g = s Il ml .e ggeatlS At rr gi um ne gn (t"Eaxp cp el pi ti co an t(imosn gS )essi;on.value.iae " ) ; } removeValue(name); //removeanyexistingbinding if ( Hvtat lp ue Ses !s =ionn uB ll ind &i &ngvE av le i = un en sttanceofHttpSessionBindingListe) { ner newHttpSessionBindingEvent(t,hi name); s } ( HttpSessionBindingListener)value).valueBoun ) ;d(e values.put(name,value); } /@d* * epr *ecated *ubl/ p icObject getValue(String name){ } returngetAttribute(name) ; publicObject getAttribute(Stringname){ if(!St varlid) ng{m s g = sm.getString("applicationSession.session.ise" ) ; throw new IllegalStateException(msg ) ; } if ( Sn ta rm ie ng=m s g= n= s uml .g le)tSt {ring("applicationSession.value.iae " ) ; throw new IllegalArgumentException(msg) ; } } returnvalues.get(name); /** *@de/ precated publEi nc um Se trrai ti no gn[]ege= tVa gl eu teANtatmreisb(u) te {Names( ) ; Ve w hc itloerne a.mhe ( asM =onreew El Vemcet nt os r(()); { } names.addElement(e.nextElement()); String[]valueNames = new String[names.size()]; names.copyInto(valueNames) ; returnvalueNames; } public EnumeratiognetAttributeNa(m) es { if(!St varlid) ng{m s g = sm.getString("applicationSession.session.ise" ) ; throw new IllegalStateException(msg ) ; } Hashtable valuesClone H = (ashtable)values.clone ( ) ; } return(Enumeration)valuesClone.k( ) ;eys /***@deprecated * / publri em co vvoeiAd tr te rm io bvuet Ve a( lu ne a( mS et) ;ring name){ } publif ic(v !ov iad li rde )mo{veAttribute(String name){ Stringm s g = sm.getString("applicationSession.session.ise" ) ; } throw new IllegalStateException(msg ) ; if (name == null) { Stringm s g = sm.getString("applicationSession.value.iae " ) ; } throw new IllegalArgumentException(msg) ; Objecto=values.get(name); if(oHttp in Sse ta sns ce ioo fH ntBti pS nedsi si nognE Bi ve n =dn in tgListener ) { newHttpSessionBindingEvent(this,name) ; } ( HttpSessionBindingListener)o).valueUnbound(e) ; values.remove(name); } publif ic(v !ov iad li sde )tM{axInactiveInterval(int interval){ Stringm s g = sm.getString("applicationSession.session.ise" ) ; } throw new IllegalStateException(msg ) ; inactiveInterval=interval; } pubi lfic (!i n tvali gde )tM{axInactiveInterval(){ Stringm s g = sm.getString("applicationSession.session.ise" ) ; } throw new IllegalStateException(msg ) ; returninactiveInter; val } } / ----------------------------------------------------------------------- ServerSession packageorg.apache.tomcat.session; voidvali/d /at ie f() we {haveaninactiveinterval,checktoseeif imppoo rt rotro gr.ga .p aa pa cc hhee..tomcatt.. uc ti ol r. eS.t* r; ingManager ; // we've exceeded it immpp or otr ja tvjav . a. nie ot.*;. * ; if(inan cth i ti vs eInterval= !=1){ importjaavv ax a.. se urt vl ielt.** ;; int)(System.currentTimeMillis()- lastAccessed ) / 1000; ( importjavax.servlet.http.*; if(i tn hv ia sl Iindtaetr ev (a )l ;> inactiveInterval ) { /C* * ore*implementationofaserversession ServerSessionManagers s=m *@authorJamesDuncanDavidson[ duncan@eng.sun.]com ServerSessionManager.getManager ( ) ; *@a/ uthorJamesTodd[gonzo@eng.sun.com] } ssm.removeSession(this) ; publicclassServerSession { } } privateStringManager = s m synchronized void invalidate() { privSatt ri en Hg aM sa hn tab gl ee r.getv Manlau gers("o =rgn .H a ep a waschet.a to ( ) ; bml ca et.session " ) ; Enumerationenum= appSessions.keys ( ) ; privvaatteeSlH to a rs n ih g ntc gar i be d la ; etiona Tp ipm Sessions= Syst=emn .H e ca w usr ht raebn le t( Ti) meM ;il();; lis whiA O lp b epj li eeccn atu (i kmoe. ny S he =asesn i Mu oo m n. rn eeExla tp e Epl mSe( s mns ) ei t) nos t n= () {; privatelongthisAccessTime ApplicationSession)appSessions.get(key ) ( ; lastAccessed = crec are tat iionT nim Te; ime } appSession.invalidate(); privatei nin tactiveInterval= 1 ; } Servt eh riS s. eisdsio =n(i Sdt ;ringid){ publiifcv(oniadm pe ut=V=al nue l( lS )tr {n ia nmge,Objectvalue){ } Stringm s g = sm.getString("serverSession.value.iae"); publr ie ct Su trrnin dg ; getId () { } throw new IllegalArgumentException(msg) ; } removeValue(name); //removeanyexistingbinding publriectluor nn gc gr ee ta Ct ri eo an tT i; i om ne T( i) me { } values.put(name,value); } publicObject getValue(String name){ publriectluor nn gl ge at sL ta As ctcAecsc; seesdsedT( ) { ime if ( Sn ta rm ie ng=m s g= n= s uml .g le)tS{ tring("serverSession.value.iae"); } throw new IllegalArgumentException(msg) ; pubboolean licAppliccr ae ta io tn eS )e {ssion getApplicationSession(Context context, } Appli( Acpap tl ii oc na St es is oi no Sn essioa np )pa Sp ep ss Si eos ns =ions.get(context ) ; } returnvalues.get(name); if(appSession == null && create) { public Enumeratiogn etValueNames() { //XXX } returnvalues.keys(); //synctoensurevalid? publicvoidremoveValue(String name){ apppS peS ss eis on sion= sn.epwu Ap tp(lc io ca ntti, a e o pn x pStessss ii on on(id) , ;this,context); } values.remove(name); } publicvoidsetMaxInactiveInterval(int interval){ //XXm Xake sure that we haven't gone over the end of our } inactiveInterval=interval; //iannae ct wi appSession veinterval- i -fso,invalidateandcreate publici n t getMaxInactiveInterval(){ returnappSession; } returninactiveInter; val } //XXXsync'd f // o r safty - nootherthreadshouldbegettingsomething } voida rp ep mS oe vsesAipop nl si .c re am to iv oe n(Sceosns ti eo xn t(Con) ; textcontext) { //s fo rl om uti to hi nsfo wr hit lh eis w, ebaurtewr ee'alpl ind ge .teTr hm ii sne iss no 'm tethi eng moe sl tseoe a l r . plta it m /** synchronizedvoidreap(){ * Ca iln le adctbi yvico tnc ita en xst bedweha el ntwriet qh ua es ct cor cd om ie nsgly i. n so that accessa n d es Enumerationenum= appSessions.keys ( ) ; * / whiO lb ejeecntu (kme.yh=aesnMuo m. rn eeExlte El me( mn) et) ns t( ) {; void/ a/ cc sestslea d( s) t{accessedtothisAccessTime asitwillbeleftover Appli( Acpap tl ii oc na St es is oi no Sn essioa np )paSp ep ss Si eo sns =ions.get(key ) ; //fromthepreviousaccess appSession.valid( ) ; ate lh t ai sstAA cce cs esTsie md e= t Sh = yi sstAe cm ce .s cs uTrir me; ntTimeMillis( ) ; } } } } voidvalidate() 6 StandardSession packageorg.apache.tomcat.session; /*** Bind an object to this session, using the specified nI am fea.nobject /** importjavaa..ii oo .. IOE bx jceec ptI io nn putSt; ream; *< ro pe> fpl ta hc eesda.menameisalreadyboundtothissession,the jec oti bs object* i Rs eturn thethfe acade. <code>HttpSession </code> for which this importjavvaa .i .oi.o Ob .jSee ct rO iuatl pu itzSa t; r belae m; *<Acfotd ee r>t Hh ti ts pSm ee st si hon dBi en xd ei cnugtLeiss, tea nn ed rift<h/e coodbej>e ,c tt heicm op nl te am ie nn et rs calls *ub/ p licHttpSession getSession(){ impp oo rt rjt aj vav .au.t ui ti ll ..EHn au sh mt earba lt eion;; *<code>valueBound ()</code>ontheobject. return((HttpSession) this); imppoo rt rjtaj vaav.au xt .i se lr .v Vleectt .o Sr er ;vletException; *@param v nalm ueN Ob ajmee ctto towh be icbhou tnh d, eo ca bnjne ot ctbe isnu blolund,cannotbenull } importjavax.servlet.http.HHttttppSSeessssiioonn;BindingEvent; *@exception IllegalStateException ifthismethodiscalledonan importjavax.servlet.http.HttpSessssiioonnBCionndt ; ienxgtListe ;nerSess// *invalidatedsession ionPub -l -i -c -M -e-t-h-o-d-s-------------------------------------importorg.apache.ttoommccaatt .. uc ta it la .l Si tn ra i. ng*M; anager ; *<@ cd oe dp er >ecats eet dAtA trs ibuo te fVer (s)i<o/ nc2o.d2e,>thismethodisreplacedby *ubl/icvoidputValue(Strn p ia nmge,Objectvalue){ /U* * pda*tetheaccessedtimeinformationforthissession. / S*tan * *dard implementation of the <b>Session</b> setAttribute(name,value); This *smethod houldbecalledbythecontextwhenarequestcomesin intesre * fa rciea.l Ti hi zsao, bbs l jo ec tthiastitcanbestoredin } for *asep sasri ti oc nu, la erveniftheapplicationdoesnotreferenceit. perstiostea * nt s di tf of re argee ntorJV tMrans ff or erredd istributable session *ubl/ p icvoidaccess(){ su * <pp >ort. / R*em* * ove the object bound with the specified name from t session. his If this.lastAccessedTime = this.thisAccessedTime; *la< c ss b>Ir MeP pr LeE seM nt EsNTAbT ot IhONt NhO eTE</b>: Aninstanceofthis *dtoheess ne os ts hio nng. doesnothaveanobjectboundwiththisnatm hi es,method thiss .. it sN he iwsAcce=s fa sls eed ;Time = System.currentTimeMil( ) ;lis *tti H ( pnStees rs ni al on)(Sev s ie s wiono ) f atn hed a ses psi p on l .ication level *<A pf >terthismethodexecutes,andiftheobjectimplements } *uHbolwie p cv ,e Jr a, vableocga iu cs oe uttshiede classitselfisnotdeclared *<code>v Ht at lp uS eeUsnsbiou nn Bd i( nd )i<n/ gc Li osdte> ne or ntheo </ bcjoedc et >, .thecontainercalls /** *aco p kfagetc ha enn< oc tocdaes >t or ag n.apache.tomcat.session</code> *@param nameNameoftheobjecttoremovefromthissession. this* seP se sr if oo nr ,mtheinternalprocessingrequiredtoinvalidate S *essH it otn pS veise si wo. n viewofthisinstancebacktoa *@exception IllegalStateException ifthismethodiscalledonan alre* adwyietxhp oi ur tet dr .iggeringanexceptionifthesessionhas *@authorCraigR.McClanahan *invalidated / session *ubl/ p icvoidexpire(){ *7 1 @:v5e 4: r1 s0i $on$Revision:1.2$$Date:2000/05/15 publicvoidremoveAttribute(String name){ //Removethissessionfromourmanager'sactive * / syncOhbr jo ec nt izo ebdjec( tat =tr ai tt br uitbe us te )s.g {et(name); sessionsif((manager!=null)&&(managerinstanceof finalimcpll asesmeSnta sH ntd tpa Serss dio Sness, iSoes nsion{ if ( return; object == null) ManagerBase ) ManagerBase)manager).remove(this); ( //---------------------------------------------i at // ftri( bo ut bS ej y ss e .t r c ei em t n m . sotv u at n ec . (e p no r a f imne t) l; nH (t "t Rp eSmeosvsin og nB ai tn td riinbguLt ie s" te + ) {ne ar me); // V ectUo nb rir nd esua lnt ys=o nbejw ec Vte scta osr so (c )i; ated with this session ------------- Constructors ( ( Hn te tw pH StetspsSieo sn sB ii onB dind giLnigsEtve on ) be j tr e (c (t H) t. tv pa Sl eu se sU in ob n) ountd his, name)); w En huimlee ratai to t( r ns a. tt hr assMore= gEelteAmtetnrtisb(u)t) e{ Names( ) ; /** } } r Se ts ru ilntgsattr .ad= dEle( mSetn ri tn( g) a) a ; ttttrrs.nextElem( ) ;ent specif* ieC donstMr an uac ge tr. anewSessionassociatedwiththe } Enumerationnames=results.elements(); } *@param manager The manager with which this whiS lt erina gm( esn.a hm ae sMor =eEl (e Smterni tn sg () n a) m{es.nextElem( ) ;ent Sess* ioni/sassociated / R*em* * ove the object bound with the specified name from t session. his If } removeAttribute(name) ; publicStandardSession(Manager manager){ *dtoheess ne os ts hio nng. doesnothaveanobjectboundwiththisnatm hi es,method //Markthissessionasinvalid su t hpi es r( .)m ;anager=manager; *<A pf >terthismethodexecutes,andiftheobjectimplements setValid(false ) ; *<code>v Ht at lp uS eeUsnsbiou nn Bd i( nd )i<n/ gc Li osdte> ne or ntheo </ bcjoedc et >, .thecontainercalls } } *@param nameNameoftheobjecttoremovefromthissession. /** ------//I -n -s -t -a -n -c -e -V -a -r -i -a -b -l -e -s ------------------------------ vari* *@exception IllegalStateException ifthismethodiscalledonan abRleel se ,a is neallobjectreferences,andinitializeinstance *invalidatedsession *pr/ eparationforreuseofthisobject. *<@ cd oe dp er >ecatr eed mov Aes Ato tr fibV ut eer () s< i/ocn ode 2> .2,thismethodisreplacedby /T*he*collectionofuserdataattributes * public void recycle() { *ubl/icvoidremoveValue(String name){ p asso* ciat/edwiththisSession. Session //Resettheinstancevariablesassociatedwiththis removeAttribute(name) ; privateHashtable attributes=new Hashta( ) ; ble ar c tetar tio bnuTt im ees=.0c L; lear(); } /** i ld a= sn tu Al cl c; essedTime=0L; mill* iT se hc eotnidm se st in hc iesmsie ds ni sg ihotn,wascreated,in man xa Ig ne ar cti=ven Iu nl tl e; r= val1 ; /B * *in* d an object to this session, using the specified nI am fea.nobject * Ja /nuary 1, 1970 GMT. isNew =true;false; isValid *roefpl ta hc eesda.menameisalreadyboundtothissession,the jec oti bs privatelongcreationTime =0L; //TellourManagerthatthisSessionhasbeenrecycled *<A pf >terthismethodexecutes,andiftheobjectimplements /** ManagerBase if(( )manager!=null)&&(managerinstanceof *The /sessionidentifierofthisSession. *<code>valueBound HttpSessionBi( nd )i <n /g cL oi ds et >e one tr heobj< e/ cc to .de>,thecontainercalls ( ManagerBase)manager).recycle(this); privateStringid=null; *@param nameNametowhichtheobjectisbound,cannotbenull } /De*sc* * riptiveinformationdescribingthis excae ra pmtionvalueIlO lb ej ge ac lt Arg tu omebnetEb xo cu ep nt di ,oncannot ifba enn aut ll temptismadetoadda Package //--Methods --------------------------------------------- Session *@@p Sess *ion/implementation. *@en xceoptsi e no rn ializI al bll ee ga olb St jaetc eE txi ce npatn io ennviri of nmt ehn it sma me rtkhe oddistc rai lb le udtaobnlea. n "Stanpdr ai rd vS aetse ss io tn a/t1i .c 0" f;inalStringinfo= *invalidated / session / *Ret* * urn the <code>isValid </code>flagforthissession. publicvoidsetAttribute(Strn ianmge,Objectvalue){ * / isValid boolean () { /T * *he*last accessed time for this Session. if(( !( m valn ueageri! ns =ta nnucl eo lf )Se &r &im aa ln ia zg ae br l. e) getDistributable()&& return(this.isValid) ; * throw( snm ew.getStr Ii ln le gg (a "lsAt ra gn um de an rtdES xe cs ep st ii oonn.setAttribute.iae " ) ; priv/atelonglastAccessedTime = creationT; ime } synchronized (attributes) { re a tmtorvi eb At utreis b. ut pe u(tn(an ma e) ; me,value); /Se * *tt*he<code>isNew </code> flag for this session. /T* * he*ManagerwithwhichthisSessionis if(v( alueHttpi Sne st sa sni ce oonfB Ht it np dSien sg si Lo in sBtie v ) nn d ai e ln u rg eL )i .s vt ae ln uer Bound) *@param isNew Thenewvalueforthe<coi dse Ne>w</code> associated. * / } (newHttpSessionBindingEvent((HttpSession) this, name)); flag* / privateManagermanager=null; } voidsetNew(boolean isNew){ /** this.isNew = isNew ; clie* ntTrhee qu measxtismbu em fo triemeinterval,inseconds,between //-------------------------------------------- HttpSession PrivateMethods } sessi *on.the Anser g vl aetivec to im ne tainermayinvalidatethis /** out.* indicates that the session should never time / * * *Ro eb aj deacsteriinapluitzesdtvreerasmi.onofthissessionobjectfromstph ec eified *Setthe<code>isValid</code>flagforthissession. *riv/atei nma p txInactiveInter= val1 ; *<<pb >>IMPLEMENTATIONNOTE</b>:Thereferencetotheowni Manager <code>*@p is a Vr al ai m d</coid sV e al > id flagThe new value for the * is not restored by this method, and must be set exply . icitl *oids v /etValid(boolean isValid){ /F* * lag*indicatingwhetherthissessionisnewor *@param streamTheinputstreamtoreadfrom this.isValid= isValid ; not.* / *@exception I COlEx acsep stNiontFoui nf dEaxnce in pp ti ui f to /o nauntput nke nr or wo nrc ol ca cs us rsis specified } privateboolean isNew =true; *riv/atevoidreadObject(ObjectInputStreamstream) p //------------------------------------------------/** throwsClassNotFoundException, IOException { Properties or* not. Flagindicatingwhetherthissessionisvalid HttpSession c // reaD te iso er niTai li mze= ((Long) the scala sr tre ia nm s. tr ae nc ae dObvjaercit a( b) l) e. slo( ne gx Vcaelpute(Ma) nag; er) /** *riv/ateboolean p isValid = false; i ds =xt (I rec isn m= .ra ea( d( OI bn jt ee cg te ( ) ; milli *sme Ri c eo dtnudi r sn g si ht n th c,eJt ai nmuear wh ye 1n ,1 t9 h7 is 0GsMeT s. sionwascreated,in /** la m ASc ntc a t sg e i) dvTeiI me ns =tr eea r((Long) v l srt )rea sm t. rreeaamd.Orbejaed cO tb (j )e )c .t l( o) n) g. Va il nu te V( alu)e() ;; *@exception IllegalStateException if this method is * Th/ e string manager for this package. isNew = (((B isValid (oBol oeoan l)ean s) treeaamm.. rr ee ad aO dbOjbejce tc (t )) (. )b)o.oblo eo al nV ealnuVea( ) ;l)u; e calle* dinvalidated on an session privateStringManager = s m //Deserialize the attribute count and attribute values *ubl/iclonggetCreationT( p i) me { StringManager.getManager("org.apache.tomcat.session " ; ) i forn (n it nt= i=( 0(;In ite <gn er ;s )t ir +e+a)m. {readObject()).intVa( ) ;lue return(this.creationTime) ; St O br jiencgtvn aa lmuee=( =Ob(jSetc rt i) ng st )rree aa m. mr.er ae dO abdjO eb ct j( ) ;ec) t; } /T* * he* HTTPsessioncontextassociatedwiththis } attributes.put(name,value); sess* ion./ } /* Retu *rn the session context with which this session is = pr ni uv lalt;e statiHc ttpSessionContextsessionContext * associated. * /W*ri* * teaserializedversionofthissessionobjecttot sh pecified andh* asn @o deprecated As of Version 2.1, this method is deprecated *<p /Th * *ec*urrentaccessedtimeforthissession. o> bject output stream. *riv/atelongthisAccessedTime = p creationT; ime t h*ereplacement. Itwillberemovedinafutureversionof* < ib n>ItMhPeLEs Me Er Ni Ta Al TiIzOeNdNrOeTpEr<e/sb e> n: tatiToh neoofwnt ih ni gsMS ae ns as gi eo rn.will Aft nc be a ol r t lingstored *Jav /aServletAPI. *e <x cpoldie c> ireadObject tly. ()</code>, you must set the associated Manager publicHttpSessionContext getSessionContext ( ) { *<<pb>>IMPLEMENTATIONNOTE</b>:AnyattributethatisnotSerializable if(sessionContext =n =ewStannu da lr ld)SessionContext ( ) ; ------//S -e -s -s -i -o -n -P -r -o -p -e -r -t -i -e -s -----------------------------*wbi els lub restihl ee< nctoldy e> idginso tri ebdu.taIbfle y< o/ucd od oen>ot prwoapn er ttayny ofsu oc ur h trai sociated ab t sutes, return(sessionContext ) ; * Manager is set to <code>true</code>. } /S* * et* thecreationtimeforthissession.This *@param streamTheoutputstreamtowriteto meth *oMdaniasge cr al wl hed nabnyet xh ie stingSessioninstanceis //---------------------------------------------*@ex/ception IOException ifaninput/outputerroroccurs HttpSession PublicMethods reused. * privatevoidwriteObject(ObjectOutputStream stream)throws IOException{ /** *@p /aram timeThenewcreationtime /t s /re Wa rm i. tw erittheeObs jc ea cl ta (r new instan Lcoeng va (r cir ae bl aetsio (e nx Tc ) ;i em pt eManager) session, *Returnt or heobjectboundwiththespecifiednameinthis publicvoidsetCreationTime(longtime) { stream.wriitteeOObb jj ee cc tt (( ni ed w) ; Long(lastAccessedT) ;ime *<code>null</code>ifnoobjectisboundwiththatname. this.c lr ae sa tt Ai co cn eT si sm ee dTime=time;=time; stream.writeObject(new I Bn oto eg leera (m na( xI insa) ; N ct eiw veInterval)); *@param nameNameoftheattributetobereturned this.thisAccessedTime =time; stream.writeObject(new Boolean(isValid)); calle* d@invalidated eox ncea pntion Ill session egalStateException if this method is } / V/ E e nc ut mA o ec rcr aue t ms i ul u oa l ntt aet st=rn stehw eVe= gcn et ao m Ae r ts t (r )i ;b o su e fr ti e aN li azm ab els e( )at; tributes *ubl/ p icObject getAttribute(Stringname){ /R * *etu *rn the session identifier for this whiS lt era itntg ( rs attr .has=MoreE(lSetm re int gs )a () t) t{rs.nextElem( ) ;ent return(attributes.get(name)); sess* ion./ Of i b(j ve al cut e vai lnu st eaa nc t= e to rf iS be ut re isa.l gi et z( aabtl te r) ; } publicString getId () { } results.addElement(attr ) ; return(this.id); //Serializetheattributecountandtheattributeve s alu /R* * etu*rnan<code>Enumeration</code>of } sn E tu rm ee ar ma .t wi ro in teO nb aj mec st(=new resultIsn .e tl eegmen rt (sr(e ); sults.size())); <cod *ec >o Snttr ainnig ng </tcho ede na >moeb sjo efctts heobjectsboundtothis /** whiS lt erina gm( esn.a hm ae sMor =eEl (e Smterni tn sg () n a) m{es.nextElem( ) ;ent sess* ion. *Setthesessionidentifierforthissession. strree am a.mw. rw it reiOt bj eeOcb tj (a etctt ri (bnu ) ; a tm es e.get(name)); calle* d@eox ncea pntion IllegalStateException if this method is *@p /aram idThenewsessionidentifier } *invalidated / session publicvoidsetId(Stringid){ } public EnumeratiognetAttributeNa(m) es { if((t mh ai ns a. gi ed ri! ns =tanu cl eo lf )&&M( am nagn ea rB gae se r)!=null)&& crosscutinvalidate(StandardSession s):s&(i ngettMaxInactiveInterval()| return(attributes.keys()); ( ManagerBase)manager).remove(this); O lo bnj gg ee cttCg ree ta Att iro in bu Ttiem (e St (r) in |g)| } this.id = id; S Et nr ui mnegr[a]tgi eo tV na gl eu teANtatmreisbuteN( ) | ames()| ManagerBase if(( )manager!=null)&&(managerinstanceof / * * voidinvalidate boolean isNew()|() | session, *Returnt or heobjectboundwiththespecifiednameinthis ( ManagerBase)manager).add(this); voids rem toAvt et Ar tt ir biubtue t( e( SS tt rriing,Obje) | ct)); *<code>null</code>ifnoobjectisboundwiththatname. } staticadvice(StandardSession s):invalidate(s){ *@param nameNameofthevaluetobereturned /** befoirfe ({ !s.isValid ( ) calle* d@eox ncea pntion IllegalStateException if this method is Sess* ion Ri em tp ul re nme dn et sa ct rip ot ni av ne dinformation about this throw( sne . wsm.geI tlS le tgr al iSn ta gt( eE "xs ce tpa ti nod nardSess. "ion *invalidatedsession format*thecorrespondingversionnumber,inthe thi" + si s e Jo .in" ) ; Point.methodName b y *@deprecatedAsofVersion2.2,thismethodisreplaced <code>& * lt;description&gt;/&lt;version;& </ gc tode>. } } *<co/de> getAttribute ()</code> *ubl/ p icString getInfo(){ publicObject getValue(String name){ return(this.info); } return(getAttribute(name)); } } //--------------------------------------------------------------PrivateClass /** /* * Ret* urn the set of names of objects bound to this / * * asso*ciRaete ur dnwitthh eth la isttimetheclientsentarequest on.areIf nothseu rc ehobjects,azero length array is returned.*iTn hi ts erc flaac ss e,it soacodn um fm oyrmim tpoletmh en eta rt eiqou nir of emt ehnet< tchoa dt e>s Ht utcph Sea ss nioonb Co jn e be tcet xtreturned</code> midnig*ht, sesJ sai nuo ar ny,a1 s,th1e 970numberofmillisecondssincesessi* *@exception IllegalStateException if this method is *when<code> HttpSession.getSessionContext ()</code>iscalled. such*asGgMe Tt .tiA nc gtoirosne stth ia nt gyourapplicationtakes, calle* dinvalidated on an session *@authorCraigR.McClanahan affe*ca tvt al hu eeas cscoe cs ia stet diw miet. hthesession,donot *@deprecatedAsofVersion2.2,thismethodisreplaced * @ id ne tperr ef cat cedwiAlslboe fre Jm av oa vedSeirn vla etfuA tP uIre2v.e 1rsi wo it nhofnothirsepA lP ac Ie .ment.T h e *ubl/iclonggetLastAccessedT( p ) { ime b y *<code> getAttributeNa(m) e< s/code> * / return(this.lastAccessedTime) ; *ubl/icString[]getValueNames(){ p final class StandardSessionContext implementsHttpSessionCont{ ext } Vectorresults=newVector(); privateVectordummy=newVector(); w En huimlee ratai to t( r ns a. tt hr assMore= gEelteAmtetnrtisb(u)t) e{ Names( ) ; /** / *Ret*urn the Manager within which this Session * r Se ts ru ilntgsattr .ad= dEle( mSetn ri tn( g) a) a ; ttttrrs.nextElem( ) ;ent *R weitt ur hninthe thsiessic oo nni tdeex nti. fiers of all sessions defined isva* lid./ Stringnames[]=newString[results.size()]; } * @deprecated As of Java Servlet API 2.1 with no replace t .men public Managegr etManager(){ for(n ia nm teis= [i0] ;=i(S <tnraimn eg s. )l res nuglts h. ;el ie+m+ en )tAt(i ) ; *Ta hn idsw mi eltlhb oedm re umsotvr ee dtiu nranf au nteumrp etvye< rs ci oodneo >fEn th ue me AP rI a.tion</c> ode return(this.manager); return(names); *ubl/ic Enumeratioge p ntIds(){ } } return(dummy.elements()); /** } valid.*SettheManagerwithinwhichthisSessionis / * * toit.*Invalidatesthissessionandunbindsanyobjectsbound *@param manager The new Manager *@exception IllegalStateException if this method is / *Ret* * urn the <code>HttpSession </code> associated with the *ubl/icvoidsetManager(Manager manager){ p call* ed ao nninvalidatedsession *specifiedsessionidentifier. this.manager=manager; *ubl/ p icvoidinvalidate(){ *@param idSessionidentifierforwhichtolookupasession } // Cause this session to expire *T@ hdies pm rec tahtoedmA usstorfet Ja uv rannSu el rv llaentdw AP iI ll2b.e 1re wi mtohvend oir ne aplace t .men } expire(); *ubf/ p lut iuc re Httv pS ee rssion ofgte he tSA ePsIs .ion(Striidn)g { bet* / weR * een tu * crl nit ehnetr ma exq im uue mstisme interval, in seconds, return(null); the* ses be sf ioo rn e.the Anegas tei rvlet container will invalidate / *Ret* urn <code>true</code> if the client does not yet know } time* outt.ime indicates that the session should never * about*ste hession,oriftheclientchoosesnottojointhe } *@exception IllegalStateException if this sessio*n.examF pol re,iftheserverusedonlycookie- basedsessions, meth *o ad nin ivsalciadl al tedseosnsion andt* hec hl ai sendtisabledtheuseofcookies,thenasessionwouldbe *ub/ p lici n t getMaxInactiveInterval(){ new*on request. each return(this.maxInactiveInter) ;val *@exception IllegalStateException if this method is } calle* dinvalidated on an session *ub/ p licboolean isNew(){ /Se * *tt*hemaximumtimeinterval,inseconds, return(this.isNew ) ; bet* webef nor celi th eentres qer uvletstscontainer will invalidate the* sestsiimoen.inA din ce ag ta et sivt ehat the session should never } time* out. *@p /aram intervalThenewmaximuminterval { publicvoidsetMaxInactiveInterval(int interval) this.maxInactiveInterval=interval; } SessionInterceptor packageorg.apache.tomcat.request; importorg.apache.tomcat.u ct oi rl e.*; immpp or otr ja tvjav . a. nie ot.*;. * ; importjaava vxa.s .eurv tliet l..ht *t;p.*; /** *Wiin llpth r eocR eqs uest. therequestanddeterminethesessionId,ant dsi et *Italsomarksthesessionasaccessed. *Tah di dsni em wpil ne te mr ecnet pa to tr isof norno lt yhhearnmdelte hs od Cso.okiessessions,pleaseenx dotr * / publicclassSessionIntercepe tx otrendsBaseIntercepi tm op rlementsRequestInterceptor{ s /t /a Gt Si ,cse fp ia nr al atcehsatrhS eE sS eS sIsOiNoInDi_d Rf Or Uo TE m_ tS hE ePj=v'r. om u 't; e iont C ned xe tb Ma un ga=g0 e; r c m ; publicSessionInterceptor(){ } publSiycsvtoeimd.soeu tt De .bpurgi (ntli n tn("d i Seb t)ug{to " + i); } debug=i; publthis.cm=cm; icvoidsetContextManager( ContextManagercm ) { } pubS lt ir ci n tngs res qs ui eo sn tI Md a= p(nRu eqlue ls;t request){ Cookiecookies[]=request.getCookies ();//assert!=null for(inti=0;i<cookies.length;i++){ Cookiecookie=cookies[i]; if(s ce os os kio en .I gd etName co = (o )k .i eeq .u ga et lV sa (l "uJ eSESSI( ) ; ONID ")) { i sefss (isoensIsdi=onId! va =lniu dl at le)S{ essionId(request , sessionId) ; } request.setRequestedSessionIdFromCookie(t) ;rue } } } Strings i g j = " ;sessionid = " ; if(nfoundAt dt ebug>0= 1) c;m.log(" XXX RURI="re+ quest.getRequestURI()); if((s fe osusn io dnAIt d= requres qu te .sgte .g te RteRq eu qu eesstURII(( )) .s .u ibnsd tr ei xnOgf (f ())!= o suing d1 At+) sig{ .length()); /e r /q ru eewsrti.t seU tRe Lq ,udeosItnUe Re Id (r te oq duoeasnty .t gh et iR ne gqmuoerset? URI().sub in sgt (0 r, foundAt) ) ; i sefss (isoensIsdi=onId! va =lniu dl at le)S{ essionId(request , sessionId) ; } request.setRequestedSessionIdFromURL(true) ; return0; } } // W Xe XXma wyhas ttil il ss te htei ctora rne dctjus bt ehr ae vti uo rn ri se fssi to hnei sne va sl sii do .nisinv d ?ali /**Validateandfixthesessionid.Ifthesessionisno at liv d return null. *I @return twillal ss eo ssi co ln eI ad n,uo prth nu ellsei sfsio no ntfv ra olm idload balancingstrings. *riv p /a /tGeS,SWterp ii nvgaglyib dac tk eStehsesi JoVnMId i( dRo en qur tee osq ptuo ef stt,hSetr si en sg ss ieo sn sik i eo cn oIo d) { //Separatethem... if((nd uelbl u! g> =0ses) sion cImd. )lo {g( Orig " sessionId " + sessio) ; nId i nid if(idex tex> =0 )s {essionId.lastIndexOf(SESSIONID_ROUTE_ ) ;SEP } sessionId =sessionId.substring(0, i d e x ) ; } if(/ se /ssG iS on ,IdWear !=enu i ll n&& asperso sb il oe nm Id. hl ee rn eg,thw(e)!m=a0y){ actuallyget //mcuolnttiepxlteS ae ns dso in oe ncfooorki te hs e(r oe na el focrotnhteerxoto.t..orold ssi soe n /o C /nctoeoxkti ce.tW rexqm = ue uss t. tgc et hCe oc nt kex fto(r)v ;alidityinthecurrceonntext. S iefss (in on uMl an lager !s= M.fis MndSe= c ss ti xo .n g( ecttSxe,ssiosne Masns ag ieor) ( n) I; d { seMq. r ue asc t. cset sRseq eude( st , ce rt d eS q xe us esi to ,s ne Is ds (i so en sI sd ionId) ; ) ; r if e(tudr eb nusge> s0 sio)nId c; m.log(" Final session id "se+ ssionId) ; } } } returnnull; publici n t beforeBody( Request rrequest ,Responseresponse){ i Sf t(rd ienbg ug r>e0q)Sc ems.s lo igo(= n "B Ie dfro er sp eon Bso e. dg yet" Se+ ssr io en qIS dessi( ) ; onId ) ; if(ret qu Sr en ss 0i ;onId==null) //G mS ul ,t si eptltehs eepsastih oa ntctor oi kb ie us te ct an ot bh eeuc so eo d, ki oe n. eTfh oi rsewaa cy h // S trcontext. ingsessionPath = rrequest.getContext().getPath(); if(se sessionPath ssionPath.le= ngth( " / ;)==0){ } /f i /(G!S se ,spsio gn gPy ab th a.cek qu tahle sjvm( r"o /" u )) t{eonthesessionid. i Sf t( rn iu nl gjvmRoute l !jvmRoute == ) r {request.getJvmRoute(); } reqSessionId= reqSessionId + SESSIONID_ROUTE_SEPjvmR +oute ; } Cookiecookie=newCookier( eq "Se JsS si Eon SIS dIONI) ;D", cookie.setP Mat xh A( gs ee (s -sion1 ) ; Path ) ; cookie.setVersion(1); r ce os op ko in es.es.eat dV de Hr es ad ie or n(0);( CookieTools.getCCooookkiieeHHeeaadd ee rr VN aa lm ue(cookie) ) , ; response.addHeader C (ookieTools.getCCooookkiieeHHeeaadd ee rr VN aa lm ue(cookie) ) , ; return0; } /**Notificationofcontextshutdown *ubl/icvoidcontextShutd( p oC wontextc t)x { throwsTomcatException c itfx( .g ce tt xS .egsestiDoenb Mu ag n() ager >(0 ).)re cm to xv .e lS oe gs (s "i Ro en ms o( vc it nx g) ; sessionsfrom"+c t) ;x } ServerSessionManager packageorg.apache.tomcat.session; importorg.apache.tomcat.c uo tr ie l.*; immpp or otr ja tvjav . a. nie ot.*;. * ; importjaava vxa.s .eurv tliet l..ht *t;p.*; /** *@authorJamesDuncanDavidson[ duncan@eng.sun.]com *@@aauuthorrJJas me osnHTu on dd te[rg[ oj nz coh @@ en egn .g su .ns .u co nm. ]] com * / publicclassServerSessionManager implementsSessionManager { privSatt ri en Sg tM ra ina gg Me ar n. aget rManag s = mer("org.apache.tomcat.session " ) ; private statiSc erverSessionManager manager;//=newServerSessionManager( ) ; protected i n t inactiveInterval = 1 ; statmi an ca{ ger=new ServerSessionManager(); } publreturn icstaticmanager; ServerSessionManager getManager(){ } privvaatt ee RH eas ph etrar be la eper;sessions=newHashtable(); privraetaepSeer= vR ee ra Sp ee sr s. ig oe nt MR ae nap ger(); { reeaa pe pre .s re. tS set rv aerrS te(s) si;onManager(this ) ; } publi Ac ppv lo ii cd ati ao cn cS ee sss eido(nConta p S extA = (ppli c , t xcaR tei quo es n tSession r , e q)f Sitnr di Se ns gsiiod n(){c t x ,id); if(a p==Snull)return; ServS s e. raScecs esi so en d ( servS ) ; = apS.getServerSess( ) ;ion apS.accessed( ) ; /e/q. r csa et cSh es esiotn- ( non a pe) ;eS dtocomputeitagain } pubS lt ir cH itn tpg Sesse ss io sn ionId= creaSteesSseisos ni Io dn G( eC no en rt act eo xt r. ) {gxenerat( ) ;eId s Ses rs vi eo rn Ss e. sp su it o( nsessisoen ss Ii don=,n see wssS io en r) v; erSession(sessionId ) ; i f1(! =inactiveInterval){ } session.setMaxInactiveInterval(inactiveInterval ) ; } returnsession.getApplicationSess( citox n, true ); publicHttpSession findSession(Context , c t x String id) { if(sSession ServerSession==nulls )Sessi r o e nturnS = (n eur ll v;erSession)sessions.get(id) ; returnsSession.getApplicationSession(ctx, false); } //XXX / // / fsr yn oc m 'dthis f o rwhsafty ile-we a no reotrheea rpitnhg r. eadThs ihsoul idsnb 'e tgteh te tinm gosstome ot a l pht ii nm g //solutionforthis,butwe'lldeterminesomethingelsee r .lat synchE rn on ui mzer dat vo ii odnerneu am p= () ses {sions.keys(); while enu (m.hasMoreEleme(n)t)s { S Oe brjver cStek ss eiyo= nenums .es n si e on xtE =le(S mer nv te (rSe )ss; ion)sessions.get(key ) ; session.reap(); } session.validate(); } syncS ht rr oi nnigzei ddvo= idsessi ro en m. og vet SI ed s( si)o; n(ServerSessionsession) { session.invalidate(); } sessions.remove(id); publicvoidremoveSessions(Context context){ Enumerationenum=sessions.keys(); whiO lb ejeecntu (kme.yh=aesnMuo m. rn eeExlte El me( mn) et) ns t( ) {; Sp A ep rl vi ec ra St ei so sn iSoenssionsessionap =pSe(S ss ei rovne =rSession)sessions.get(key ) ; session.getApplicationSession(context, false); if(appSS ee ssi so inon.in!v =aln i ul d l) ate{( ) ; } } } /** *Usedbycontexttoconfigurethesessionmanager'sinavci tt iytimeout. *CoThe ntex Se tss oin ont Ma hne ago er thermh aa ynhd avh eassom ietd 'e sfa tuilmtesoeust sisoe ntti bmyet oh ut e,ld ot ye m h ep n et *sed ss eisocnr mi an patgoerwe ab. cx( m clordi)n.gT th oitshm iestv ha od lule. tstheContextconforgure the *@param minutes The session inactivity timeout in minutes. *ubl/icvoidsetSessionTimeOut(intminutes) { p i f/ 1/ (T! h=emamn ia nu gteer s) wor{kswithseconds... } inactiveInterval=(minutes*60); } } StandardManager //------------------------------------------------------LifecycleMethods packageorg.apache.tomcat.session; impp oo rt rjt aj vav .au.t ii o. lI .OEEn xu ce mp etria ot nion;; imppoo rt rjtaj vaa v. a. uu ttil.H Vaesc hta obrl; e ; importj or ag v. aa xp .a sc eh re v.lteotm.chattt .p c. aC to ao lk ii ne a; .*; importo jr ag v. aa xp .a sc ehrev.lteot m. ch att .p u. tH il t. tS pt Sr ei sn sg iMoann;ager ; importorg.w3c.dom.Na om ded ;NodeMap; *C*on* / figurethiscomponent,basedonthespecifiedconfiag ti uor n *p ca om rp ao mn ee tn et rs i. nsTthai ns ce me it shcordes ah to eu dl ,dab nd ec ba ef lo lr ee d< ic mo md ee d> is attaerlty(c e ra ) od f <et / >t h e * is called. *@p (<B ar >a FmIXME:paWrhaamtet oe br js ect Cotnyfpiegusrhaotuilodnth pi as rar mea tl el ry sbe f? o) r this component *@exception IllegalStateException ifthiscomponenthasalreadybeen *@ec xocnefpitgi uo rn edanL di /f oe rcys ct la eE rx tc ee dptionif this component detects a fatal error * i/ ntheconfigurationparametersitwasgiven publt ic hvroo id wcsoL niffi eg cy uc rl ee(EN xo cd ep et piaornamete {rs) //V if (configured) alidateandupdateourcurrentcomponentstate throw( sne mw.getSt Lr ii fn eg c( y" cs lt ea En xd ca er pd tM ia onager.alreadyConfigu")); red co i fnf( ip gu areadm =e tr tu eer;s == null) return; //Pa if (!(" rseMaannd agperro"c .es qs uao lu sr (pc ao rn af mi et ge urs a.tgieotn NopdaerNamet () e)r)s ) Namereturn; dNodeMapattributes= parameters.getAttributes(); Nodenode=null; i node f (nod a=t etr!i= butneu s. lglet )Na{medItem("checkInterval" ) ; try{setCheckInterval(Integer.parseInt(node.getNodeValue ())); } cat ; ch (Throwabl/e/ Xt T Xh) X row {exception? } } node a=ttributes.getNamedItem("maxActiveSessions" ) ; if ( tr ny o{de != null) { } cat s ch etM( a Tx hA rc ow ta ib vl ee Sessit on )s(Int{ eger.parseInt(node.getNodeValue ( ) ; } ; // XT XhX row exception? } i node f (nod a=t etr! ib =utn es u.l ge lt)Nam {edItem("maxInactiveInterval " ) ; try{setMaxInactiveInterval(Integer.parseInt(node.getNodeValue())); } cat ; ch (Throwabl/e/ Xt T Xh) X row {exception? } } } ** / Sta*ndard implementation of the <b>Manager</b> interface thprovides at *a nn o ospetsi so in oa nl,pecrosnifsitgeu nr ca ebleo,r mdaixsitmruimbutnaubmlbeerca op fabi al ci tt ii ves,seb su st ioallowed. s ns du op eport *<Lpi >f nect yhcelef colnlfoiwgiu nr gatf iornmo af t:thiscomponentassumesanXMLnode *<code &l >t;Manager className= " org.apache.tomcat.session.StandardManager " * m ch aex ck IInna te crtvi al v="60" eInter= 1 m " v" a/ xl >ActiveSessi= "ons1 " *<w /c ho ed ree>youcanadjustthefollowingparameters,withdefaul al tuev s *<u inlsqu> arebrackets: *<l i th > < breac dhc eh cekcIknste fr o< v r/abe l >x-pirT ehd ese in ste sri va olns.(in[6s0 ec ]onds) between background *<l i be > < bactmia ve xAa ctti ov nc eeS ,es or si<o/nbs >1 - foTrhen mo axi lm im ui mt n.u1 ] mbe[rofsessionsallowedto *<l i i > < bnacm tai xv In iat cy tivb eI enfto erveal<w/hbi>ch ts Th eh re vlet defauc lo tnt mai xn ie mr umis nuamlb le or weodftsoec to in md esoo uf t * theads eefsa si uolnt,soerssion 1t fo irmn eoou li tmi stp.ecTi hi fsiv eadlu iens thh ou elw debb eaop ve prl rid i cd oa e nn t def pr lom yment *</udes> lcriptor,ifany. [- 1 ] *@authorCraigR.McClanahan *@ve /rsion$Revision:1.1.1.1$$Date:2000/05/0221:28:30$ public final claS sts andardManager em i xp tleenmd es nManagerBase tsLifecycle, Runnable { //-------------------------------------------------Ins -t -anceVariables /** *The /interval(inseconds)betweenchecksforexpiredsi eos ns. privatei nchteckInterval =60; /** *Has /thiscomponentbeenconfiguredyet? privateboolean configured=false; /Th*ed* * escriptiveinformationaboutthisimplementation. *riv/ p atestaticfinalStringinfo="StandardManager/1.0"; *T* / he* maximumnumberofactiveSessionsallowed,or1 for no limit. *rote/cted i p n t maxActiveSessi= -ons1 ; /* * The*string manager for this package. *riv/ateStringManager = p s m StringManager.getManager("org.apache.tomcat.session " ) ; /** *Has /thiscomponentbeenstartedyet? privateboolean started = false; /** * Th/ e background thread. privateThreadthread=null; /** *The /backgroundthreadcompletionsemaphore. privateboolean threadDone =false; /** *Nam /etoregisterforthebackgroundthread. private Strintg hreadName S = "tandardMana" ; ger //---------------------------------------------------------Pr -o -perties /** * Re/ turn the check interval (in seconds) for this Manager. publici n t getCheckInter( v) al { return(this.checkInterval ) ; } /** * Set the check interval (in seconds) for this Manager. *@p /aram checkInterT vhaelnewcheckinterval publicvoidsetCheckInterval(intcheckInterval){ this.checkInterval = checkInterval; } /** *tR het cu ornredsepsocnrdii pn tg iveri sn if oo nr nmuamtbieorn,ian bt oh ue tfo th ri ms atManagerimpl ne ta mte ionand *<co/ de>& lt;description&gt;/&lt;version&gt ;</code>. publicString getInfo(){ return(this.info); } /** *n Ro etur ln imit. he maximum number of active Sessions allowed, 1 or f o r *ub/ p lici n t getMaxActiveSessi( ) {ons return(this.maxActiveSessions) ; } /** *Se no ttl hi emi mt a.ximumnumberofactivesSessionsallowed,or- 1for *@param max The new maximum number of sessions *ubl/icvoidsetMaxActiveSessions(mi p ax n)t{ this.maxActiveSessions =max; } /** *c Po rm epo an renfto.rTthhiesbmeegtihnondin sg hooufld acbteic va elu ls ee do afttehre<pcuobdlei>cci ho m ou g d n er sf te o( f) t< h/ ic sode>, * and before any of the public methods of the componentut ai rleized. *@ ce ox nc fe ip gt ui ro end(ifr Il elq eg uai lS rte at def Ex ocr ep tthii onscomi pf on te hn is t)componenthasnotyetbeen *@started exception IllegalStateException ifthiscomponenthasalreadybeen *@e tx hc aetpt pi ro enventL sif teh cy icsle cEo xc meppo ti noe ni nftfth rio smc boe mp ioneg ntusdetd ects a fatal error *ubl p /icvoidstart()throLw if secycleException{ //Validateandupdateourcurrentcomponentstate if(!t c hr ownfn iew gured)LifecycleException if(start( semd.)getString("standardManager.notConfigu")); red throw( snm ew.getStL rin fg e(c"ysc tl ae nE da xr cd eMpatni ao gn er.alreadyStarted")); started = true; //Startthe( threadStart ) ;backgroundreaperthread } /G * *ra* cefully terminate the active use of the public meth of odsthis *icno sm tp ao nn ceo nf tt .hiTshciosmpmoentehnotd.shouldbethelastonecalledag oiv nen *@exception IllegalStateException ifthiscomponenthasnotbeenstarted *@ beexecn ep sttioop npedIllegalStateException ifthiscomponenthasalready *@e tx hc ae tpn te ie od nstoLbie fer ce yc pl oerEt xc ee dptionif this component detects a fatal error *ubl/icvoidstop()throws LifecycleExcept{ion p /f i /(V!asl ti ad ra tt ee d)andupdateourcurrentcomponentstate throw( snm ew.getStL rin fg e(c"ysc tl ae nE da xr cd eMpatni ao gn er.notStarted")); started = false; /h/ t re Sat dSoto pptheb( ) ;ackgroundreaperthread // Expire all active sessions f So er s( siin ot ns ie=ss 0i ;oin< s[s] e= sf sin od nS se.slseinogntsh(;i)++; ){ S if t(a !s ne dsasr io dn S.eisV sa s il eos is n di(on=)() StandardSession)sessions[i]; sessi con. te in xu pe i; re(); } } //-------------------------------------------------------- PrivateMethods StandardSessionManager packageorg.apache.tomcat.session; importjava.io.IOException ; importjavax.servlet.http.Cookie; importo jr ag v. aa xp .a sc eh re v. lt eo tm .c ha tt. pc .a Hta tl pi Sn ea s. si *o;n; importorg.apache.tomcat.core.Context; importorg.apache.tomcat.core.Request; immpp or otr or tgo.rag p. ac ah pe a.cthoe m. ct at o. mccoart e.c Re os rpeo.nS ses ;sionMana ;ger importorg.apache.tomcat.util.SessionUtil; Methods //-----------------------------------------------------P-u-b -lic /** *Markthespecifiedsession'slastaccessedtime.This oul sdb he * called for each request by a RequestInterceptor. *@param session The session to be marked * / publicvoidaccessed(Contextctx,Requestreq,Stringid){ HttpSession i f(session= s= es ns ui loln) =r fi ent dS uer ss ni;on(ctx ,id); /** if(sessioninstanceof Session) *Specializedimplementationoforg.apache.tomcat.core.SessionManager ((Session)session).access(); *<pt >hat adapts to the new compob ne an st edManagerimplementation. //cachetheHttpSession- avoidanotherfind * XXX Atpresent,useof<code> StandardManager</code>ishardcoded, req.setSession (session); *andlifecycleconfigurationisnotsupported. } *<<pb>>IMPLEMENTATIONNOTE</b>:Oncewecommittothenew //XXXshouldwethrowexceptionorjustreturnnull?? Manager/Session publicHttpSession findSession ( Contec t xt ,Stringid){ *t ph ae rc ao di rg em l, ev Iewl o. uT lh desT uo gm gc ea st. mN oe vx in tg "M ta hn ealg oe gr i" ciin mt pe lr ef me an ct ee ad ch te sr ack e me or bliinto ke atry{Sessionsession= manager.findSession) ;(id * collection class, and has minimal knowledge of the detaileq dues rt if(session!=null) *processingsemanticsofhandlingsessions. returnsession.getSession( ) ; *<p>XXX Atpresent,thereisnoway(viatheSessionManager interface) } catch (IOExceptione){ *ao f Cor ntexttotelltheManagerthatwecreatewhatthedefasession ult return(null); *timeoutforthiswebapplication(specifiedinthedeployment } * should be. descriptor) publicHttpSession createSession(Contcext) {x * returnmanager.createSession().getSession(); *@authorCraigR.McClanahan } * / /** public final claS stsandardSessionManager down.* Remove all sessions because our associated Context isng bei shut implementsSessionManager { * *@param c t x Thecontextthatisbeingshutdown //----------------------------------------------------------*ubl/icvoidremoveSessions(Context ) p c t x{ Constructors //XcXoXnX tX eX xt asm,anwaege jrum sa tywbaens tha tr oer debmyom vu elti hp ele sessionsc t xof! /C*re* * ateanewSessionManager that adapts to the corresponding //Themanagerwillstillrunafterthat(i.e.keepad bast e Manager // connection open *imp/ lementation. if(mta ry n{ agerinstanceof Lifecycle){ publicStandardSessionManager(){ ((Lifecycle)manager).stop(); } catch (LifecycleException e) { i maf na (gm eran=ag nee wrinstaS nt ca en od fardMaL ni af gec ry(cle){; } throw new IllegalStateException ("" + e); try{ } ((Lifecycle)manager).configure(null); } cat ( ch (Li(f Le if ce ycy lc el)emEa xn ca eg pe ti ro )n .stare t( )); { } throw new IllegalStateException ("" + e); /** } } time* ouUts .edbycontexttoconfigurethesessionmanager'sinavcitti y * } *CoThe ntex Se tss oin ont Ma hne ago er thermh aa ynhd avh eassom ietd 'e sfa tuilmtesoeust sisoe ntti bmyet oh ut e,ld ot ye m h ep n et * descriptorweb.x( ml ).ThismethodletstheContextconforgure the //-------------------------------------------------Instance *sessionmanageraccordingtothisvalue. Variables *@param minutes The session inactivity timeout in minutes. * / /** publicvoidsetSessionTimeOut(intminutes) { *Th/ eManagerimplementationweareactuallyusing. i f/ 1/ (T! h=emamn ia nu gteer s) wor{kswithseconds... privateManagermanager=null; manager.setMaxInactiveInterval(minutes *60); } } } / I*nva * *lidate all sessions that have expired. *riv/atevoidprocessExpires p () { longtimeNow= System.currentTimeMillis ( ) ; Sessionsessions[]=findSessions( ) ; for(i Sn tt ai nd =a0r ;diS<esesss ie i osos nn is on .= l( engthS; tai nd +a +r) dS{ ession)sessions[i]; if(!c so enstsii nu oe n;.isValid( ) ) ifn (ma txInactiveInter< s = ve as 0 lsi)on.getMaxInactiveInter( ) ;val i nc to i tn mt eiInd ul ee ;= // Truncate, do not round up if(( i ti nmt e) Idlet >= (imeNow maxInactivseeIs ns ti eo rn v. ag letLas)tAccessedTime()) / 1000L); } } session.expire(); /S * *lee *p for the duration specified by the <code>checkInterval</code> *pro/perty. privatevoidthreadSleep(){ try{Thread.sleep(checkInterval *1000L); } cat ; ch (InterruptedExceptione){ } } /** *sSetsasritot nh te imbeaocuktgsr.oundthreadthatwillperiodicallyche f o rck *riv/atevoidthreadStart(){ p if (thread != null) return; thrr ea edaDd on =enewT= hrfalse; ead(this, threadN) ;ame thhrr ea eda.s de.ts Da teamo rnt(( tr )u;e) ; } //-----------------------------------------------------Pub -l -icMethods /** *sCe ot nt st ir nu gcstsa pn ed cir fe it eudrnbyath ni ew sMsa en sa si go en r'o sbj pe rcotp,erbtaisees d.on Tht ehsion ee f sae ul s d t *m ie dtho wd illofbethe assrie gt nu er dned byse ts hs ii son. methoIdf,aand newava si el sa sb il oe nv ci aa nnb ge o eth Ie d(created) *foranyreason,return<code>null</code>. *@ instantiated exception Illefor galSta any teExcreason eption ifanewsessioncannotbe *ubl p /ic Sessiocn reateSession(){ if((maxActiveSessions > =0 )& t (hs ro e wssi ne o wns.sizeI( l) l> eg =alStatme aE xx Ace tp iv te iS oe nssions ) sm.getString("standardManager.createSession.")); ( ise return(super.createSess( ) ; ion } /* * Sto* p the background thread that is periodically checkif o r ng *ses/siontimeouts. privatevoidthreadStop () { if ( return; thread == null) thh re rae dD aod ne.int=e trr uer ;upt(); try{thread.join(); } cat ; ch (InterruptedExceptione){ } thread=null; } //------------------------------------------------------BackgroundThread /T*he*backgroundthreadthatchecksforsessiontimeouts * dsh aun tdown. publ * /ic void run() { // Loop until the termination semaphore is set whilethreadSleep (!threadDone( ) ; ) { } processExpires ( ) ; } AspectJ Workshop -- Xerox PARC } AOP Course 2003 – p.6/36 Motivation (cont.) language support to… modu What we would like: S anda dSess on StandardSession App ca onSess on ApplicationSession /================================================================= * *TheApacheSoftwareLicense,Version1.1 *re Co sp eyrrv ie gh dt.(c) 1999 The Apache Software Foundation. All rs ight * Redistribution and use in source and binary forms, with orthow ui t *m are odifimet: cation,arepermittedprovidedthatthefollowingcotn io dnis * 1. Redistributions of source code must retain the above co ight pyr * notice,thislistofconditionsandthefollowingdiscle r .aim *2.nR oe td ii cs et ,rt ih bi us tiloinsstionfbcionnad ri ytf ior nm sm au ns dttr hepf rol dl uc oe witnhgedaibsocvle p ra yri cgm h oti n * distribution. thedocumentationand/orothermaterialsprovidedwiththe * 3. The end- user documentation included with the redistribution, if * any ", Th mi ust pr io nd cu lc ut de in tc hl eufdo el sls oo wf it nw gaacknowlegement redevelopedby:the * AlterA np aatce he lyS,of tthwi ar seac Fk on uonwd la et gi eo me nnt(httpm :a /y /wa wp wp .eaapracihne.tohreg/s)o.f"tware * ifandwhereversuchthirditself, party acknowlegements normallyappear. * 4. The names "The Jakarta Project", "Tomcat", and "Apachetw Sa orf e * Foundation"mustnotbeusedtoendorseorpromoteprodsuct derived * per fm ri os msio tn h, ispls eo af st ewacroenta wc ittha op ua tche p@ ra ip oa rchw er .i ot rt ge .n permission. Forr ittew n *5.Productsderivedfromthissoftwaremaynotbecalled"che" Apa * permins os riomn ayof"t Ah pa ech Aep"aca hpepeGarouipn.their names without prior we nritt * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR I E DMPL * WO AFRRAM NET RC IHE AN ST, ABIL IIN TY CLUD AN IDNG,FIT BNU ES TSNOFT ORLIA MITP EAD RTIC TU O LA ,RTHPE URPI OS M EPLIAE RE D WAR TIES RAN *D II TSCC LO AN IT MR EI DB.UTI ON RSNO BEEV LE IN AT BLSEHA FL OL RT AH NE YA DP IA RC EH CE T,SO IF NT DW IA RR EE CTF,OU IND CA IT DA O R L ,I EO NN T *L SI PM EI CT IA EL D,TO E, XEP MR PO LC AU RR YE ,MO ER NTCON FSS EU QB US ET NI TT IU AL TEDG AO MO AD GE SSOR (IS NE CR LV UI DC IE NS G; ,L B N O F TO US TS *UOSR NE,T AO N DR Y ATTA T( H ,I EN OC RL YU PDR OIO FNF GILT INS AE; BGILL O II R GTEY B N, U CE SI WH N OERTSHSO ET RIHN EI T RN E WI RS R CE O U) N PTRA IAR OCIN TS) ,INHG SOTWRI E INV CE TA RNLY CY E L D IA I O AT U BYS W T I A ,A N D *SUCH OF THE DAMAGE. USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSI T YBILIO F *================================================================= *i Tn hd ii svs io df ut aw lasre onco bn es hi as lt fsoo fftv ho elA up na tc ah re yS cof ntw ra ir be utF iou nn sda mt ad ie onb .ym yF m oo a rr n e *<i hn tf tp o: r/ m/ aw tw iw o. nap oa nch te h. eor Ag p/ a> c. heSoftwareFoundation,pleasesee *[Additionalnotices,ifrequiredbypriorlicensingcondit s ]ion * / packageorg.apache.tomcat.session; importorg.apache.tomcat.core.*; importj oa r va g.. io apach. * ; e.tomcat.util.StringManager ; immpp or otr ja tvjaa .n vea t.*u;til.*; importjavax.servleett..htt*p.* ;; /** *Coreimplementationofanapplicationlevelsession *@authorrJJaamseosnDHuu nn ct ae nr D[ aj vi cdhs@oenn [g.sd uu nn.c] cao n@ meng.sun.]com *@a/ uthorJamesTodd[gonzo@eng.sun.com] publicclassApplicationSessimo pl nements HttpSession { privateStringManager = s m privSatt ri en Hg aM sa hn tab gl ee r.getv Manlau ger s("o =rgn .H a ep a waschet.a to ( ) ; bml ca et.session " ) ; privvaatt ee SS te rr iv ne griSde;ssion serverSession ; privatel Cong tc er xe ta ctoinotneTx it m; e = System.currentTimeMil();; lis privatelionn gthisAccessTime TiT me; i ln a ta sc tt Ai cv ceI sn st ee drval= crec 1 ; are tat iionn ime privateboolean valid = true; Appli Cc oa nti eoxntSceosnstieox nt () S{ tring i d , ServerSession serverSession, thhis i.sse .rcve ornSe tsesi xotn=co= s netre ve xrt Se ;ssion; this.id = id; this.inactiveInterval = context.getSessionTimeOut( ) ; if(this.inactiveInterval *= ! 1 =){60; } } ServerSession getServerSession ( ) { } returnserverSession; /** * Ca iln le adctbi yvico tnc ita en xst bedweha el ntwriet qh ua es ct cor cd om ie nsgly i. n so that accessa n d es * / void/ a/ cc sestsl ea d( s) t{accessedtothisAccessTime asitwillbeleftover /a/sf l tA rcocm es tsh ed e=pretv hiisA ocu ce ssa sTcim cee ;ss thisAccessTime = System.currentTimeMillis( ) ; } validate(); voidvalidate(){ // i f(ii fnawcetih va ev Ie nte ar nva il n!= acti1v)e{interval,checktoseeifw eeexceeded 'v it i nt in ( h tt i) s( IS ny ts et re vm a.lc=urrentTimeMillis()- lastAccessed ) / 1000; if(thisInterval> inactiveInterval ) { } invalidate(); } } //HTTPSESSIONIMPLEMENTATIONMETHODS public fS(tvra il ng id){getId () { } elr setu{ rnid; Stringm s g = sm.getString("applicationSession.session.ise" ) ; } throw new IllegalStateException(msg ) ; } publiifc(lvoanlgigde )t {CreationT( i) me { } elr seet{urncreationT; ime Stringm s g = sm.getString("applicationSession.session.ise" ) ; } throw new IllegalStateException(msg ) ; } /** * *@de/ precated publicHttpSessionContext getSessionContext ( ) { } return neSw essionContextImpl( ) ; publiclonggetLastAccessedT( ) { ime if(vraeltiudr )n {lastAcces; sed } elS setr{ingm s g = sm.getString("applicationSession.session.ise" ) ; throw new IllegalStateException(msg ) ; } } publicvos iedrivn ev ra Sl es is di ao tn e.(r)e{ moveApplicationSession(context) ; //removeeverythinginthesession w En huimlee rateinou ( nme. nu hm a=svMaolr ues E. lk eemyes (n( )t )s ; { r Se tmr oi ve nVg alu nea (m na emeS ) ; =tri (ng)enum.nextElement(); } } valid = false; publicboolean isNew(){ if(!St varlid) ng{m s g = sm.getString("applicationSession.session.ise" ) ; throw new IllegalStateException(msg ) ; } if(r th eitsu Ac rc net sr sT uiem; e = creationTime){ } elr setu {rnfalse; } } / **@ *deprecated * / publsi et cAvto ti ri dbpuu te t(V namle, uv ea( lu Se t)r ;n ia nmge,Objectvalue){ } publif ic(v !ov iad li sd) et{Attribute(Strn ianmge,Objectvalue){ Stringm s g = sm.getString("applicationSession.session.ise" ) ; } throw new IllegalStateException(msg ) ; if (name == null) { t Shr t owrine n wgm s g = s Il ml .e ggeatlS At rr gi um ne gn (t"Eaxp cp el pi ti co an t(imosn gS )essi;on.value.iae " ) ; } removeValue(name); //removeanyexistingbinding if ( Hvtat lp ue Ses !s =ionn uB ll ind &i &ngvE av le i = un en sttanceofHttpSessionBindingListe) { ner newHttpSessionBindingEvent(t,hi name); s } ( HttpSessionBindingListener)value).valueBoun ) ;d(e values.put(name,value); } /@d* * epr *ecated *ubl/ p icObject getValue(String name){ } returngetAttribute(name) ; publicObject getAttribute(Stringname){ if(!St varlid) ng{m s g = sm.getString("applicationSession.session.ise" ) ; throw new IllegalStateException(msg ) ; } if ( Sn ta rm ie ng=m s g= n= s uml .g le)tSt {ring("applicationSession.value.iae " ) ; throw new IllegalArgumentException(msg) ; } } returnvalues.get(name); /** *@de/ precated publEi nc um Se trrai ti no gn[]ege= tVa gl eu teANtatmreisb(u) te {Names( ) ; Ve w hc itloerne a.mhe ( asM =onreew El Vemcet nt os r(()); { } names.addElement(e.nextElement()); String[]valueNames = new String[names.size()]; names.copyInto(valueNames) ; returnvalueNames; } public EnumeratiognetAttributeNa(m) es { if(!St varlid) ng{m s g = sm.getString("applicationSession.session.ise" ) ; throw new IllegalStateException(msg ) ; } Hashtable valuesClone H = (ashtable)values.clone ( ) ; } return(Enumeration)valuesClone.k( ) ;eys /***@deprecated * / publri em co vvoeiAd tr te rm io bvuet Ve a( lu ne a( mS et) ;ring name){ } publif ic(v !ov iad li rde )mo{veAttribute(String name){ Stringm s g = sm.getString("applicationSession.session.ise" ) ; } throw new IllegalStateException(msg ) ; if (name == null) { Stringm s g = sm.getString("applicationSession.value.iae " ) ; } throw new IllegalArgumentException(msg) ; Objecto=values.get(name); if(oHttp in Sse ta sns ce ioo fH ntBti pS nedsi si nognE Bi ve n =dn in tgListener ) { newHttpSessionBindingEvent(this,name) ; } ( HttpSessionBindingListener)o).valueUnbound(e) ; values.remove(name); } publif ic(v !ov iad li sde )tM{axInactiveInterval(int interval){ Stringm s g = sm.getString("applicationSession.session.ise" ) ; } throw new IllegalStateException(msg ) ; inactiveInterval=interval; } pubi lfic (!i n tvali gde )tM{axInactiveInterval(){ Stringm s g = sm.getString("applicationSession.session.ise" ) ; } throw new IllegalStateException(msg ) ; returninactiveInter; val } } / ----------------------------------------------------------------------- S S on ServerSession packageorg.apache.tomcat.session; voidvali/d /at ie f() we {haveaninactiveinterval,checktoseeif imppoo rt rotro gr.ga .p aa pa cc hhee..tomcatt.. uc ti ol r. eS.t* r; ingManager ; // we've exceeded it immpp or otr ja tvjav . a. nie ot.*;. * ; if(inan cth i ti vs eInterval!= = 1){ importjaavv ax a.. se urt vl ielt.** ;; int)(System.currentTimeMillis()- lastAccessed ) / 1000; ( importjavax.servlet.http.*; if(i tn hv ia sl Iindtaetr ev (a )l ;> inactiveInterval ) { *C* / ore*implementationofaserversession ServerSessionManagers s=m *@authorJamesDuncanDavidson[ duncan@eng.sun.]com ServerSessionManager.getManager ( ) ; *@a/ uthorJamesTodd[gonzo@eng.sun.com] } ssm.removeSession(this) ; publicclassServerSession { } } privateStringManager = s m synchronized void invalidate() { privSatt ri en Hg aM sa hn tab gl ee r.getv Manlau ger s("o =rgn .H a ep a waschet.a to ( ) ; bml ca et.session " ) ; Enumerationenum= appSessions.keys ( ) ; privvaatteeSlH to a rs n ih g ntc gar i be d la ; etiona Tp ipm Sessions= Syst=em. nH e ca w usr ht raebn le t( Ti) meM ;il();; lis whiA O lp b epj li eeccn atu (i kmoe. ny S he =asesn i Mu oo m n. rn eeExla tp e Epl mSe( s mns ) ei t) nos t n= () {; privatelongthisAccessTime lastAccessed = crec are tat iionT nim Te; ime ApplicationSession)appSessions.get(key ) ( ; } appSession.invalidate(); privatei nin tactiveInterval= 1 ; } Servt eh riS s. eisdsio =n(i Sdt ;ringid){ publiifcv(oniadm pe ut=V=al nue l( lS )tr {n ia nmge,Objectvalue){ } Stringm s g = sm.getString("serverSession.value.iae"); publr ie ct Su trrnin dg ; getId () { } throw new IllegalArgumentException(msg) ; } removeValue(name); //removeanyexistingbinding publriectluor nn gc gr ee ta Ct ri eo an tT i; i om ne T( i) me { } values.put(name,value); } publicObject getValue(String name){ publriectluor nn gl ge at sL ta As ctcAecsc; seesdsedT( ) { ime if ( Sn ta rm ie ng=m s g= n= s uml .g le)tS{ tring("serverSession.value.iae"); } throw new IllegalArgumentException(msg) ; pubboolean licAppliccr ae ta io tn eS )e {ssion getApplicationSession(Context context, } Appli( Acpap tl ii oc na St es is oi no Sn essioa np )pa Sp es ps Si eos ns =ions.get(context ) ; } returnvalues.get(name); if(appSession == null && create) { public Enumeratiogn etValueNames() { //XXX } returnvalues.keys(); //synctoensurevalid? publicvoidremoveValue(String name){ apppS peS ss eis on sion= sn.epwu Ap tp(lc io ca ntti, a e o pn x pStessss ii on on(id, ) ;this,context); } values.remove(name); } publicvoidsetMaxInactiveInterval(int interval){ //XXm Xake sure that we haven't gone over the end of our } inactiveInterval=interval; //iannae ct wi appSession veinterval- i -fso,invalidateandcreate publici n t getMaxInactiveInterval(){ returnappSession; } returninactiveInter; val } //XXXsync'd f // o r safty - nootherthreadshouldbegettingsomething } voida rp ep mS oe vsesAipop nl si .c re am to iv oe n(Sceosns ti eo xn t(Con) ; textcontext) { //s fo rl om uti to hi nsfo wr hit lh eis w, ebaurtewr ee'alpl ind ge .teTr hm ii sne iss no 'm tethi eng moe sl tseoe a l r . plta it m /** synchronizedvoidreap(){ * Ca iln le adctbi yvico tnc ita en xst bedweha el ntwriet qh ua es ct cor cd om ie nsgly i. n so that accessa n d es Enumerationenum= appSessions.keys ( ) ; * / whiO lb ejeecntu (kme.yh=aesnMuo m. rn eeExlte El me( mn) et) ns t( ) {; void/ a/ cc sestslea d( s) t{accessedtothisAccessTime asitwillbeleftover Appli( Acpap tl ii oc na St es is oi no Sn essioa np )paSp ep ss Si eo sns =ions.get(key ) ; //fromthepreviousaccess appSession.valid( ) ; ate lh t ai sstAA cce cs esTsie md e= = S th yi sstAe cm ce .s cs uTrir me; ntTimeMillis( ) ; } } } } voidvalidate() 11 /*** Bind an object to this session, using the specified nI am fea.nobject /** packageorg.apache.tomcat.session; *< ro pe> fpl ta hc eesda.menameisalreadyboundtothissession,the jec oti bs object* i Rs eturn thethfe acade. <code>HttpSession </code> for which this importjavaa..ii oo .. IOE bx jceec ptI io nn putSt; ream; *<Acfotd ee r>t Hh ti ts pSm ee st si hon dBi en xd ei cnugtLeiss, tea nn ed rift<h/e coodbej>e ,c tt heicm op nl te am ie nn et rs calls *ub/ p licHttpSession getSession(){ importjavvaa .i .oi.o Ob .jSee ct rO iuatl pu itzSa t; r belae m; *<code>valueBound ()</code>ontheobject. return((HttpSession) this); impp oo rt rjt aj vav .au.t ui ti ll ..EHn au sh mt earba lt eion;; *@param v nalm ueN Ob ajmee ctto towh be icbhou tnh d, eo ca bnjne ot ctbe isnu blolund,cannotbenull } imppoo rt rjtaj vaav.au xt .i se lr .v Vleectt .o Sr er ;vletException; *@exception IllegalStateException ifthismethodiscalledonan importjavax.servlet.http.HHttttppSSeessssiioonn;BindingEvent; *invalidatedsession ionPub -l -i -c -M -e-t-h-o-d-s-------------------------------------importjavax.servlet.http.HttpSessssiioonnBCionndt ; ienxgtListe ;nerSess// *<@ cd oe dp er >ecats eet dAtA trs ibuo te fVer (s)i<o/ nc2o.d2e,>thismethodisreplacedby importorg.apache.ttoommccaatt .. uc ta it la .l Si tn ra i. ng*M; anager ; *ubl/icvoidputValue(Strn p ia nmge,Objectvalue){ /U* * pda*tetheaccessedtimeinformationforthissession. setAttribute(name,value); / S*tan * *dard implementation of the <b>Session</b> This *smethod houldbecalledbythecontextwhenarequestcomesin } intesre * fa rciea.l Ti hi zsao, bbs l jo ec tthiastitcanbestoredin for *asep sasri ti oc nu, la erveniftheapplicationdoesnotreferenceit. perstiostea * nt s di tf of re argee ntorJV tMrans ff or erredd istributable session *ubl/ p icvoidaccess(){ / R*em* * ove the object bound with the specified name from t session. his If su * <pp >ort. this.lastAccessedTime = this.thisAccessedTime; *dtoheess ne os ts hio nng. doesnothaveanobjectboundwiththisnatm hi es,method *la< c ss b>Ir MeP pr LeE seM nt EsNTAbT ot IhONt NhO eTE</b>: Aninstanceofthis thiss .. it sN he iwsAcce=s fa sls eed ;Time = System.currentTimeMil( ) ;lis *<A pf >terthismethodexecutes,andiftheobjectimplements *tti H ( pnStees rs ni al on)(Sev s ie s wiono ) f atn hed a ses psi p on l .ication level } *<code>v Ht at lp uS eeUsnsbiou nn Bd i( nd )i<n/ gc Li osdte> ne or nthe< o/ bcjoedc et >, .thecontainercalls *uHbolwie p cv ,e Jr a, vableocga iu cs oe uttshiede classitselfisnotdeclared /** *@param nameNameoftheobjecttoremovefromthissession. *aco p kfagetc ha enn< oc tocdaes >t or ag n.apache.tomcat.session</code> this* seP se sr if oo nr ,mtheinternalprocessingrequiredtoinvalidate *@exception IllegalStateException ifthismethodiscalledonan *essH S it otn pS veise si wo. n viewofthisinstancebacktoa alre* adwyietxhp oi ur tet dr .iggeringanexceptionifthesessionhas *invalidated / session *@authorCraigR.McClanahan *ubl/ p icvoidexpire(){ publicvoidremoveAttribute(String name){ *7 1 @:v5e 4: r1 s0i $on$Revision:1.2$$Date:2000/05/15 //Removethissessionfromourmanager'sactive syncOhbr jo ec nt izo ebdjec( tat =tr ai tt br uitbeus te )s.g {et(name); * / sessionsif((manager!=null)&&(managerinstanceof if ( return; object == null) finalimcpll asesmeSnta sH ntd tpa Serss dio Sness, iSoes nsion{ ManagerBase ) ManagerBase)manager).remove(this); ( i at // ftri( bo ut bS ej y ss e .t r c ei em t n m . sotv u at n ec . (e p no r a f imne t) l; nH (t "t Rp eSmeosvsin og nB ai tn td riinbguLt ie s" te + ) {ne ar me); //---------------------------------------------// V ectUo nb rir nd esua lnt ys=o nbejw ec Vte scta osr so (c )i; ated with this session ( ( Hn te tw pH StetspsSieo sn sB ii onB dind giLnigsEtve on ) be j tr e (c (t H) t. tv pa Sl eu se sU in ob n) ountd his, name)); ------------- Constructors w En huimlee ratai to t( r ns a. tt hr assMore= gEelteAmtetnrtisb(u)t) e{ Names( ) ; } } /** r Se ts ru ilntgsattr .ad= dEle( mSetn ri tn( g) a) a ; ttttrrs.nextElem( ) ;ent } specif* ieC donstMr an uac ge tr. anewSessionassociatedwiththe Enumerationnames=results.elements(); } *@param manager The manager with which this whiS lt erina gm( esn.a hm ae sMor =eEl (e Smterni tn sg () n a) m{es.nextElem( ) ;ent / R*em* * ove the object bound with the specified name from t session. his If Sess* ioni/sassociated } removeAttribute(name) ; *dtoheess ne os ts hio nng. doesnothaveanobjectboundwiththisnatm hi es,method publicStandardSession(Manager manager){ //Markthissessionasinvalid *<A pf >terthismethodexecutes,andiftheobjectimplements su t hpi es r( .)m ;anager=manager; setValid(false ) ; *<code>v Ht at lp uS eeUsnsbiou nn Bd i( nd )i<n/ gc Li osdte> ne or nthe< o/ bcjoedc et >, .thecontainercalls } } *@param nameNameoftheobjecttoremovefromthissession. /** *@exception IllegalStateException ifthismethodiscalledonan ------//I -n -s -t -a -n -c -e -V -a -r -i -a -b -l -e -s ------------------------------ vari* abRleel se ,a is neallobjectreferences,andinitializeinstance *invalidatedsession *pr/ eparationforreuseofthisobject. *<@ cd oe dp er >ecatr eed mov Aes Ato tr fibV ut eer () s< i/ocn ode 2> .2,thismethodisreplacedby /T*he*collectionofuserdataattributes * public void recycle() { *ubl/icvoidremoveValue(String name){ p asso* ciat/edwiththisSession. Session //Resettheinstancevariablesassociatedwiththis removeAttribute(name) ; privateHashtable attributes=new Hashta( ) ; ble ar c tetar tio bnuTt im ees=.0c L; lear(); } /** i =t nA uc lc le ;ssedTime=0L; ld as mill* iT se hc eotnidm se st in hc iesmsie ds ni sg ihotn,wascreated,in man xa Ig ne ar cti=ven Iu nl tl e; r= val1 ; /B * *in* d an object to this session, using the specified nI am fea.nobject * Ja /nuary 1, 1970 GMT. isNew =true;false; isValid *roefpl ta hc eesda.menameisalreadyboundtothissession,the jec oti bs privatelongcreationTime =0L; //TellourManagerthatthisSessionhasbeenrecycled *<A pf >terthismethodexecutes,andiftheobjectimplements /** ManagerBase if(( )manager!=null)&&(managerinstanceof *<code>valueBound HttpSessionBi( nd )i <n /g cL oi ds et >e one tr heobj< e/ cc to .de>,thecontainercalls *The /sessionidentifierofthisSession. ( ManagerBase)manager).recycle(this); *@param nameNametowhichtheobjectisbound,cannotbenull privateStringid=null; } excae ra pmtionvalueIlO lb ej ge ac lt Arg tu omebnetEb xo cu ep nt di ,oncannot ifba enn aut ll temptismadetoadda /De*sc* * riptiveinformationdescribingthis Package //--Methods --------------------------------------------- Session *@@p *@en xceoptsi e no rn ializI al bll ee ga olb St jaetc eE txi ce npatn io ennviri of nmt ehn it sma me rtkhe oddistc rai lb le udtaobnlea. n Sess *ion/implementation. *invalidated / session "Stanpdr ai rd vS aetse ss io tn a/t1i .c 0" f;inalStringinfo= / *Ret* * urn the <code>isValid </code>flagforthissession. publicvoidsetAttribute(Strn ianmge,Objectvalue){ * / isValid boolean () { if(( !( m valn ueageri! ns =ta nnucl eo lf )Se &r &im aa ln ia zg ae br l. e) getDistributable()&& /T * *he*last accessed time for this Session. return(this.isValid) ; throw( snm ew.getStr Ii ln le gg (a "lsAt ra gn um de an rtdES xe cs ep st ii oonn.setAttribute.iae " ) ; * } priv/atelonglastAccessedTime = creationT; ime synchronized (attributes) { re a tmtorvi eb At utreis b. ut pe u(tn(an ma e) ; me,value); /Se * *tt*he<code>isNew </code> flag for this session. /T* * he*ManagerwithwhichthisSessionis if(v( alueHttpi Sne st sa sni ce oonfB Ht it np dSien sg si Lo in sBtie v ) nn d ai e ln u rg eL )i .s vt ae ln uer Bound) *@param isNew Thenewvalueforthe<coi dse Ne>w</code> associated. * / } (newHttpSessionBindingEvent((HttpSession) this, name)); flag* / privateManagermanager=null; } voidsetNew(boolean isNew){ /** this.isNew = isNew ; clie* ntTrhee qu measxtismbu em fo triemeinterval,inseconds,between //-------------------------------------------- HttpSession PrivateMethods } sessi *on.the Anser g vl aetivec to im ne tainermayinvalidatethis /** out.* indicates that the session should never time / * * *Ro eb aj deacsteriinapluitzesdtvreerasmi.onofthissessionobjectfromstph ec eified *Setthe<code>isValid</code>flagforthissession. *riv/atei nma p txInactiveInter= val1 ; *<<pb >>IMPLEMENTATIONNOTE</b>:Thereferencetotheowni Manager <code>*@p is a Vr al ai m d</coid sV e al > id flagThe new value for the * is not restored by this method, and must be set exply . icitl *oids v /etValid(boolean isValid){ /F* * lag*indicatingwhetherthissessionisnewor *@param streamTheinputstreamtoreadfrom this.isValid= isValid ; not.* / *@exception I COlEx acsep stNiontFoui nf dEaxnce in pp ti ui f to /o nauntput nke nr or wo nrc ol ca cs us rsis specified } privateboolean isNew =true; *riv/atevoidreadObject(ObjectInputStreamstream) p //------------------------------------------------/** throwsClassNotFoundException, IOException { Properties or* not. Flagindicatingwhetherthissessionisvalid HttpSession // creaD te iso er niTai li mze= ((Long) the scala sr tre ia nm s. tr ae nc ae dObvjaercit a( b) l) e. slo( ne gx Vcaelpute(Ma) nag; er) /** *riv/ateboolean p isValid = false; i ds =xt (I rec isn m= .ra ea( d( OI bn jt ee cg te ( ) ; milli *sme Ri c eo dtnudi r sn g si ht n th c,eJt ai nmuear wh ye 1n ,1 t9 h7 is 0GsMeT s. sionwascreated,in /** la m ASc ntc a t sg e i) dvTeiI me ns =tr eea r((Long) v l srt )rea sm t. rreeaamd.Orbejaed cO tb (j )e )c .t l( o) n) g. Va il nu te V( alu)e(; ); *@exception IllegalStateException if this method is * Th/ e string manager for this package. isNew = (((B isValid (oBol oeoan l)ean s) treeaamm.. rr ee ad aO dbOjbejce tc (t )) (. )b)o.oblo eo al nV ealnuVea( ) ;l)u; e calle* dinvalidated on an session privateStringManager = s m //Deserialize the attribute count and attribute values *ubl/iclonggetCreationT( p i) me { StringManager.getManager("org.apache.tomcat.session " ; ) i forn (n it nt= i=( 0(;In ite <gn er ;s )t ir +e+a)m. {readObject()).intVa( ) ;lue return(this.creationTime) ; O St br jiencgtvn aa lmuee=( =Ob(jSetc rt i) ng st )rree aa m. mr.er ae dO abdjO eb ct j( ) ;ec) t; } /T* * he* HTTPsessioncontextassociatedwiththis } attributes.put(name,value); sess* ion./ } /* Retu *rn the session context with which this session is = pr ni uv lalt;e statiHc ttpSessionContextsessionContext * associated. * /W*ri* * teaserializedversionofthissessionobjecttot sh pecified andh* asn @o deprecated As of Version 2.1, this method is deprecated *<p /Th * *ec*urrentaccessedtimeforthissession. o> bject output stream. *riv/atelongthisAccessedTime = p creationT; ime t h*ereplacement. Itwillberemovedinafutureversionof* < ib n>ItMhPeLEs Me Er Ni Ta Al TiIzOeNdNrOeTpEr<e/sb e> n: tatiToh neoofwnt ih ni gsMS ae ns as gi eo rn.will Aft nc be a ol r t lingstored *Jav /aServletAPI. *e <x cpoldie c> ireadObject tly. ()</code>, you must set the associated Manager publicHttpSessionContext getSessionContext ( ) { *<<pb>>IMPLEMENTATIONNOTE</b>:AnyattributethatisnotSerializable if(sessionContext =n =ewStannu da lr ld)SessionContext ( ) ; ------//S -e -s -s -i -o -n -P -r -o -p -e -r -t -i -e -s -----------------------------*wbi els lub restihl ee< nctoldy e> idginso tri ebdu.taIbfle y< o/ucd od oen>ot prwoapn er ttayny ofsu oc ur h trai sociated ab t sutes, return(sessionContext ) ; * Manager is set to <code>true</code>. } /S* * et* thecreationtimeforthissession.This *@param streamTheoutputstreamtowriteto meth *oMdaniasge cr al wl hed nabnyet xh ie stingSessioninstanceis //---------------------------------------------*@ex/ception IOException ifaninput/outputerroroccurs HttpSession PublicMethods reused. * privatevoidwriteObject(ObjectOutputStream stream)throws IOException{ /** *@p /aram timeThenewcreationtime /t s /re Wa rm i. tw erittheeObs jc ea cl ta (r new instan Lcoeng va (r cir ae bl aetsio (e nx Tc ) ;i em pt eManager) session, *Returnt or heobjectboundwiththespecifiednameinthis publicvoidsetCreationTime(longtime) { stream.wriitteeOObb jj ee cc tt (( ni ed w) ; Long(lastAccessedT) ;ime *<code>null</code>ifnoobjectisboundwiththatname. this.c lr ae sa tt Ai co cn eT si sm ee dTime=time;=time; stream.writeObject(new I Bn oto eg leera (m na( xI insa) ; N ct eiw veInterval)); *@param nameNameoftheattributetobereturned this.thisAccessedTime =time; stream.writeObject(new Boolean(isValid)); calle* d@invalidated eox ncea pntion Ill session egalStateException if this method is } V E // e nc ut mA o ec rcr aue t ms i ul u oa l ntt aet st=rn stehw eVe= gcn et ao m Ae r ts t (r )i ;b o su e fr ti e aN li azm ab els e( )at; tributes *ubl/ p icObject getAttribute(Stringname){ /R * *etu *rn the session identifier for this whiS lt era itntg ( rs attr .has=MoreE(lSetm re int gs )a () t) t{rs.nextElem( ) ;ent return(attributes.get(name)); sess* ion./ i Of b(j ve al cut e vai lnu st eaa nc t= e to rf iS be ut re isa.l gi et z( aabtl te r) ; } publicString getId () { } results.addElement(attr ) ; return(this.id); //Serializetheattributecountandtheattributeve s alu /R* * etu*rnan<code>Enumeration</code>of } sn E tu rm ee ar ma .t wi ro in teO nb aj mec st(=new resultIsn .e tl eegmen rt (sr(e ); sults.size())); <cod *ec >o Snttr ainnig ng </tcho ede na >moeb sjo efctts heobjectsboundtothis /** whiS lt erina gm( esn.a hm ae sMor =eEl (e Smterni tn sg () n a) m{es.nextElem( ) ;ent sess* ion. *Setthesessionidentifierforthissession. strree am a.mw. rw it reiOt bj eeOcb tj (a etctt ri (bnu ) ; a tm es e.get(name)); calle* d@eox ncea pntion IllegalStateException if this method is *@p /aram idThenewsessionidentifier } *invalidated / session publicvoidsetId(Stringid){ } public EnumeratiognetAttributeNa(m) es { if((t mh ai ns a. gi ed ri! ns =tanu cl eo lf )&&M( am nagn ea rB gae se r)!=null)&& crosscutinvalidate(StandardSession s):s&(i ngettMaxInactiveInterval()| return(attributes.keys()); ( ManagerBase)manager).remove(this); O lo bnj gg ee cttCg ree ta Att iro in bu Ttiem (e St (r) in |g)| } this.id = id; Et S nr ui mnegr[a]tgi eo tV na gl eu teANtatmreisbuteN( ) | ames()| ManagerBase if(( )manager!=null)&&(managerinstanceof / * * voidinvalidate boolean isNew()|() | session, *Returnt or heobjectboundwiththespecifiednameinthis ( ManagerBase)manager).add(this); voids rem toAvt et Ar tt ir biubtue t( e( SS tt rriing,Obje) | ct)); *<code>null</code>ifnoobjectisboundwiththatname. } staticadvice(StandardSession s):invalidate(s){ *@param nameNameofthevaluetobereturned /** befoirfe ({ !s.isValid ( ) calle* d@eox ncea pntion IllegalStateException if this method is Sess* ion Ri em tp ul re nme dn et sa ct rip ot ni av ne dinformation about this throw( sne . wsm.geI tlS le tgr al iSn ta gt( eE "xs ce tpa ti nod nardSess. "ion *invalidatedsession format*thecorrespondingversionnumber,inthe thi" + si s e Jo .in" ) ; Point.methodName b y *@deprecatedAsofVersion2.2,thismethodisreplaced <code>& * lt;description&gt;/&lt;version;& </ gc tode>. } } *<co/de> getAttribute ()</code> *ubl/ p icString getInfo(){ publicObject getValue(String name){ return(this.info); } return(getAttribute(name)); } } /** //--------------------------------------------------------------PrivateClass /* * Ret* urn the set of names of objects bound to this / * * asso*ciRaete ur dnwitthh eth la isttimetheclientsentarequest on.areIf nothseu rc ehobjects,azero length array is returned.*iTn hi ts erc flaac ss e,it soacodn um fm oyrmim tpoletmh en eta rt eiqou nir of emt ehnet< tchoa dt e>s Ht utcph Sea ss nioonb Co jn e be tcet xtreturned</code> midnig*ht, sesJ sai nuo ar ny,a1 s,th1e 970numberofmillisecondssincesessi* *@exception IllegalStateException if this method is such*asGgMe Tt .tiA nc gtoirosne stth ia nt gyourapplicationtakes, *when<code> HttpSession.getSessionContext ()</code>iscalled. calle* dinvalidated on an session *@authorCraigR.McClanahan affe*ca tvt al hu eeas cscoe cs ia stet diw miet. hthesession,donot *@deprecatedAsofVersion2.2,thismethodisreplaced * @ id ne tperr ef cat cedwiAlslboe fre Jm av oa vedSeirn vla etfuA tP uIre2v.e 1rsi wo it nhofnothirsepA lP ac Ie .ment.T h e *ubl/iclonggetLastAccessedT( p ) { ime b y *<code> getAttributeNa(m) e< s/code> * / return(this.lastAccessedTime) ; *ubl/icString[]getValueNames(){ p final class StandardSessionContext implementsHttpSessionCont{ ext } Vectorresults=newVector(); privateVectordummy=newVector(); w En huimlee ratai to t( r ns a. tt hr assMore= gEelteAmtetnrtisb(u)t) e{ Names( ) ; /** / *Ret*urn the Manager within which this Session * r Se ts ru ilntgsattr .ad= dEle( mSetn ri tn( g) a) a ; ttttrrs.nextElem( ) ;ent *R weitt ur hninthe thsiessicoo nni tdeex nti. fiers of all sessions defined isva* lid./ Stringnames[]=newString[results.size()]; } * @deprecated As of Java Servlet API 2.1 with no replace t .men public Managegr etManager(){ for(n ia nm teis= [i0] ;=i(S <tnraimn eg s. )l res nuglts h. ;el ie+m+ en )tAt(i ) ; *Ta hn idsw mi eltlhb oedm re umsotvr ee dtiu nranf au nteumrp etvye< rs ci oodneo >fEn th ue me AP rI a.tion</c> ode return(this.manager); return(names); *ubl/ic Enumeratioge p ntIds(){ } } return(dummy.elements()); /** } valid.*SettheManagerwithinwhichthisSessionis / * * toit.*Invalidatesthissessionandunbindsanyobjectsbound *@param manager The new Manager *@exception IllegalStateException if this method is / *Ret* * urn the <code>HttpSession </code> associated with the *ubl/icvoidsetManager(Manager manager){ p call* ed ao nninvalidatedsession *specifiedsessionidentifier. this.manager=manager; *ubl/ p icvoidinvalidate(){ *@param idSessionidentifierforwhichtolookupasession } // Cause this session to expire *T@ hdies pm rec tahtoedmA usstorfet Ja uv rannSu el rv llaentdw AP iI ll2b.e 1re wi mtohvend oir ne aplace t .men } expire(); *ubf/ p lut iuc re Httv pS ee rssion ofgte he tSA ePsIs .ion(Striidn)g { bet* / weR * een tu * crl nit ehnetr ma exq im uue mstisme interval, in seconds, return(null); the* ses be sf ioo rn e.the Anegas tei rvlet container will invalidate / *Ret* urn <code>true</code> if the client does not yet know } time* outt.ime indicates that the session should never * about*ste hession,oriftheclientchoosesnottojointhe } *@exception IllegalStateException if this sessio*n.examF pol re,iftheserverusedonlycookie- basedsessions, meth *o ad nin ivsalciadl al tedseosnsion andt* hec hl ai sendtisabledtheuseofcookies,thenasessionwouldbe *ub/ p lici n t getMaxInactiveInterval(){ new*on request. each return(this.maxInactiveInter) ;val *@exception IllegalStateException if this method is } calle* dinvalidated on an session *ub/ p licboolean isNew(){ /Se * *tt*hemaximumtimeinterval,inseconds, return(this.isNew ) ; bet* webef nor celi th eentres qer uvletstscontainer will invalidate the* sestsiimoen.inA din ce ag ta et sivt ehat the session should never } time* out. *@p /aram intervalThenewmaximuminterval { publicvoidsetMaxInactiveInterval(int interval) this.maxInactiveInterval=interval; } HTTPR SessionInterceptor Sess on n e cep o packageorg.apache.tomcat.request; importorg.apache.tomcat.u ct oi rl e.*; immpp or otr ja tvjav . a. nie ot.*;. * ; importjaava vxa.s .eurv tliet l..ht *t;p.*; /** *Wiin llpth r eocR eqs uest. therequestanddeterminethesessionId,ant dsi et *Italsomarksthesessionasaccessed. *Tah di dsni em wpil ne te mr ecnet pa to tr isof norno lt yhhearnmdelte hs od Cso.okiessessions,pleaseenx dotr * / publicclassSessionIntercepe tx otrendsBaseIntercepi tm op rlementsRequestInterceptor{ s /t /a Gt Si ,cse fp ia nr al atcehsatrhS eE sS eS sIsOiNoInDi_d Rf Or Uo TE m_ tS hE ePj=v'r. om u 't; e iont C ned xe tb Ma un ga=g0 e; r c m ; publicSessionInterceptor(){ } publSiycsvtoeimd.soeu tt De .bpurgi (ntli n tn("d i Seb t)ug{to " + i); } debug=i; publthis.cm=cm; icvoidsetContextManager( ContextManagercm ) { } pubS lt ir ci n tngs res qs ui eo sn tI Md a= p(nRe uqlue ls;t request){ Cookiecookies[]=request.getCookies ();//assert!=null for(inti=0;i<cookies.length;i++){ Cookiecookie=cookies[i]; if(s ce os os kio en .I gd etName co = (o )k .i eeq .u ga et lV sa (l "uJ eSESSI( ) ; ONID ")) { i sefss (isoensIsdi=onId! va =lniu dl at le)S{ essionId(request , sessionId) ; } request.setRequestedSessionIdFromCookie(t) ;rue } } } Strings i g j = " ;sessionid = " ; if(nfoundAt dt ebug>0= 1) c;m.log(" XXX RURI="re+ quest.getRequestURI()); if((s fe osusn io dnAIt d= requres qu te .sgte .g te RteRq eu qu eesstURII(( )) .s .u ibn sd tr ei xnOgf (f ())!= o suing d1 At+) sig{ .length()); /e r /q ru eewsrti.t seU tRe Lq ,udeosItnUe Re Id (r te oq duoeasnty .t gh et iR ne gqmuoerset? URI().sub in sgt (0 r, foundAt) ) ; i sefss (isoensIsdi=onId! va =lniu dl at le)S{ essionId(request , sessionId) ; } request.setRequestedSessionIdFromURL(true) ; return0; } } // W Xe XXma wyhas ttil il ss te htei ctora rne dctjus bt ehr ae vti uo rn ri se fssi to hnei sne va sl sii do .nisinv d ?ali /**Validateandfixthesessionid.Ifthesessionisno at livd return null. *I @return twillal ss eo ssi co ln eI ad n,uo prth nu ellsei sfsio no ntfv ra olm idload balancingstrings. *riv p /a /tGeS,SWterp ii nvgaglyib dac tk eStehsesi JoVnMId i( dRo en qur tee osq ptuo ef stt,hSetr si en sg ss ieo sn sik i eo cn oIo d) { //Separatethem... if((nd uelbl u! g> =0ses) sion cImd. )lo {g( Orig " sessionId " + sessio) ; nId if(idex i nid tex= >0 )s {essionId.lastIndexOf(SESSIONID_ROUTE_ ) ;SEP } sessionId =sessionId.substring(0, i d e x ) ; } if(/ se /ssG iS on ,IdWear !=enu i ll n&& asperso sb il oe nm Id. hl ee rn eg,thw(e)!m=a0y){ actuallyget //mcuolnttiepxlteS ae ns dso in oe ncfooorki te hs e(r oe na el focrotnhteerxoto.t..orold ssi soe n /o C /nctoeoxkti ce.tW rexqm = ue uss t. tgc et hCe oc nt kex fto(r)v ;alidityinthecurrceonntext. i Sefss (in on uMl an lager !s= M.fis MndSe= c ss ti xo .n g( ecttSxe,ssiosne Masns ag ieor) ( n) I; d { seMq. r ue asc t. cset sRseq eude( st , ce rt d eS q xe us esi to ,s ne Is ds (i so en sI sd ionId) ; ) ; i rf e(tudr eb nusge> s0 sio)nId c; m.log(" Final session id "se+ ssionId) ; } } } returnnull; publici n t beforeBody( Request rrequest ,Responseresponse){ i Sf t(rd ienbg ug r>e0q)Sc ems.s lo igo(= n "B Ie dfro er sp eon Bso e. dg yet" Se+ ssr io en qIS dessi( ) ; onId ) ; if(ret qu Sr en ss 0i ;onId==null) //G mS ul ,t si eptltehs eepsastih oa ntctor oi kb ie us te ct an ot bh eeuc so eo d, ki oe n. eTfh oi rsew aa cy h // S trcontext. ingsessionPath = rrequest.getContext().getPath(); if(se sessionPath ssionPath.le= ngth( " / ;)==0){ } i /f /(G!S se ,spsio gn gPy ab th a.cek qu tahle sjvm( r"o /" u )) t{eonthesessionid. i Sf t( rn iu nl gjvmRoute l !jvmRoute == ) r {request.getJvmRoute(); } reqSessionId= reqSessionId + SESSIONID_ROUTE_SEPjvmR +oute ; } Cookiecookie=newCookier( eq "Se JsS si Eon SIS dIONI) ;D", cookie.setP Mat xh A( gs ee (s -sion1 ) ; Path ) ; cookie.setVersion(1); c re os op ko in es.es.eat dV de Hr es ad ie or n(0);C (ookieTools.getCCooookkiieeHHeeaadd ee rr VN aa lm ue(cookie) ) , ; response.addHeader C (ookieTools.getCCooookkiieeHHeeaadd ee rr VN aa lm ue(cookie) ) , ; return0; } /**Notificationofcontextshutdown *ubl/icvoidcontextShutd( p oC wontextc t)x { throwsTomcatException c itfx( .g ce tt xS .egsestiDoenb Mu ag n() ager >(0 ).)re cm to xv .e lS oe gs (s "i Ro en ms o( vc it nx g) s ;essionsfrom"+c t) ;x } Se ve Sess onManage ServerSessionManager packageorg.apache.tomcat.session; importorg.apache.tomcat.c uo tr ie l.*; immpp or otr ja tvjav . a. nie ot.*;. * ; importjaava vxa.s .eurv tliet l..ht *t;p.*; /** *@authorJamesDuncanDavidson[ duncan@eng.sun.]com *@@aauuthorrJJas me osnHTu on dd te[rg[ oj nz coh @@ en egn .g su .ns .u co nm. ]] com * / publicclassServerSessionManager implementsSessionManager { privSatt ri en Sg tM ra ina gg Me ar n. aget rManag s = mer("org.apache.tomcat.session " ) ; private statiSc erverSessionManager manager;//=newServerSessionManager( ) ; protected i n t inactiveInterval = 1 ; statmi an ca{ ger=new ServerSessionManager(); } publreturn icstaticmanager; ServerSessionManager getManager(){ } privvaatt ee RH eas ph etrar be la eper;sessions=newHashtable(); privraetaepSeer= vR ee ra Sp ee sr s. ig oe nt MR ae nap ger(); { reeaa pe pre .s re. tS set rv aerrS te(s) si;onManager(this ) ; } publi Ac ppv lo ii cd ati ao cn cS ee sss eido(nConta p S extA = (ppli c , t xcaR tei quo es n tSession r , e q)f Sitnr di Se ns gsiiod n(){c t x ,id); if(a p==Snull)return; ServS s e. raScecs esi so en d ( servS ) ; = apS.getServerSess( ) ;ion apS.accessed( ) ; /e/q. r csa et cSh es esiotn- n aon ( pe) ;eS dtocomputeitagain } pubS lt ir cH itn tpg Sesse ss io sn ionId= creaSteesSseisos ni Io dn G( eC no en rt act eo xt r. ) {gxenerat( ) ;eId S ses rs vi eo rn Ss e. sp su it o( nsessisoen ss Ii don=,n see wssS io en r) v; erSession(sessionId ) ; i f1(! =inactiveInterval){ } session.setMaxInactiveInterval(inactiveInterval ) ; } returnsession.getApplicationSess( citox n, true ); publicHttpSession findSession(Context , c t x String id) { if(sSession ServerSession==nulls )Sessi r o e nturnS = (n eur ll v;erSession)sessions.get(id) ; returnsSession.getApplicationSession(ctx, false); } //XXX / // / fsr yn oc m 'dthis f o rwhsafty ile-we a no reotrheea rpitnhg r. eadThs ihsoul idsnb 'e tgteh te tinm gosstome ot a l pht ii nm g //solutionforthis,butwe'lldeterminesomethingelsee r .lat synchE rn on ui mzer dat vo ii odnerneu am p= () ses {sions.keys(); while enu (m.hasMoreEleme(n)t)s { Oe S brjver cStek ss eiyo= nenums .es n si e on xtE =le(S mer nv te (rSe )ss; ion)sessions.get(key ) ; session.reap(); } session.validate(); } syncS ht rr oi nnigzei ddvo= idsessi ro en m. og vet SI ed s( si)o; n(ServerSessionsession) { session.invalidate(); } sessions.remove(id); publicvoidremoveSessions(Context context){ Enumerationenum=sessions.keys(); whiO lb ejeecntu (kme.yh=aesnMuo m. rn eeExlte El me( mn) et) ns t( ) {; A Sp ep rl vi ec ra St ei so sn iSoenssionsessionap =pSe(S ss ei rovne =rSession)sessions.get(key ) ; session.getApplicationSession(context, false); if(appSS ee ssi so inon.in!v =aln i ul d l) ate{( ) ; } } } /** *Usedbycontexttoconfigurethesessionmanager'sinavci tt iytimeout. *CoThe ntex Se tss oin ont Ma hne ago er thermh aa ynhd avh eassom ietd 'e sfa tuilmtesoeust sisoe ntti bmyet oh ut e,ld ot ye m h ep n et *sed ss eisocnr mi an patgoerwe ab. cx( m clordi)n.gT th oitshm iestv ha od lule. tstheContextconforgure the *@param minutes The session inactivity timeout in minutes. *ubl/icvoidsetSessionTimeOut(intminutes) { p i f/ 1/ (T! h=emamn ia nu gteer s) wor{kswithseconds... } inactiveInterval=(minutes*60); } } S anda dManage StandardManager //------------------------------------------------------LifecycleMethods packageorg.apache.tomcat.session; impp oo rt rjt aj vav .au.t ii o. lI .OEEn xu ce mp etria ot nion;; imppoo rt rjtaj vaa v. a. uu ttil.H Vaesc hta obrl; e ; importj or ag v. aa xp .a sc eh re v.lteotm.chattt .p c. aC to ao lk ii ne a; .*; importo jr ag v. aa xp .a sc ehrev.lteot m. ch att .p u. tH il t. tS pt Sr ei sn sg iMoann;ager ; importorg.w3c.dom.Na om ded ;NodeMap; *C*on* / figurethiscomponent,basedonthespecifiedconfiag ti uor n *p ca om rp ao mn ee tn et rs i. nsTthai ns ce me it shcordes ah to eu dl ,dab nd ec ba ef lo lr ee d< ic mo md ee d> is attaerlty(c e ra ) od f <et / >t h e * is called. *@p (<B ar >a FmIXME:paWrhaamtet oe br js ect Cotnyfpiegusrhaotuilodnth pi as rar mea tl el ry sbe f? o) r this component *@exception IllegalStateException ifthiscomponenthasalreadybeen *@ec xocnefpitgi uo rn edanL di /f oe rcys ct la eE rx tc ee dptionif this component detects a fatal error * i/ ntheconfigurationparametersitwasgiven publt ic hvroo id wcsoL niffi eg cy uc rl ee(EN xo cd ep et piaornamete {rs) //V if (configured) alidateandupdateourcurrentcomponentstate throw( sne mw.getSt Lr ii fn eg c( y" cs lt ea En xd ca er pd tM ia onager.alreadyConfigu")); red co i fnf( ip gu areadm =e tr tu eer;s == null) return; //Pa if (!(" rseMaannd agperro"c .es qs uao lu sr (pc ao rn af mi et ge urs a.tgieotn NopdaerNamet () e)r)s ) Namereturn; dNodeMapattributes= parameters.getAttributes(); Nodenode=null; i node f (nod a=t etr!i= butneu s. lglet )Na{medItem("checkInterval" ) ; try{setCheckInterval(Integer.parseInt(node.getNodeValue ())); } cat ; ch (Throwabl/e/ Xt T Xh) X row {exception? } } node a=ttributes.getNamedItem("maxActiveSessions" ) ; if ( tr ny o{de != null) { } cat s ch etM( a Tx hA rc ow ta ib vl ee Sessit on )s(Int{ eger.parseInt(node.getNodeValue ( ) ; } ; // XT XhX row exception? } i node f (nod a=t etr! ib =utn es u.l ge lt)Nam {edItem("maxInactiveInterval " ) ; try{setMaxInactiveInterval(Integer.parseInt(node.getNodeValue())); } cat ; ch (Throwabl/e/ Xt T Xh) X row {exception? } } } ** / Sta*ndard implementation of the <b>Manager</b> interface thprovides at *a nn o ospetsi so in oa nl,pecrosnifsitgeu nr ca ebleo,r mdaixsitmruimbutnaubmlbeerca op fabi al ci tt ii ves,seb su st ioallowed. s ns du op eport *<Lpi >f nect yhcelef colnlfoiwgiu nr gatf iornmo af t:thiscomponentassumesanXMLnode *<code &l >t;Manager className= " org.apache.tomcat.session.StandardManager " * m ch aex ck IInna te crtvi al v="60" eInter= 1 m " v" a/ xl >ActiveSessi= "ons1 " *<w /c ho ed ree>youcanadjustthefollowingparameters,withdefaul al tuev s *<u inlsqu> arebrackets: *<l i th > < breac dhc eh cekcIknste fr o< v r/abe l >x-pirT ehd ese in ste sri va olns.(in[6s0 ec ]onds) between background *<l i be > < bactmia ve xAa ctti ov nc eeS ,es or si<o/nbs >1 - foTrhen mo axi lm im ui mt n.u1 ] mbe[rofsessionsallowedto *<l i i > < bnacm tai xv In iat cy tivb eI enfto erveal<w/hbi>ch ts Th eh re vlet defauc lo tnt mai xn ie mr umis nuamlb le or weodftsoec to in md esoo uf t * theads eefsa si uolnt,soerssion 1t fo irmn eoou li tmi stp.ecTi hi fsiv eadlu iens thh ou elw debb eaop ve prl rid i cd oa e nn t def pr lom yment *</udes> lcriptor,ifany. [- 1 ] *@authorCraigR.McClanahan *@ve /rsion$Revision:1.1.1.1$$Date:2000/05/0221:28:30$ public final claS sts andardManager em i xp tleenmd es nManagerBase tsLifecycle, Runnable { //-------------------------------------------------Ins -t -anceVariables /** *The /interval(inseconds)betweenchecksforexpiredsi eos ns. privatei nchteckInterval =60; /** *Has /thiscomponentbeenconfiguredyet? privateboolean configured=false; /Th*ed* * escriptiveinformationaboutthisimplementation. *riv/ p atestaticfinalStringinfo="StandardManager/1.0"; *T* / he* maximumnumberofactiveSessionsallowed,or1 for no limit. *rote/cted i p n t maxActiveSessi= -ons1 ; ** / The*string manager for this package. *riv/ateStringManager = p s m StringManager.getManager("org.apache.tomcat.session " ) ; /** *Has /thiscomponentbeenstartedyet? privateboolean started = false; /** * Th/ e background thread. privateThreadthread=null; /** *The /backgroundthreadcompletionsemaphore. privateboolean threadDone =false; /** *Nam /etoregisterforthebackgroundthread. private Strintg hreadName S = "tandardMana" ; ger //---------------------------------------------------------Pr -o -perties /** * Re/ turn the check interval (in seconds) for this Manager. publici n t getCheckInter( v) al { return(this.checkInterval ) ; } /** * Set the check interval (in seconds) for this Manager. *@p /aram checkInterT vhaelnewcheckinterval publicvoidsetCheckInterval(intcheckInterval){ this.checkInterval = checkInterval; } /** *tR het cu ornredsepsocnrdii pn tg iveri sn if oo nr nmuamtbieorn,ian bt oh ue tfo th ri ms atManagerimpl ne ta mte ionand *<co/ de>& lt;description&gt;/&lt;version&gt ;</code>. publicString getInfo(){ return(this.info); } /** *n Ro etur ln imit. he maximum number of active Sessions allowed, 1 or f o r *ub/ p lici n t getMaxActiveSessi( ) {ons return(this.maxActiveSessions) ; } /** *Se no ttl hi emi mt a.ximumnumberofactivesSessionsallowed,or- 1for *@param max The new maximum number of sessions *ubl/icvoidsetMaxActiveSessions(mi p ax n)t{ this.maxActiveSessions =max; } /** *c Po rm epo an renfto.rTthhiesbmeegtihnondin sg hooufld acbteic va elu ls ee do afttehre<pcuobdlei>cci ho m ou g d n er sf te o( f) t< h/ ic sode>, * and before any of the public methods of the componentut ai rleized. *@ ce ox nc fe ip gt ui ro end(ifr Il elq eg uai lS rte at def Ex ocr ep tthii onscomi pf on te hn is t)componenthasnotyetbeen *@started exception IllegalStateException ifthiscomponenthasalreadybeen *@e tx hc aetpt pi ro enventL sif teh cy icsle cEo xc meppo ti noe ni nftfth rio smc boe mp ioneg ntusdetd ects a fatal error *ubl p /icvoidstart()throLw if secycleException{ //Validateandupdateourcurrentcomponentstate if(!t c hr ownfn iew gured)LifecycleException if(start( semd.)getString("standardManager.notConfigu")); red throw( snm ew.getStL rin fg e(c"ysc tl ae nE da xr cd eMpatni ao gn er.alreadyStarted")); started = true; //Startthe( threadStart ) ;backgroundreaperthread } /G * *ra* cefully terminate the active use of the public meth of odsthis *icno sm tp ao nn ceo nf tt .hiTshciosmpmoentehnotd.shouldbethelastonecalledag oiv nen *@exception IllegalStateException ifthiscomponenthasnotbeenstarted *@ beexecn ep sttioop npedIllegalStateException ifthiscomponenthasalready *@e tx hc ae tpn te ie od nstoLbie fer ce yc pl oerEt xc ee dptionif this component detects a fatal error *ubl/icvoidstop()throws LifecycleExcept{ion p /f i /(V!asl ti ad ra tt ee d)andupdateourcurrentcomponentstate throw( snm ew.getStL rin fg e(c"ysc tl ae nE da xr cd eMpatni ao gn er.notStarted")); started = false; /h/ t re Sat dSoto pptheb( ) ;ackgroundreaperthread // Expire all active sessions S fo er s( siin ot ns ie=ss 0i ;oin< s[s] e= sf sin od nS se.slseinogntsh(;i)++; ){ i Sf t(a !s ne dsasr io dn S.eisV sa s il eos is n di(on=)() StandardSession)sessions[i]; sessi con. te in xu pe i; re(); } } //-------------------------------------------------------- PrivateMethods S anda dSess onManage StandardSessionManager packageorg.apache.tomcat.session; importjava.io.IOException ; importjavax.servlet.http.Cookie; importo jr ag v. aa xp .a sc eh re v. lt eo tm .c ha tt. pc .a Hta tl pi Sn ea s. si *o;n; importorg.apache.tomcat.core.Context; importorg.apache.tomcat.core.Request; immpp or otr or tgo.rag p. ac ah pe a.cthoe m. ct at o. mccoart e.c Re os rpeo.nS ses ;sionMana ;ger importorg.apache.tomcat.util.SessionUtil; Methods //-----------------------------------------------------P-u-b -lic /** *Markthespecifiedsession'slastaccessedtime.This oul sdb he * called for each request by a RequestInterceptor. *@param session The session to be marked * / publicvoidaccessed(Contextctx,Requestreq,Stringid){ HttpSession i f(session= s= es ns ui loln) =r fi ent dS uer ss ni;on(ctx ,id); /** if(sessioninstanceof Session) *Specializedimplementationoforg.apache.tomcat.core.SessionManager ((Session)session).access(); *<pt >hat adapts to the new compob ne an st edManagerimplementation. //cachetheHttpSession- avoidanotherfind * XXX Atpresent,useof<code> StandardManager</code>ishardcoded, req.setSession (session); *andlifecycleconfigurationisnotsupported. } *<<pb>>IMPLEMENTATIONNOTE</b>:Oncewecommittothenew //XXXshouldwethrowexceptionorjustreturnnull?? Manager/Session publicHttpSession findSession ( Contec t xt ,Stringid){ *t ph ae rc ao di rg em l, ev Iewl o. uT lh desT uo gm gc ea st. mN oe vx in tg "M ta hn ealg oe gr i" ciin mt pe lr ef me an ct ee ad ch te se ack r me or bliinto ke atry{Sessionsession= manager.findSession) ;(id * collection class, and has minimal knowledge of the detaileq dues rt if(session!=null) *processingsemanticsofhandlingsessions. returnsession.getSession( ) ; *<p>XXX Atpresent,thereisnoway(viatheSessionManager interface) } catch (IOExceptione){ fao * Cor ntexttotelltheManagerthatwecreatewhatthedefasession ult return(null); *timeoutforthiswebapplication(specifiedinthedeployment } * should be. descriptor) publicHttpSession createSession(Contcext) {x * returnmanager.createSession().getSession(); *@authorCraigR.McClanahan } * / /** public final claS stsandardSessionManager down.* Remove all sessions because our associated Context isng bei shut implementsSessionManager { * *@param c t x Thecontextthatisbeingshutdown //----------------------------------------------------------*ubl/icvoidremoveSessions(Context ) p c t x{ Constructors //XcXoXnX tX eX xt asm,anwaege jrum sa tywbaens tha tr oer debmyom vu elti hp ele sessionsc t xof! /C*re* * ateanewSessionManager that adapts to the corresponding //Themanagerwillstillrunafterthat(i.e.keepad bast e Manager // connection open *imp/ lementation. if(mta ry n{ agerinstanceof Lifecycle){ publicStandardSessionManager(){ ((Lifecycle)manager).stop(); } catch (LifecycleException e) { i maf na (gm eran=ag nee wrinstaS nt ca en od fardMaL ni af gec ry(cle){; } throw new IllegalStateException ("" + e); try{ } ((Lifecycle)manager).configure(null); } cat ( ch (Li(f Le if ce ycy lc el)emEa xn ca eg pe ti ro )n .stare t( )); { } throw new IllegalStateException ("" + e); /** } } time* ouUts .edbycontexttoconfigurethesessionmanager'sinavcitti y * } *CoThe ntex Se tss oin ont Ma hne ago er thermh aa ynhd avh eassom ietd 'e sfa tuilmtesoeust sisoe ntti bmyet oh ut e,ld ot ye m h ep n et * descriptorweb.x( ml ).ThismethodletstheContextconforgure the //-------------------------------------------------Instance *sessionmanageraccordingtothisvalue. Variables *@param minutes The session inactivity timeout in minutes. * / /** publicvoidsetSessionTimeOut(intminutes) { *Th/ eManagerimplementationweareactuallyusing. i f/ 1/ (T! h=emamn ia nu gteer s) wor{kswithseconds... privateManagermanager=null; manager.setMaxInactiveInterval(minutes *60); } } } HTTP getRequest( setContentT getOutptutS setSess onId ... / I*nva * *lidate all sessions that have expired. *riv/atevoidprocessExpires p () { longtimeNow= System.currentTimeMillis ( ) ; Sessionsessions[]=findSessions( ) ; for(i Sn tt ai nd =a0r ;diS<esesss ie i osos nn is on .= l( engthS; tai nd +a +r) dS{ ession)sessions[i]; if(!c so enstsii nu oe n;.isValid( ) ) ifn (ma txInactiveInter< s = ve as 0 lsi)on.getMaxInactiveInter( ) ;val i nc to i tn mt eiInd ul ee ;= // Truncate, do not round up if(( i ti nmt e) Idlet >= (imeNow maxInactivseeIs ns ti eo rn v. ag letLas)tAccessedTime()) / 1000L); } } session.expire(); /S * *lee *p for the duration specified by the <code>checkInterval</code> *pro/perty. privatevoidthreadSleep(){ try{Thread.sleep(checkInterval *1000L); } cat ; ch (InterruptedExceptione){ } } /** *sSetsasritot nh te imbeaocuktgsr.oundthreadthatwillperiodicallyche f o rck *riv/atevoidthreadStart(){ p if (thread != null) return; thrr ea edaDd on =enewT= hrfalse; ead(this, threadN) ;ame thhrr ea eda.s de.ts Da teamo rnt(( tr )u;e) ; } //-----------------------------------------------------Pub -l -icMethods /** *sCe ot nt st ir nu gcstsa pn ed cir fe it eudrnbyath ni ew sMsa en sa si go en r'o sbj pe rc otp,erbtaisees d.on Tht ehsion ee f sae ul s d t *m ie dtho wd illofbethe assrie gt nu er dned byse ts hs ii son. methoIdf,aand newava si el sa sb il oe nv ci aa nnb ge o eth Ie d(created) *foranyreason,return<code>null</code>. *@ instantiated exception Illefor galSta any teExcreason eption ifanewsessioncannotbe *ubl p /ic Sessiocn reateSession(){ if((maxActiveSessions > =0 )& ( ths ro e wssi ne o wns.sizeI( l) l> eg =alStatme aE xx Ace tp iv te iS oe nssions ) sm.getString("standardManager.createSession.")); ( ise return(super.createSess( ) ; ion } /* * Sto* p the background thread that is periodically checkif o r ng *ses/siontimeouts. privatevoidthreadStop () { if ( return; thread == null) thh re rae dD aod ne.int=e trr uer ;upt(); try{thread.join(); } cat ; ch (InterruptedExceptione){ } thread=null; } //------------------------------------------------------BackgroundThread /T*he*backgroundthreadthatchecksforsessiontimeouts * dsh aun tdown. publ * /ic void run() { // Loop until the termination semaphore is set whilethreadSleep (!threadDone( ) ; ) { } processExpires ( ) ; } AspectJ Workshop -- Xerox PARC getCook es( getRequestU getSess on( getRequeste ... } 12 Aspec J Wo kshop Xe ox AOP Course 2003 – p 7 36 This Course In this week, I intend to: • Explain the underlying problem • Present the idea of Aspect-Oriented Programming (AOP) • Give an Overview of some existing approaches • Present AspectJ in detail • Show some practical applications • Get you to do programming exercises • Explore possible benefits and dangers AOP Course 2003 – p.8/36 Prerequisistes • You need to know about Java. • You should know about OO design. • If you have been involved in the development of a large system, so much the better! Questions. . . AOP Course 2003 – p.9/36 Who is this guy? • Background in logic, formal methods, program verification • Involved in the development of large software • Not actually used AOP in a real system. (Yet?) AOP Course 2003 – p.10/36 Books General Ideas of AOP, overview of approaches: Chapter 8 of Czarnecki, Eisenecker. Generative Programming. Addison-Wesley, 2000 AspectJ in particular: Ramnivas Laddad. AspectJ in Action. Manning 2003. Also AspecJ, slightly out-dated: Ivan Kiselev. Aspect-Oriented Porgramming with AspectJ. Sams 2003. AOP Course 2003 – p.11/36 Web Sites Aspect-Oriented Analysis and Design Portal: http://www.aosd.net/ Current AspectJ development: http://eclipse.org/aspectj/ Origin of AspectJ at Xerox PARC: http://www.parc.com/research/csl/projects/aspectj/default.html AOP Course 2003 – p.12/36 Introduction AOP Course 2003 – p.13/36 Concerns • XML parsing • UML pattern matching • Logging • Session management • .. . are concerns of a software system. Separation of Concerns is a time-honored principle of Software design. AOP Course 2003 – p.14/36 Separation of Concerns D. Parnas. On the Criteria to Be Used in Decomposing Systems into Modules. Comm. ACM 15, 12 (December 1972), 1053-1058. Design principles for decomposition: • Information-hiding modules • Identify design decisions that are likely to change. • Isolate these in separate modules (separation of concerns) AOP Course 2003 – p.15/36 Cross-Cutting Concerns In the motivation, • XML parsing and URL pattern matching fit the class hierarchy, • Logging and Session Mangement do not. A cross-cutting concern is one that needs to be addressed in more than one of the modules in the hierarchical structure of the software. Cross-cutting concerns are also called aspects. ➠ What is an aspect depends on the chosen decomposition! AOP Course 2003 – p.16/36 Problems with Cross-Cutting Concerns Cross-cutting concerns pose problems for standard, e.g. OO programming techniques: • hard and error-prone to introduce in an existing system • hard to change afterwards • hard to understand/explain to newcomers ➠ Cross-cutting implementation of cross-cutting concerns does not provide separation of concens. AOP Course 2003 – p.17/36 Solutions Possible treatment of cross-cutting concerns: ➠ Refactor them away. Change the module hierarchy so that the aspect becomes modular, often through application of adequate design patterns. But: • often performance penaltiy through indirection • often leaves some cross-cutting boiler-plate • can’t hope to capture all aspects AOP Course 2003 – p.18/36 Aspect-Oriented Programming A programming methodology is called Aspect-Oriented if it provides possibilities to cleanly separate concerns that would otherwise be cross-cutting. There are various Aspect-Oriented methods. They differ in the kinds of aspects they can address and in the ways aspects and their relation to the chosen hierarchical decomposition are expressed. AOP Course 2003 – p.19/36 Example: Demeter Law of Demeter: An object should only call methods on this, instance variables, method arguments. ➠ no this.getWife().getMother().getMaidenName() chains. Prevents dependency on too many other classes. Forward information and control through a maze of little methods. ➠ Still a lot to change when the class structure changes. AOP Course 2003 – p.20/36 Demeter (cont.) Solution in ‘Demeter’ (Karl Lieberherr): Specify traversal strategies which say in which classes we are interested in, not how to navigate to get there. ➠ structure-shy behaviour specification Demeter handles the aspect of navigating through the class structure. AOP Course 2003 – p.21/36 Join Points Analyse commonly occurring aspects. ➠ cross-cutting implementations can often be formulated in terms like • Before . . . is called, always check for . . . • If any of . . . throws an exception, . . . • Everytime . . . gets changed, notify . . . • .. . AOP Course 2003 – p.22/36 Join Points (cont.) Implementations of aspects are attached to certain points in the implementation: • method calls • constructor calls • field access (read/write) • exceptions • .. . These correspond to point in the dynamic execution of the program. Such points are called join points AOP Course 2003 – p.23/36 Code Example: Figure Editor Figure * +makePoint(..) +makeLine(..) FigureElement +moveBy(int,int) Display Point +getX() +getY() +setX(int) +setY(int) +moveBy(int,int) Line 2 +getP1() +getP2() +setP1(Point) +setP2(Point) +moveBy(int,int) AOP Course 2003 – p.24/36 Code Example (cont.) class Line implements FigureElement { private Point p1, p2; Point getP1() { return p1; } Point getP2() { return p2; } void setP1(Point p1) { this.p1 = p1; } void setP2(Point p2) { this.p2 = p2; } void moveBy(int dx, int dy) { p1.moveBy(dx,dy); p2.moveBy(dx,dy); } } class Point implements FigureElement { private int x = 0, y = 0; int getX() { return x; } int getY() { return y; } void setX(int x) { this.x = x; } void setY(int y) { this.y = y; } void moveBy(int dx, int dy) { x += dx; y += dy; } } AOP Course 2003 – p.25/36 Some Join Points point 1 moveBy a line moveBy point 2 moveBy AOP Course 2003 – p.26/36 Pointcuts A pointcut designates a set of join points for any program execution. At execution, any join point may or may not be selected by a pointcut. Examples: • all calls to public methods of the Point class • every execution of a constructor with one int argument • every write access to a public field • .. . Membership of a join point can be determined at runtime. AOP Course 2003 – p.27/36 Advice Advice is code that should be inserted before, after or even instead of existing code at some set of join points. ‘Mainstream’ AOP: • Designate sets of join points using some specification language for pointcuts. • Declare advice to be executed before/after/instead of the calls/method exexutions/field accesses etc. selected by the pointcut. AOP Course 2003 – p.28/36 Example Display updating in the Figure Editor: “After every change in a FigureElement’s state, update the display”. AOP implementation: ➠ pointcut to select every state-changing method in FigureElement classes. ➠ ‘after’-advice which calls display update code. AOP Course 2003 – p.29/36 Implementation of AOP Original idea: A program called aspect weaver is used to weave the advice code into the main program code. Often, join point membership in a pointcut can be decided statically. ➠ no need to insert code at every possible join point. Modern systems: • some do weaving and compilation in one step • some can do weaving at runtime (e.g. on Java byte-code) AOP Course 2003 – p.30/36 Static Cross-Cutting Pointcuts and advice modify the dynamic behaviour of software. Possible modifications of static structure: • Every sub-class of FigureElement should implement the Drawable interface. • Every FigureElement should have a ‘modified’ flag. • .. . Note that this might be necessary to specify dynamic behaviour. ‘Introduction’ of members in existing classes often possible in AOP systems. AOP Course 2003 – p.31/36 AspectJ • Extensions of the Java language for • pointcuts • attaching advice • static cross-cutting • Originally developed at Xerox PARC • First versions in Spring of 2000 • Hosted by eclipse.org since December 2002 • We’ll hear a lot about it later this week. AOP Course 2003 – p.32/36 Spin-Offs • AspectC++ for C++ • AspectC# for C# • AspectC for C • .. . See www.aosd.net for more AOP Course 2003 – p.33/36 AspectWerkz • Also for Java, but without language extensions. • Specify advice and pointcuts through Java API. • Specify some weaving details and static cross-cutting in external XML files. • Allows aspect weaving at runtime by changing the ClassLoader. Won’t talk about it here, because a specialized language makes the concepts clearer. AOP Course 2003 – p.34/36 Other library-based approaches • Nanning Aspects, also for Java • AspectS for Smalltalk • Aspect.pm for Perl • .. . Note the predominance of interpreted, ‘dynamic’ languages Again, there are more examples on www.aosd.net AOP Course 2003 – p.35/36 Conclusion You should now know about. . . • the motivation for AOP • what a concern is • what an aspect is • join points, pointcuts, and advice • static vs. dynamic cross-cutting • the existence of various different AOP systems Tomorrow you will learn how to write aspects in AspectJ AOP Course 2003 – p.36/36