Embed
Email

AOP – Aspect Oriented Programming

Document Sample

Shared by: dandanhuanghuang
Categories
Tags
Stats
views:
0
posted:
12/4/2011
language:
English
pages:
31
Aspect Oriented

Programming and other

topics



Introduction to the Seminar



Amiram Yehudai

Aspect Oriented Software

Development (AOSD)

 Emerging technologies that seek new

modularizations of software systems

 Modularization is an important theme

in software engineering

 “Separation and Localization of

concerns”

 Traditional engineering : decompose

system into units of core functionality

2

Concerns



 Core concerns vs. crosscutting

concerns (eg. security).

 AOP – programming with multiple

crosscutting concerns or aspects.

 Express each concerns in its own

module.





3

good modularity

XML parsing









 XML parsing in org.apache.tomcat

– red shows relevant lines of code

– nicely fits in one box 4

good modularity

URL pattern matching









 URL pattern matching in org.apache.tomcat

– red shows relevant lines of code

– nicely fits in two boxes (using inheritance) 5

logging is not modularized…









 where is logging in org.apache.tomcat

– red shows lines of code that handle logging

– not in just one place

– not even in a small number of places 6

session expiration is not modularized…

ApplicationSession StandardSession

/* public void inva lidat e() { package org. apac he.to mcat. sessi on; /**

* ==== ===== ==== ===== ===== ===== ===== ==== ===== ===== ===== ===== ==== ===== == serv erSe ssion .remo veApp licat ionS essio n(con text) ; /** * Bind an o bject to t his s essio n, u sing the s pecif ied n ame. If an ob ject

* * Retur n th e Ht tpSes sion fo r whi ch th is * of th e sa me na me is alre ady b ound to t his s essio n, th e ob ject is

* The Apach e So ftwar e Lic ense, Vers ion 1.1 // r emov e eve rythi ng in the sess ion import java. io.I OExce ption ; object * repla ced.

* import java. io.O bject Input Strea m; * is th e fa cade. *

* Copy right (c) 1999 The Apach e Sof twar e Fou ndati on. All r ight s Enum erat ion e num = valu es.ke ys() ; import java. io.O bject Outpu tStre am; */ * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts

* rese rved. whil e (e num.h asMor eElem ents( )) { import java. io.S erial izabl e; pub lic H ttpS essio n get Sessi on() { * Htt pSess ionBi nding Liste ner, th e con taine r ca lls

* Stri ng na me = (Stri ng)en um.n extEl ement (); import java. util .Enum erati on; * val ueBou nd() on the objec t.

* Redi strib utio n and use in so urce and binar y for ms, w ith o r wi thout remo veVal ue(na me); import java. util .Hash table ; retu rn ( (Http Sessi on) t his); *

* modi ficat ion, are permi tted provi ded that the f ollow ing c ondi tions } import java. util .Vect or; * @para m na me Na me to whic h the obj ect i s bou nd, c annot be null

* are met: import javax .ser vlet. Servl etExc eptio n; } * @para m va lue O bject to b e bou nd, canno t be null

* vali d = false ; import javax .ser vlet. http. HttpS essio n; *

* 1. R edist ribu tions of s ource code mus t ret ain t he ab ove c opyr ight } import javax .ser vlet. http. HttpS essio nBin dingE vent; * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n

* n otice , th is li st of cond ition s an d the foll owing disc laim er. import javax .ser vlet. http. HttpS essio nBin dingL isten er; // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- - * inva lida ted s essio n

