Lecture 7 Aspect-orientation (AO*)

A new paradigm in Software Engineering

Copyright © Yijun Yu, 2005

Spring 2005 ECE450H1S Software Engineering II Last lecture and tutorial … Software Quality Measurements • We have shown the use of quality measurements to monitor the progress of software development • The development/restructuring (maintenance) activities (refactoring, tuning, adding features) can be guided by the metrics of softgoals

Spring 2005 ECE450H1S Software Engineering II Today … On Aspect Orientation • Today we explain the paradigm of aspect- orientation 1. Concepts: What are aspects? 2. Practices: Aspect-orientation at large – AOP: Aspect-oriented programming – AOSD: Aspect-oriented software development – AORE: Aspect-oriented requirements engineering – AOSR: Aspect-oriented software reuse (probably next lecture) 3. A case study of AORE 4. Summary

Spring 2005 ECE450H1S Software Engineering II 1. What are aspects?

1. Some design principles • Divide and conquer: problem solving/design principle • Modularization: high cohesion/low coupling Separation of concerns • DRY: Don’t Repeat Yourself Increase the fan-in 2. Previous paradigms • 70s – 80s: Structured programming (Goto’s considered harmful) => Structured Analysis, Structured Design • 80s – 90s: Object-oriented programming (OOP) => OOA/OOD => UML 3. Why another paradigm ? • Since late 90s … Separation of the crosscutting concerns 4. What are aspects? – Modularizing the crosscutting concerns

Spring 2005 ECE450H1S Software Engineering II 1.1 Some design principles Structured programming • What is structured program? – A program has no more GOTO’s – Only three kinds of structure prevails • Sequential • If-then-else • Loops [Dijkstra: Goto considered harmful] – In other words, every statement block has single-entry, single-exit as Hammock Graph [Weiser: Program slicing] • “Whenever possible, we wish to maximize fan-in during the design process. Fan-in is the raison d’être of modularity. Each instance of multiple fan-in means that some duplicate code has been avoided.” raison d'être: grounds for existence (http://www.french-linguistics.co.uk/dictionary/) [Yourdon & Constantine79] Structured Design (pg. 172, see also http://wwwpa.win.tue.nl/wstomv/quotes/structured-design.html) [parnas: Modularization, information hiding]

Spring 2005 ECE450H1S Software Engineering II (1) A decomposition hierarchy from abstract to concrete: Divide and Conquer, Structured Design; (2) Don’t Repeat Yourself, Factoring / Refactoring …

C C

CC C

C

Spring 2005 ECE450H1S Software Engineering II Example

MOVE UNTIL VALUE

FIND SCAN

REMOVALL

STRINGCOMP

Yourdon & Constantine, SD, pg.168

Spring 2005 ECE450H1S Software Engineering II 1.1 Some design principles Object-oriented programming • Everything is an object () • Information hiding / Encapsulation: object groups related data and the operations on the data into a module • Object has structural relationships: – inheritance: generalization / specialization: isA/instanceOf – aggregation : hasA / isPartOf – associations: 1-to-many, 1-to-1, many-to-many • In the end, the structurally-related objects are packaged into components

Spring 2005 ECE450H1S Software Engineering II 1.2 Aspect-orientation • Component language (any structured or OO language, even corresponding design and requirements specification) • What are crosscutting concerns? • An aspect language – What are joinpoints? – What are pointcuts? – What are advices? • A weaving mechanism

Spring 2005 ECE450H1S Software Engineering II Aspect concepts

• Concepts: cross-cutting, AOP hides the join points component, aspect, join points, weaving

C Aspect

Spring 2005 ECE450H1S Software Engineering II AOP (THE MAGIC)

MOVE UNTIL VALUE

FIND SCAN

REMOVALL

STRINGCOMP

Spring 2005 ECE450H1S Software Engineering II AOP (NOT REALLY MAGIC)

VALUE

MOVE UNTIL

FIND SCAN

REMOVALL FIND: AT LINE 5 VALUE: AT LINE7 SCAN: AT LINE 15 MOVE UNTIL: AT LINE 8 REMOVALL: AT LINE 2 STRINGCOMP

Spring 2005 ECE450H1S Software Engineering II AOP example