* pub lic b oole an is New() { import javax .ser vlet. http. HttpS essio nCon text; Session Publ ic M ethod s *

* 2. R edist ribu tions in b inary form mus t rep roduc e the abov e co pyrig ht if ( ! va lid) { import org.a pach e.tom cat.c atali na.*; * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d by

* n otice , th is li st of cond ition s an d the foll owing disc laim er in Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); import org.a pach e.tom cat.u til.S tring Mana ger; * se tAttr ibute ()

* t he do cume ntati on an d/or other mat erial s pro vided with the /** */

* d istri buti on. thro w new Ille galSt ateEx cept ion(m sg); * Updat e th e acc essed time info rmat ion f or th is se ssion . pub lic v oid putVa lue(S tring name , Ob ject value ) {

* } /** This me thod

* 3. T he en d-us er do cumen tatio n inc lude d wit h the redi strib utio n, if * Stan dard impl ement ation of t he Ses sion * shoul d be call ed by the conte xt w hen a requ est c omes in setA ttri bute( name, valu e);

* a ny, m ust inclu de th e fol lowin g ac knowl egeme nt: if ( this Acces sTime == c reati onTi me) { interfa ce. This obje ct is for a p artic ular

* "Th is p roduc t inc ludes soft ware deve loped by t he retu rn tr ue; * seri aliza ble, so t hat i t can be s tore d in * sessi on, even if th e app licat ion does not r efere nce i t. }

* Ap ache Soft ware Found ation (ht tp:// www.a pache .org/ )." } el se { persist ent s tora ge or tran sferr ed */

* A ltern atel y, th is ac knowl egeme nt m ay ap pear in th e sof twar e retu rn fa lse; * to a diff eren t JVM for distr ibuta ble sessi on pub lic v oid acces s() {

itself, } support . /**

* i f and whe rever such thir d-par ty a cknow legem ents norma lly appea r. } * this .las tAcce ssedT ime = this .thi sAcce ssedT ime; * Remov e th e obj ect b ound with the speci fied name from this sess ion. If

* * I MPLEM ENTA TION NOTE: An i nsta nce o f thi s this .thi sAcce ssedT ime = Syst em.c urren tTime Milli s(); * the s essi on do es no t hav e an obje ct bo und w ith t his n ame, this meth od

* 4. T he na mes "The Jakar ta Pr oject ", " Tomca t", a nd "A pache Sof tware class r epres ents both the this .isN ew=fa lse; * does noth ing.

* F ounda tion " mus t not be u sed t o en dorse or p romot e pro duct s /** * inte rnal (Ses sion) and appli catio n le vel } *

derived * @depr ecat ed (HttpSe ssion ) vi ew of the sessi on. * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts

* f rom t his softw are w ithou t pri or w ritte n per missi on. F or w ritte n */ * Howe ver, beca use t he cl ass i tself is not d eclar ed * Htt pSess ionBi nding Liste ner, th e con taine r ca lls

* p ermis sion , ple ase c ontac t apa che@ apach e.org . public, Java log ic ou tside /** * val ueUnb ound( ) o n th e obj ect.

* pub lic v oid putVa lue(S tring name , Ob ject value ) { * of t he org.a pache .tomc at.se ssio n * Perfo rm t he in terna l pro cessi ng r equir ed to inva lidat e *

* 5. P roduc ts d erive d fro m thi s sof twar e may not be ca lled "Apa che" setA ttri bute( name, valu e); package cann ot c ast a n this se ssion , * @para m na me Na me of the objec t to remo ve fr om th is se ssio n.

* n or ma y "A pache " app ear i n the ir n ames witho ut pr ior w ritt en } * Http Sessi on v iew o f thi s ins tance bac k to a * witho ut t rigge ring an ex cepti on i f the sess ion h as *

* p ermis sion of t he Ap ache Group . Session view . already expi red. * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n

* pub lic v oid setAt tribu te(St ring name , Obj ect v alue) { * */ * inva lida ted s essio n

* THIS SOFT WARE IS P ROVID ED `` AS IS '' A ND AN Y EXP RESSE D OR IMPL IED if ( ! va lid) { * @aut hor C raig R. M cClan ahan pub lic v oid expir e() { */

* WARR ANTIE S, I NCLUD ING, BUT N OT LI MITE D TO, THE IMPLI ED WA RRAN TIES Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); * @ver sion $Rev ision : 1.2 $ $D ate: 2000 /05/1 5 pub lic v oid remov eAttr ibute (Stri ng n ame) {

* OF M ERCHA NTAB ILITY AND FITNE SS FO R A PARTI CULAR PURP OSE A RE 17:54:1 0 $ // R emov e thi s ses sion from our manag er's activ e

* DISC LAIME D. IN NO EVEN T SHA LL TH E AP ACHE SOFTW ARE F OUNDA TION OR thro w new Ille galSt ateEx cept ion(m sg); */ session s sync hron ized (attr ibute s) {

* ITS CONTR IBUT ORS B E LIA BLE F OR AN Y DI RECT, INDI RECT, INCI DENT AL, } if ( (man ager != nu ll) & & (ma nage r ins tance of Obje ct ob ject = att ribut es.g et(na me);

* SPEC IAL, EXEM PLARY , OR CONSE QUENT IAL DAMAG ES (I NCLUD ING, BUT NOT final c lass Stan dardS essio n Manager Base) ) if ( objec t == null)

* LIMI TED T O, P ROCUR EMENT OF S UBSTI TUTE GOOD S OR SERVI CES; LOSS OF if ( name == n ull) { imp lemen ts H ttpSe ssion , Ses sion { ((Ma nager Base) mana ger). remo ve(th is); retur n;

* USE, DATA , OR PROF ITS; OR BU SINES S IN TERRU PTION ) HOW EVER CAUS ED AN D Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ; attr ibute s.rem ove(n ame);

* ON A NY TH EORY OF L IABIL ITY, WHETH ER I N CON TRACT , STR ICT L IABI LITY, // U nbin d any obje cts a ssoci ated with this sess ion // S ystem .out. print ln( "Remo ving attri bute " + name );

* OR T ORT ( INCL UDING NEGL IGENC E OR OTHE RWISE ) ARI SING IN AN Y WA Y OUT thro w new Ille galAr gumen tExc eptio n(msg ); // ----- ---- ----- ----- ----- ----- ---- ----- ----- --- Vect or r esult s = n ew Ve ctor( ); if ( objec t ins tance of Ht tpSe ssion Bindi ngLis tener ) {

* OF T HE US E OF THIS SOFT WARE, EVEN IF ADVIS ED OF THE POSSI BILI TY OF } ------- ----- - Co nstru ctors Enum erat ion a ttrs = get Attri bute Names (); ((Htt pSess ionBi nding List ener) obje ct).v alueU nbou nd

* SUCH DAMA GE. whil e (a ttrs. hasMo reEle ments ()) { ( new H ttpSe ssion Bind ingEv ent(( HttpS essio n) t his, name) );

* ==== ===== ==== ===== ===== ===== ===== ==== ===== ===== ===== ===== ==== ===== == remo veVa lue(n ame); // remov e an y exi sting bind ing Stri ng at tr = (Stri ng) a ttrs .next Eleme nt(); }

* /** resu lts.a ddEle ment( attr) ; }

* This soft ware cons ists of vo lunta ry c ontri butio ns ma de by man y if ( valu e != null && va lue i nsta nceof Http Sessi onBin ding Liste ner) { * Const ruct a ne w Ses sion assoc iate d wit h the }

* indi vidua ls o n beh alf o f the Apac he S oftwa re Fo undat ion. For more Http Sessi onBin dingE vent e = specifi ed Ma nage r. Enum erat ion n ames = res ults. elem ents( ); }

* info rmati on o n the Apac he So ftwar e Fo undat ion, pleas e see new H ttpSe ssion Bindi ngEv ent(t his, name) ; * whil e (n ames. hasMo reEle ments ()) {

* . * @para m ma nager The manag er wi th w hich this Stri ng na me = (Stri ng) n ames .next Eleme nt();

* ((Ht tpSes sionB indin gList ener )valu e).va lueBo und(e ); Session is a ssoc iated remo veAtt ribut e(nam e); /**

* [Add ition al n otice s, if requ ired by p rior licen sing condi tion s] } */ } * Remov e th e obj ect b ound with the speci fied name from this sess ion. If

* pub lic S tand ardSe ssion (Mana ger m anag er) { * the s essi on do es no t hav e an obje ct bo und w ith t his n ame, this meth od

*/ valu es.p ut(na me, v alue) ; // M ark this sessi on as inva lid * does noth ing.

} supe r(); setV alid (fals e); *

this .man ager = man ager; * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts

/** } * Htt pSess ionBi nding Liste ner, th e con taine r ca lls

package org. apac he.to mcat. sessi on; * @depr ecat ed } * val ueUnb ound( ) o n th e obj ect.

*/ *

import org.a pach e.tom cat.c ore.* ; pub lic O bjec t get Value (Stri ng na me) { /** * @para m na me Na me of the objec t to remo ve fr om th is se ssio n.

import org.a pach e.tom cat.u til.S tring Mana ger; retu rn g etAtt ribut e(nam e); // ----- ---- ----- ----- ----- ----- ---- ----- ----- --- * Relea se a ll ob ject refer ences , an d ini tiali ze in stanc e *

import java. io.* ; } ------- Inst ance Vari ables variabl es, i n * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n

import java. net. *; * prepa rati on fo r reu se of this obj ect. * inva lida ted s essio n

import java. util .*; pub lic O bjec t get Attri bute( Strin g na me) { */ *

import javax .ser vlet. *; if ( ! va lid) { /** pub lic v oid recyc le() { * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d by

import javax .ser vlet. http. *; Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); * The c olle ction of u ser d ata a ttri butes * re moveA ttrib ute()

associa ted w ith this Sessi on. // R eset the insta nce v ariab les assoc iated with this */

/** thro w new Ille galSt ateEx cept ion(m sg); */ Session pub lic v oid remov eValu e(Str ing n ame) {

* Core impl emen tatio n of an ap plica tion leve l ses sion } pri vate Hash table attr ibute s = n ew H ashta ble() ; attr ibut es.cl ear() ;

* crea tion Time = 0L; remo veAt tribu te(na me);

* @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om] if ( name == n ull) { id = nul l;









SessionInterceptor StandardManager StandardSessionManager

* @aut hor J ason Hunt er [j ch@en g.sun .com ] Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ; /** last Acce ssedT ime = 0L; }

* @aut hor J ames Todd [gon zo@en g.sun .com ] * The t ime this sessi on wa s cre ated , in mana ger = nul l;

*/ thro w new Ille galAr gumen tExc eptio n(msg ); millise conds sin ce mi dnigh t, maxI nact iveIn terva l = - 1;

} * Janua ry 1 , 197 0 GMT . isNe w = true; /**

public class App licat ionSe ssion impl emen ts Ht tpSes sion { */ isVa lid = fal se; * Bind an o bject to t his s essio n, u sing the s pecif ied n ame. If an ob ject

retu rn v alues .get( name) ; pri vate long crea tionT ime = 0L; * of th e sa me na me is alre ady b ound to t his s essio n, th e ob ject is

pri vate Stri ngMan ager sm = } // T ell our M anage r tha t thi s Se ssion has been recyc led * repla ced.

Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" ); if ( (man ager != nu ll) & & (ma nage r ins tance of *

pri vate Hash table valu es = new H asht able( ); /** /** Manager Base) ) * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts

pri vate Stri ng id ; * @depr ecat ed * The s essi on id entif ier o f thi s Se ssion . ((Ma nager Base) mana ger). recy cle(t his); * Htt pSess ionBi nding Liste ner, th e con taine r ca lls package org. apac he.to mcat. reque st;

pri vate Serv erSes sion serve rSess ion; */ */ * val ueBou nd() on the objec t. pub lic i nt b efore Body( Requ est r requ est, Respo nse r espon se ) {

pri vate Cont ext c ontex t; pub lic S trin g[] g etVal ueNam es() { pri vate Stri ng id = nu ll; } * import org.a pach e.tom cat.c ore.* ; Stri ng r eqSes sionI d = r espon se.g etSes sionI d();

pri vate long crea tionT ime = Syst em.c urren tTime Milli s();; Enum erat ion e = ge tAttr ibute Name s(); * @para m na me Na me to whic h the obj ect i s bou nd, c annot be null import org.a pach e.tom cat.u til.* ; if( debu g>0 ) cm.l og("B efore Bod y " + reqS essio nId ) ;

pri vate long this Acces sTime = cr eati onTim e; Vect or n ames = new Vect or(); * @para m va lue O bject to b e bou nd, canno t be null import java. io.* ; if( reqS essio nId== null) package org. apac he.to mcat. sessi on; package org. apac he.to mcat. sessi on; // ---- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- Pub lic

pri vate long last Acces sed = crea tion Time; /** // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- Sess ion * import java. net. *; retu rn 0; // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- - Li fecyc le Me thods Methods

pri vate int inact iveIn terva l = - 1; whil e (e .hasM oreEl ement s()) { * Descr ipti ve in forma tion descr ibin g thi s Package Meth ods * @exce ptio n Ill egalA rgume ntExc epti on if an a ttemp t is made to a dd a import java. util .*; import java. io.I OExce ption ;

pri vate bool ean v alid = tru e; name s.add Eleme nt(e. nextE leme nt()) ; Session impl emen tatio n. * non- seri aliza ble o bject in a n en viron ment marke d dis trib utabl e. import javax .ser vlet. http. *; import java. util .Enum erati on; import java. io.I OExce ption ;

} */ * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n // G S, s et th e pat h att ribut e to the cooki e. Th is wa y import java. util .Hash table ; /**

import javax .ser vlet. http. Cooki e;

App licat ionS essio n(Str ing i d, Se rver Sessi on se rverS essio n, pri vate stat ic fi nal S tring info = /** * inva lida ted s essio n /** // m ulti ple s essio n coo kies can be us ed, o ne fo r eac h import java. util .Vect or; * Confi gure this comp onent , bas ed o n the spec ified conf igur ation

/**

Cont ext conte xt) { Stri ng[] valu eName s = n ew St ring [name s.siz e()]; "Standa rdSes sion /1.0" ; * Retur n th e is Valid f lag f or th is se ssion . */ * Will proc ess the r eques t and dete rmin e the sess ion I d, an d se t it // c onte xt. import org.a pach e.tom cat.c atali na.*; * param eter s. T his m ethod shou ld b e cal led i mmedi ately aft er th e import javax .ser vlet. http. HttpS essio n;

this .ser verSe ssion = se rverS essi on; */ pub lic v oid setAt tribu te(St ring name , Obj ect v alue) { * in t he Re ques t. Stri ng s essio nPath = rr eques t.ge tCont ext() .getP ath() ; import javax .ser vlet. http. Cooki e; * compo nent inst ance is cr eated , an d bef ore start () * Mark the speci fied sessi on's last acce ssed time. Thi s sh ould be

import org.a pach e.tom cat.c atali na.*;

this .con text = con text; name s.co pyInt o(val ueNam es); boo lean isVa lid() { * It a lso m arks the sessi on as acce ssed . if(s essi onPat h.len gth() == 0 ) { import javax .ser vlet. http. HttpS essio n; * is ca lled .

* calle d fo r eac h req uest by a Requ estIn terce ptor.

this .id = id; /** if ( (man ager != nu ll) & & man ager .getD istri butab le() && * sess ionPa th = "/"; import org.a pach e.tom cat.u til.S tring Mana ger; * import org.a pach e.tom cat.c ore.C ontex t;

retu rn v alueN ames; * The l ast acces sed t ime f or th is S essio n. retu rn ( this. isVal id); !( valu e ins tance of Se riali zabl e)) * This impl emen tatio n onl y han dles Cook ies s essio ns, p lease ext end o r } import org.w 3c.d om.Na medNo deMap ; * @para m pa ramet ers C onfig urati on p arame ters for t his c ompo nent *

import org.a pach e.tom cat.c ore.R eques t;

this .ina ctive Inter val = cont ext. getSe ssion TimeO ut(); */ thro w new Ille galAr gumen tExc eptio n * add new i nter cepto rs fo r oth er me thod s. import org.w 3c.d om.No de; * ( FIXM E: Wh at ob ject type shou ld th is re ally be?)

* @para m se ssion The sessi on to be marke d

} pri vate long last Acces sedTi me = crea tionT ime; } (sm.g etStr ing(" stand ardS essio n.set Attri bute. iae" )); * // G S, p iggyb ack t he jv m rou te o n the sess ion i d. * import org.a pach e.tom cat.c ore.R espon se;

if ( this .inac tiveI nterv al != -1) { */ if(! sess ionPa th.eq uals( "/")) { * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready been */

import org.a pach e.tom cat.c ore.S essio nMan ager;

this .inac tiveI nterv al *= 60; pub lic E nume ratio n get Attri buteN ames () { sync hron ized (attr ibute s) { public class Ses sionI nterc eptor exte nds Base Inter cepto r imp leme nts R eques tInte rcept or { Stri ng jv mRout e = r reque st.g etJvm Route (); /** * conf igur ed an d/or start ed

pub lic v oid acces sed(C ontex t ctx , Re quest req, Stri ng id ) {

} if ( ! va lid) { /** /** remo veAtt ribut e(nam e); if(n ull ! = jvm Route ) { * Stan dard impl ement ation of t he Man ager i nterf ace t hat provi des * @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l err or import org.a pach e.tom cat.u til.S essio nUti l;

} Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); * The M anag er wi th wh ich t his S essi on is * Set t he isNew fl ag f or th is se ssion . attr ibute s.put (name , val ue); // GS, s epar ates the s essio n id from the jvm r oute reqSe ssion Id = reqSe ssio nId + SESS IONID _ROUT E_SE P + j vmRou te; * no s essio n pe rsist ence or di strib utab le ca pabil ities , but doe s sup port * in t he c onfig urati on pa ramet ers it wa s giv en Http Sess ion s essio n=fin dSess ion( ctx, id);

associa ted. * if ( value inst anceo f Htt pSes sionB indin gList ener) sta tic f inal char SESS IONID _ROUT E_SE P = ' .'; } * an o ption al, confi gurab le, m aximu m nu mber of ac tive sessi ons allow ed. */

if( sess ion = = nul l) re turn;

Ser verSe ssio n get Serve rSess ion() { thro w new Ille galSt ateEx cept ion(m sg); */ * @para m is New T he ne w val ue fo r th e is New ((Htt pSess ionBi nding List ener) valu e).va lueBo und int debu g=0; } * pub lic v oid confi gure( Node param eter s)

retu rn s erver Sessi on; } pri vate Mana ger m anage r = n ull; flag ( new H ttpSe ssion Bind ingEv ent(( HttpS essio n) t his, name) ); Con textM anag er cm ; * Life cycle con figur ation of t his c ompo nent assum es an XML node thro ws L ifecy cleEx cepti on { if ( sess ion i nstan ceof Sessi on)

/**

} */ } Cook ie c ookie = ne w Coo kie(" JSES SIONI D", * in t he fo llow ing f ormat :

((Se ssion ) ses sion) .acce ss() ;

Hash tabl e val uesCl one = (Has htab le)va lues. clone (); voi d set New( boole an is New) { pub lic S essi onInt ercep tor() { r eqSe ssion Id); * // V alid ate a nd up date our c urre nt co mpone nt st ate * Spec ializ ed i mplem entat ion o f org .apa che.t omcat .core .Sess ionM anage r

/** /** } } cook ie.s etMax Age(- 1); * <M anag er cl assNa me="o rg.ap ache .tomc at.se ssion .Stan dard Manag er" if ( conf igure d)

* that adap ts t o the new compo nent- base d Man ager imple menta tion .

* Calle d by cont ext w hen r eques t co mes i n so that acces ses and retu rn ( Enume ratio n)val uesCl one. keys( ); * The m axim um ti me in terva l, in sec onds, betw een this .isN ew = isNew ; cook ie.s etPat h(ses sionP ath); * check Inter val=" 60" m axAc tiveS essio ns="- 1" thro w new Life cycle Excep tion

// c ache the HttpS essio n - a void anot her f ind

* inact ivit ies c an be deal t wit h ac cordi ngly. } client reque sts befor e pub lic v oid setDe bug( int i ) { cook ie.s etVer sion( 1); * maxIn activ eInte rval= "-1" /> (sm.g etStr ing(" stand ardM anage r.alr eadyC onfig ured ")); *

*/ * the s ervl et co ntain er ma y inv alid ate t his } // ----- ---- ----- ----- ----- ----- ---- ----- ----- - Htt pSess ion Priva te Me thods Syst em.o ut.pr intln ("Set debu g to " + i); * conf igur ed = true; req. setS essio n( se ssion );

* XXX - At pres ent, use o f St anda rdMan ager is hard code d,

session . A nega tive time debu g=i; resp onse .addH eader ( Coo kieTo ols. getCo okieH eader Name( cook ie), * wher e you can adju st th e fol lowin g pa ramet ers, with defau lt v alues if ( para meter s == null)

}

voi d acc esse d() { /** * indic ates that the sessi on sh ould neve r tim e } Coo kieTo ols. getCo okieH eader Value (coo kie)) ; * in s quare bra ckets : retu rn; * and lifec ycle conf igura tion is no t su pport ed.

// s et l ast a ccess ed to this Acce ssTim e as it wi ll be lef t ove r * @depr ecat ed out. /** /** cook ie.s etVer sion( 0); *

*

// f rom the p revio us ac cess */ */ * Set t he isVal id flag for this sessi on. * Read a se riali zed v ersio n of this sess ion o bject from the spec ified pub lic v oid setCo ntext Manag er( C onte xtMan ager cm ) { resp onse .addH eader ( Coo kieTo ols. getCo okieH eader Name( cook ie), * ch eckI nterv al - T he in terv al (i n sec onds) betw een backg round // P arse and proce ss ou r con figu ratio n par amete rs

// XXX s houl d we throw exce ption or just retur n nul l ??

last Acce ssed = thi sAcce ssTim e; pri vate int maxIn activ eInte rval = -1 ; * * objec t in put s tream . this .cm= cm; Coo kieTo ols. getCo okieH eader Value (coo kie)) ; * threa d ch ecks for e xpire d ses sion s. [ 60] if ( !("M anage r".eq uals( param eter s.get NodeN ame() ))) * I MPLEM ENTA TION NOTE: Once we commi t to the n ew

this Acce ssTim e = S ystem .curr entT imeMi llis( ); pub lic v oid remov eValu e(Str ing n ame) { * @para m is Valid The new v alue for the * } * ma xAct iveSe ssion s - Th e ma ximum numb er of sess ions allo wed t o retu rn; Manager /Sess ion pub lic H ttpS essio n fin dSess ion( Cont ext c tx, S tring id ) {

remo veAt tribu te(na me); i sVali d flag * IM PLEM ENTAT ION N OTE: The refer ence to th e own ing Manag er retu rn 0 ; * be ac tive at o nce, or -1 for no l imit. [-1 ] Name dNod eMap attri butes = pa rame ters. getAt tribu tes() ;

* para digm, I w ould sugge st mo ving the logic impl ement ed he re b ack i nto try {

vali date (); } /** */ * is no t re store d by this metho d, a nd mu st be set expli citl y. pub lic i nt r eques tMap( Reque st re ques t ) { } * ma xIna ctive Inter val - The defau lt ma ximum numb er o f sec onds of Node nod e = n ull;

} * Flag indi catin g whe ther this sess ion i s new or voi d set Vali d(boo lean isVal id) { * Stri ng s essio nId = null ; * inact ivit y bef ore w hich the s ervl et co ntain er is allo wed to ti me ou t * the core leve l. T he To mcat. Next "Man ager" inte rface acts mor e lik e a Sess ion s essio n = m anage r.fi ndSes sion( id);

pub lic v oid remov eAttr ibute (Stri ng n ame) { not. * @para m st ream The i nput strea m to read from * a ses sion , or -1 fo r no limit . T his v alue shoul d be over ridde n fro m node = a ttrib utes. getNa medIt em(" check Inter val") ;

* coll ectio n cl ass, and h as mi nimal kno wledg e of the d etail ed r eques t if(s essio n!=nu ll)

voi d val idat e() { if ( ! va lid) { */ this .isV alid = isV alid; * Cook ie c ookie s[]=r eques t.get Cook ies() ; // asser t !=n ull /** Noti fica tion of co ntext shut down * the d efau lt se ssion time out s peci fied in th e web appl icat ion d eploy ment if ( node != n ull) {

// i f we have an i nacti ve in terv al, c heck to se e if we'v e exc eeded it Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); pri vate bool ean i sNew = tru e; } * @exce ptio n Cla ssNot Found Excep tion if a n unk nown class is speci fied */ * descr ipto r, if any. [-1 ] try { * proc essin g se manti cs of hand ling sess ions. retur n ses sion. getSe ssio n();

if ( inac tiveI nterv al != -1) { * @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s for( int i=0; i setCh eckIn terva l(Int eger .pars eInt( node. getNo deVa lue() ));

* } ca tch (IOEx cepti on e) {

int thisI nterv al = thro w new Ille galSt ateEx cept ion(m sg); */ Cook ie co okie = coo kies[ i]; thro ws T omcat Excep tion * } ca tch ( Throw able t) {

(int) (Syst em.cu rrent Time Milli s() - last Acces sed) / 10 00; } /** // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- - pri vate void read Objec t(Obj ectIn putS tream stre am) { * @aut hor C raig R. M cClan ahan ; // XXX - Thr ow e xcept ion? * XXX - At pres ent, there is n o way (vi a the Sess ionMa nager int erfac e) }

* Flag indi catin g whe ther this sess ion i s val id HttpSes sion Prop ertie s thro ws C lassN otFou ndExc eptio n, I OExce ption { if ( cooki e.get Name( ).equ als( "JSES SIONI D")) { if( ctx. getDe bug() > 0 ) ctx .log ("Rem oving sess ions from " + ctx ) ; * @ver sion $Rev ision : 1.1 .1.1 $ $Da te: 2000/ 05/02 21:2 8:30 $ } for

retu rn ( null) ;

if ( thisI nterv al > inact iveI nterv al) { if ( name == n ull) { or not. sessi onId = coo kie.g etVa lue() ; ctx. getS essio nMana ger() .remo veSe ssion s(ctx ); */ }

* a Co ntext to tell the M anage r tha t we crea te wh at th e def ault sess ion

inval idate (); Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ; */ // D eser ializ e the scal ar in stan ce va riabl es (e xcept Man ager) sessi onId= valid ateSe ssio nId(r eques t, se ssion Id); } }

} pri vate bool ean i sVali d = f alse; /** crea tion Time = ((L ong) strea m.re adObj ect() ).lon gValu e(); if (s essio nId!= null) { public final cla ss St andar dMana ger node = a ttrib utes. getNa medIt em(" maxAc tiveS essio ns"); * time out f or t his w eb ap plica tion (spe cifie d in the d eploy ment

} thro w new Ille galAr gumen tExc eptio n(msg ); * Retur n th e tim e whe n thi s ses sion was creat ed, i n id = (St ring) stre am.re adObj ect( ); r eques t.set Reque sted Sessi onIdF romCo okie( true ); ext ends Mana gerBa se if ( node != n ull) { descrip tor)

} } millise conds sin ce last Acce ssedT ime = ((Lo ng) s trea m.rea dObje ct()) .long Valu e(); } } imp lemen ts L ifecy cle, Runna ble { try { pub lic H ttpS essio n cre ateSe ssion (Con text ctx) {

* shou ld be .

/** * midni ght, Janu ary 1 , 197 0 GMT . maxI nact iveIn terva l = ( (Inte ger) stre am.re adObj ect() ).in tValu e(); } setMa xActi veSes sions (Int eger. parse Int(n ode.g etNo deVal ue()) );

retu rn manag er.cr eateS essio n(). getSe ssion ();

// HTTP SESS ION I MPLEM ENTAT ION M ETHO DS Obje ct o = va lues. get(n ame); * The s trin g man ager for t his p acka ge. * isNe w = ((Boo lean) stre am.re adOb ject( )).bo olean Value (); } } ca tch ( Throw able t) { *

*/ * @exce ptio n Ill egalS tateE xcept ion if th is me thod is isVa lid = ((B oolea n) st ream. read Objec t()). boole anVal ue() ; // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- Ins tance Vari ables ; // XXX - Thr ow e xcept ion? }

* @aut hor C raig R. M cClan ahan

pub lic S trin g get Id() { if ( o in stanc eof H ttpSe ssion Bind ingLi stene r) { pri vate Stri ngMan ager sm = called on an Stri ng s ig="; jsess ionid ="; }

if ( vali d) { Http Sessi onBin dingE vent e = * inva lida ted s essio n // D eser ializ e the attr ibute cou nt an d att ribut e val ues int foun dAt=- 1; } */

retu rn id ; new H ttpSe ssion Bindi ngEv ent(t his,n ame); StringM anage r.ge tMana ger(" org.a pache .tom cat.s essio n") */ int n = ((Int eger) stre am.re adOb ject( )).in tValu e(); if( debu g>0 ) cm.l og(" XXX R URI= " + r eques t.get Reque stUR I()); /** /**

} el se { ; pub lic l ong getCr eatio nTime () { for (int i = 0; i // XXX w hat is th e cor rect behav ior if th e ses sion is in vali d ? * The d escr iptiv e inf ormat ion a bout this impl ement ation . // c onte xts, we ju st wa nt to rem ove t he se ssion s of ctx!

/**

thro w new Ille galSt ateEx cept ion(m sg); */ * repl acem ent. It w ill b e rem oved in a futu re ve rsion of * IM PLEM ENTAT ION N OTE: The ownin g Man ager will not be st ored // We ma y st ill s et it and just retu rn se ssion inva lid. */

// T he m anage r wil l sti ll ru n af ter t hat ( i.e. keep dat abase

} inac tive Inter val = inte rval; pri vate long this Acces sedTi me = crea tionT ime; the * in th e se riali zed r epres entat ion of th is Se ssion . Af ter calli ng pri vate stat ic fi nal S tring info = " Stand ardMa nager /1.0" ; /** * Creat e a new S essio nMana ger t hat adapt s to the c orres pond ing

} } * Java Ser vlet API. * rea dObje ct(), yo u mu st se t the asso ciate d Ma nager /** Vali date and fix t he se ssion id. If t he se ssion is n ot v alid retur n nul l. * Prepa re f or th e beg innin g of acti ve us e of the p ublic met hods of th is Manager // c onne ction open

*/ * expli citl y. * It w ill also clean up t he se ssio n fro m loa d-bal ancin g st rings . * compo nent . Th is me thod shoul d be call ed af ter conf igure (),

* imple ment ation . if ( mana ger i nstan ceof Lifec ycle ) {

/** pub lic i nt g etMax Inact iveIn terva l() { pub lic H ttpS essio nCont ext g etSes sion Conte xt() { * * @retu rn s essio nId, or nu ll if not vali d /** * and b efor e any of t he pu blic meth ods o f the comp onent are util ized.

* if ( ! va lid) { * IM PLEM ENTAT ION N OTE: Any attri bute that is no t Se riali zable */ * The m axim um nu mber of ac tive Sess ions allow ed, o r -1 for no li mit. * */ try {

* @depr ecat ed Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); // ----- ---- ----- ----- ----- ----- ---- ----- ----- --- if ( sess ionCo ntext == n ull) * will be s ilent ly ig nored . If you do n ot wa nt an y suc h at tribu tes, pri vate Stri ng va lidat eSess ionId (Req uest reque st, S tring ses sionI d){ */ * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s no t yet been

pub lic S tand ardSe ssion Manag er() { ((Lif ecycl e) ma nager ).st op();

*/ ------- Sess ion Prope rties sess ionCo ntext = ne w Sta ndar dSess ionCo ntext (); * be su re t he d istri butab le prop erty of ou r as socia ted // G S, W e pig gybac k the JVM id o n top of t he se ssion coo kie pro tecte d in t max Activ eSess ions = -1 ; * conf igur ed (i f req uired for this comp onent )

thro w new Ille galSt ateEx cept ion(m sg); retu rn ( sessi onCon text) ; * Manag er i s set to true. // S epar ate t hem . .. * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready been } ca tch ( Lifec ycleE xcept ion e) {

pub lic H ttpS essio nCont ext g etSes sion Conte xt() { } * * star ted

mana ger = new Stan dardM anage r(); throw new Illeg alSta teEx cepti on("" + e) ;

retu rn n ew Se ssion Conte xtImp l(); /** } * @para m st ream The o utput stre am t o wri te to if( debu g>0 ) cm.l og(" Orig sess ionId " + sess ionId ); /** * @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l err or

} retu rn i nacti veInt erval ; * Set t he c reati on ti me fo r thi s se ssion . Th is * if ( null != s essio nId) { * The s trin g man ager for t his p acka ge. * that pre vents this comp onent fro m bei ng us ed if ( mana ger i nstan ceof Lifec ycle ) { }

} method is ca lled by t he * @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s int idex = ses sionI d.las tInd exOf( SESSI ONID_ ROUTE _SEP ); */ */

try { }

pub lic l ong getLa stAcc essed Time( ) { } * Manag er w hen a n exi sting Sess ion insta nce i s // ----- ---- ----- ----- ----- ----- ---- ----- ----- --- */ if(i dex > 0) { pri vate Stri ngMan ager sm = pub lic v oid start () th rows Lifec ycle Excep tion {

if ( vali d) { reused. HttpSes sion Publ ic Me thods pri vate void writ eObje ct(Ob jectO utpu tStre am st ream) thro ws I OExce ption { sessi onId = ses sionI d.su bstri ng(0, idex ); Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" ); ((Lif ecycl e) ma nager ).co nfigu re(nu ll);

retu rn la stAcc essed ; * } // V alid ate a nd up date our c urre nt co mpone nt st ate

((Lif ecycl e) ma nager ).st art() ; }

} el se { //----- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- ----- ---- * @para m ti me Th e new crea tion time // W rite the scala r ins tance var iable s (ex cept Manag er) } if ( !con figur ed)

Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); */ /** stre am.w riteO bject (new Long( crea tionT ime)) ; /** thro w new Life cycle Excep tion } ca tch ( Lifec ycleE xcept ion e) {

pub lic v oid setCr eatio nTime (long tim e) { * Retur n th e obj ect b ound with the speci fied name in th is stre am.w riteO bject (id); if ( sess ionId != n ull & & ses sion Id.le ngth( )!=0) { * Has t his compo nent been start ed y et? (sm.g etStr ing(" stand ardM anage r.not Confi gured "));

throw new Illeg alSta teEx cepti on("" + e) ; /**

thro w new Ille galSt ateEx cept ion(m sg); session , or stre am.w riteO bject (new Long( last Acces sedTi me)); // G S, We are in a probl em h ere, we ma y act ually get */ if ( star ted)

} this .cre ation Time = tim e; * nul l i f no objec t is boun d wit h tha t nam e. stre am.w riteO bject (new Integ er(m axIna ctive Inter val)) ; // m ultip le Se ssion cook ies (one for t he ro ot pri vate bool ean s tarte d = f alse; thro w new Life cycle Excep tion } * Used by c ontex t to confi gure the sessi on ma nager 's in acti vity

} this .las tAcce ssedT ime = time ; * stre am.w riteO bject (new Boole an(i sNew) ); // c ontex t and one for t he r eal c ontex t... or ol d se ssion (sm.g etStr ing(" stand ardM anage r.alr eadyS tarte d")) ; timeout .

}

this .thi sAcce ssedT ime = time ; * @para m na me Na me of the attri bute to b e ret urned stre am.w riteO bject (new Boole an(i sVali d)); // c ookie . We must check for vali dity in th e cur rent cont ext. star ted = tru e;

*

* Cont ext c tx=re quest .getC onte xt(); /**

} * @exce ptio n Ill egalS tateE xcept ion if th is me thod is // A ccum ulate the names of s eria lizab le at tribu tes Sess ionMa nager sM = ctx. getS essio nMana ger() ; * The b ackg round thre ad. // S tart the backg round reap er t hread * The S essi onMan ager may h ave s ome defau lt se ssion time out , the

}

called on an Vect or r esult s = n ew Ve ctor( ); if(n ull ! = sM. findS essio n(ct x, se ssion Id)) { */ thre adSt art() ;

* Conte xt o n the othe r han d has it' s tim eout set b y the dep loyme nt

* inva lida ted s essio n Enum erat ion a ttrs = get Attri bute Names (); sM.ac cesse d(ctx , req uest , ses sionI d ); pri vate Thre ad th read = nul l;

/** */ whil e (a ttrs. hasMo reEle ments ()) { reque st.se tRequ ested Sess ionId (sess ionId ); } * descr ipto r (we b.xml ). Th is me thod lets the Conte xt co nfor gure the

* Retur n th e ses sion ident ifier for this pub lic O bjec t get Attri bute( Strin g na me) { Stri ng at tr = (Stri ng) a ttrs .next Eleme nt(); if( d ebug> 0 ) c m.log (" F inal sessi on id " + sess ionId );

* sessi on m anage r acc ordin g to this valu e.

session . Obje ct va lue = attr ibute s.ge t(att r); retur n ses sionI d; /** // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- Ins tance

*/ retu rn ( attri butes .get( name) ); if ( value inst anceo f Ser iali zable ) } * The b ackg round thre ad co mplet ion semap hore. /** Variabl es *

pub lic S trin g get Id() { resul ts.ad dElem ent(a ttr) ; } */ * Grace full y ter minat e the acti ve u se of the publi c met hods of t his

* @para m mi nutes The sessi on in acti vity timeo ut in minu tes.

} } retu rn n ull; pri vate bool ean t hread Done = fal se; * compo nent . Th is me thod shoul d be the last one c alled on a giv en

retu rn ( this. id); } * insta nce of th is co mpone nt. */

// S eria lize the a ttrib ute c ount and the attri bute valu es *

/** pub lic v oid setSe ssion TimeO ut(in t mi nutes ) {

} /** stre am.w riteO bject (new Integ er(r esult s.siz e())) ; /** * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s no t bee n sta rted

* Retur n an Enu merat ion of Enum erat ion n ames = res ults. elem ents( ); * Name to r egist er fo r the back grou nd th read. * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready * The M anag er im pleme ntati on we are actu ally using . if(- 1 != minu tes) {

S tring o bject s whil e (n ames. hasMo reEle ments ()) { */ * been sto pped

*/ // T he ma nager work s wit h se conds ...

/** * conta inin g the name s of the o bjec ts bo und t o thi s Stri ng na me = (Stri ng) n ames .next Eleme nt(); pri vate Stri ng th readN ame = "Sta ndar dMana ger"; * @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l err or

* Set t he s essio n ide ntifi er fo r th is se ssion . session . stre am.wr iteOb ject( name) ; * that nee ds to be r eport ed pri vate Mana ger m anage r = n ull; mana ger.s etMax Inact iveIn terv al(mi nutes * 60 );

* * stre am.wr iteOb ject( attri bute s.get (name )); */

}

* @para m id The new s essio n ide ntif ier * @exce ptio n Ill egalS tateE xcept ion if th is me thod is } // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- ---- Prope rties pub lic v oid stop( ) thr ows L ifecy cleE xcept ion {

*/ called on an }

pub lic v oid setId (Stri ng id ) { * inva lida ted s essio n // V alid ate a nd up date our c urre nt co mpone nt st ate

}

*/ } /** if ( !sta rted)

if ( (thi s.id != nu ll) & & (ma nage r != null) && pub lic E nume ratio n get Attri buteN ames () { * Retur n th e che ck in terva l (in sec onds) for this Manag er. thro w new Life cycle Excep tion

(m anag er in stanc eof M anage rBas e)) cro sscut inv alida te(St andar dSess ion s): s & (i nt ge tMaxI nact iveIn terva l() | */ (sm.g etStr ing(" stand ardM anage r.not Start ed")) ;

((Ma nager Base) mana ger). remo ve(th is); retu rn ( attri butes .keys ()); l ong g etCre atio nTime () | pub lic i nt g etChe ckInt erval () { star ted = fal se;

O bject getA ttri bute( Strin g) |

this .id = id; } E numer ation get Attri buteN ames( ) | retu rn ( this. check Inter val); // S top the b ackgr ound reape r th read

S tring [] ge tVal ueNam es() | thre adSt op();









ServerSession

if ( (man ager != nu ll) & & (ma nage r ins tance of v oid i nvali date () | }

Manager Base) ) /** b oolea n isN ew() | // E xpir e all acti ve se ssion s

((Ma nager Base) mana ger). add( this) ; * Retur n th e obj ect b ound with the speci fied name in th is v oid r emove Attr ibute (Stri ng) | Sess ion sessi ons[] = fi ndSes sion s();

session , or v oid s etAtt ribu te(St ring, Obje ct)); /** for (int i = 0; i nul l i f no objec t is boun d wit h tha t nam e. * Set t he c heck inter val ( in se cond s) fo r thi s Man ager. Stan dardS essio n ses sion = (S tanda rdSes sion) sess ions [i];

* sta tic a dvic e(Sta ndard Sessi on s) : in valid ate(s ) { * if ( !sess ion.i sVali d())

* @para m na me Na me of the value to be re turne d befo re { * @para m ch eckIn terva l The new chec k int erval conti nue;

/** * if ( !s.is Valid ()) */ sess ion.e xpire ();

* Retur n de scrip tive infor matio n ab out t his * @exce ptio n Ill egalS tateE xcept ion if th is me thod is throw new Illeg alSta teEx cepti on pub lic v oid setCh eckIn terva l(int che ckInt erval ) { }

Session impl emen tatio n and called on an ( s.sm. getSt ring( "sta ndard Sessi on."









ServerSessionManager

* the c orre spond ing v ersio n num ber, in t he * inva lida ted s essio n + th isJoi nPoin t.met hodNa me this .che ckInt erval = ch eckIn terv al; }

format * + ". ise") );

* * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d } }

package org. apac he.to mcat. sessi on; void va lidat e() { & lt;de scri ption >/ <v ersio n> ;. by } // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- --- Priva te Me thods

// i f we have an i nacti ve in terv al, c heck to se e if */ * ge tAttr ibute ()

import org.a pach e.tom cat.c ore.* ; // w e've exce eded it pub lic S trin g get Info( ) { */ /**

import org.a pach e.tom cat.u til.S tring Mana ger; pub lic O bjec t get Value (Stri ng na me) { * Retur n de scrip tive infor matio n ab out t his M anage r imp leme ntati on an d /**

import java. io.* ; if ( inac tiveI nterv al != -1) { retu rn ( this. info) ; * the c orre spond ing v ersio n num ber, in t he fo rmat * Inval idat e all sess ions that have expi red.

import java. net. *; int thisI nterv al = retu rn ( getAt tribu te(na me)); } * < ;desc ripti on> ;/< ;ver sion& gt; . */

import java. util .*; (int) (Syst em.cu rrent Time Milli s() - last Acces sed) / 10 00; } */ pri vate void proc essEx pires () {

import javax .ser vlet. *; } pub lic S trin g get Info( ) {

import javax .ser vlet. http. *; if ( thisI nterv al > inact iveI nterv al) { // ---- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- - Pri vate Class long tim eNow = Sys tem.c urren tTim eMill is();

inval idate (); /** retu rn ( this. info) ; Sess ion sessi ons[] = fi ndSes sion s();

/** * Retur n th e las t tim e the clie nt s ent a requ est /** // XXX

* Core impl emen tatio n of a ser ver s essi on Serve rSess ionMa nager ssm = associa ted w ith this * Retur n th e set of n ames of ob ject s bou nd to this /** package org. apac he.to mcat. sessi on; // sync' d fo r saf ty -- no o ther thre ad sh ould be ge tting som ethin g } for (int i = 0; i Ht tpSes sion Conte xt // from this whil e we are r eapin g. T his i sn't the m ost o ptim al Stan dardS essio n ses sion = (S tanda rdSes sion) sess ions [i];

* @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om] midnigh t, Ja nuar y 1, 1970 * are n o su ch ob jects , a z ero-l engt h arr ay is retu rned. * inte rface , to conf orm t o the requ irem ent t hat s uch a n obj ect be re turne d import org.a pach e.tom cat.u til.* ; // solut ion for t his, but w e'll dete rmine some thing else lat er. if ( !sess ion.i sVali d())

* @aut hor J ames Todd [gon zo@en g.sun .com ] ssm.r emove Sessi on(th is); * GMT. Act ions that your appli cati on ta kes, * * when Ht tpSes sion. getSe ssion Cont ext() is call ed. import org.a pach e.tom cat.c ore.* ; /** conti nue;

*/ } such as gett ing or se tting * @exce ptio n Ill egalS tateE xcept ion if th is me thod is * import java. io.* ; syn chron ized void reap () { * Retur n th e max imum numbe r of acti ve Se ssion s all owed, or -1 fo r int maxIn activ eInte rval = se ssion .getM axIna ctive Inte rval( );

} * a val ue a ssoci ated with the s essi on, d o not called on an * @aut hor C raig R. M cClan ahan import java. net. *; Enum erat ion e num = sess ions. keys (); * no li mit. if ( maxIn activ eInte rval = max Inact iveI nterv al)

pri vate Hash table valu es = new H asht able( ); retu rn ( this. lastA ccess edTim e); * ge tAttr ibute Names () * sessi on.ex pire( );

pri vate Hash table appS essio ns = new Hasht able( ); whil e (e num.h asMor eElem ents( )) { */ final c lass Stan dardS essio nCont ext i mple ments Http Sessi onCon text { * @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om] sess ion.r eap() ; } }

pri vate Stri ng id ; Obje ct ke y = e num.n extEl emen t(); } pub lic S trin g[] g etVal ueNam es() { * @aut hor J ason Hunt er [j ch@en g.sun .com ] sess ion.v alida te(); }

pri vate long crea tionT ime = Syst em.c urren tTime Milli s();; Appl icati onSes sion appSe ssio n = * @aut hor J ames Todd [gon zo@en g.sun .com ] }

pri vate long this Acces sTime = cr eati onTim e; (Appl icati onSes sion) appS essio ns.ge t(key ); Vect or r esult s = n ew Ve ctor( ); pri vate Vect or du mmy = new Vecto r(); */ } /**

pri vate long last Acces sed = crea tion Time; /** Enum erat ion a ttrs = get Attri bute Names (); * Set t he m aximu m num ber o f act ives Sess ions allow ed, o r -1 for /**

pri vate int inact iveIn terva l = - 1; appS essio n.inv alida te(); * Retur n th e Man ager withi n whi ch t his S essio n whil e (a ttrs. hasMo reEle ments ()) { /** public class Ser verSe ssion Manag er im plem ents Sessi onMan ager { syn chron ized void remo veSes sion( Serv erSes sion sessi on) { * no li mit. * Sleep for the durat ion s pecif ied by th e ch eckIn terv al

} is vali d. Stri ng at tr = (Stri ng) a ttrs .next Eleme nt(); * Retur n th e ses sion ident ifier s of all sessi ons d efine d Stri ng i d = s essio n.get Id(); * * prope rty.

Ser verSe ssio n(Str ing i d) { } */ resu lts.a ddEle ment( attr) ; * withi n th is co ntext . pri vate Stri ngMan ager sm = * @para m ma x The new maxim um nu mber of s essio ns */

this .id = id; pub lic M anag er ge tMana ger() { } * Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" ); sess ion. inval idate (); */ pri vate void thre adSle ep() {

} pub lic v oid putVa lue(S tring name , Ob ject value ) { Stri ng n ames[ ] = n ew St ring[ resu lts.s ize() ]; * @depr ecat ed As of J ava S ervle t AP I 2.1 with no r eplac emen t. pri vate stat ic Se rverS essio nMana ger manag er; / / = n ew Se rver Sessi onMan ager( ); sess ions .remo ve(id ); pub lic v oid setMa xActi veSes sions (int max) {

if ( name == n ull) { retu rn ( this. manag er); for (int i = 0; i Enu merat ion } try {

pub lic S trin g get Id() { Stri ng ms g = s m.get Strin g("s erver Sessi on.va lue.i ae") ; name s[i] = (St ring) resu lts. eleme ntAt( i); * and will be r emove d in a fut ure versi on of the API. pro tecte d in t ina ctive Inter val = -1; this .max Activ eSess ions = max ; Thre ad.sl eep(c heckI nterv al * 1000 L);

retu rn i d; } retu rn ( names ); */ pub lic v oid remov eSess ions( Conte xt c ontex t) { } ca tch (Inte rrupt edExc eptio n e) {

} thro w new Ille galAr gumen tExc eptio n(msg ); pub lic E nume ratio n get Ids() { sta tic { Enum erat ion e num = sess ions. keys (); } ;

} } mana ger = new Serv erSes sionM anag er(); }

pub lic l ong getCr eatio nTime () { /** retu rn ( dummy .elem ents( )); } whil e (e num.h asMor eElem ents( )) {

retu rn c reati onTim e; remo veVa lue(n ame); // remov e an y exi sting bind ing * Set t he M anage r wit hin w hich this Sess ion i s Obje ct ke y = e num.n extEl emen t(); // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- Publ ic Me thods }

} valu es.p ut(na me, v alue) ; valid. /** } pub lic s tati c Ser verSe ssion Manag er g etMan ager( ) { Serv erSes sion sessi on = (Ser verSe ssion )sess ions. get( key);

} * * Inval idat es th is se ssion and unbi nds a ny ob jects boun d retu rn m anage r; Appl icati onSes sion appSe ssio n =

pub lic l ong getLa stAcc essed Time( ) { * @para m ma nager The new M anage r to it. } sessi on.ge tAppl icati onSe ssion (cont ext, false ); /** /**

retu rn l astAc cesse d; pub lic O bjec t get Value (Stri ng na me) { */ * /** * Const ruct and retur n a n ew se ssio n obj ect, based on t he d efaul t * Start the back groun d thr ead t hat will perio dical ly ch eck for

} if ( name == n ull) { pub lic v oid setMa nager (Mana ger m anag er) { * @exce ptio n Ill egalS tateE xcept ion if th is me thod is * Retur n th e Ht tpSes sion as socia ted w ith t he pri vate Hash table sess ions = new Has htabl e(); if ( appSe ssion != n ull) { * setti ngs speci fied by th is Ma nage r's p roper ties. The ses sion * sessi on t imeou ts.

Stri ng ms g = s m.get Strin g("s erver Sessi on.va lue.i ae") ; called on * speci fied sess ion i denti fier. pri vate Reap er re aper; appSe ssion .inva lidat e(); * id wi ll b e ass igned by t his m etho d, an d ava ilabl e via the getI d() */

pub lic A ppli catio nSess ion g etApp lica tionS essio n(Con text cont ext, this .man ager = man ager; * an i nval idate d ses sion * } * metho d of the retur ned s essio n. If a new s essio n can not be cr eated pri vate void thre adSta rt() {

bool ean creat e) { thro w new Ille galAr gumen tExc eptio n(msg ); */ * @para m id Sess ion i denti fier for which to l ook u p a s essi on pri vate Serv erSes sionM anage r() { } * for a ny r eason , ret urn null .

Appl icat ionSe ssion appS essio n = } } pub lic v oid inval idate () { * reap er = Reap er.ge tReap er(); } * if ( thre ad != null )

(App licat ionSe ssion )appS essi ons.g et(co ntext ); * @depr ecat ed As of J ava S ervle t AP I 2.1 with no r eplac emen t. reap er.s etSer verSe ssion Manag er(t his); * @exce ptio n Ill egalS tateE xcept ion if a new s essio n can not be retu rn;

retu rn v alues .get( name) ; // C ause this sess ion t o exp ire * This met hod m ust r eturn null and will be r emove d in a reap er.s tart( ); /** * inst anti ated for a ny re ason

if ( appS essio n == null && cr eate ) { } /** expi re() ; * futu re v ersio n of the A PI. } * Used by c ontex t to confi gure the sessi on ma nager 's in acti vity timeo ut. */ thre adDo ne = false ;

* Retur n th e max imum time inter val, in s econd s, */ * pub lic S essi on cr eateS essio n() { thre ad = new Threa d(thi s, th read Name) ;

// X XX pub lic E nume ratio n get Value Names () { between clie nt r eques ts } pub lic H ttpS essio n get Sessi on(St ring id) { pub lic v oid acces sed( Conte xt ct x, R eques t req , Str ing i d ) { * The S essi onMan ager may h ave s ome defau lt se ssion time out , the thre ad.s etDae mon(t rue);

// s ync t o ens ure v alid? retu rn v alues .keys (); * befor e th e ser vlet conta iner will inva lidat e Appl icat ionSe ssion apS= (Appl icat ionSe ssion )find Sessi on( ctx, id); * Conte xt o n the othe r han d has it' s tim eout set b y the dep loyme nt if ( (max Activ eSess ions >= 0) && thre ad.s tart( );

} the ses sion. A negat ive retu rn ( null) ; if( apS= =null ) ret urn; * descr ipto r (we b.xml ). Th is me thod lets the Conte xt co nfor gure the (s essi ons.s ize() >= m axAct iveS essio ns))

appS essio n = n ew Ap plica tion Sessi on(id , thi s, co ntex t); * time indi cates that the sessi on s hould neve r /** * sessi on m anage r acc ordin g to this valu e. thro w new Ille galSt ateEx cept ion }

appS essio ns.pu t(con text, app Sessi on); pub lic v oid remov eValu e(Str ing n ame) { time ou t. * Retur n t rue if t he c lient does not yet k now } Serv erSe ssion serv S=apS .getS erve rSess ion() ; * (sm.g etStr ing(" stand ardM anage r.cre ateSe ssion .ise "));

} valu es.r emove (name ); * about t he serv S.ac cesse d(); * @para m mi nutes The sessi on in acti vity timeo ut in minu tes.

} * @exce ptio n Ill egalS tateE xcept ion if th is * sessi on, or if the clien t cho oses not to jo in th e } apS. acce ssed( ); */ retu rn ( super .crea teSes sion( )); /**

// X XX method is ca lled on session . Fo r pub lic v oid setSe ssion TimeO ut(in t mi nutes ) { * Stop the backg round thre ad th at i s per iodic ally check ing for

// m ake sure that we ha ven't gon e ove r the end of ou r pub lic v oid setMa xInac tiveI nterv al(i nt in terva l) { * an i nval idate d ses sion * examp le, if th e ser ver u sed o nly cooki e-bas ed se ssion s, // c ache it - no n eed t o com pute it a gain if(- 1 != minu tes) { } * sessi on t imeou ts.

// i nact ive i nterv al -- if s o, i nvali date and c reate inac tive Inter val = inte rval; */ and the clie nt req. setS essio n( ap S ); // T he ma nager work s wit h se conds ... */

// a new appS essio n } pub lic i nt g etMax Inact iveIn terva l() { * has d isab led t he us e of cooki es, then a ses sion would be } inac tiveI nterv al = (minu tes * 60) ; pri vate void thre adSto p() {

new on each }

retu rn a ppSes sion; pub lic i nt g etMax Inact iveIn terva l() { retu rn ( this. maxIn activ eInte rval ); * reque st. pub lic H ttpS essio n cre ateSe ssion (Con text ctx) { } if ( thre ad == null )

} retu rn i nacti veInt erval ; * Stri ng s essio nId = Sess ionId Gene rator .gene rateI d(); } retu rn;

} } * @exce ptio n Ill egalS tateE xcept ion if th is me thod is Serv erSe ssion sess ion = new Serv erSes sion( sessi onId) ;

voi d rem oveA pplic ation Sessi on(Co ntex t con text) { called on an sess ions .put( sessi onId, sess ion) ; thre adDo ne = true;

appS essi ons.r emove (cont ext); // XXX * inva lida ted s essio n thre ad.i nterr upt() ;

} // sync' d fo r saf ty -- no o ther thre ad sh ould be ge tting som ethin g /** */ if(- 1 != inac tiveI nterv al) { try {

// from this whil e we are r eapin g. T his i sn't the m ost o ptim al * Set t he m aximu m tim e int erval , in seco nds, pub lic b oole an is New() { sess ion. setMa xInac tiveI nterv al(i nacti veInt erval ); thre ad.jo in();

/** // solut ion for t his, but w e'll dete rmine some thing else lat er. between clie nt r eques ts } } ca tch (Inte rrupt edExc eptio n e) {

* Calle d by cont ext w hen r eques t co mes i n so that acces ses and * befor e th e ser vlet conta iner will inva lidat e retu rn ( this. isNew ); retu rn s essio n.get Appli catio nSes sion( ctx, true ); ;

* inact ivit ies c an be deal t wit h ac cordi ngly. syn chron ized void reap () { the ses sion. A negat ive } }

*/ Enum erat ion e num = appS essio ns.k eys() ; * time indi cates that the sessi on s hould neve r }