ApplicationSession StandardSession privat e lon g la stAcc essed = cr eatio nTim e; if (ina ctive Inte rval != -1 ) { stream. write Obje ct(ne w Lon g(las tAcce ssed Time) ); pri vate int inact iveIn terva l = - 1; int thisI nterv al = (int) (Syst em.cu rrent Time Milli s() - void a ccess ed() { lastAcc essed ) / 1000; // s et l ast a ccess ed to this Acce ssTim e as it wi ll be lef t ove sM.acc essed (ctx , req uest, sess ionId ); // f rom the p revio us ac cess if ( thisI nterv al > inact iveI nterv al) { last Acce ssed = thi sAcce ssTim e; inval idate (); public void acc essed ( Con text ctx, Requ est r eq, S tring id ) { /* public void inva lidat e() { package org. apac he.to mcat. sessi on; /** this Acce ssTim e = S ystem .curr entT imeMi llis( ); Appl icat ionSe ssion apS= (Appl icat ionSe ssion )find Sessi on( ctx, * ======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 Serve rSess ionMa nager ssm = id); * * Retur n th e Ht tpSes sion< /cod e> 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 vali date (); S erver Sessi onMan ager .getM anage r(); if( apS= =null ) ret urn; * 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. *

ssm.r emove Sessi on(th is); Serv erSe ssion serv S=apS .getS erve rSess ion() ; * 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 voi d val idat e() { } serv S.ac cesse d(); * 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< /code >, th e con taine r ca lls // i f we have an i nacti ve in terv al, c heck to se e if we'v e exc eeded } apS. acce ssed( ); * Stri ng na me = (Stri ng)en um.n extEl ement (); import java. util .Enum erati on; * val ueBou nd()< /code > on the objec t. it } * 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); * if ( inac tiveI nterv al != -1) { // c ache it - no n eed t o com pute it a gain * 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 int thisI nterv al = privat e lon g la stAcc essed Time = cre atio nTime ; req. setS essio n( ap S ); * 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 (int) (Syst em.cu rrent Time Milli s() - last Acces sed) / 10 00; * 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 if ( thisI nterv al > inact iveI nterv al) { * 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 inval idate (); /** * pub lic b oole an is New() { import javax .ser vlet. http. HttpS essio nCon text; Session Publ ic M ethod s * } /** * Retur n th e las t tim e the clie nt s ent a requ est * 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 } * Inval idat e all sess ions that have expi red. associa ted w ith this * 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 () } */ * sessi on, as th e num ber o f mil lise conds sinc e mid night , * t he do cume ntati on an d/or other mat erial s pro vided with the /** */ pri vate void proc essEx pires () { January 1, 1 970 * 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 ) { public long get LastA ccess edTim e() { * GMT. Act ions that your appli cati on ta kes, such as * } /** This *m e Ptehrofdo rm t he in terna l pro cessi ng r equir ed to inva lidat e if ( vali d) { long tim eNow = Sys tem.c urren tTim eMill is(); getting or s etti ng * 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< /b> this s*e sshioounl ,d be call ed by the conte xt w hen a requ est c omes in setA ttri bute( name, valu e); retu rn la stAcc essed ; Sess ion sessi ons[] = fi ndSes sion s(); * a val ue a ssoci ated with the s essi on, d o not affe ct th 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 wairthioc utl atr rigge ring an ex cepti on i f the sess ion h as } el se { access time. * "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 alread*y sexspsi roend,. even if th e app licat ion does not r efere nce i t. } Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); for (int i = 0; i < ses sions .len gth; i++) { */ * Ap ache Soft ware Found ation (ht tp:// www.a pache .org/ )." } el se { persist ent s tora ge or tran sferr ed */ Stan dardS essio n ses sion = (S tanda rdSes sion) sess ions [i]; pub lic l ong getLa stAcc essed Time( ) { * 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 eaxcpciers es() { thro w new Ille galSt ateEx cept ion(m sg); if ( !sess ion.i sVali d()) itself, } support . /** } conti nue; retu rn ( this. lastA ccess edTim e); * i f and whe rever such thir d-par ty a cknow legem ents norma lly appea r. } *

/t/h iRs e.mloavs et Atchcie s sseedsT siimoen = f rtohmi s o.utrh i msaAncacge esrs'esd T aicmtei;v e * Remov e th e obj ect b ound with the speci fied name from this sess ion. If } int maxIn activ eInte rval = se ssion .getM axIna ctive Inte rval( ); * * I MPLEM ENTA TION NOTE< /b>: An i nsta nce o f thi s session sthis .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 if ( maxIn activ eInte rval < 0) } * 4. T he na mes "The Jakar ta Pr oject ", " Tomca t", a nd "A pache Sof tware class r epres ents both the itfh i(s (.miasnN aegwe=rf a !l=s en;u ll) & & (ma nage r ins tance of * does noth ing. conti nue; * 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 Manag}er Base) ) *

public long get LastA ccess edTim e() { int timeI dle = // T runca te, do no t rou nd up derived * @depr ecat ed (HttpSe ssion ) vi ew of the sessi on. ((Ma nager Base) mana ger). remo ve(th is); * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts retu rn l astAc cesse d; (int) ((ti meNow - se ssio n.get LastA ccess edTim e()) / this .las tAcce ssedT ime = time ; * 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< /code >, th e con taine r ca lls } 1000L); * p ermis sion , ple ase c ontac t apa che@ apach e.org . public, Java log ic ou tside /** // U nbin d any obje cts a ssoci ated with this sess ion * val ueUnb ound( ) o n th e obj ect. if ( timeI dle > = max Inact iveI nterv al) * pub lic v oid putVa lue(S tring name , Ob ject value ) { * of t he org.a pache .tomc at.se ssio n * PVeercfto orrm rt ehseu litn st e=r nna elw pVreo cteosrs(i )n;g r equir ed to inva lidat e * sessi on.ex pire( ); * 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 sEsniuomn e,rat ion a ttrs = get Attri bute Names (); * @para m na me Na me of the objec t to remo ve fr om th is se ssio n. privat e lon g la stAcc essed = cr eatio nTim e; /** } * 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 * wwihtihlo eu t( at trtirgsg.e hraisnMgo raenE leex mcenptsi (o)n) i {f the sess ion h as * * Updat e th e acc essed time info rmat ion f or th is se ssion . } * p ermis sion of t he Ap ache Group . Session view . already expi Srterdi. ng at tr = (Stri ng) a ttrs .next Eleme nt(); * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n This me thod void a ccess ed() { * pub lic v oid setAt tribu te(St ring name , Obj ect v alue) { * */ resu lts.a ddEle ment( attr) ; * inva lida ted s essio n * shoul d be call ed by the conte xt w hen a requ est c omes in // s et l ast a ccess ed to this Acce ssTim e as it wi ll be lef t ove r * 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 l}ic v oid expir e() { */ for a p artic ular // f rom the p revio us ac cess * 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 Enum erat ion n ames = res ults. elem ents( ); pub lic v oid remov eAttr ibute (Stri ng n ame) { * sessi on, even if th e app licat ion does not r efere nce i t. * OF M ERCHA NTAB ILITY AND FITNE SS FO R A PARTI CULAR PURP OSE A RE 17:54:1 0 $ w/h/i lR e m(onv aem etsh.i hsa sMeos rseiEolne mfernotms (o)u)r {manag er's activ e */ last Acce ssed = thi sAcce ssTim 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 Stri ng na me = (Stri ng) n ames .next Eleme nt(); sync hron ized (attr ibute s) { pub lic v oid acces s() { this Acce ssTim e = S ystem .curr entT imeMi llis( ); * ITS CONTR IBUT ORS B E LIA BLE F OR AN Y DI RECT, INDI RECT, INCI DENT AL, } if ( r(emmaon vaegAetrt r!i=b untu el(ln)a m& e&) ;(ma nage r ins tance of Obje ct ob ject = att ribut es.g et(na me); * Mark the speci fied sessi on's last acce ssed time. Thi s sh ould be * SPEC IAL, EXEM PLARY , OR CONSE QUENT IAL DAMAG ES (I NCLUD ING, BUT NOT final c lass Stan dardS essio n Manager B}ase) ) if ( objec t == null) this .las tAcce ssedT ime = this .thi sAcce ssedT ime; } * calle d fo r eac h req uest by a Requ estIn terce ptor. * 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; this .thi sAcce ssedT ime = Syst em.c urren tTime Milli s(); * 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") ; // M ark this sessi on as inva lid attr ibute s.rem ove(n ame); this .isN ew=fa lse; * * ON A NY TH EORY OF L IABIL ITY, WHETH ER I N CON TRACT , STR ICT L IABI LITY, s/e/t VU anlbidn (df alnsy e )o;bje 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 ) { * @para m se ssion The sessi on to be marke d void va lidat e() { * 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) ); // i f we have an i nacti ve in terv al, c heck to se e if lastAc cesse dTim e = 0 L; * ======remo veVa lue(n ame); // remov e an y exi sting bind ing Stri ng at tr = (Stri ng) a ttrs .next Eleme nt(); } // w e've exce eded it pub lic v oid acces sed(C ontex t ctx , Re quest req, Stri ng id ) { * /** /** resu lts.a ddEle ment( attr) ; } lastAc cesse dTim e = ( (Long ) str eam.r eadO bject ()).l ongVa lue() ; Http Sess ion s essio n=fin dSess ion( ctx, id); * 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 * Re}lea se a ll ob ject refer ences , an d ini tiali ze in stanc e maxI nact iveIn terva l = ( (Inte ger) if( sess ion = = nul l) re turn; * 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. variabl esE,n uim nerat ion n ames = res ults. elem ents( ); } stream. readO bjec t()). intVa lue() ; * 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) ; * * prwehpial rea t(in oanm efso. rh arseMuo sre Eolfe mtehnits (o)b)j e{ct. isNe w = ((Boo lean) stre am.re adOb ject( )).bo olean Value (); if ( sess ion i nstan ceof Sessi on) * . * @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 pub lic v oriedm o rvecAytct lrei(b)u t {e(nam e); /** ((Se ssion ) ses sion) .acce ss() ; * [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) { // R eset the insta nce v ariab les assoc iated with this * 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) ; Session // M ark this sessi on as inva lid * does noth ing. // c ache the HttpS essio n - a void anot her f ind } supe r(); astetrV iabluitd e(sf.aclls ea)r;() ; *

req. setS essio n( se ssion ); this .man ager = man ager; crea tion Time = 0L; * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts /** } id = nul l; * Htt pSess ionBi nding Liste ner< /code >, th e con taine r ca lls } package org. apac he.to mcat. sessi on; * @depr ecat ed } manager = nu ll; * val ueUnb ound( ) o n th e obj ect. */ maxI nact iveIn terva l = - 1; * import org.a pach e.tom cat.c ore.* ; pub lic O bjec t get Value (Stri ng na me) { /** isNe w = true; * @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); // ------* RieslVea lsied a =l lf aolb sje;ct 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. *; * p/r/e pTa erlalt i ounr fMo arn argeeu rs et hoaf t tthhiis s oSbej sescito.n has been recyc led * inva lida ted s essio n import java. util .*; pub lic O bjec t get Attri bute( Strin g na me) { */ if ( (man ager != nu ll) & & (ma nage r ins tance of * import javax .ser vlet. *; if ( ! va lid) { /** Managpeurb Blaisce )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 ((Ma nager Base) mana ger). recy cle(t his); * 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); */ Sess}ion 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) { // --i-d- -= - -n-u-l -l-;------Sess ion * @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") ; /** Package Mleatsht oAdcsce 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; SessionInterceptor StandardManager StandardSessionManager } * Janua ry 1 , 197 0 GMT . /** isNe w = true; /** public class App licat ionSe ssion impl emen ts Ht tpSes sion { */ * ReitsuVra nl itdh e= ;is Valid f lag f or th is se ssion . * 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 package org. apac he.to mcat. reque st; pri vate Stri ngMan ager sm = } boo le/a/n T ieslVla loiudr( )M a{nage r tha t thi s Se ssion has been recyc led * repla ced. pub lic i nt b efore Body( Requ est r requ est, Respo nse r espon se ) { 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 *

import org.a pach e.tom cat.c ore.* ; Stri ng r eqSes sionI d = r espon se.g etSes sionI d(); pri vate Hash table valu es = new H asht able( ); /** /** Manager Braesteu) r)n ( this. isVal id); * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts 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 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< /code >, th e con taine r ca lls 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 Serv erSes sion serve rSess ion; */ */ } * val ueBou nd()< /code > on the objec t. import java. net. *; retu rn 0; // ------Li fecyc le Me thods Methods pri vate Cont ext c ontex t; pub lic S trin g[] g etVal ueNam es() { pri vate Stri ng id = nu ll; } * import java. util .*; import java. io.I OExce ption ; 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 javax .ser vlet. http. *; import java. util .Enum erati on; import java. io.I OExce ption ; 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 // G S, s et th e pat h att ribut e to the cooki e. Th is wa y import java. util .Hash table ; /** // XXX shoul d we thro w exc eptio n or just retu rn nu ll ?? privaptrei vbaotoel elaong v allaisdt A=c cters use;d = crea tion Time; /** /*/ S-e-t- -t- h-e- -<- c-o-d-e->- i-s-N-e-w- <-/-c-o-d- e->- -f-l- a-g- -f- o-r- -t-h- i-s- -s-e- s-s-i-o-n- .Sess ion * import javax .ser vlet. http. Cooki e; /** // 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 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 Packa*ge Meth ods * @exce ptio n Ill egalA rgume ntExc epti on if an a ttemp t is made to a dd a /p*u*b lic H ttpS essio n fin dSess ion( Cont ext c tx, S tring id ) { * 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; Apprpi lviactaet ibonoSl esasniov na(lSitdr i=n gtriu de,; Se rver Sessi on se rverS essio n, name s.add Eleme nt(e. nextE leme nt()) ; Session impl emen tatio n. * @para m is New T he ne w val ue fo r th e is New * non- seri aliza ble o bject in a n en viron ment marke d dis trib utabl e. * 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 < code> start () * Matrky t{he speci fied sessi on's last acce ssed time. Thi s sh ould be Cont ext conte xt) { } */ flag * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n import org.a pach e.tom cat.c atali na.*; * 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 . App ltihciast .isoenrS veesrsSieo sns(iSotnr i=n gsei rdv,e rSSe ersvseir oSne;ssi on se rverS essio n, pri vate stat ic fi nal S tring info = /*/* * inva lida ted s essio n * calle dS efsos ri oena cs he srseiqo une s=t m bayn aag e Rre.qfui ensdtSIens tseirocne( pitdo)r;. * 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; tChoinst .ecxotn tceoxnt e =x tc)o n{ text; Stri ng[] valu eName s = n ew St ring [name s.siz e()]; "Standa rdSes sion /1.0" ; vo*i dR esteutr Nne wt(h beo ois NVeawl)i d { f lag f or th is se ssion . */ * 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 * if(s essio n!=nu ll) this .isde r =v eirdS;e ssion = se rverS essi on; */ pub lic v oid setAt tribu te(St ring name , Obj ect v alue) { import org.a pach e.tom cat.c ore.R eques t; * 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?) this .con text = con text; name s.co pyInt o(val ueNam es); boo ltehains .iissVNa elwid=( ) i s{New ; * @para m se srseitounr nT hse s seisosni. ogne ttSoe sbsei o mna(r)k;e d * // 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; this .inda c=t ivde; Inter val = cont ext. getSe ssion TimeO ut(); /** if ( (man ager != nu ll) & & man ager .getD istri butab le() && */ 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 */ } ca tch (IOEx cepti on e) { 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)) import org.a pach e.tom cat.c ore.S essio nMan ager; 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 itfh i(s t.hiinsa .citniavce tIinvteIr nvtaelrv= a lco!n=t e-x1t). g{etSe ssion TimeO ut(); */ thro w new Ille galAr gumen tExc eptio n pub li}c v oid acces sed(C ontex t ctx , Re quest req, Stri ng id ) { if(n ull ! = jvm Route ) { * Stan dard impl ement ation of t he Man ager< /b> 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; this .inac tiveI nterv al *= 60; } pri vate long last Acces sedTi me = crea tionT ime; } (sm.g etStr ing(" stand ardS essio n.set Attri bute. iae" )); // 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 Hrtetpu Srens s( inounlls) e;ssio n=fin dSess ion( ctx, id); }if ( this .inac tiveI nterv al != -1) { /** 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. */ } this .inac tiveI nterv al *= 60; pub lic E nume ratio n get Attri buteN ames () { /** * Set t he < code> isVal id flag for this sessi on. sync hron ized (attr ibute s) { } if( sess ion = = nul l) re turn; int debu g=0; } *

pub lic v oid confi gure( Node param eter s) } if ( ! va lid) { /** The M anag er wi th wh ich t his S essi on is /** remo veAtt ribut e(nam e); 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) S}er verSe ssio n get Serve rSess ion() { Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); associ*a tTehde. M anag er wi th wh ich t his S essi on is * @Speatr at mhei s< Vcaoldied> iTshNe w nu ef l faogr f tohre th is se ssion . attr ibute s.put (name , val ue); /** Cook ie c ookie = ne w Coo kie(" JSES SIONI D", * in t he fo llow ing f ormat : retu rn s erver Sessi on; assoc*i/a ted. *i sVali d flag if ( value inst anceo f Htt pSes sionB indin gList ener) pub lic H (t(tSpeS sesisoino )n scerse saitoenS)e .sascicoen s(sC(o)n ;text ctx) { 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 }Ser verSe ssio n get Serve rSess ion() { thro w new Ille galSt ateEx cept ion(m sg); p*r/i vate Mana ger m anage r = n ull; */ @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 } 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) retu rn manag er.cr eateS essio n(). getSe ssion (); retu rn s erver Sessi on; } pri vate Mana ger m anage r = n ull; flagvoi d set Vali d(boo lean isVal id) { ( new H ttpSe ssion Bind ingEv ent(( HttpS essio n) t his, name) ); * that adap ts t o the new compo nent- base d Man ager imple menta tion . 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 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 ")); *

* Calle d by cont ext w hen r eques t co mes i n so that acces ses and Hash tabl e val uesCl one = (Has htab le)va lues. clone (); /** voi dt hsiest .NieswV( abloiodle =a nisiVs aNleiwd); { Syst em.o ut.pr intln ("Set debu g to " + i); * conf igur ed = true; req. setS essio n( se ssion ); /* * inact ivit ies c an be deal t wit h ac cordi ngly. /** The m axim um ti me in terva l, in sec onds, betw een } } * XXX - At pres ent, use o f St anda rdMan ager< /code > is hard code d, 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) */ 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( ); client* rTehqeu em satxsi m buemf otri eme in terva l, in sec onds, betw een this .isN ew = isNew ; }/** } 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. * inact ivit ies c an be deal t wit h ac cordi ngly. } clien*t trheeq ues setrsv l beetfocro entain er ma y inv alid ate t his cook ie.s etVer sion( 0); *

    * Remov e al l ses sions beca use o ur a ssoci ated Conte xt is bei ng sh ut */ sessio*n .t h eA s neergval teitvec o tnitmaein er ma y inv alid ate t his /}/ ------// ------Htt pSess ion Priva te Me thods *

    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 down. // HTTP SESS ION I MPLEM ENTAT ION M ETHO DS sessi*o n i.n d iAc anteegsa ttihvaet ttihme sessi on sh ould neve r tim e HttpSes sion Prop ertie s // XXX s houl d we throw exce ption or just retur n nul l ?? 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< /b>: Once we commi t to the n ew voi d acc esse d() { /** out. * indic ates that the sessi on sh ould neve r tim e * } *
  • 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 ) { pub li/c/ Ss terti nl ga sgte ta Icdc(e)s s {ed to this Acce ssTim e as it wi ll be lef t ove r * @depr ecat ed out. */ /** /** 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 m ct x The cont ext t hat i s be ing s hut d own i/f/ (f vraolmi dt)h e{ p revio us ac cess */ p*r/i vate int maxIn activ eInte rval = -1 ; /** Set t he < code> 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 * para digm, I w ould sugge st mo ving the logic impl ement ed he re b ack i nto try { 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; last rAectcue rsns eidd ;= thi sAcce ssTim e; pri vate int maxIn activ eInte rval = -1 ; * Retur n th e tim e whe n thi s ses sion was creat ed, i n * objec t in put s tream . */ 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); }t heils sAec c{e ssTim e = S ystem .curr entT imeMi llis( ); pub lic v oid remov eValu e(Str ing n ame) { millis*e c@opnadrsa msins cVealid The new v alue for the *

    * 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") ; pub lic v oid remov eSess ions( Conte xt c tx) { Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); remo veAt tribu te(na me); /** i msiVdanli gdhu afrlya g1 , 197 0 GMT . * IM PLEM ENTAT ION N OTE: The refer ence to th e own ing Manag er * 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) 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) { vali date (); } /** Flag indi catin g whe ther this sess ion i s new or */ * is no t re store d by this metho d, a nd mu st be set expli citl y. */ * 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(); } thro w new Ille galSt ateEx cept ion(m sg); not. * Flag indi catin g whe ther this sess ion i s new or v*o i @de xsceet pVtailoi nd (Iblolo elgealnS tiastVeaEl xicde)p t{ ion if th is me thod is * for( int i=0; i setCh eckIn terva l(Int eger .pars eInt( node. getNo deVa lue() )); // X XX X XX a manag er ma y be shar ed by mult iple } pub lic v oid remov eAttr ibute (Stri ng n ame) { not. */ called on an * @para m st ream The i nput strea m to read from *

    } ca tch (IOEx cepti on e) { Cook ie co okie = coo kies[ i]; thro ws T omcat Excep tion * } ca tch ( Throw able t) { }voi d val idat e() { if ( ! va lid) { p*r/i vate bool ean i sNew = tru e; * itnhvias l.idsaV taeldi ds e=s siisoV nalid; * // c onte xts, we ju st wa nt to rem ove t he se ssion s of ctx! { * @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) } // 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 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 // T he m anage r wil l sti ll ru n af ter t hat ( i.e. keep dat abase pub licf l( oinga c gteitvCerI enatteirov naTlim!e= ( )- 1{) { pub lic l ong getCr eatio nTime () { * @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s retu rn ( null) ; sessi onId = coo kie.g etVa lue() ; ctx. getS essio nMana ger() .remo veSe ssion s(ctx ); */ } if ( vianlti dt)h i{sI nterv al = thro w new Ille galSt ateEx cept ion(m sg); /** */ * a Co ntext to tell the M anage r tha t we crea te wh at th e def ault sess ion // c onne ction open sessi onId= valid ateSe ssio nId(r eques t, se ssion Id); } } retu r(ni nctr) e(aStyisot neTmi.mceu ;rrent Time Milli s() - last Acces sed) / 10 00; } /* * Flag indi catin g whe ther this sess ion i s val id // -r-e-t-u- r-n- -(- t-h-i-s-.- c-r-e-a-t- i-o-n-T-i- m-e-)-;------pri vate void read Objec t(Obj ectIn putS tream stre am) 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 if ( mana ger i nstan ceof Lifec ycle ) { } el se { or not*. 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 { r eques t.set Reque sted Sessi onIdF romCo okie( true ); ext ends Mana gerBa se if ( node != n ull) { descrip tor) Sitfr i( ntgh imssI gnt=e rsv ma.lge>t Sitnraicnt gi(v"eaI pnptleircv atli)o n{ Sessi on.se ssio n.ise "); if ( name == n ull) { or no*t/. } try { } } imp lemen ts L ifecy cle, Runna ble { try { pub lic H ttpS essio n cre ateSe ssion (Con text ctx) { inval idate (); Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ; pr*i/ vate bool ean i sVali d = f alse; // D eser ializ e the scal ar in stan ce va riabl es (e xcept Man ager) * shou ld be . } setMa xActi veSes sions (Int eger. parse Int(n ode.g etNo deVal ue()) ); ((Lif ecycl e) ma nager ).st op(); thro w new Ille galSt ateEx cept ion(m sg); crea tion Time = ((L ong) strea m.re adObj ect() ).lon gValu e(); retu rn manag er.cr eateS essio n(). getSe ssion (); } pri vate bool ean i sVali d = f alse; /** } ca tch ( Throw able t) { * } } ca tch ( Lifec ycleE xcept ion e) { } 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( ); // ------Ins tance Vari ables ; // XXX - Thr ow e xcept ion? } } } /** milli*s e Rceotnudrs n stihn ec eses sion conte xt wi th w hich this sessi on is isValid =l a(s(t BAococle esasne)d T sitmreea= m .(r(eLao dnOgb)j es cttr(e)a )m.broeoa ldeOabnjVe acltu(e)() ).;long Valu e(); * @aut hor C raig R. M cClan ahan Stri ng s ig="; jsess ionid ="; } throw new Illeg alSta teEx cepti on("" + e) ; /* * The s trin g man ager for t his p acka ge. associ*a tmeid.ni ght, Janu ary 1 , 197 0 GMT . maxI nact iveIn terva l = ( (Inte ger) stre am.re adObj ect() ).in tValu e(); int foun dAt=- 1; } */ /*/* 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. * /i/s NDe ewse=r i(a(lBiozo eletahne) asttrre iabmu.tre acdoOub njte catn( d) )a.tbto roilbeuatn eV avlaule u(e)s; } if( debu g>0 ) cm.l og(" XXX R URI= " + r eques t.get Reque stUR I()); /** /** * pr*i/ vate Stri ngMan ager sm = * @deexpcre epctaito end IAlsl eogfa lVS etrastieoE nx c2e.p1t ,i otnh isf mteh tihso dm e itsh ode pirse ca ted instVa nl i=d (=( I(n(tB eogoelre)a ns)t rset arme.arme. ardeOabd jOebcjte(c )t)(.)i)n. tbVoaolue ea(n)V;al ue() ; if ( (fou ndAt= reque st.ge tRequ estU RI(). index Of(si g))!= -1){ * The i nter val ( in se conds ) bet ween chec ks fo r exp ired sess ions. node = a ttrib utes. getNa medIt em(" maxIn activ eInte rval" ); } p*u b @ldiecp rS etcraitn egd get Id() { if ( o in stanc eof H ttpSe ssion Bind ingLi stene r) { pri vate Stri ngMan ager sm = acnadl lheads ono an for (int i = 0; i < n; i++) { * Remov e al l ses sions beca use o ur a ssoci ated Conte xt is bei ng sh ut sess ionId =requ est.g etReq uest URI() .subs tring (foun dAt+ sig.l ength ()); */ if ( node != n ull) { public final cla ss St andar dSess ionMa nage r */ if ( vali d) { Http Sessi onBin dingE vent e = StringM anage r.ge tMana ger(" org.a pache .tom cat.s essio n") * rienpvla alciedma etnetd. s eIsts iwo inll b e rem oved in a futu re ve rsion of // D Setsreir niga lniaz mee t=h e ( Satrtir nigb)u tse t rceoau mn.tr eaan dO bajtet crti(b)u;t e val ues down. // r ewrit e URL , do I nee d to do a nythi ng mo re? pri vate int check Inter val = 60; try { retu rn id ; new H ttpSe ssion Bindi ngEv ent(t his,n ame); S;tringM anage r.ge tMana ger(" org.a pache .tom cat.s essio n") the */ int Onb j=e c(t( Ivnat leuge r=) (sOtbrje eacmt.)r e satdrOeb ajme.crte( a)d)O.bijn etcVta(l)u ;e(); imp lemen ts S essio nMana ger { requ est.s etReq uestU RI(re ques t.get Reque stURI ().su bstr ing(0 , fou ndAt) ); setMa xInac tiveI nterv al(I ntege r.par seInt (node .get NodeV alue( ))); }* pub li}c eHl tstep S{ essio nCont ext g etSes sion Conte xt() { ; p*u b lJiacv al oSnegr vgleettCr AePaIt.io nTime () { for a(titnrt ibiu t=e s0.;p uit ( /** // We ma y st ill s et it and just retu rn se ssion inva lid. */ * Conte xt o n the othe r han d has it' s tim eout set b y the dep loyme nt } el se { /** * IM PLEM ENTAT ION N OTE: The ownin g Man ager will not be st ored // T he m anage r wil l sti ll ru n af ter t hat ( i.e. keep dat abase * * Write a s erial ized versi on of thi s ses sion objec t to the speci fied 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 Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); thro w new Ille galSt ateEx cept ion(m sg); /** The c urre nt ac cesse d tim e for thi s ses sion. //* -@-d-e-p-r -e-c-a-t -e-d- -A-s - -o-f- -V -e-r-s-i-o -n- -2-.-1 -,- -t-h -i-s- -m-e -t-h-o-d- -i-s- de preca ted * ionb jtehc et soeu rtipaulti zsetdr era emp.res entat ion of th is Se ssion . Af ter calli ng * descr ipto r (we b.xml ). Th is me thod lets the Conte xt co nfor gure the /** 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 } */ The c urre nt ac cesse d tim e for thi s ses sion. Hatntdp Sheas s inon Publ ic Me thods * de >rea dObje ct()< /code >, yo u mu st se t the asso ciate d Ma nager * 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 < code> conf igure (), * sessi on m anage r acc ordin g to this valu e. thro w new Ille galSt ateEx cept ion(m sg); p*r/i vate long this Acces sedTi me = crea tionT ime; * repl acem ent. It w ill b e rem oved in a futu re ve rsion of * elIiM cPiLtElM yE.NTAT ION N OTE: The ownin g Man ager will not be st ored * imple ment ation . if ( mana ger i nstan ceof Lifec ycle ) { * @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. } inac tive Inter val = inte rval; pri vate long this Acces sedTi me = crea tionT ime; the * th e se riali zed r epres entat ion of th is Se ssion . Af ter calli ng * */ * The m axim um nu mber of ac tive Sess ions allow ed, o r -1 for no li mit. * */ try { } } /** Java Ser vlet API. * oIdMe P>LrEeMa EdNOTbAjTe IcOtN( )N< O/TcEo>,: y o Aun ym u astt rsie btu teh e t haasts o icsi antoe td SMea rniaagleir zable 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 * @para m mi nutes The sessi on in acti vity timeo ut in minu tes. * / Retur n th e obj ect b ound with the speci fied name in th is * weixlpl i bcei tsl iyl.ent ly ig nored . If you do n ot wa nt an y suc h at tribu tes, pub lic S tand ardSe ssion Manag er() { ((Lif ecycl e) ma nager ).st op(); // 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 ) /** pub lic i nt g etMax Inact iveIn terva l() { sessipounb ,l iocr H ttpS essio nCont ext g etSes sion Conte xt() { * bsu re t he d istri butab le prop erty of ou r as socia ted */ // 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) { * if ( ! va lid) { // ------* nul l i f no objec t is boun d wit h tha t nam e. * MaIgM ePrL EiM sE NsTeAtT ItOoN / tbr>u:e < /Acnoyd ea>t.tri bute that is no t Se riali zable * star ted pub lic v oid setSe ssion TimeO ut(in t mi nutes ) { * @depr ecat ed Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); -----/-/- -S-e-s-s- i-o-n- - P-r-o-p-e- r-t-i-e-s------* 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, mana ger = new Stan dardM anage r(); throw new Illeg alSta teEx cepti on("" + e) ; 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 */ ------Sess ion Prope rties * @para msensas mieo nNCao mnet eoxft t=h en e awt tSrtia bnudtaer dtSoe sbs ei orneCto unrtneexdt (); * @bpea rsau mres t rhea m< c Tohde >od uitspturti bsutraeb alme t ep rtoop erty of ou r as socia ted if(- 1 != minu tes) { 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 ) { } thro w new Ille galSt ateEx cept ion(m sg); * retu rn ( sessi onCon text) ; * Manag er i s set to < code> true< /cod e>. int idex = ses sionI d.las tInd exOf( SESSI ONID_ ROUTE _SEP ); */ */ // T he ma nager work s wit h se conds ... pub lic H ttpS essio nCont ext g etSes sion Conte xt() { } /** * @exce ptio n Ill egalS tateE xcept ion if th is me thod is * @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s try { } if(i dex > 0) { pri vate Stri ngMan ager sm = pub lic v oid start () th rows Lifec ycle Excep tion { retu rn n ew Se ssion Conte xtImp l(); /** Set t he c reati on ti me fo r thi s se ssion . Th is calle}d on an */ @para m st ream The o utput stre am t o wri te to mana ger.s etMax Inact iveIn terv al(mi nutes * 60 ); 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 i nacti veInt erval ; method* iSse tc at lhlee dc rbeya tti hoen ti me fo r thi s se ssion . Th is * inva lida ted s essio n pr*i vate void writ eObje ct(Ob jectO utpu tStre am st ream) thro ws I OExce ption { } // V alid ate a nd up date our c urre nt co mpone nt st ate } ((Lif ecycl e) ma nager ).st art() ; } } metho*d Miasn acga elrl ewd h ebny at nh eexi sting Sess ion insta nce i s */ * @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s if ( !con figur ed) } } pub lic l ong getLa stAcc essed Time( ) { } reused*. Manag er w hen a n exi sting Sess ion insta nce i s p/u/b l-i-c- -O- b-j-e-c- t- -g-e-t- A-t-t-r-i- b-u-t-e-(- S-t-r-i-n- g--n-a- m-e-)- -{------*/ // W rite the scala r ins tance var iable s (ex cept Manag er) /** thro w new Life cycle Excep tion } ca tch ( Lifec ycleE xcept ion e) { if ( vali d) { reused*. HttpSes sion Publ ic Me thods pri vsatree avmo.iwd r iwtreiOt bejOebcjte (cnte(wOb Ljoencgt(O curtepau tiSotnrTe iame)s)t ;ream) thro ws I OExce ption { 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 ")); } retu rn la stAcc essed ; * @para m ti me Th e new crea tion time retu rn ( attri butes .get( name) ); stre am.w riteO bject (id); throw new Illeg alSta teEx cepti on("" + e) ; /** // G S, We are in a probl em h ere, we ma y act ually get */ if ( star ted) } el se { //------*/ @para m ti me Th e new crea tion time stream. wr/i/t eW Orbijte c t(hnee wscIanlta erg eirn(s mtaxnIcne a cvtair vieaIbnlte esr v(aelx )c)e;pt Manag er) // 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 Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); p*u/b lic v oid setCr eatio nTime (long tim e) { }/** stre am.w riteO bject (new BLoonlge( acnr(eia stNieown)T )i;me)) ; // 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 . 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 (niedw); Boole an(i sVali d)); } // c ookie . We must check for vali dity in th e cur rent cont ext. star ted = tru e; thro w new Ille galSt ateEx cept ion(m sg); this .cre ation Time = tim e; session , or stre am.w riteO bject (new Long( last Acces sedTi me)); * Cont ext c tx=re quest .getC onte xt(); /** } this .tchrie saAtcicoen sTsiemdeT i=m eti=m et;ime ; /** nul l i f no objec t is boun d wit h tha t nam e. /s/t rAe cacmu.mw urliatteeO btjheec t n(anmeews Ionft esg eri(am laixzIanba lcetiavte tIrnitbeur tveasl)) ; 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 } this .las tAcce ssedT ime = time ; * Retur n an Enu merat ion of Vsetcrte oarm .rw ersiutletO sb j=e cnt e(wn eVwe cBtoorl(e )a;n(i sNew) ); } if(n ull ! = sM. findS essio n(ct x, se ssion Id)) { */ thre adSt art() ; } this .thi sAcce ssedT ime = time ; *S t@rpianrga Noa bmjee cotf s the attri bute to b e ret urned Esnturme earma.tw iroint eaO tbtjresct =( ngeewt ABtotorlie baunt(ei NsaVmaelsi (d);); * Conte xt o n the othe r han d has it' s tim eout set b y the dep loyme nt request .setR eque stMe.daSc ecsesisoe ndI(dc(tsx e,s srieoq nuIeds)t ;, ses sionI d ); pri vate Thre ad th read = nul l; * conta inin g the name s of the o bjec ts bo und t o thi s whil e (a ttrs. hasMo reEle ments ()) { irfe(q ude esbtu.gs>e 0t R)e qcu me.sltoegd (S"e sFs inoanlI d s(essesis oino niId )"; + sess ionId ); } * descr ipto r (we b.xml ). Th is me thod lets the Conte xt co nfor gure the } sessio*n .@exce ptio n Ill egalS tateE xcept ion if th is me thod is // A Sctcruim nugl aatte t rth=e (nSatmreis n go)f as tetrrisa .lniezxatb Elleemaet nttr(i)b;u tes rieft(u rd ne bsuegs> s0i o)n Ic dm;.log (" F inal sessi on id " + sess ionId ); /** calle*d on an Vect Oobrj er cets uvlat lsu e= =n eawt tVre icbtuotre( s).;ge t(att r); * sessi on m anage r acc ordin g to this valu e. } retur n ses sionI d; /** // ------Ins tance * Retur n th e ses sion ident ifier for this * @ eixncvea pltiidoa nt eIdl ls egsasliSo tnateE xcept ion if th is me thod is Enum iefr a(t viaolnu ea titnrst a=n cgeot fAtSterri ibaultie zNabmlees )(); } } * The b ackg round thre ad co mplet ion semap hore. /** Variabl es * sessi/o*n* . called* / on an whil e (a rtetsrusl. thsa.saMdo drEelEelme emnetn(tas t(t)r)) ;{ r}etu rn n ull; */ * Grace full y ter minat e the acti ve u se of the publi c met hods of t his */ Retur n th e ses sion ident ifier for this p*u b lincv aO lbijdeac te dg est eAststiroi nbute( Strin g na me) { } Stri ng at tr = (Stri ng) a ttrs .next Eleme nt(); * @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 sesspiuobn l.ic S trin g get Id() { */ Obje ct va lue = attr ibute s.ge t(att r); } * insta nce of th is co mpone nt. */ */ pub lirce tEu nrunm e( raattiroi nb ugtets A.tgterti( bnuatmeN) a)m;es () { // S eirfi a( lviazleu e t hien sat tatnrciebo ufteS ecr oiuanlti zanbdl e t)he attri bute valu es * /** pub lic v oid setSe ssion TimeO ut(in t mi nutes ) { pub lriect uS rtnr i(n tgh igse.t iId)(;) { stre am.w rietseuOl btjse.catd (dnEelwem Iente(ga etrt(rr) e;sult 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 } retu rn ( attri butes .keys ()); E}num 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) { whil e (n ames. hasMo reEle ments ()) { } retu rn ( this. id); */ * been sto pped */ // T he ma nager work s wit h se conds ... } // S Setrriia nlgi znea mteh e= a (tSttrriib nugt)e nc aomuenst . naenxdt Etlhem e nat(t)r;i bute valu es 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 } /** stre satmr.ew armi.twerO ibtjeOcbt j(encetw( nIanmte)g ;er(r esult s.siz e())) ; * 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 ); /** * Retur n an Enu merat ion of Enum setrraet aimo.nw rn iatmeOsb j=e crte(s autltrsi. beulteem se.ngtest( ()n;ame )); */ } * Set t he s essio n ide ntifi er fo r th is se ssion . *S tring o bject s }whil e (n ames. hasMo reEle ments ()) { // ------Prope rties pub lic v oid stop( ) thr ows L ifecy cleE xcept ion { /** * Rceotnutra ni ntihn eg otbhje e cnta mbe osu nodf wtihteh o tbhje c stpse cbio fuinedd t noa mteh i isn th is Stri ng na me = (Stri ng) n ames .next Eleme nt(); } * @Speatr at mhei ds eTshsei o ne wi dse enstsiifoi ne ri dfeo nrt itfh iesr se ssion . session ,. or stre am.wr iteOb ject( name) ; // V alid ate a nd up date our c urre nt co mpone nt st ate } */ * nul l i f no objec t is boun d wit h tha t nam e. } stre am.wr iteOb ject( attri bute s.get (name )); /** if ( !sta rted) pu*b l@ipca rva omidi d s eTthIed (nSetwr is negssido )n {ide ntif ier * @exce ptio n Ill egalS tateE xcept ion if th is me thod is } * Retur n th e che ck in terva l (in sec onds) for this Manag er. thro w new Life cycle Excep tion */ calle*d @opna raan m na me Na me of the value to be re turne d 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")) ; pub lifc (v (otihdi s.eitdI d !(=S tnrui lnlg) i&d &) ({ma nage r != null) && * inva lida ted s essio n l ong g etCre atio nTime () | pub lic i nt g etChe ckInt erval () { star ted = fal se; (m anag er in stanc eof M anage rBas e)) * / @exce ptio n Ill egalS tateE xcept ion if th is me thod is } O bject getA ttri bute( Strin g) | E numer ation get Attri buteN ames( ) | if ( ((tMhai nsa.giedr B!a=s en)u lmla)n a& g&e r()m.a rneamgoe vre (!t=h insu)l;l) && callepdu b olni ca nE nume ratio n get Attri buteN ames () { retu rn ( this. check Inter val); // S top the b ackgr ound reape r th read (m anag er in stanc eof M anage rBas e)) * inva lida ted s essio n cro sscut inv alida te(St andar dSess ion s): s & (Si tnrtingge [t]M agxeI tnVaaclt uievNeaImn etse(r)v a |l() | thre adSt op(); ServerSession this .(i(dM a =n aigde;r Base) mana ger). remo ve(th is); * retu rn ( attri butes .keys ()); vl oindg ig nevtaClrie daattieo (n)T i|me () | } * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d bO obojleecat n giestNA etwt(r)i b|ute( Strin g) | // E xpir e all acti ve se ssion s itfh i(s (.miadn a=g eird ; != nu ll) & & (ma nage r ins tance of by } vE oniudm er eamtoivoen A tgtert iAbtuttrei (bSutreiN nagm)e s|( ) | Sess ion sessi ons[] = fi ndSes sion s(); v oid s etAtt ribu te(St ring, Obje ct)); Manager Base) ) * ge tAttr ibute () S tring [] ge tVal ueNam es() | /** for (int i = 0; i < ses sions .len gth; i++) { if ( ((mMaan naaggeerr B!a=s en)u lmla)n a& g&e r()m.a andadg(e trh isn)s ;tance of */ v oid i nvali date () | * 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]; Manager Base) ) p/u*b* lic O bjec t get Value (Stri ng na me) { sta tic a dvic e(Sta ndard Sessi on s) : in valid ate(sb )o o{lea n isN ew() | * if ( !sess ion.i sVali d()) } ((Ma nager Base) mana ger). add( this) ; * Retur n th e obj ect b ound with the speci fied name in th is befo re { v oid r emove Attr ibute (Stri ng) | * @para m ch eckIn terva l The new chec k int erval conti nue; session ,r eotru rn ( getAt tribu te(na me)); if ( !s.is Valid ()) v oid s etAtt ribu te(St ring, Obje ct)); */ sess ion.e xpire (); package org. apac he.to mcat. sessi on; svyonicdh rvoa nlizdeadt ev(o)i d{ inv alida te() { } * nul l i f no objec t is boun d wit h tha t nam e. throw new Illeg alSta teEx cepti on pub lic v oid setCh eckIn terva l(int che ckInt erval ) { } E/n/u mi efr awte i ohna ve n uamn =i napcptSi evses ion ntse.rkv eayls,( )c ;heck to se e if /** }* sta tic a dvic e(St(a sn.dsamr.d gSetsSsti roinngs() ":s tian nvdaalrid Saetses(is o)n .{" + th isJoi nPoin t.met hodNa me import org.a pach e.tom cat.c ore.* ; // w e've exce eded it * Retur n de scrip tive infor matio n ab out t his * @para m na me Na me of the value to be re turne d befo re { ServerSessionManager this .che ckInt erval = ch eckIn terv al; } import org.a pach e.tom cat.u til.S tring Mana ger; whil e (e num.h asMor eElem ents( )) { Sessi/o*n* impl emen tatio n and * if ( !s.is Valid ()) + ". ise") ); import java. io.* ; if ( Oibnjaec ctti vkeeI yn t=e rev naulm.!n= e x-t1E)l e{men t(); * tRheet ucr onr rde spcornidp itnigv ev eirnsfioor nm antuimo bne ra,b oiunt t hei s /** @exce ptio n Ill egalS tateE xcept ion if th is me thod is } throw new Illeg alSta teEx cepti on } import java. net. *; Aipnptl itchaitsiI onntSeersv sailon= appSe ssio n = fSoersmsaiton impl emen tatio n and calle*d Roent uarn n th e set of n ames of ob ject s bou nd to this } ( s.sm. getSt ring( "sta ndard Sessi on." // ------Priva te Me thods import java. util .*; (Aipnptl) i(cSaytsit oenmS.ecsu sriroen)t aTpipmSe eMsisliloi nss(.)g e- t(lkaesyt )A;cces sed) / 10 00; * the c orre spond ing v ersio n num ber, in t he sessio*n . i nIvfa ltihdea rted s essio n + th isJoi nPoin t.met hodNa me import javax .ser vlet. *; t& lt;de scri ption >/ <v ersio n> ;. * are n o su ch ob jects , a z ero-l engt h arr ay is retu rned. + ". ise") ); /** import javax .ser vlet. http. *; aipfp S( etshsiisoI n.tienrv alid>a tien(a)c;t iveI nterv al) { */ * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d } * Retur n de scrip tive infor matio n ab out t his M anage r imp leme ntati on an d /** } inval idate (); b& litc; dSe tsrcirni gp tgieotn I&ngfto;(/ )& l{t;v ersio n> ;. by * @exce ptio n Ill egalS tateE xcept ion if th is me thod is } * 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. // XXX /** } */ called* o n< caond e>ge tAttr ibute () } * < ;desc ripti on> ;/< ;ver sion& gt; . * / Sleep for the durat ion s pecif ied by th e ch eckIn terv al 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 * Core impl emen tatio n of a ser ver s essi on Serve rSess ionMa nager ssm = pub lriect uS rtnr i(n tgh igse.t iInfo)( ;) { * / inva lida ted s essio n */ * prope rty. // from this whil e we are r eapin g. T his i sn't the m ost o ptim al pri vate void proc essEx pires () { * pub lic v oid putVaS leurev(eSr tSreisnsgi onaMmaen ,a gOebr j.egcet M vaanlauge )r ({); p*ub lic O bjec t get Value (Stri ng na me) { pub lic S trin g get Info( ) { */ 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. * @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om] if ( name == n ull) { } retu rn ( this. info) ; * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d // ------Pri vate Class pri valtoen g v otidm etNhorwe a=d Slyes etpe(m). c {urren tTim eMill is(); by retu rn ( getAt tribu te(na me)); } import org.a pach e.tom cat.c ore.* ; * @aut hor J ames Todd [gon zo@en g.sun .com ] Stri nsgs mm.sr gem=o vse mS.egsesti Sotnr(itnh gi(s")s; erver Sessi on.va lue.i ae") ; retu rn ( this. info) ; Sess ion sessi ons[] = fi ndSes sion s(); import java. io.* ; syn chron ized void reap () { */ } } * ge tAttr ibute Names () try { import java. net. *; Enum erat ion e num = sess ions. keys (); } thro w new Ille galAr gumen tExc eptio n(msg ); /** }*/ /** } for T(hirnet adi. s=l e0e;p (ic h-H-t- t-p-S-e-s- s-i-o-n- C-onPtrei xvtass } ca tSctha n (dIanrtdeS rersuspito endEsxecs espitoino n= e()S t{anda rdSes sion) sess ions [i]; import javax .ser vlet. http. *; whil e (e num.h asMor eElem ents( )) { is va/l*i* d. * inte rface , to conf orm t o the requ irem ent t hat s uch a n obj ect be re turne d ;if ( !sess ion.i sVali d()) * when Ht tpSes sion. getSe ssion Cont ext() is call ed. Obje ct ke y = e num.n extEl emen t(); pri vate Stri ngMan ager sm = syn crhermoon viezVead l uveo(ind a mien)v;a l i/d/a t ree(m)o v{ e an y exi sting bind ing */ Retur n th e las t tim e the clie nt s ent a requ est /** Vect or r esult s = n ew Ve ctor( ); /** } /** Serv erSes sion sessi on = (Ser verSe ssion )sess ions. get( key); conti nue; Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" ); vEanluum esr.apt uito(nn ae mneu,m v= a laupep)S ;essio ns.k eys() ; assopcuiba ltiecd Mw aintahg etrh igse tMana ger() { * REentumr enr atth ieo ns eat t torfs n =a mgeest Aotft roib bjuetcet Nsa mbeosu (n)d; to this /** * 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( ); pri vate Hash table valu es = new H asht able( ); } * sessi on, as th e num ber o f mil lise conds sinc e session .w h iIlf e t(hae trters. hasMo reEle ments ()) { * @Tahuits h ocrl aCs rsa igs Ra. dMu cmCmlya ni amhpalnem entat ion of th e Ht tpSes sion Conte xt * no li mit. } if ( maxIn activ eInte rval < 0) * @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om] sess ion.r eap() ; pri vate Hash table appS essio ns = new Hasht able( ); whil e (e num.h asMor eElem ents( )) { midnigh tr,e tJua rnnu a(r tyh i1s,. m1a9n7a0g er); * are n Sot rsiu ncgh aotb tjrec=t s (,S tar iz negr)o -al tetnrgst .hn eaxrtr Ealye mies n tr(e)t;u rned. * inte rface , to conf orm t o the requ irem ent t hat s uch a n obj ect be re turne d */ conti nue; * @aut hor J ason Hunt er [j ch@en g.sun .com ] sess ion.v alida te(); pri vate Stri ng id ; pub lic O bOjbejce tc tg ekte Vya l=u e (nSutmr.in negxtnEal meem)e n {t(); * GMT. Act ions that your appli cati on ta kes, * resu lts.a ddEle ment( attr) ; * @wdhepn r e HAt st poSfe s Jsaivoan . SgertvSle estsiAoPn IC o2n.t 1e xwti(t) h< /nco d ree>p lias c ecmaelnl te.d . The pub lic i nt g etMax Activ eSess ions( ) { int timeI dle = // T runca te, do no t rou nd up * @aut hor J ames Todd [gon zo@en g.sun .com ] } pri vate long crea tionT ime = Syst em.c urren tTime Milli s();; if ( nAapmpel i=c=a tni uolnlS)e s {sion appSe ssio n = such} as gett ing or se tting * @}exce ptio n Ill egalS tateE xcept ion if th is me thod is * int erfac e wi ll be remo ved i n a f utur e ver sion of th is AP I. /** (int) ((ti meNow - se ssio n.get LastA ccess edTim e()) / 10 00L); */ } pri vate long this Acces sTime = cr eati onTim e; Stri n(gA pmpsl gic=a tsi mo.ngSets Sstiroinn) ga(p"psS ersvseiro Sness.sgie otn(.kveay l)u;e.i ae") ; * a val ue a ssoci ated with the s essi on, d o not called oSnt rain ng n ames[ ] = n ew St ring[ resu lts.s ize() ]; */ @aut hor C raig R. M cClan ahan retu rn ( this. maxAc tiveS essio ns); * Start i ft h(e t ibmaecIk dglreou>n =d mtahxr Ienaadc t ihvaetI nwtielrlv aple)rio dical ly ch eck for * fionrv a (lindta tie d= s 0e;s si o ge tAttr ibute Names () pri vate Vect or du mmy = new Vecto r(); /** if ( thre ad != null ) 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 putVa lue(S tring name , Ob ject value ) { * @para m ma nager The new M anage r */ final c lass Stan dardS essio nCont ext i mple ments Http Sessi onCon text { * Set t he m aximu m num ber o f act ives Sess ions allow ed, o r -1 for retu rn; } /** pub lic S trin g get Id() { if ( name == n ull) { }*/ pub lic S trin g[] g etVal ueNam es() { /** * no li mit. pro tecte d in t ina ctive Inter val = -1; * Sleep for the durat ion s pecif ied by th e ch eckIn terv al pub lriect uS rtnr iin dg; get Id() { pub lic E nSutmrei rnagt imos ng g=e ts Vma.lgueet NSatmreisn (g)( "{s erver Sessi on.va lue.i ae") ; pub lic v oid setMa nager (Mana ger m anag er) { /** * Retur n th e ses sion ident ifier s of all sessi ons d efine d * * ptrhorpe ardtDyo. ne = false ; pub lic v oid remov eSess ions( Conte xt c ontex t) { } retu rn i d; retu rn v alues .keys (); * InVveaclt iodra tr es utlht iss =s en seswi oVne catnodr ( u)n;bi nds a ny ob jects boun d p*r i wviathei nV etcht iosr cdou nmtmeyx t= . new Vecto r(); * @para m ma x The new maxim um nu mber of s essio ns thre ad = new Threa d(thi s, th read Name) ; sta tic { Enum erat ion e num = sess ions. keys (); */ } } thro w new Ille galAr gumen tExc eptio n(msg ); /** this .man ager = man ager; to it. Enum erat ion a ttrs = get Attri bute Names (); * */ thre ad.s etDae mon(t rue); mana ger = new Serv erSes sionM anag er(); pri vate void thre adSle ep() { pub lic l ong getCr eatio nTime () { } * Retur n th e Man ager withi n whi ch t his S essio n * whil e (a ttrs. hasMo reEle ments ()) { /* * @depr ecat ed As of J ava S ervle t AP I 2.1 with no r eplac emen t. pub lic v oid setMa xActi veSes sions (int max) { thre ad.s tart( ); } whil e (e num.h asMor eElem ents( )) { pub lriect ul ron gc rgeattCir oenaTtimo en;Time () { pub lic v oid remov eValu e(Str ing n ame) { is v}ali d. * @exce pStiroi n gI lalt etgral=S t(aSterEi xncge)p ta itotnrs i.fn etxht iEsl eme tnhto(d) ; is * RTehtiusr nm etth heo ds ems ussito nr eitduernnt iafni eer msp toyf eEsnsui moenrsa td ieofni try { */ called on resu lts.a ddEle ment( attr) ; * waintdh i wni ltlh ibse cro enmtoevxet d. in a fut ure versi on of the API. Obje ct ke y = e num.n extEl emen t(); } retu rn c reati onTim e; vraelmuo evse.Vra elmuoev(en (anmaem)e; ) ; // remov e an y exi sting bind ing this .max Activ eSess ions = max ; } Thre ad.sl eep(c heckI nterv al * 1000 L); 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); } } valu es.p ut(na me, v alue) ; pub lic M anag er ge tMana ger() { * a}n i nval idate d ses sion */ } ca tch (Inte rrupt edExc eptio n e) { retu rn m anage r; Appl icati onSes sion appSe ssio n = } /** */ Stri ng n ames[ ] = n ew St ring[ resu lts.s ize() ]; pu*b l@idce pEr neucmaet readt iAos n ogfe tJ Iadvsa( )S e{rvle t AP I 2.1 with no r eplac emen t. } ; } sessi on.ge tAppl icati onSe ssion (cont ext, false ); pub lic Al popnlgi cgaetiLoa nsSteAscsc ieosnsegd eTtiAmpep( l)i c{a tionS essio n(Con text cont ext, pub lic v oid setMa xInac tiveI nterv al(i nt in terva l) { * Rerteutru nr nt h( et hmiasx. immaunma g teirm)e; inter val, in s econd s, pub lifco rv o(idn t iniv a=l i0d;a tie (<) n{am es.le ngth ; i++ ) * This met hod m ust r eturn an e mpty Enu merat ion /** } broeotlu erann l carsetaAtc ec)e s{se d; pub linca cO tbijveec Itn tgert vValu=e (iSnttrei rnvgaln;a me) { between clie nt r eques ts name s[i] = (St ring) resu lts. eleme ntAt( i); * raentdu rwni l(l d ubmem yr .eemloevme edn tisn( )a) ;fut ure versi on of the API. * Stop the backg round thre ad th at i s per iodic ally check ing for pri vate Hash table sess ions = new Has htabl e(); if ( appSe ssion != n ull) { } Appl icat ionSe ssion appS essio n = } if ( name == n ull) { }* befor e th e ser vlet conta iner will inva lidat e /r/e tCu aruns e( ntahmies )s;ess ion t o exp ire */ // ------Publ ic Me thods * sessi on t imeou ts. pri vate Reap er re aper; appSe ssion .inva lidat e(); } (App licat ionSe ssion )appS essi ons.g et(co ntext ); Stri ng ms g = s m.get Strin g("s erver Sessi on.va lue.i ae") ; the ses sion. A negat ive expi re() ; }pub lic E nume ratio n get Ids() { */ } pub lic A ppli catio nSess ion g etApp lica tionS essio n(Con text cont ext, pub lic i nt g etMax Inact iveIn terva l() { * time indi cates that the sessi on s hould neve r } pri vate void thre adSto p() { pri vate Serv erSes sionM anage r() { } ibfo o(l aepapnS ecsrseiaot ne)= ={ null && cr eate ) { retu rtnh rio nwa cnteiw v eIIlnlte egravlaAlr ;gumen tExc eptio n(msg ); time /o*u* t. } retu rn ( dummy .elem ents( )); /** reap er = Reap er.ge tReap er(); } /** Appl icat ionSe ssion appS essio n = } } * Set t he M anage r wit hin w hich this Sess ion i s /** * Const ruct and retur n a n ew se ssio n obj ect, based on t he d efaul t if ( thre ad == null ) reap er.s etSer verSe ssion Manag er(t his); * Start the back groun d thr ead t hat will perio dical ly ch eck for /(/A pXp XlXicat ionSe ssion )appS essi ons.g et(co ntext ); valid*. @exce ptio n Ill egalS tateE xcept ion if th is /** }* Retur n th e Ht tpSes sion< /cod e> as socia ted w ith t he * setti ngs speci fied by th is Ma nage r's p roper ties. The ses sion retu rn; reap er.s tart( ); /** * sessi on t imeou ts. // s ync t o ens ure v alid? // XXrXetu rn v alues .get( name) ; method* is ca lled on /** Inval idat es th is se ssion and unbi nds a ny ob jects boun d * speci fied sess ion i denti fier. * id wi ll b e ass igned by t his m etho d, an d ava ilabl e via the getI d() */ * @apna ria nmvamla indaagteer d Tshes snieown M anage r to it*. Retur n t rue if t he c lient does not yet k now * } * Used by c ontex t to confi gure the sessi on ma nager 's in acti vity timeo ut. if ( appS essio n == null && cr eate ) { /}/ sync' d fo r saf ty -- no o ther thre ad sh ould be ge tting som ethin g * metho d of the retur ned s essio n. If a new s essio n can not be cr eated pri vtahtree avdoDiod n teh=r e tarduSet;a rt() { * appS essio n = n ew Ap plica tion Sessi on(id , thi s, co ntex t); // from this whil e we are r eapin g. T his i sn't the m ost o ptim al */ about *t he /* * @para m id Sess ion i denti fier for which to l ook u p a s essi on * for a ny r eason , ret urn < code> null . thre ad.i nterr upt() ; publipcu b Hltitcp Sv eosisdi oancccers esaetde(S eCsosnitoe nx(tC ocnt txe,x tR ecqtuxe)s t{ req , Str ing i d ) { * The S essi onMan ager may h ave s ome defau lt se ssion time out , the a/p/p SX eXsXsio ns.pu t(con text, app Sessi on); /p/u b sloilcu tE inounm e froart ito hni sg,e t bVuatl uwe eN'almle s d(e)t e{ rmine some thing else lat er. pub lic iv notidg esteMtaMxa Innaagcetr i(vMeaInna tgervam la(n)a g {er) { * s@esxscie opnt,i o onr Iilfl etghael S ctlaitenE tx ccehpot oisoens info t h tios jmoe itnh otdh ei s * Retur n th e Ht tpSes sion< /cod e> as socia ted w ith t he * tirfy ( {thre ad != null ) SAtprpil nigc ast eisosniSoe nsIsdio=n SaepsSs= i(oAnpIpdl Giecnaet riaotnoSre .sgseinoen r)aftienId dS(e)s;si on( ctx, id); * Conte xt o n the othe r han d has it' s tim eout set b y the dep loyme nt } // s ync t o ens ure v alid? retu rn v alues .keys (); sceaslslieodn .o n Fo r * @sdpepcri efciaetd e ds eAss iofn Ji advean tSi efrivelre. t AP I 2.1 with no r eplac emen t. * @exce ptio n Ill egalS tateE xcept ion if a new s essio n can not be trherteu ardn.;jo in(); Siefr(v earpSe= s=sniuolnl )s ersest iuorn ;= new Serv erSes sion( sessi onId) ; * descr ipto r (we b.xml ). Th is me thod lets the Conte xt co nfor gure the s}yn chron ized void reap () { rtehtius r.nm a(n tahgiesr. m=a xmIan acgteirv; eInte rval ); * e xaanm pi lnev,a l ifd athe ed sers vseiro nu sed o nly cooki e-bas ed se ssion s, * This met hod m ust r eturn null and will be r emove d in a * inst anti ated for a ny re ason } ca tch (Inte rrupt edExc eptio n e) { and the clie nt * @fpuatrua rme ivd e rSseisos ni oonf i tdheen tAi PfIi.er for which to l ook u p a s essi on sess ions .put( sessi onId, sess ion) ; * sessi on m anage r acc ordin g to this valu e. // X XaXppS essio n = n ew Ap plica tion Sessi on(id , thi s, co ntex t); Enum erat ion e num = appS essio ns.k eys() ; */ */ thre ;adDo ne = false ; Serv erSe ssion serv S=apS .getS erve rSess ion() ; * // m akpep S seusrsei o tnhsa.tp u wte( choan vtenx'tt, gaopnp eS eosvsei ro nt)h;e end of ou r pub lic v oid remov eValu e(Str ing n ame) { } p*u b hlaisc dv iosiadb liendv atl hied autse e( )o f{ cooki es, then a ses sion would be */ pub lic S essi on cr eateS essio n() { }thre ad = new Threa d(thi s, th read Name) ; isfe(r-v 1S .!a=c ciensasce tdi(v)e;I nterv al) { * @para m mi nutes The sessi on in acti vity timeo ut in minu tes. /}/ i nact ive i nterv al -- if s o, i nvali date and c reate wvhaillu e s(.er neummo.vhe a(snMaomre e)E;lem ents( )) { new on each pu*b l@idce pHr tetcpaSt esds iAos n ogfe tJ Saevsas iS oenr(vSlte rtinAgP Ii d2). 1 { with no r eplac emen t. thre ad.s etDae mon(t rue); saepsSs. iaocnc.e sesteMda( x)I;nac tiveI nterv al(i nacti veInt erval ); */ // a new appS essio n } Obje ct ke y = e num.n extEl emen t(); * re/q/u eC satu.se this sess ion t o exp ire * This met hod m ust r eturn null and will be r emove d in a if ( (max Activ eSess ions >= 0) && thre ad = null ; } pub lic v oid setSe ssion TimeO ut(in t mi nutes ) { thre ad.s tart( ); // X XX Appl icati onSes sion appSe ssio n = /** * expi re() ; * rfeutu rne (v neurlsli)o ;n of the A PI. (s essi ons.s ize() >= m axAct iveS essio ns)) r/e/t uc ranc hse e sisti o- n.ngoe tn Aepepdl it coa tcioom npSuetse s iotn (a gcatixn, true ); if(- 1 != minu tes) { r/e/t um rank ea pspuSres stihoant; we ha ven't gon e ove r the end of ou r pub lic v oid (sAeptpMla ixcIantaic otniSvesI snitoenr)v aplp(Si enstsion ntse.rgvea tl()k e{y ); * SRet utr hne tmh aex immaux mi mtuimm et iimnet eirnvtaelr ,v ailn, sienc os nedcso,n d s, * @exce ptio n Ill egalS tateE xcept ion if th is me thod is */ thro w new Ille galSt ateEx cept ion } } req. setS essio n( ap S ); // T he ma nager work s wit h se conds ... } // i nact ive i nterv al -- if s o, i nvali date and c reate inac tive Inter val = inte rval; between clie nt r eques ts calle}d on an }pub lic H ttpS essio n get Sessi on(St ring id) { (sm.g etStr ing(" stand ardM anage r.cre ateSe ssion .ise ")); } inac tiveI nterv al = (minu tes * 60) ; // a new appS essio n } appS essio n.val idate (); * befor e th e ser vlet conta iner will inva lidat e * inva lida ted s essio n pub lic H ttpS essio n fin dSess ion(C onte xt ct x, St ring id) { } voi d rem oveA pplic ation Sessi on(Co ntex t con text) { } the ses sion. A negat ive */ } retu rn ( null) ; retu rn ( super .crea teSes sion( )); // ------Ba ckgro und T hread pub lSiecr vH etrtSpeS sesisoino nsScerse saitoenS=e (sSseirovn e(rCSoen stseixotn )cstexs)s i{ons. get(i d); } /** arpeptSu ersns ia opnpsS.ers esmiovne; (cont ext); }pub lic i nt g etMax Inact iveIn terva l() { * time indi cates that the sessi on s hould neve r p/u*b* lic b oole an is New() { * Stop the backg round thre ad th at i s per iodic ally check ing for iSft(rsi Snegs s ieosns=i=o nuIldl)= rSetsus rino nnIud lGle;ne rator .gene rateI d(); } } } retu rn i nacti veInt erval ; time ou t. * Retur n t rue if t he c lient does not yet k now } } * sessi on t imeou ts. Serv erSe ssion sess ion = new Serv erSes sion( sessi onId) ; } * about t hreetu rn ( this. isNew ); /*/* rsetsus rino ns S.epsusti( osne.sgsei toAnpIpdl, i csaetsis oinoSne) s;sion (ctx, fals e); /v*o*i d rem oveA pplic ation Sessi on(Co ntex t con text) { * @peaxrcae mptino tne rIvlal le gTahleS tnaetwe E mxacxeipmt uimo ni nitfe rtvh ails * sessi on, or if the clien t cho oses not to jo in th e } * The b ackg round thre ad th at ch ecks for sessi on ti meout s an d shu tdown . } pri vate void thre adSto p() { * CalplpeS de sbsyi ocnosn.tr exmto vwe h(ecno nrt eqxute)s; t co mes i n so that acces ses and // XXX metho*d/ is ca lled on sess}ion . Fo r */ if(- 1 != inac tiveI nterv al) { }* inact ivit ies c an be deal t wit h ac cordi ngly. // sync' d fo r saf ty -- no o ther thre ad sh ould be ge tting som ethin g pu*b l iacn vi onivda l siedtaMtae xdI nsaecs tsivoenI nterv al(i nt in terva l) * examp le, if th e ser ver u sed o nly cooki e-bas ed se ssion s, pub lifc (v tohirde ardu n=(=) n{ull ) sess ion. setMa xInac tiveI nterv al(i nacti veInt erval ); */ // from this whil e we are r eapin g. T his i sn't the m ost o ptim al { */ and the clie nt } retu rn; /** // solut ion for t his, but w e'll dete rmine some thing else lat er. 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 // L oop until the termi natio n se mapho re is set retu rn s essio n.get Appli catio nSes sion( ctx, true ); * Calle d by cont ext w hen r eques t co mes i n so that acces ses and this .max Inact iveIn terva l = i nter val; new on each wthirle ea d(D!o tnhere=a dtDrounee; ) { } vo*i di nvaaclt idvait ei(e)s c an be deal t wit h ac cordi ngly. syn chron ized void reap () { retu rn ( this. maxIn activ eInte rval ); * reque st. thre tahdr.ei andtSelrer eup(t)(;) ; */ Enum erat ion e num = appS essio ns.k eys() ; } * proc essEx pires (); pub lic H ttpS essio n fin dSess ion(C onte xt ct x, St ring id) { try { } * @exce ptio n Ill egalS tateE xcept ion if th is me thod is } Serv erSe ssion sSes sion= (Serv erSe ssion )sess ions. get(i d); thre ad.jo in(); voi d acc esse d() { whil e (e num.h asMor eElem ents( )) { called on an } ca tch (Inte rrupt edExc eptio n e) { if(s Sess ion== null) retu rn nu ll; // 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(); * inva lida ted s essio n } ; // f rom the p revio us ac cess Appl icati onSes sion appSe ssio n = /** */ } retu rn s Sessi on.ge tAppl icati onSe ssion (ctx, fals e); (Appl icati onSes sion) appS essio ns.ge t(key ); * Set t he m aximu m tim e int erval , in seco nds, pub lic b oole an is New() { } last Acce ssed = thi sAcce ssTim e; between clie nt r eques ts } thre ad = null ; this Acce ssTim e = S ystem .curr entT imeMi llis( ); appS essio n.val idate (); * befor e th e ser vlet conta iner will inva lidat e retu rn ( this. isNew ); } the ses sion. A negat ive } } } * time indi cates that the sessi on s hould neve r } } time ou t. voi d val idat e() * // ------Ba ckgro und T hread * @para m in terva l The new maxim um i nterv al */ pub lic v oid setMa xInac tiveI nterv al(i nt in terva l) /** { * The b ackg round thre ad th at ch ecks for sessi on ti meout s an d shu tdown . */ this .max Inact iveIn terva l = i nter val; 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 (); } Spring 2005 ECE450H1S Software Engineering II } } Stan Wagon’s bike My square-wheel bike, on permanent display at Macalester College. This construction, believe it or not, earned me an entry in "Ripley's Believe It or Not"; beats standing in a block of ice for three days or growing three-foot long fingernails. -- http://www.stanwago n.com Stan Wagon ([email protected] du), Prof. of Mathematics and Computer Science, Macalester College, St. Paul, Minnesota

    Spring 2005 ECE450H1S Software Engineering II The Weaver

    MOVE UNTIL VALUE

    SCAN

    FIND

    REMOVALL FIND: AT LINE 5 VALUE: AT LINE7 SCAN: AT LINE 15 MOVE UNTIL: AT LINE 8

    REMOVALL: AT LINE 2 STRINGCOMP

    Yourdon & Constantine, SD, pg.168 Spring 2005 ECE450H1S Software Engineering II AspectJ The DRIVER aspect

    aspect Logging { The GROUND

    pointcut NeedLogging(): call(voidFIND()) || call(voidMOVEUNTIL()) || call(voidREMOVALL)|| pointcut call(voidSCAN() || call(voidVALUE());

    after() returning: NeedLogging() { STRINGCOMP(); The WAGON } }

    advice

    Spring 2005 ECE450H1S Software Engineering II 2. Aspect-orientation at large 2.1 Aspect-oriented Programming • It permeates into almost every popular high-level programming languages • Java Hyper/J, AspectJ, AJDT, JBoss • C/C++/C# AspectC/C++, C# • PHP AOPHP, AspectPHP … and many many more: see AOSD.NET

    Spring 2005 ECE450H1S Software Engineering II Every AOP mechanism has to support • Definition and representation of aspects – Definition of Advices in the component language – Definition of Joinpoints in regular expressions • Optionally, they can introduce new data members, changing the structures of components – Representation: New keywords, New directives, XML, but never change the code of components directly • Implementing a weaver – As preprocessor => generates woven components in the component language (AspectC, AOPHP) – As instrumenting compiler => generates woven components in the bytecode for the languages supporting reflection (AspectJ) – As interpretator => interpreting the woven code on-the-fly (AspectPHP)

    Spring 2005 ECE450H1S Software Engineering II 2. Aspect-orientation at large 2.2 Aspect-Oriented SD

    • AO includes the whole lifecycle of SE – http://www.aosd.net • There is a conference AOSD • There are workshops on Early Aspects at AOSD, OOPSLA, ICSE • Hot topics related to all other SD technologies – Aspect-oriented Refactoring – Aspect Mining – Aspect-oriented Debugging – Aspect-oriented Testing – Aspect-oriented Slicing – Aspect-oriented Model Checking …

    Spring 2005 ECE450H1S Software Engineering II 2. Aspect-orientation at large 2.3 Aspect-Oriented RE

    • Lessons learnt from success stories – SP => SA – OOP => OOA – Why not AOP => AOA? • Separation of crosscutting concerns earlier • Avoid duplication as early as possible • Identify aspects before mining them from code • Discover aspects in the early requriements – From structured requirement documents – From unstructured (textual) documents • Verify discovered (candidate) aspects in AOP

    Spring 2005 ECE450H1S Software Engineering II 3. A Case Study on AORE 1. Quickly go through goal-oriented requirements engineering 2. A requirements engineering process to elicit early aspects (goal aspects) 3. A reverse engineering exercise to identify candidate aspects (code aspects) 4. Linking goal aspects with code aspects

    Spring 2005 ECE450H1S Software Engineering II 3.1 Requirements Goal Models • A goal model is an intentional model • A goal can be decomposed into AND or OR subgoals • A goal model has both hard and soft goals – A hard goal can be either satisfied or denied – A soft goal is partially satisfied => satisficed • Soft goal uses HELP (+), HURT (-), MAKE (++) or BREAK (--) correlations to show partial satisfaction (satisfice) from a set of subgoals

    Spring 2005 ECE450H1S Software Engineering II 3.1.1 Hard goal model

    Spring 2005 ECE450H1S Software Engineering II 3.1.2 Soft goal model

    Spring 2005 ECE450H1S Software Engineering II 3.1.3 Goal-Oriented Requirements Analysis FS: Fully satisfied T: satisfied PS: Partially satisfied F: denied UN: Unknown U: unknown PD: Partially denied Get Reliable ++: MAKE Get Reliable FD: Fully denied Reply Goal: Reply CF: Conflict Contact a Friend

    ++: MAKE OR +: HELP --: BREAK

    Goal: Goal: Goal: Email a Friend Mail a Friend Call a Friend

    AND

    Text Editor SMTP Spring 2005 ECE450H1S Software Engineering II FS: Fully satisficed T: satisfied PS: Partially satisficed F: denied UN: Unknown U: unknown PD: Partially denied Get Reliable ++: MAKE Get Reliable FD: Fully denied Reply Goal: Reply CF: Conflict Contact a Friend ++: MAKE OR +: HELP --: BREAK

    Goal: Goal: Goal: Email a Friend Mail a Friend Call a Friend

    AND

    Text Editor SMTP Spring 2005 ECE450H1S Software Engineering II 3.1.4 V-graph

    In order to reason about interplay of functional and non-functional requirements, we create a particular type of goal model, called V-graph

    Spring 2005 ECE450H1S Software Engineering II correlation

    Goal SSooftfgtgooaall

    n

    o n

    i

    t io u t

    u b

    i b

    r i t r t

    n n

    o o

    c c

    Task

    Spring 2005 VECE450H1S Software Engineering II 3.2 The Process – Start from root-level goals and soft goals, correlate and decompose them into a V-graph – A goal analysis based on the label propagation algorithm is used to check for: • Conflicts • Inconsistencies • Denial of any goal or soft goals – After resolving the problems, a proper V- graph is obtained – Then we list the candidate aspects from the V-graph Spring 2005 ECE450H1S Software Engineering II list objectives co rre la se root soft te po goal om goals dec

    resolve conflict ssoofftt soft goals ggooaallss goals goals

    tion rela tasks cor ose tasks omp dec No conflict d ec om po se Consistent Satisfied & V model satisficed

    soft list goals goals aspects aspects Spring 2005 tasks ECE450H1S Software Engineering II 3.3 A Case Study

    • Medi@Shop adapted from literature: Castro, Kolp, Mylopoulos, Towards requirements-driven information systems engineering: the Tropos project, Journal of Information Systems, 2002. Can we find aspects from early requirements? • osCommerce studied from an LAMP (Linux, Apache, MySQL, PHP) Open-Source project: (http://www.oscommerce.com) Do they manifest in the developed software?

    Spring 2005 ECE450H1S Software Engineering II osCommerce (version 2.2m2)

    Spring 2005 ECE450H1S Software Engineering II Duplications in code

    Spring 2005 ECE450H1S Software Engineering II Candidate code aspects in the code Clone detection (by Semantic Design,Inc)

    LOC #clones Code description Need refactoring? 1 319 require($path . $file); No 1 260 echo $expression; No 559 2 class email; No 2 292 define ($variable, $value); No 76 2 class mime; No 4 67 messageStack->add ($error); Yes (NFR) 15 15 Postal code zone check Yes (FR) 22 10 require(application_top.); Yes (FR/NFR) SSL check 3 64 Set HTML head CHARSET Yes (NFR)

    Spring 2005 ECE450H1S Software Engineering II 3.4 Identifying goal aspects Correlate initial goals and softgoals

    T0 T1

    Spring 2005 ECE450H1S Software Engineering II Inconsistent decomposition

    T1 T2

    Spring 2005 ECE450H1S Software Engineering II Resolving inconsistency

    T2 T3

    Spring 2005 ECE450H1S Software Engineering II Further decomposition

    T3 T4

    Spring 2005 ECE450H1S Software Engineering II Further…

    Spring 2005 ECE450H1S STo5ftware Engineering II Spring 2005 ECE450H1S STo6ftware Engineering II Resolving Conflicts

    T6 T7

    Spring 2005 ECE450H1S Software Engineering II Result candidate aspects

    Spring 2005 ECE450H1S Software Engineering II Goal Aspects goal aspect Responsiveness[transaction] { pointcut transaction(): Preparing[cart,product]) || CheckingOut[cart, product, account, stock]); required () by: transaction() { SessionCookie[transaction](); } }; • AspectJ-like syntax • Allow weaving the operationalized tasks with goals specified in the pointcut

    Spring 2005 ECE450H1S Software Engineering II Your exercise • Reverse Engineering Identify some aspects in the OpenOME – Clone-detection or Callgraph extraction – Goal analysis • Forward Engineering – Implement some new NFR through AspectJ

    Spring 2005 ECE450H1S Software Engineering II 4. Summary • The concepts of aspect-orientation • The practise of AOP, AOSD, AORE, AOSR • A Case study of AORE

    Spring 2005 ECE450H1S Software Engineering II Further readings [AOP] G. Kiczales, J. Lamping, A. Mendhekar, C. Maeda, C. Lopes, J.-M. Loingtier, and J. Irwin. “Aspect oriented programming”. LNCS, 1241:220--242, Oct. 1997. [AORefactoring] C. Zhang, H.-A. Jacobsen. “Refactoring Middleware with Aspects”. TPDS 14(1):1058-1073. 2003 [AOMining] C. Zhang, H.-A. Jacobsen. “PRISM is research in Aspect Mining”. OOPSLA, 2004. [AORE] Y. Yu, J.C. Leite, J. Mylopoulos. “From goals to aspects: discovering aspects from goal models”. RE’04, 2004.

    Spring 2005 ECE450H1S Software Engineering II What’s next … • A tutorial on aspect-oriented programming tools – AspectJ – Eclipse/AJDT – Visualizing Aspects – Aspect mining tool • A lecture on (aspect-oriented) Software Reuse – Q7 in the OpenOME

    Spring 2005 ECE450H1S Software Engineering II