time ou t. pub lic H ttpS essio n fin dSess ion(C onte xt ct x, St ring id) { thre ad = null ;

voi d acc esse d() { whil e (e num.h asMor eElem ents( )) { * Serv erSe ssion sSes sion= (Serv erSe ssion )sess ions. get(i d);

// s et l ast a ccess ed to this Acce ssTim e as it wi ll be lef t ove r Obje ct ke y = e num.n extEl emen t(); * @para m in terva l The new maxim um i nterv al if(s Sess ion== null) retu rn nu ll; }

// f rom the p revio us ac cess Appl icati onSes sion appSe ssio n = */

(Appl icati onSes sion) appS essio ns.ge t(key ); pub lic v oid setMa xInac tiveI nterv al(i nt in terva l) retu rn s Sessi on.ge tAppl icati onSe ssion (ctx, fals e);

} // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- - Ba ckgro und T hread









7

last Acce ssed = thi sAcce ssTim e; {

this Acce ssTim e = S ystem .curr entT imeMi llis( ); appS essio n.val idate ();

} this .max Inact iveIn terva l = i nter val;

} } /**

} } * The b ackg round thre ad th at ch ecks for sessi on ti meout s an d shu tdown .

voi d val idat e() */

pub lic v oid run() {



// L oop until the termi natio n se mapho re is set

whil e (! threa dDone ) {

thre adSle ep();

proc essEx pires ();

}



}





}

Implications of

Non-modularization

 Redundant code

– same fragment of code in many places

 Difficult to reason about

– non-explicit structure

– the big picture of the tangling isn’t clear

 Difficult to change

– have to find all the code involved

– and be sure to change it consistently

– and be sure not to break it by accident



8

If we just could…

App ca onSess on

ApplicationSession S andardSess on

StandardSession

/* public void inva lidat e() { package org. apac he.to mcat. sessi on; /**

* ==== ===== ==== ===== ===== ===== ===== ==== ===== ===== ===== ===== ==== ===== ==

= serv erSe ssion .remo veApp licat ionS essio n(con text) ; /** * Bind an o bject to t his s essio n, u sing the s pecif ied n ame. If an ob ject

* * Retur n th e Ht tpSes sion fo r whi ch th is * of th e sa me na me is alre ady b ound to t his s essio n, th e ob ject is

* The Apach e So ftwar e Lic ense, Vers ion 1.1 // r emov e eve rythi ng in the sess ion import java. io.I OExce ption ; object * repla ced.

* import java. io.O bject Input Strea m; * is th e fa cade. *

* Copy right (c) 1999 The Apach e Sof twar e Fou ndati on. All r ight s Enum erat ion e num = valu es.ke ys() ; import java. io.O bject Outpu tStre am; */ * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts

* rese rved. whil e (e num.h asMor eElem ents( )) { import java. io.S erial izabl e; pub lic H ttpS essio n get Sessi on() { * Htt pSess ionBi nding Liste ner, th e con taine r ca lls

* Stri ng na me = (Stri ng)en um.n extEl ement (); import java. util .Enum erati on; * val ueBou nd() on the objec t.

* Redi strib utio n and use in so urce and binar y for ms, w ith o r wi thout remo veVal ue(na me); import java. util .Hash table ; retu rn ( (Http Sessi on) t his); *

* modi ficat ion, are permi tted provi ded that the f ollow ing c ondi tions } import java. util .Vect or; * @para m na me Na me to whic h the obj ect i s bou nd, c annot be null

* are met: import javax .ser vlet. Servl etExc eptio n; } * @para m va lue O bject to b e bou nd, canno t be null

* vali d = false ; import javax .ser vlet. http. HttpS essio n; *

* 1. R edist ribu tions of s ource code mus t ret ain t he ab ove c opyr ight } import javax .ser vlet. http. HttpS essio nBin dingE vent; * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n

* n otice , th is li st of cond ition s an d the foll owing disc laim er. import javax .ser vlet. http. HttpS essio nBin dingL isten er; // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- - * inva lida ted s essio n

* pub lic b oole an is New() { import javax .ser vlet. http. HttpS essio nCon text; Session Publ ic M ethod s *

* 2. R edist ribu tions in b inary form mus t rep roduc e the abov e co pyrig ht if ( ! va lid) { import org.a pach e.tom cat.c atali na.*; * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d by

* n otice , th is li st of cond ition s an d the foll owing disc laim er in Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); import org.a pach e.tom cat.u til.S tring Mana ger; * se tAttr ibute ()

* t he do cume ntati on an d/or other mat erial s pro vided with the /** */

* d istri buti on. thro w new Ille galSt ateEx cept ion(m sg); * Updat e th e acc essed time info rmat ion f or th is se ssion . pub lic v oid putVa lue(S tring name , Ob ject value ) {

* } /** This me thod

* 3. T he en d-us er do cumen tatio n inc lude d wit h the redi strib utio n, if * Stan dard impl ement ation of t he Ses sion * shoul d be call ed by the conte xt w hen a requ est c omes in setA ttri bute( name, valu e);

* a ny, m ust inclu de th e fol lowin g ac knowl egeme nt: if ( this Acces sTime == c reati onTi me) { interfa ce. This obje ct is for a p artic ular

* "Th is p roduc t inc ludes soft ware deve loped by t he retu rn tr ue; * seri aliza ble, so t hat i t can be s tore d in * sessi on, even if th e app licat ion does not r efere nce i t. }

* Ap ache Soft ware Found ation (ht tp:// www.a pache .org/ )." } el se { persist ent s tora ge or tran sferr ed */

* A ltern atel y, th is ac knowl egeme nt m ay ap pear in th e sof twar e retu rn fa lse; * to a diff eren t JVM for distr ibuta ble sessi on pub lic v oid acces s() {

itself, } support . /**

* i f and whe rever such thir d-par ty a cknow legem ents norma lly appea r. } * this .las tAcce ssedT ime = this .thi sAcce ssedT ime; * Remov e th e obj ect b ound with the speci fied name from this sess ion. If

* * I MPLEM ENTA TION NOTE: An i nsta nce o f thi s this .thi sAcce ssedT ime = Syst em.c urren tTime Milli s(); * the s essi on do es no t hav e an obje ct bo und w ith t his n ame, this meth od

* 4. T he na mes "The Jakar ta Pr oject ", " Tomca t", a nd "A pache Sof tware class r epres ents both the this .isN ew=fa lse; * does noth ing.

* F ounda tion " mus t not be u sed t o en dorse or p romot e pro duct s /** * inte rnal (Ses sion) and appli catio n le vel } *

derived * @depr ecat ed (HttpSe ssion ) vi ew of the sessi on. * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts

* f rom t his softw are w ithou t pri or w ritte n per missi on. F or w ritte n */ * Howe ver, beca use t he cl ass i tself is not d eclar ed * Htt pSess ionBi nding Liste ner, th e con taine r ca lls

* p ermis sion , ple ase c ontac t apa che@ apach e.org . public, Java log ic ou tside /** * val ueUnb ound( ) o n th e obj ect.

* pub lic v oid putVa lue(S tring name , Ob ject value ) { * of t he org.a pache .tomc at.se ssio n * Perfo rm t he in terna l pro cessi ng r equir ed to inva lidat e *

* 5. P roduc ts d erive d fro m thi s sof twar e may not be ca lled "Apa che" setA ttri bute( name, valu e); package cann ot c ast a n this se ssion , * @para m na me Na me of the objec t to remo ve fr om th is se ssio n.

* n or ma y "A pache " app ear i n the ir n ames witho ut pr ior w ritt en } * Http Sessi on v iew o f thi s ins tance bac k to a * witho ut t rigge ring an ex cepti on i f the sess ion h as *

* p ermis sion of t he Ap ache Group . Session view . already expi red. * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n

* pub lic v oid setAt tribu te(St ring name , Obj ect v alue) { * */ * inva lida ted s essio n

* THIS SOFT WARE IS P ROVID ED `` AS IS '' A ND AN Y EXP RESSE D OR IMPL IED if ( ! va lid) { * @aut hor C raig R. M cClan ahan pub lic v oid expir e() { */

* WARR ANTIE S, I NCLUD ING, BUT N OT LI MITE D TO, THE IMPLI ED WA RRAN TIES Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); * @ver sion $Rev ision : 1.2 $ $D ate: 2000 /05/1 5 pub lic v oid remov eAttr ibute (Stri ng n ame) {

* OF M ERCHA NTAB ILITY AND FITNE SS FO R A PARTI CULAR PURP OSE A RE 17:54:1 0 $ // R emov e thi s ses sion from our manag er's activ e

* DISC LAIME D. IN NO EVEN T SHA LL TH E AP ACHE SOFTW ARE F OUNDA TION OR thro w new Ille galSt ateEx cept ion(m sg); */ session s sync hron ized (attr ibute s) {

* ITS CONTR IBUT ORS B E LIA BLE F OR AN Y DI RECT, INDI RECT, INCI DENT AL, } if ( (man ager != nu ll) & & (ma nage r ins tance of Obje ct ob ject = att ribut es.g et(na me);

* SPEC IAL, EXEM PLARY , OR CONSE QUENT IAL DAMAG ES (I NCLUD ING, BUT NOT final c lass Stan dardS essio n Manager Base) ) if ( objec t == null)

* LIMI TED T O, P ROCUR EMENT OF S UBSTI TUTE GOOD S OR SERVI CES; LOSS OF if ( name == n ull) { imp lemen ts H ttpSe ssion , Ses sion { ((Ma nager Base) mana ger). remo ve(th is); retur n;

* USE, DATA , OR PROF ITS; OR BU SINES S IN TERRU PTION ) HOW EVER CAUS ED AN D Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ; attr ibute s.rem ove(n ame);

* ON A NY TH EORY OF L IABIL ITY, WHETH ER I N CON TRACT , STR ICT L IABI LITY, // U nbin d any obje cts a ssoci ated with this sess ion // S ystem .out. print ln( "Remo ving attri bute " + name );

* OR T ORT ( INCL UDING NEGL IGENC E OR OTHE RWISE ) ARI SING IN AN Y WA Y OUT thro w new Ille galAr gumen tExc eptio n(msg ); // ----- ---- ----- ----- ----- ----- ---- ----- ----- --- Vect or r esult s = n ew Ve ctor( ); if ( objec t ins tance of Ht tpSe ssion Bindi ngLis tener ) {

* OF T HE US E OF THIS SOFT WARE, EVEN IF ADVIS ED OF THE POSSI BILI TY OF } ------- ----- - Co nstru ctors Enum erat ion a ttrs = get Attri bute Names (); ((Htt pSess ionBi nding List ener) obje ct).v alueU nbou nd

* SUCH DAMA GE. whil e (a ttrs. hasMo reEle ments ()) { ( new H ttpSe ssion Bind ingEv ent(( HttpS essio n) t his, name) );

* ==== ===== ==== ===== ===== ===== ===== ==== ===== ===== ===== ===== ==== ===== == remo veVa lue(n ame); // remov e an y exi sting bind ing Stri ng at tr = (Stri ng) a ttrs .next Eleme nt(); }

* /** resu lts.a ddEle ment( attr) ; }

* This soft ware cons ists of vo lunta ry c ontri butio ns ma de by man y if ( valu e != null && va lue i nsta nceof Http Sessi onBin ding Liste ner) { * Const ruct a ne w Ses sion assoc iate d wit h the }

* indi vidua ls o n beh alf o f the Apac he S oftwa re Fo undat ion. For more Http Sessi onBin dingE vent e = specifi ed Ma nage r. Enum erat ion n ames = res ults. elem ents( ); }

* info rmati on o n the Apac he So ftwar e Fo undat ion, pleas e see new H ttpSe ssion Bindi ngEv ent(t his, name) ; * whil e (n ames. hasMo reEle ments ()) {

* . * @para m ma nager The manag er wi th w hich this Stri ng na me = (Stri ng) n ames .next Eleme nt();

* ((Ht tpSes sionB indin gList ener )valu e).va lueBo und(e ); Session is a ssoc iated remo veAtt ribut e(nam e); /**

* [Add ition al n otice s, if requ ired by p rior licen sing condi tion s] } */ } * Remov e th e obj ect b ound with the speci fied name from this sess ion. If

* pub lic S tand ardSe ssion (Mana ger m anag er) { * the s essi on do es no t hav e an obje ct bo und w ith t his n ame, this meth od

*/ valu es.p ut(na me, v alue) ; // M ark this sessi on as inva lid * does noth ing.

} supe r(); setV alid (fals e); *

this .man ager = man ager; * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts

/** } * Htt pSess ionBi nding Liste ner, th e con taine r ca lls

package org. apac he.to mcat. sessi on; * @depr ecat ed } * val ueUnb ound( ) o n th e obj ect.

*/ *

import org.a pach e.tom cat.c ore.* ; pub lic O bjec t get Value (Stri ng na me) { /** * @para m na me Na me of the objec t to remo ve fr om th is se ssio n.

import org.a pach e.tom cat.u til.S tring Mana ger; retu rn g etAtt ribut e(nam e); // ----- ---- ----- ----- ----- ----- ---- ----- ----- --- * Relea se a ll ob ject refer ences , an d ini tiali ze in stanc e *

import java. io.* ; } ------- Inst ance Vari ables variabl es, i n * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n

import java. net. *; * prepa rati on fo r reu se of this obj ect. * inva lida ted s essio n

import java. util .*; pub lic O bjec t get Attri bute( Strin g na me) { */ *

import javax .ser vlet. *; if ( ! va lid) { /** pub lic v oid recyc le() { * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d by

import javax .ser vlet. http. *; Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); * The c olle ction of u ser d ata a ttri butes * re moveA ttrib ute()

associa ted w ith this Sessi on. // R eset the insta nce v ariab les assoc iated with this */

/** thro w new Ille galSt ateEx cept ion(m sg); */ Session pub lic v oid remov eValu e(Str ing n ame) {

* Core impl emen tatio n of an ap plica tion leve l ses sion } pri vate Hash table attr ibute s = n ew H ashta ble() ; attr ibut es.cl ear() ;

* crea tion Time = 0L; remo veAt tribu te(na me);

* @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om] if ( name == n ull) { id = nul l;









SessionInterceptor

Sess on n ercep or S andardManager

StandardManager S andardSess onManager

StandardSessionManager

* @aut hor J ason Hunt er [j ch@en g.sun .com ] Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ; /** last Acce ssedT ime = 0L; }

* @aut hor J ames Todd [gon zo@en g.sun .com ] * The t ime this sessi on wa s cre ated , in mana ger = nul l;

*/ thro w new Ille galAr gumen tExc eptio n(msg ); millise conds sin ce mi dnigh t, maxI nact iveIn terva l = - 1;

} * Janua ry 1 , 197 0 GMT . isNe w = true; /**

public class App licat ionSe ssion impl emen ts Ht tpSes sion { */ isVa lid = fal se; * Bind an o bject to t his s essio n, u sing the s pecif ied n ame. If an ob ject

retu rn v alues .get( name) ; pri vate long crea tionT ime = 0L; * of th e sa me na me is alre ady b ound to t his s essio n, th e ob ject is

pri vate Stri ngMan ager sm = } // T ell our M anage r tha t thi s Se ssion has been recyc led * repla ced.

Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" ); if ( (man ager != nu ll) & & (ma nage r ins tance of *

pri vate Hash table valu es = new H asht able( ); /** /** Manager Base) ) * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts

pri vate Stri ng id ; * @depr ecat ed * The s essi on id entif ier o f thi s Se ssion . ((Ma nager Base) mana ger). recy cle(t his); * Htt pSess ionBi nding Liste ner, th e con taine r ca lls package org. apac he.to mcat. reque st;

pri vate Serv erSes sion serve rSess ion; */ */ * val ueBou nd() on the objec t. pub lic i nt b efore Body( Requ est r requ est, Respo nse r espon se ) {

pri vate Cont ext c ontex t; pub lic S trin g[] g etVal ueNam es() { pri vate Stri ng id = nu ll; } * import org.a pach e.tom cat.c ore.* ; Stri ng r eqSes sionI d = r espon se.g etSes sionI d();

pri vate long crea tionT ime = Syst em.c urren tTime Milli s();; Enum erat ion e = ge tAttr ibute Name s(); * @para m na me Na me to whic h the obj ect i s bou nd, c annot be null import org.a pach e.tom cat.u til.* ; if( debu g>0 ) cm.l og("B efore Bod y " + reqS essio nId ) ;

pri vate long this Acces sTime = cr eati onTim e; Vect or n ames = new Vect or(); * @para m va lue O bject to b e bou nd, canno t be null import java. io.* ; if( reqS essio nId== null) package org. apac he.to mcat. sessi on; package org. apac he.to mcat. sessi on; // ---- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- Pub lic

pri vate long last Acces sed = crea tion Time; /** // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- Sess ion * import java. net. *; retu rn 0; // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- - Li fecyc le Me thods Methods

pri vate int inact iveIn terva l = - 1; whil e (e .hasM oreEl ement s()) { * Descr ipti ve in forma tion descr ibin g thi s Package Meth ods * @exce ptio n Ill egalA rgume ntExc epti on if an a ttemp t is made to a dd a import java. util .*; import java. io.I OExce ption ;

pri vate bool ean v alid = tru e; name s.add Eleme nt(e. nextE leme nt()) ; Session impl emen tatio n. * non- seri aliza ble o bject in a n en viron ment marke d dis trib utabl e. import javax .ser vlet. http. *; import java. util .Enum erati on; import java. io.I OExce ption ;

} */ * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n // G S, s et th e pat h att ribut e to the cooki e. Th is wa y import java. util .Hash table ; /**

import javax .ser vlet. http. Cooki e;

App licat ionS essio n(Str ing i d, Se rver Sessi on se rverS essio n, pri vate stat ic fi nal S tring info = /** * inva lida ted s essio n /** // m ulti ple s essio n coo kies can be us ed, o ne fo r eac h import java. util .Vect or; * Confi gure this comp onent , bas ed o n the spec ified conf igur ation

/**

Cont ext conte xt) { Stri ng[] valu eName s = n ew St ring [name s.siz e()]; "Standa rdSes sion /1.0" ; * Retur n th e is Valid f lag f or th is se ssion . */ * Will proc ess the r eques t and dete rmin e the sess ion I d, an d se t it // c onte xt. import org.a pach e.tom cat.c atali na.*; * param eter s. T his m ethod shou ld b e cal led i mmedi ately aft er th e import javax .ser vlet. http. HttpS essio n;

this .ser verSe ssion = se rverS essi on; */ pub lic v oid setAt tribu te(St ring name , Obj ect v alue) { * in t he Re ques t. Stri ng s essio nPath = rr eques t.ge tCont ext() .getP ath() ; import javax .ser vlet. http. Cooki e; * compo nent inst ance is cr eated , an d bef ore start () * Mark the speci fied sessi on's last acce ssed time. Thi s sh ould be

import org.a pach e.tom cat.c atali na.*;

this .con text = con text; name s.co pyInt o(val ueNam es); boo lean isVa lid() { * It a lso m arks the sessi on as acce ssed . if(s essi onPat h.len gth() == 0 ) { import javax .ser vlet. http. HttpS essio n; * is ca lled .

* calle d fo r eac h req uest by a Requ estIn terce ptor.

this .id = id; /** if ( (man ager != nu ll) & & man ager .getD istri butab le() && * sess ionPa th = "/"; import org.a pach e.tom cat.u til.S tring Mana ger; * import org.a pach e.tom cat.c ore.C ontex t;

retu rn v alueN ames; * The l ast acces sed t ime f or th is S essio n. retu rn ( this. isVal id); !( valu e ins tance of Se riali zabl e)) * This impl emen tatio n onl y han dles Cook ies s essio ns, p lease ext end o r } import org.w 3c.d om.Na medNo deMap ; * @para m pa ramet ers C onfig urati on p arame ters for t his c ompo nent *

import org.a pach e.tom cat.c ore.R eques t;

this .ina ctive Inter val = cont ext. getSe ssion TimeO ut(); */ thro w new Ille galAr gumen tExc eptio n * add new i nter cepto rs fo r oth er me thod s. import org.w 3c.d om.No de; * ( FIXM E: Wh at ob ject type shou ld th is re ally be?)

* @para m se ssion The sessi on to be marke d

} pri vate long last Acces sedTi me = crea tionT ime; } (sm.g etStr ing(" stand ardS essio n.set Attri bute. iae" )); * // G S, p iggyb ack t he jv m rou te o n the sess ion i d. * import org.a pach e.tom cat.c ore.R espon se;

if ( this .inac tiveI nterv al != -1) { */ if(! sess ionPa th.eq uals( "/")) { * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready been */

import org.a pach e.tom cat.c ore.S essio nMan ager;

this .inac tiveI nterv al *= 60; pub lic E nume ratio n get Attri buteN ames () { sync hron ized (attr ibute s) { public class Ses sionI nterc eptor exte nds Base Inter cepto r imp leme nts R eques tInte rcept or { Stri ng jv mRout e = r reque st.g etJvm Route (); /** * conf igur ed an d/or start ed

pub lic v oid acces sed(C ontex t ctx , Re quest req, Stri ng id ) {

} if ( ! va lid) { /** /** remo veAtt ribut e(nam e); if(n ull ! = jvm Route ) { * Stan dard impl ement ation of t he Man ager i nterf ace t hat provi des * @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l err or import org.a pach e.tom cat.u til.S essio nUti l;

} Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); * The M anag er wi th wh ich t his S essi on is * Set t he isNew fl ag f or th is se ssion . attr ibute s.put (name , val ue); // GS, s epar ates the s essio n id from the jvm r oute reqSe ssion Id = reqSe ssio nId + SESS IONID _ROUT E_SE P + j vmRou te; * no s essio n pe rsist ence or di strib utab le ca pabil ities , but doe s sup port * in t he c onfig urati on pa ramet ers it wa s giv en Http Sess ion s essio n=fin dSess ion( ctx, id);

associa ted. * if ( value inst anceo f Htt pSes sionB indin gList ener) sta tic f inal char SESS IONID _ROUT E_SE P = ' .'; } * an o ption al, confi gurab le, m aximu m nu mber of ac tive sessi ons allow ed. */

if( sess ion = = nul l) re turn;

Ser verSe ssio n get Serve rSess ion() { thro w new Ille galSt ateEx cept ion(m sg); */ * @para m is New T he ne w val ue fo r th e is New ((Htt pSess ionBi nding List ener) valu e).va lueBo und int debu g=0; } * pub lic v oid confi gure( Node param eter s)

retu rn s erver Sessi on; } pri vate Mana ger m anage r = n ull; flag ( new H ttpSe ssion Bind ingEv ent(( HttpS essio n) t his, name) ); Con textM anag er cm ; * Life cycle con figur ation of t his c ompo nent assum es an XML node thro ws L ifecy cleEx cepti on { if ( sess ion i nstan ceof Sessi on)

/**

} */ } Cook ie c ookie = ne w Coo kie(" JSES SIONI D", * in t he fo llow ing f ormat :

((Se ssion ) ses sion) .acce ss() ;

Hash tabl e val uesCl one = (Has htab le)va lues. clone (); voi d set New( boole an is New) { pub lic S essi onInt ercep tor() { r eqSe ssion Id); * // V alid ate a nd up date our c urre nt co mpone nt st ate * Spec ializ ed i mplem entat ion o f org .apa che.t omcat .core .Sess ionM anage r

/** /** } } cook ie.s etMax Age(- 1); * <M anag er cl assNa me="o rg.ap ache .tomc at.se ssion .Stan dard Manag er" if ( conf igure d)

* that adap ts t o the new compo nent- base d Man ager imple menta tion .

* Calle d by cont ext w hen r eques t co mes i n so that acces ses and retu rn ( Enume ratio n)val uesCl one. keys( ); * The m axim um ti me in terva l, in sec onds, betw een this .isN ew = isNew ; cook ie.s etPat h(ses sionP ath); * check Inter val=" 60" m axAc tiveS essio ns="- 1" thro w new Life cycle Excep tion

// c ache the HttpS essio n - a void anot her f ind

* inact ivit ies c an be deal t wit h ac cordi ngly. } client reque sts befor e pub lic v oid setDe bug( int i ) { cook ie.s etVer sion( 1); * maxIn activ eInte rval= "-1" /> (sm.g etStr ing(" stand ardM anage r.alr eadyC onfig ured ")); *

*/ * the s ervl et co ntain er ma y inv alid ate t his } // ----- ---- ----- ----- ----- ----- ---- ----- ----- - Htt pSess ion Priva te Me thods Syst em.o ut.pr intln ("Set debu g to " + i); * conf igur ed = true; req. setS essio n( se ssion );

* XXX - At pres ent, use o f St anda rdMan ager is hard code d,

session . A nega tive time debu g=i; resp onse .addH eader ( Coo kieTo ols. getCo okieH eader Name( cook ie), * wher e you can adju st th e fol lowin g pa ramet ers, with defau lt v alues if ( para meter s == null)

}

voi d acc esse d() { /** * indic ates that the sessi on sh ould neve r tim e } Coo kieTo ols. getCo okieH eader Value (coo kie)) ; * in s quare bra ckets : retu rn; * and lifec ycle conf igura tion is no t su pport ed.

// s et l ast a ccess ed to this Acce ssTim e as it wi ll be lef t ove r * @depr ecat ed out. /** /** cook ie.s etVer sion( 0); *

*

// f rom the p revio us ac cess */ */ * Set t he isVal id flag for this sessi on. * Read a se riali zed v ersio n of this sess ion o bject from the spec ified pub lic v oid setCo ntext Manag er( C onte xtMan ager cm ) { resp onse .addH eader ( Coo kieTo ols. getCo okieH eader Name( cook ie), * ch eckI nterv al - T he in terv al (i n sec onds) betw een backg round // P arse and proce ss ou r con figu ratio n par amete rs

// XXX s houl d we throw exce ption or just retur n nul l ??

last Acce ssed = thi sAcce ssTim e; pri vate int maxIn activ eInte rval = -1 ; * * objec t in put s tream . this .cm= cm; Coo kieTo ols. getCo okieH eader Value (coo kie)) ; * threa d ch ecks for e xpire d ses sion s. [ 60] if ( !("M anage r".eq uals( param eter s.get NodeN ame() ))) * I MPLEM ENTA TION NOTE: Once we commi t to the n ew

this Acce ssTim e = S ystem .curr entT imeMi llis( ); pub lic v oid remov eValu e(Str ing n ame) { * @para m is Valid The new v alue for the * } * ma xAct iveSe ssion s - Th e ma ximum numb er of sess ions allo wed t o retu rn; Manager /Sess ion pub lic H ttpS essio n fin dSess ion( Cont ext c tx, S tring id ) {

remo veAt tribu te(na me); i sVali d flag * IM PLEM ENTAT ION N OTE: The refer ence to th e own ing Manag er retu rn 0 ; * be ac tive at o nce, or -1 for no l imit. [-1 ] Name dNod eMap attri butes = pa rame ters. getAt tribu tes() ;

* para digm, I w ould sugge st mo ving the logic impl ement ed he re b ack i nto try {

vali date (); } /** */ * is no t re store d by this metho d, a nd mu st be set expli citl y. pub lic i nt r eques tMap( Reque st re ques t ) { } * ma xIna ctive Inter val - The defau lt ma ximum numb er o f sec onds of Node nod e = n ull;

} * Flag indi catin g whe ther this sess ion i s new or voi d set Vali d(boo lean isVal id) { * Stri ng s essio nId = null ; * inact ivit y bef ore w hich the s ervl et co ntain er is allo wed to ti me ou t * the core leve l. T he To mcat. Next "Man ager" inte rface acts mor e lik e a Sess ion s essio n = m anage r.fi ndSes sion( id);

pub lic v oid remov eAttr ibute (Stri ng n ame) { not. * @para m st ream The i nput strea m to read from * a ses sion , or -1 fo r no limit . T his v alue shoul d be over ridde n fro m node = a ttrib utes. getNa medIt em(" check Inter val") ;

* coll ectio n cl ass, and h as mi nimal kno wledg e of the d etail ed r eques t if(s essio n!=nu ll)

voi d val idat e() { if ( ! va lid) { */ this .isV alid = isV alid; * Cook ie c ookie s[]=r eques t.get Cook ies() ; // asser t !=n ull /** Noti fica tion of co ntext shut down * the d efau lt se ssion time out s peci fied in th e web appl icat ion d eploy ment if ( node != n ull) {

// i f we have an i nacti ve in terv al, c heck to se e if we'v e exc eeded it Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); pri vate bool ean i sNew = tru e; } * @exce ptio n Cla ssNot Found Excep tion if a n unk nown class is speci fied */ * descr ipto r, if any. [-1 ] try { * proc essin g se manti cs of hand ling sess ions. retur n ses sion. getSe ssio n();

if ( inac tiveI nterv al != -1) { * @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s for( int i=0; i setCh eckIn terva l(Int eger .pars eInt( node. getNo deVa lue() ));

* } ca tch (IOEx cepti on e) {

int thisI nterv al = thro w new Ille galSt ateEx cept ion(m sg); */ Cook ie co okie = coo kies[ i]; thro ws T omcat Excep tion * } ca tch ( Throw able t) {

(int) (Syst em.cu rrent Time Milli s() - last Acces sed) / 10 00; } /** // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- - pri vate void read Objec t(Obj ectIn putS tream stre am) { * @aut hor C raig R. M cClan ahan ; // XXX - Thr ow e xcept ion? * XXX - At pres ent, there is n o way (vi a the Sess ionMa nager int erfac e) }

* Flag indi catin g whe ther this sess ion i s val id HttpSes sion Prop ertie s thro ws C lassN otFou ndExc eptio n, I OExce ption { if ( cooki e.get Name( ).equ als( "JSES SIONI D")) { if( ctx. getDe bug() > 0 ) ctx .log ("Rem oving sess ions from " + ctx ) ; * @ver sion $Rev ision : 1.1 .1.1 $ $Da te: 2000/ 05/02 21:2 8:30 $ } for

retu rn ( null) ;

if ( thisI nterv al > inact iveI nterv al) { if ( name == n ull) { or not. sessi onId = coo kie.g etVa lue() ; ctx. getS essio nMana ger() .remo veSe ssion s(ctx ); */ }

* a Co ntext to tell the M anage r tha t we crea te wh at th e def ault sess ion

inval idate (); Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ; */ // D eser ializ e the scal ar in stan ce va riabl es (e xcept Man ager) sessi onId= valid ateSe ssio nId(r eques t, se ssion Id); } }

} pri vate bool ean i sVali d = f alse; /** crea tion Time = ((L ong) strea m.re adObj ect() ).lon gValu e(); if (s essio nId!= null) { public final cla ss St andar dMana ger node = a ttrib utes. getNa medIt em(" maxAc tiveS essio ns"); * time out f or t his w eb ap plica tion (spe cifie d in the d eploy ment

} thro w new Ille galAr gumen tExc eptio n(msg ); * Retur n th e tim e whe n thi s ses sion was creat ed, i n id = (St ring) stre am.re adObj ect( ); r eques t.set Reque sted Sessi onIdF romCo okie( true ); ext ends Mana gerBa se if ( node != n ull) { descrip tor)

} } millise conds sin ce last Acce ssedT ime = ((Lo ng) s trea m.rea dObje ct()) .long Valu e(); } } imp lemen ts L ifecy cle, Runna ble { try { pub lic H ttpS essio n cre ateSe ssion (Con text ctx) {

* shou ld be .

/** * midni ght, Janu ary 1 , 197 0 GMT . maxI nact iveIn terva l = ( (Inte ger) stre am.re adObj ect() ).in tValu e(); } setMa xActi veSes sions (Int eger. parse Int(n ode.g etNo deVal ue()) );

retu rn manag er.cr eateS essio n(). getSe ssion ();

// HTTP SESS ION I MPLEM ENTAT ION M ETHO DS Obje ct o = va lues. get(n ame); * The s trin g man ager for t his p acka ge. * isNe w = ((Boo lean) stre am.re adOb ject( )).bo olean Value (); } } ca tch ( Throw able t) { *

*/ * @exce ptio n Ill egalS tateE xcept ion if th is me thod is isVa lid = ((B oolea n) st ream. read Objec t()). boole anVal ue() ; // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- Ins tance Vari ables ; // XXX - Thr ow e xcept ion? }

* @aut hor C raig R. M cClan ahan

pub lic S trin g get Id() { if ( o in stanc eof H ttpSe ssion Bind ingLi stene r) { pri vate Stri ngMan ager sm = called on an Stri ng s ig="; jsess ionid ="; }

if ( vali d) { Http Sessi onBin dingE vent e = * inva lida ted s essio n // D eser ializ e the attr ibute cou nt an d att ribut e val ues int foun dAt=- 1; } */

retu rn id ; new H ttpSe ssion Bindi ngEv ent(t his,n ame); StringM anage r.ge tMana ger(" org.a pache .tom cat.s essio n") */ int n = ((Int eger) stre am.re adOb ject( )).in tValu e(); if( debu g>0 ) cm.l og(" XXX R URI= " + r eques t.get Reque stUR I()); /** /**

} el se { ; pub lic l ong getCr eatio nTime () { for (int i = 0; i // XXX w hat is th e cor rect behav ior if th e ses sion is in vali d ? * The d escr iptiv e inf ormat ion a bout this impl ement ation . // c onte xts, we ju st wa nt to rem ove t he se ssion s of ctx!

/**

thro w new Ille galSt ateEx cept ion(m sg); */ * repl acem ent. It w ill b e rem oved in a futu re ve rsion of * IM PLEM ENTAT ION N OTE: The ownin g Man ager will not be st ored // We ma y st ill s et it and just retu rn se ssion inva lid. */

// T he m anage r wil l sti ll ru n af ter t hat ( i.e. keep dat abase

} inac tive Inter val = inte rval; pri vate long this Acces sedTi me = crea tionT ime; the * in th e se riali zed r epres entat ion of th is Se ssion . Af ter calli ng pri vate stat ic fi nal S tring info = " Stand ardMa nager /1.0" ; /** * Creat e a new S essio nMana ger t hat adapt s to the c orres pond ing

} } * Java Ser vlet API. * rea dObje ct(), yo u mu st se t the asso ciate d Ma nager /** Vali date and fix t he se ssion id. If t he se ssion is n ot v alid retur n nul l. * Prepa re f or th e beg innin g of acti ve us e of the p ublic met hods of th is Manager // c onne ction open

*/ * expli citl y. * It w ill also clean up t he se ssio n fro m loa d-bal ancin g st rings . * compo nent . Th is me thod shoul d be call ed af ter conf igure (),

* imple ment ation . if ( mana ger i nstan ceof Lifec ycle ) {

/** pub lic i nt g etMax Inact iveIn terva l() { pub lic H ttpS essio nCont ext g etSes sion Conte xt() { * * @retu rn s essio nId, or nu ll if not vali d /** * and b efor e any of t he pu blic meth ods o f the comp onent are util ized.

* if ( ! va lid) { * IM PLEM ENTAT ION N OTE: Any attri bute that is no t Se riali zable */ * The m axim um nu mber of ac tive Sess ions allow ed, o r -1 for no li mit. * */ try {

* @depr ecat ed Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); // ----- ---- ----- ----- ----- ----- ---- ----- ----- --- if ( sess ionCo ntext == n ull) * will be s ilent ly ig nored . If you do n ot wa nt an y suc h at tribu tes, pri vate Stri ng va lidat eSess ionId (Req uest reque st, S tring ses sionI d){ */ * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s no t yet been

pub lic S tand ardSe ssion Manag er() { ((Lif ecycl e) ma nager ).st op();

*/ ------- Sess ion Prope rties sess ionCo ntext = ne w Sta ndar dSess ionCo ntext (); * be su re t he d istri butab le prop erty of ou r as socia ted // G S, W e pig gybac k the JVM id o n top of t he se ssion coo kie pro tecte d in t max Activ eSess ions = -1 ; * conf igur ed (i f req uired for this comp onent )

thro w new Ille galSt ateEx cept ion(m sg); retu rn ( sessi onCon text) ; * Manag er i s set to true. // S epar ate t hem . .. * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready been } ca tch ( Lifec ycleE xcept ion e) {

pub lic H ttpS essio nCont ext g etSes sion Conte xt() { } * * star ted

mana ger = new Stan dardM anage r(); throw new Illeg alSta teEx cepti on("" + e) ;

retu rn n ew Se ssion Conte xtImp l(); /** } * @para m st ream The o utput stre am t o wri te to if( debu g>0 ) cm.l og(" Orig sess ionId " + sess ionId ); /** * @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l err or

} retu rn i nacti veInt erval ; * Set t he c reati on ti me fo r thi s se ssion . Th is * if ( null != s essio nId) { * The s trin g man ager for t his p acka ge. * that pre vents this comp onent fro m bei ng us ed if ( mana ger i nstan ceof Lifec ycle ) { }

} method is ca lled by t he * @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s int idex = ses sionI d.las tInd exOf( SESSI ONID_ ROUTE _SEP ); */ */

try { }

pub lic l ong getLa stAcc essed Time( ) { } * Manag er w hen a n exi sting Sess ion insta nce i s // ----- ---- ----- ----- ----- ----- ---- ----- ----- --- */ if(i dex > 0) { pri vate Stri ngMan ager sm = pub lic v oid start () th rows Lifec ycle Excep tion {

if ( vali d) { reused. HttpSes sion Publ ic Me thods pri vate void writ eObje ct(Ob jectO utpu tStre am st ream) thro ws I OExce ption { sessi onId = ses sionI d.su bstri ng(0, idex ); Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" ); ((Lif ecycl e) ma nager ).co nfigu re(nu ll);

retu rn la stAcc essed ; * } // V alid ate a nd up date our c urre nt co mpone nt st ate

((Lif ecycl e) ma nager ).st art() ; }

} el se { //----- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- ----- ---- * @para m ti me Th e new crea tion time // W rite the scala r ins tance var iable s (ex cept Manag er) } if ( !con figur ed)

Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); */ /** stre am.w riteO bject (new Long( crea tionT ime)) ; /** thro w new Life cycle Excep tion } ca tch ( Lifec ycleE xcept ion e) {

pub lic v oid setCr eatio nTime (long tim e) { * Retur n th e obj ect b ound with the speci fied name in th is stre am.w riteO bject (id); if ( sess ionId != n ull & & ses sion Id.le ngth( )!=0) { * Has t his compo nent been start ed y et? (sm.g etStr ing(" stand ardM anage r.not Confi gured "));

throw new Illeg alSta teEx cepti on("" + e) ; /**

thro w new Ille galSt ateEx cept ion(m sg); session , or stre am.w riteO bject (new Long( last Acces sedTi me)); // G S, We are in a probl em h ere, we ma y act ually get */ if ( star ted)

} this .cre ation Time = tim e; * nul l i f no objec t is boun d wit h tha t nam e. stre am.w riteO bject (new Integ er(m axIna ctive Inter val)) ; // m ultip le Se ssion cook ies (one for t he ro ot pri vate bool ean s tarte d = f alse; thro w new Life cycle Excep tion } * Used by c ontex t to confi gure the sessi on ma nager 's in acti vity

} this .las tAcce ssedT ime = time ; * stre am.w riteO bject (new Boole an(i sNew) ); // c ontex t and one for t he r eal c ontex t... or ol d se ssion (sm.g etStr ing(" stand ardM anage r.alr eadyS tarte d")) ; timeout .

}

this .thi sAcce ssedT ime = time ; * @para m na me Na me of the attri bute to b e ret urned stre am.w riteO bject (new Boole an(i sVali d)); // c ookie . We must check for vali dity in th e cur rent cont ext. star ted = tru e;

*

* Cont ext c tx=re quest .getC onte xt(); /**

} * @exce ptio n Ill egalS tateE xcept ion if th is me thod is // A ccum ulate the names of s eria lizab le at tribu tes Sess ionMa nager sM = ctx. getS essio nMana ger() ; * The b ackg round thre ad. // S tart the backg round reap er t hread * The S essi onMan ager may h ave s ome defau lt se ssion time out , the

}

called on an Vect or r esult s = n ew Ve ctor( ); if(n ull ! = sM. findS essio n(ct x, se ssion Id)) { */ thre adSt art() ;

* Conte xt o n the othe r han d has it' s tim eout set b y the dep loyme nt

* inva lida ted s essio n Enum erat ion a ttrs = get Attri bute Names (); sM.ac cesse d(ctx , req uest , ses sionI d ); pri vate Thre ad th read = nul l;

/** */ whil e (a ttrs. hasMo reEle ments ()) { reque st.se tRequ ested Sess ionId (sess ionId ); } * descr ipto r (we b.xml ). Th is me thod lets the Conte xt co nfor gure the

* Retur n th e ses sion ident ifier for this pub lic O bjec t get Attri bute( Strin g na me) { Stri ng at tr = (Stri ng) a ttrs .next Eleme nt(); if( d ebug> 0 ) c m.log (" F inal sessi on id " + sess ionId );

* sessi on m anage r acc ordin g to this valu e.

session . Obje ct va lue = attr ibute s.ge t(att r); retur n ses sionI d; /** // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- Ins tance

*/ retu rn ( attri butes .get( name) ); if ( value inst anceo f Ser iali zable ) } * The b ackg round thre ad co mplet ion semap hore. /** Variabl es *

pub lic S trin g get Id() { resul ts.ad dElem ent(a ttr) ; } */ * Grace full y ter minat e the acti ve u se of the publi c met hods of t his

* @para m mi nutes The sessi on in acti vity timeo ut in minu tes.

} } retu rn n ull; pri vate bool ean t hread Done = fal se; * compo nent . Th is me thod shoul d be the last one c alled on a giv en

retu rn ( this. id); } * insta nce of th is co mpone nt. */

// S eria lize the a ttrib ute c ount and the attri bute valu es *

/** pub lic v oid setSe ssion TimeO ut(in t mi nutes ) {

} /** stre am.w riteO bject (new Integ er(r esult s.siz e())) ; /** * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s no t bee n sta rted

* Retur n an Enu merat ion of Enum erat ion n ames = res ults. elem ents( ); * Name to r egist er fo r the back grou nd th read. * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready * The M anag er im pleme ntati on we are actu ally using . if(- 1 != minu tes) {

S tring o bject s whil e (n ames. hasMo reEle ments ()) { */ * been sto pped

*/ // T he ma nager work s wit h se conds ...

/** * conta inin g the name s of the o bjec ts bo und t o thi s Stri ng na me = (Stri ng) n ames .next Eleme nt(); pri vate Stri ng th readN ame = "Sta ndar dMana ger"; * @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l err or

* Set t he s essio n ide ntifi er fo r th is se ssion . session . stre am.wr iteOb ject( name) ; * that nee ds to be r eport ed pri vate Mana ger m anage r = n ull; mana ger.s etMax Inact iveIn terv al(mi nutes * 60 );

* * stre am.wr iteOb ject( attri bute s.get (name )); */

}

* @para m id The new s essio n ide ntif ier * @exce ptio n Ill egalS tateE xcept ion if th is me thod is } // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- ---- Prope rties pub lic v oid stop( ) thr ows L ifecy cleE xcept ion {

*/ called on an }

pub lic v oid setId (Stri ng id ) { * inva lida ted s essio n // V alid ate a nd up date our c urre nt co mpone nt st ate

}

*/ } /** if ( !sta rted)

if ( (thi s.id != nu ll) & & (ma nage r != null) && pub lic E nume ratio n get Attri buteN ames () { * Retur n th e che ck in terva l (in sec onds) for this Manag er. thro w new Life cycle Excep tion

(m anag er in stanc eof M anage rBas e)) cro sscut inv alida te(St andar dSess ion s): s & (i nt ge tMaxI nact iveIn terva l() | */ (sm.g etStr ing(" stand ardM anage r.not Start ed")) ;

((Ma nager Base) mana ger). remo ve(th is); retu rn ( attri butes .keys ()); l ong g etCre atio nTime () | pub lic i nt g etChe ckInt erval () { star ted = fal se;

O bject getA ttri bute( Strin g) |

this .id = id; } E numer ation get Attri buteN ames( ) | retu rn ( this. check Inter val); // S top the b ackgr ound reape r th read

S tring [] ge tVal ueNam es() | thre adSt op();









ServerSess on

ServerSession

if ( (man ager != nu ll) & & (ma nage r ins tance of v oid i nvali date () | }

Manager Base) ) /** b oolea n isN ew() | // E xpir e all acti ve se ssion s

((Ma nager Base) mana ger). add( this) ; * Retur n th e obj ect b ound with the speci fied name in th is v oid r emove Attr ibute (Stri ng) | Sess ion sessi ons[] = fi ndSes sion s();

session , or v oid s etAtt ribu te(St ring, Obje ct)); /** for (int i = 0; i nul l i f no objec t is boun d wit h tha t nam e. * Set t he c heck inter val ( in se cond s) fo r thi s Man ager. Stan dardS essio n ses sion = (S tanda rdSes sion) sess ions [i];

* sta tic a dvic e(Sta ndard Sessi on s) : in valid ate(s ) { * if ( !sess ion.i sVali d())

* @para m na me Na me of the value to be re turne d befo re { * @para m ch eckIn terva l The new chec k int erval conti nue;

/** * if ( !s.is Valid ()) */ sess ion.e xpire ();

* Retur n de scrip tive infor matio n ab out t his * @exce ptio n Ill egalS tateE xcept ion if th is me thod is throw new Illeg alSta teEx cepti on pub lic v oid setCh eckIn terva l(int che ckInt erval ) { }

Session impl emen tatio n and called on an ( s.sm. getSt ring( "sta ndard Sessi on."









ServerSessionManager

ServerSess onManager

* the c orre spond ing v ersio n num ber, in t he * inva lida ted s essio n + th isJoi nPoin t.met hodNa me this .che ckInt erval = ch eckIn terv al; }

format * + ". ise") );

* * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d } }

package org. apac he.to mcat. sessi on; void va lidat e() { & lt;de scri ption >/ <v ersio n> ;. by } // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- --- Priva te Me thods

// i f we have an i nacti ve in terv al, c heck to se e if */ * ge tAttr ibute ()

import org.a pach e.tom cat.c ore.* ; // w e've exce eded it pub lic S trin g get Info( ) { */ /**

import org.a pach e.tom cat.u til.S tring Mana ger; pub lic O bjec t get Value (Stri ng na me) { * Retur n de scrip tive infor matio n ab out t his M anage r imp leme ntati on an d /**

import java. io.* ; if ( inac tiveI nterv al != -1) { retu rn ( this. info) ; * the c orre spond ing v ersio n num ber, in t he fo rmat * Inval idat e all sess ions that have expi red.

import java. net. *; int thisI nterv al = retu rn ( getAt tribu te(na me)); } * < ;desc ripti on> ;/< ;ver sion& gt; . */

import java. util .*; (int) (Syst em.cu rrent Time Milli s() - last Acces sed) / 10 00; } */ pri vate void proc essEx pires () {

import javax .ser vlet. *; } pub lic S trin g get Info( ) {

import javax .ser vlet. http. *; if ( thisI nterv al > inact iveI nterv al) { // ---- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- - Pri vate Class long tim eNow = Sys tem.c urren tTim eMill is();

inval idate (); /** retu rn ( this. info) ; Sess ion sessi ons[] = fi ndSes sion s();

/** * Retur n th e las t tim e the clie nt s ent a requ est /** // XXX

* Core impl emen tatio n of a ser ver s essi on Serve rSess ionMa nager ssm = associa ted w ith this * Retur n th e set of n ames of ob ject s bou nd to this /** package org. apac he.to mcat. sessi on; // sync' d fo r saf ty -- no o ther thre ad sh ould be ge tting som ethin g } for (int i = 0; i Ht tpSes sion Conte xt // from this whil e we are r eapin g. T his i sn't the m ost o ptim al Stan dardS essio n ses sion = (S tanda rdSes sion) sess ions [i];

* @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om] midnigh t, Ja nuar y 1, 1970 * are n o su ch ob jects , a z ero-l engt h arr ay is retu rned. * inte rface , to conf orm t o the requ irem ent t hat s uch a n obj ect be re turne d import org.a pach e.tom cat.u til.* ; // solut ion for t his, but w e'll dete rmine some thing else lat er. if ( !sess ion.i sVali d())

* @aut hor J ames Todd [gon zo@en g.sun .com ] ssm.r emove Sessi on(th is); * GMT. Act ions that your appli cati on ta kes, * * when Ht tpSes sion. getSe ssion Cont ext() is call ed. import org.a pach e.tom cat.c ore.* ; /** conti nue;

*/ } such as gett ing or se tting * @exce ptio n Ill egalS tateE xcept ion if th is me thod is * import java. io.* ; syn chron ized void reap () { * Retur n th e max imum numbe r of acti ve Se ssion s all owed, or -1 fo r int maxIn activ eInte rval = se ssion .getM axIna ctive Inte rval( );

} * a val ue a ssoci ated with the s essi on, d o not called on an * @aut hor C raig R. M cClan ahan import java. net. *; Enum erat ion e num = sess ions. keys (); * no li mit. if ( maxIn activ eInte rval = max Inact iveI nterv al)

pri vate Hash table valu es = new H asht able( ); retu rn ( this. lastA ccess edTim e); * ge tAttr ibute Names () * sessi on.ex pire( );

pri vate Hash table appS essio ns = new Hasht able( ); whil e (e num.h asMor eElem ents( )) { */ final c lass Stan dardS essio nCont ext i mple ments Http Sessi onCon text { * @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om] sess ion.r eap() ; } }

pri vate Stri ng id ; Obje ct ke y = e num.n extEl emen t(); } pub lic S trin g[] g etVal ueNam es() { * @aut hor J ason Hunt er [j ch@en g.sun .com ] sess ion.v alida te(); }

pri vate long crea tionT ime = Syst em.c urren tTime Milli s();; Appl icati onSes sion appSe ssio n = * @aut hor J ames Todd [gon zo@en g.sun .com ] }

pri vate long this Acces sTime = cr eati onTim e; (Appl icati onSes sion) appS essio ns.ge t(key ); Vect or r esult s = n ew Ve ctor( ); pri vate Vect or du mmy = new Vecto r(); */ } /**

pri vate long last Acces sed = crea tion Time; /** Enum erat ion a ttrs = get Attri bute Names (); * Set t he m aximu m num ber o f act ives Sess ions allow ed, o r -1 for /**

pri vate int inact iveIn terva l = - 1; appS essio n.inv alida te(); * Retur n th e Man ager withi n whi ch t his S essio n whil e (a ttrs. hasMo reEle ments ()) { /** public class Ser verSe ssion Manag er im plem ents Sessi onMan ager { syn chron ized void remo veSes sion( Serv erSes sion sessi on) { * no li mit. * Sleep for the durat ion s pecif ied by th e ch eckIn terv al

} is vali d. Stri ng at tr = (Stri ng) a ttrs .next Eleme nt(); * Retur n th e ses sion ident ifier s of all sessi ons d efine d Stri ng i d = s essio n.get Id(); * * prope rty.

Ser verSe ssio n(Str ing i d) { } */ resu lts.a ddEle ment( attr) ; * withi n th is co ntext . pri vate Stri ngMan ager sm = * @para m ma x The new maxim um nu mber of s essio ns */

this .id = id; pub lic M anag er ge tMana ger() { } * Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" ); sess ion. inval idate (); */ pri vate void thre adSle ep() {

} pub lic v oid putVa lue(S tring name , Ob ject value ) { Stri ng n ames[ ] = n ew St ring[ resu lts.s ize() ]; * @depr ecat ed As of J ava S ervle t AP I 2.1 with no r eplac emen t. pri vate stat ic Se rverS essio nMana ger manag er; / / = n ew Se rver Sessi onMan ager( ); sess ions .remo ve(id ); pub lic v oid setMa xActi veSes sions (int max) {

if ( name == n ull) { retu rn ( this. manag er); for (int i = 0; i Enu merat ion } try {

pub lic S trin g get Id() { Stri ng ms g = s m.get Strin g("s erver Sessi on.va lue.i ae") ; name s[i] = (St ring) resu lts. eleme ntAt( i); * and will be r emove d in a fut ure versi on of the API. pro tecte d in t ina ctive Inter val = -1; this .max Activ eSess ions = max ; Thre ad.sl eep(c heckI nterv al * 1000 L);

retu rn i d; } retu rn ( names ); */ pub lic v oid remov eSess ions( Conte xt c ontex t) { } ca tch (Inte rrupt edExc eptio n e) {

} thro w new Ille galAr gumen tExc eptio n(msg ); pub lic E nume ratio n get Ids() { sta tic { Enum erat ion e num = sess ions. keys (); } ;

} } mana ger = new Serv erSes sionM anag er(); }

pub lic l ong getCr eatio nTime () { /** retu rn ( dummy .elem ents( )); } whil e (e num.h asMor eElem ents( )) {

retu rn c reati onTim e; remo veVa lue(n ame); // remov e an y exi sting bind ing * Set t he M anage r wit hin w hich this Sess ion i s Obje ct ke y = e num.n extEl emen t(); // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- Publ ic Me thods }

} valu es.p ut(na me, v alue) ; valid. /** } pub lic s tati c Ser verSe ssion Manag er g etMan ager( ) { Serv erSes sion sessi on = (Ser verSe ssion )sess ions. get( key);

} * * Inval idat es th is se ssion and unbi nds a ny ob jects boun d retu rn m anage r; Appl icati onSes sion appSe ssio n =

pub lic l ong getLa stAcc essed Time( ) { * @para m ma nager The new M anage r to it. } sessi on.ge tAppl icati onSe ssion (cont ext, false ); /** /**

retu rn l astAc cesse d; pub lic O bjec t get Value (Stri ng na me) { */ * /** * Const ruct and retur n a n ew se ssio n obj ect, based on t he d efaul t * Start the back groun d thr ead t hat will perio dical ly ch eck for

} if ( name == n ull) { pub lic v oid setMa nager (Mana ger m anag er) { * @exce ptio n Ill egalS tateE xcept ion if th is me thod is * Retur n th e Ht tpSes sion as socia ted w ith t he pri vate Hash table sess ions = new Has htabl e(); if ( appSe ssion != n ull) { * setti ngs speci fied by th is Ma nage r's p roper ties. The ses sion * sessi on t imeou ts.

Stri ng ms g = s m.get Strin g("s erver Sessi on.va lue.i ae") ; called on * speci fied sess ion i denti fier. pri vate Reap er re aper; appSe ssion .inva lidat e(); * id wi ll b e ass igned by t his m etho d, an d ava ilabl e via the getI d() */

pub lic A ppli catio nSess ion g etApp lica tionS essio n(Con text cont ext, this .man ager = man ager; * an i nval idate d ses sion * } * metho d of the retur ned s essio n. If a new s essio n can not be cr eated pri vate void thre adSta rt() {

bool ean creat e) { thro w new Ille galAr gumen tExc eptio n(msg ); */ * @para m id Sess ion i denti fier for which to l ook u p a s essi on pri vate Serv erSes sionM anage r() { } * for a ny r eason , ret urn null .

Appl icat ionSe ssion appS essio n = } } pub lic v oid inval idate () { * reap er = Reap er.ge tReap er(); } * if ( thre ad != null )

(App licat ionSe ssion )appS essi ons.g et(co ntext ); * @depr ecat ed As of J ava S ervle t AP I 2.1 with no r eplac emen t. reap er.s etSer verSe ssion Manag er(t his); * @exce ptio n Ill egalS tateE xcept ion if a new s essio n can not be retu rn;

retu rn v alues .get( name) ; // C ause this sess ion t o exp ire * This met hod m ust r eturn null and will be r emove d in a reap er.s tart( ); /** * inst anti ated for a ny re ason

if ( appS essio n == null && cr eate ) { } /** expi re() ; * futu re v ersio n of the A PI. } * Used by c ontex t to confi gure the sessi on ma nager 's in acti vity timeo ut. */ thre adDo ne = false ;

* Retur n th e max imum time inter val, in s econd s, */ * pub lic S essi on cr eateS essio n() { thre ad = new Threa d(thi s, th read Name) ;

// X XX pub lic E nume ratio n get Value Names () { between clie nt r eques ts } pub lic H ttpS essio n get Sessi on(St ring id) { pub lic v oid acces sed( Conte xt ct x, R eques t req , Str ing i d ) { * The S essi onMan ager may h ave s ome defau lt se ssion time out , the thre ad.s etDae mon(t rue);

// s ync t o ens ure v alid? retu rn v alues .keys (); * befor e th e ser vlet conta iner will inva lidat e Appl icat ionSe ssion apS= (Appl icat ionSe ssion )find Sessi on( ctx, id); * Conte xt o n the othe r han d has it' s tim eout set b y the dep loyme nt if ( (max Activ eSess ions >= 0) && thre ad.s tart( );

} the ses sion. A negat ive retu rn ( null) ; if( apS= =null ) ret urn; * descr ipto r (we b.xml ). Th is me thod lets the Conte xt co nfor gure the (s essi ons.s ize() >= m axAct iveS essio ns))

appS essio n = n ew Ap plica tion Sessi on(id , thi s, co ntex t); * time indi cates that the sessi on s hould neve r /** * sessi on m anage r acc ordin g to this valu e. thro w new Ille galSt ateEx cept ion }

appS essio ns.pu t(con text, app Sessi on); pub lic v oid remov eValu e(Str ing n ame) { time ou t. * Retur n t rue if t he c lient does not yet k now } Serv erSe ssion serv S=apS .getS erve rSess ion() ; * (sm.g etStr ing(" stand ardM anage r.cre ateSe ssion .ise "));

} valu es.r emove (name ); * about t he serv S.ac cesse d(); * @para m mi nutes The sessi on in acti vity timeo ut in minu tes.

} * @exce ptio n Ill egalS tateE xcept ion if th is * sessi on, or if the clien t cho oses not to jo in th e } apS. acce ssed( ); */ retu rn ( super .crea teSes sion( )); /**

// X XX method is ca lled on session . Fo r pub lic v oid setSe ssion TimeO ut(in t mi nutes ) { * Stop the backg round thre ad th at i s per iodic ally check ing for

// m ake sure that we ha ven't gon e ove r the end of ou r pub lic v oid setMa xInac tiveI nterv al(i nt in terva l) { * an i nval idate d ses sion * examp le, if th e ser ver u sed o nly cooki e-bas ed se ssion s, // c ache it - no n eed t o com pute it a gain if(- 1 != minu tes) { } * sessi on t imeou ts.

// i nact ive i nterv al -- if s o, i nvali date and c reate inac tive Inter val = inte rval; */ and the clie nt req. setS essio n( ap S ); // T he ma nager work s wit h se conds ... */

// a new appS essio n } pub lic i nt g etMax Inact iveIn terva l() { * has d isab led t he us e of cooki es, then a ses sion would be } inac tiveI nterv al = (minu tes * 60) ; pri vate void thre adSto p() {

new on each }

retu rn a ppSes sion; pub lic i nt g etMax Inact iveIn terva l() { retu rn ( this. maxIn activ eInte rval ); * reque st. pub lic H ttpS essio n cre ateSe ssion (Con text ctx) { } if ( thre ad == null )

} retu rn i nacti veInt erval ; * Stri ng s essio nId = Sess ionId Gene rator .gene rateI d(); } retu rn;

} } * @exce ptio n Ill egalS tateE xcept ion if th is me thod is Serv erSe ssion sess ion = new Serv erSes sion( sessi onId) ;

voi d rem oveA pplic ation Sessi on(Co ntex t con text) { called on an sess ions .put( sessi onId, sess ion) ; thre adDo ne = true;

appS essi ons.r emove (cont ext); // XXX * inva lida ted s essio n thre ad.i nterr upt() ;

} // sync' d fo r saf ty -- no o ther thre ad sh ould be ge tting som ethin g /** */ if(- 1 != inac tiveI nterv al) { try {

// from this whil e we are r eapin g. T his i sn't the m ost o ptim al * Set t he m aximu m tim e int erval , in seco nds, pub lic b oole an is New() { sess ion. setMa xInac tiveI nterv al(i nacti veInt erval ); thre ad.jo in();

/** // solut ion for t his, but w e'll dete rmine some thing else lat er. between clie nt r eques ts } } ca tch (Inte rrupt edExc eptio n e) {

* Calle d by cont ext w hen r eques t co mes i n so that acces ses and * befor e th e ser vlet conta iner will inva lidat e retu rn ( this. isNew ); retu rn s essio n.get Appli catio nSes sion( ctx, true ); ;

* inact ivit ies c an be deal t wit h ac cordi ngly. syn chron ized void reap () { the ses sion. A negat ive } }

*/ Enum erat ion e num = appS essio ns.k eys() ; * time indi cates that the sessi on s hould neve r }

time ou t. pub lic H ttpS essio n fin dSess ion(C onte xt ct x, St ring id) { thre ad = null ;

voi d acc esse d() { whil e (e num.h asMor eElem ents( )) { * Serv erSe ssion sSes sion= (Serv erSe ssion )sess ions. get(i d);

// s et l ast a ccess ed to this Acce ssTim e as it wi ll be lef t ove r Obje ct ke y = e num.n extEl emen t(); * @para m in terva l The new maxim um i nterv al if(s Sess ion== null) retu rn nu ll; }

// f rom the p revio us ac cess Appl icati onSes sion appSe ssio n = */

(Appl icati onSes sion) appS essio ns.ge t(key ); pub lic v oid setMa xInac tiveI nterv al(i nt in terva l) retu rn s Sessi on.ge tAppl icati onSe ssion (ctx, fals e);

} // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- - Ba ckgro und T hread









9

last Acce ssed = thi sAcce ssTim e; {

this Acce ssTim e = S ystem .curr entT imeMi llis( ); appS essio n.val idate ();

} this .max Inact iveIn terva l = i nter val;

} } /**

} } * The b ackg round thre ad th at ch ecks for sessi on ti meout s an d shu tdown .

voi d val idat e() */

pub lic v oid run() {



// L oop until the termi natio n se mapho re is set

whil e (! threa dDone ) {

thre adSle ep();

proc essEx pires ();

}



}





}

Terminology (1)



 Concerns – is a particular goal, concept,

or area of interest. An engineering

process deals with many concerns. High

level vs. low level, localized vs. system

wide.

 Crosscutting concerns – concerns that in

conventional implementations cannot be

implemented without scattering code.

10

Terminology (2)



 Code tangling

– A module deals with several concerns

– Intermixed code blocks

 Code scattering

– Duplicated code blocks

– Complementary code blocks





11

Terminology (3)



 Aspect – a modular unit designed to

implement a concern. May include

code (called advice) and indication

where, when and how to invoke it.









12

Terminology (4)



 Join Points – well defined places in the

execution flow where additional

behavior can be attached.

 Advice – the behavior to execute at a

join point (before/after/instead).

 Pointcut designator – describes a set

of join points.



13

Terminology (5)



 Composition – bringing together

separately created software elements.

Different languages provide a variety

of composition techniques.

 Weaving - the process of composing

core functionality modules with

aspects, yielding a working system.



14

Terminology (6)



 Statics vs. dynamics – Static elements

determined before program execution

(typically at compile time). Dynamic things

happen at execution. The terms refer to eg.

weaving, join points, etc.

 The tyranny of the dominant decomposition

– programs can be modularized in one way

– concerns that do not align with that

modularization are scattered and tangled

15

Papers – partial source



 Aspect-Oriented Software

Development Robert E. Filman, Tzilla

Elrad, Siobhán Clarke, Mehmet Aksit

 another link

 A collection of papers (2005)

 Additional papers – other topics in

Programming Languages.

 Topic that you propose.

16

List of Papers



1. Principles and Design Rationale of

Composition Filters

2. AspectJ - First lecture!!

3. Trace-Based Aspects + Stateful

Aspects

4. Using Mixin Technology to Improve

Modularity

17

List of Papers (cont)



5. Supporting AOP Using Reflection

6. Using Bytecode Transformation to

Integrate New Features

7. Expressing Aspects Using UML

Behavioral and Structural Diagrams







18

Other papers



8. The Spec# programming

system: An overview.

9. Shakeins: Nonintrusive Aspects for

Middleware Frameworks

10. JTL: the Java tools language.

11. Non-null References by Default in

Java

19

Other papers (cont.)



12. An Overview of CaesarJ.

13. Traits: Composable Units of Behavior (The

Scala Programming Language?)

14. The Java Modeling Language (JML)

15. Design Pattern Implementations in Java

and AspectJ

16. design patterns in C#3.0

17. The Spring Framework and Spring AOP

20

Other papers (cont.)



18. Fortress -- programming language

designed for high-performance computing

19. X10 -- type-safe, parallel object-oriented

language

20. The paradoxical success of aspect-oriented

programming

21. Expressing Design by Contract principles

using Aspects



21

The wrong way

 Consider the next class :



public class SomeBusinessClass extends

OtherBusinessClass

{

// Core data members

// Override methods in the base class

public void

performSomeOperation(OperationInformation info)

{

// ==== Perform the core operation ====

}

}





22

The wrong way(2)

 But what about logging capabilities ?



public class SomeBusinessClass extends

OtherBusinessClass

{

// Core data members

...Log stream ;

// Override methods in the base class

public void

performSomeOperation(OperationInformation info)

{

...log the start of operation

// ==== Perform the core operation ====

...log the complition of operation

}

}

23

The wrong way(3)

 Actually, we want it multithreaded…



public class SomeBusinessClass extends

OtherBusinessClass

{

// Core data members

...Log stream ;

// Override methods in the base class

public void

performSomeOperation(OperationInformation info)

{

...lock the object – thread safety

...log the start of operation

// ==== Perform the core operation ====

...log the complition of operation

...unlock the object

} 24

}

The wrong way(4)



 Who enforces your contract ?



public class SomeBusinessClass extends OtherBusinessClass

{

// Core data members

...Log stream ;

// Override methods in the base class

public void

performSomeOperation(OperationInformation info)

{

...ensure info satisfies contract

...lock the object – thread safety

...log the start of operation

// ==== Perform the core operation ====

...log the complition of operation

...unlock the object

}

} 25

The wrong way(5)

 Authorization ? Authentication ?



public class SomeBusinessClass extends OtherBusinessClass

{

// Core data members

...Log stream ;

// Override methods in the base class

public void

performSomeOperation(OperationInformation info)

{

...ensure authorization

...ensure info satisfies contract

...lock the object – thread safety

...log the start of operation

// ==== Perform the core operation ====

...log the complition of operation

...unlock the object

}

} 26

The wrong way(6)

 Persistence ? Cache consistency ?



public class SomeBusinessClass extends OtherBusinessClass

{

// Core data members

...Log stream ;

...cache update_status ;

// Override methods in the base class

public void performSomeOperation(OperationInformation info)

{

...ensure authorization

...ensure info satisfies contract

...lock the object – thread safety

...ensure cache is up to date

...log the start of operation

// ==== Perform the core operation ====

...log the complition of operation

...unlock the object

}

public void save(PersitanceStorage ps) {...}

public void load(PersitanceStorage ps) {...} 27

}

Breaking modularity



 Got the picture ?

 Non-modularization

due to client-server

nature of OOP

 Current popular

solution EJB,

servlets, dynamic

proxies



28

How does AOP do it ?









AOP development stages

29

More AOP and AspectJ



 Book:

AspectJ in Action

Practical Aspect-

Oriented

Programming

Ramnivas Laddad









30

More AOP and AspectJ

 Online Documentation:

http://dev.eclipse.org/viewcvs/indextech.cgi/~checkout

~/aspectj-home/doc/index.html



 Mailing list:

http://aosd.net/









31



Related docs
Other docs by dandanhuanghua...
CSCE_Postgrad_Research_Students_Guidelines
Views: 0  |  Downloads: 0
F
Views: 6  |  Downloads: 0
SDS_User_Manual
Views: 3  |  Downloads: 0
systémy - FEL wiki
Views: 0  |  Downloads: 0
Alan Kalter - Bio 020812
Views: 0  |  Downloads: 0
Battery Balancer - Control Board
Views: 0  |  Downloads: 0
cocuk_1_erkekler
Views: 0  |  Downloads: 0
CARLSON.TESTIMONY
Views: 0  |  Downloads: 0
New_York_2011_info_letter_1_
Views: 0  |  Downloads: 0
By registering with docstoc.com you agree to our
privacy policy

You are almost ready to download!

You are almost ready to download!