Unesp - Bauru - SP
Programação Orientada a Aspectos
e a linguagem AspectJ
Profa. Dra. Rosana Teresinha Vaccare Braga
4 de maio de 2005
(material elaborado por Valter Camargo e Paulo Masiero)
Instituto de Ciências Matemáticas e de Computação
Universidade de São Paulo
Laboratório de Engenharia de Software
Roteiro
• Introdução
– Histórico
– Limitação do Paradigma OO
– Entrelaçamento/espalhamento de código
– O que é um interesse transversal ?
• Programação Orientada a Aspectos
– Conceitos básicos e características
• AspectJ
– Principais construções
• Conclusão
2
Introdução – histórico
• Por muito tempo o objetivo da engenharia de software...
– “Decomposição IDEAL dos conceitos” importantes do problema a ser
solucionado...
– Manutenibilidade, reuso, modularidade, evolução Software com
qualidade
• Esse objetivo motivou a evolução dos paradigmas de programação
(procedimental, estruturado, etc) até chegar na orientação a objetos
3
Paradigma Procedimental ou
Estruturado
Decomposição em procedimentos ou funções
Exemplo:
Banco
Abrir
Contacorrente
Abrir
Poupança
Depositar
Ver o saldo
Sacar
Fechar
conta
Tornar cliente
especial
4
Paradigma Orientado a Objetos
Decomposição em classes de objetos
Exemplo:
Conta
Cliente
possui
nome
tipo
1
tornarEspecial()
conta-corrente
número
valor
abrir()
1..n fechar()
sacar()
depositar()
verSaldo()
Poupança
limiteEspecial
diaRendimento
verSaldo()
verSaldo()
5
Introdução – OO é Unidimensional
•
Possui determinadas limitações quando o assunto é
decomposição ideal dos interesses
–
Causa entrelaçamento e espalhamento de código de diferentes
interesses
•
A fonte desses problemas é a sua “unidimensionalidade”
•
Unidimensional implica que há apenas um tipo de módulo dominante,
isto é, uma única dimensão (= simétrico)
6
Introdução - OO é Unidimensional
• Os módulos dominantes das abordagens “simétricas” não são
adequados para modularizar interesses transversais (crosscutting
concerns) :
– Entrelaçamento (tangling) de códigos com diferentes interesses em
um mesmo módulo
– Espalhamento do código de um interesse por inúmeros módulos do
sistema
7
Exemplo de Entrelaçamento
Código do Parser XML no Tomcat entrelaçado com um módulo
funcional
8
Exemplo de Espalhamento
Código para Logging no Tomcat
9
Exemplo de Espalhamento Gerenc.
de Sessões
StandardSession
ApplicationSession
/*
* ==== ===== ==== ===== ===== ===== ===== ==== ===== ===== ===== ===== ==== ===== ==
*
* The Apach e So ftwar e Lic ense, Vers ion 1.1
*
* Copy right (c) 1999 The Apach e Sof twar e Fou ndati on. All r ight s
* rese rved.
*
* Redi strib utio n and use in so urce and binar y for ms, w ith o r wi thout
* modi ficat ion, are permi tted provi ded that the f ollow ing c ondi tions
* are met:
*
* 1. R edist ribu tions of s ource code mus t ret ain t he ab ove c opyr ight
*
n otice , th is li st of cond ition s an d the foll owing disc laim er.
*
* 2. R edist ribu tions in b inary form mus t rep roduc e the abov e co pyrig ht
*
n otice , th is li st of cond ition s an d the foll owing disc laim er in
*
t he do cume ntati on an d/or other mat erial s pro vided with the
*
d istri buti on.
*
* 3. T he en d-us er do cumen tatio n inc lude d wit h the redi strib utio n, if
*
a ny, m ust inclu de th e fol lowin g ac knowl egeme nt:
*
"Th is p roduc t inc ludes soft ware deve loped by t he
*
Ap ache Soft ware Found ation (ht tp:// www.a pache .org/ )."
*
A ltern atel y, th is ac knowl egeme nt m ay ap pear in th e sof twar e
itself,
*
i f and whe rever such thir d-par ty a cknow legem ents norma lly appea r.
*
* 4. T he na mes "The Jakar ta Pr oject ", " Tomca t", a nd "A pache Sof tware
*
F ounda tion " mus t not be u sed t o en dorse or p romot e pro duct s
derived
*
f rom t his softw are w ithou t pri or w ritte n per missi on. F or w ritte n
*
p ermis sion , ple ase c ontac t apa che@ apach e.org .
*
* 5. P roduc ts d erive d fro m thi s sof twar e may not be ca lled "Apa che"
*
n or ma y "A pache " app ear i n the ir n ames witho ut pr ior w ritt en
*
p ermis sion of t he Ap ache Group .
*
* THIS SOFT WARE IS P ROVID ED `` AS IS '' A ND AN Y EXP RESSE D OR IMPL IED
* WARR ANTIE S, I NCLUD ING, BUT N OT LI MITE D TO, THE IMPLI ED WA RRAN TIES
* OF M ERCHA NTAB ILITY AND FITNE SS FO R A PARTI CULAR PURP OSE A RE
* DISC LAIME D. IN NO EVEN T SHA LL TH E AP ACHE SOFTW ARE F OUNDA TION OR
* ITS CONTR IBUT ORS B E LIA BLE F OR AN Y DI RECT, INDI RECT, INCI DENT AL,
* SPEC IAL, EXEM PLARY , OR CONSE QUENT IAL DAMAG ES (I NCLUD ING, BUT NOT
* LIMI TED T O, P ROCUR EMENT OF S UBSTI TUTE GOOD S OR SERVI CES; LOSS OF
* USE, DATA , OR PROF ITS; OR BU SINES S IN TERRU PTION ) HOW EVER CAUS ED AN D
* ON A NY TH EORY OF L IABIL ITY, WHETH ER I N CON TRACT , STR ICT L IABI LITY,
* OR T ORT ( INCL UDING NEGL IGENC E OR OTHE RWISE ) ARI SING IN AN Y WA Y OUT
* OF T HE US E OF THIS SOFT WARE, EVEN IF ADVIS ED OF THE POSSI BILI TY OF
* SUCH DAMA GE.
* ==== ===== ==== ===== ===== ===== ===== ==== ===== ===== ===== ===== ==== ===== ==
*
* This soft ware cons ists of vo lunta ry c ontri butio ns ma de by man y
* indi vidua ls o n beh alf o f the Apac he S oftwa re Fo undat ion. For more
* info rmati on o n the Apac he So ftwar e Fo undat ion, pleas e see
* <htt p://w ww.a pache .org/ >.
*
* [Add ition al n otice s, if requ ired by p rior licen sing condi tion s]
*
*/
public void inva lidat e() {
serv erSe ssion .remo veApp licat ionS essio n(con text) ;
// r emov e eve rythi ng in the sess ion
Enum erat ion e num = valu es.ke ys() ;
whil e (e num.h asMor eElem ents( )) {
Stri ng na me = (Stri ng)en um.n extEl ement ();
remo veVal ue(na me);
}
vali d = false ;
}
pub lic b oole an is New() {
if ( ! va lid) {
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);
package org. apac he.to mcat. sessi on;
import java. io.I OExce ption ;
import java. io.O bject Input Strea m;
import java. io.O bject Outpu tStre am;
import java. io.S erial izabl e;
import java. util .Enum erati on;
import java. util .Hash table ;
import java. util .Vect or;
import javax .ser vlet. Servl etExc eptio n;
import javax .ser vlet. http. HttpS essio n;
import
javax.s ervle t.ht tp.Ht tpSes sionB indin gEve nt;
import
javax.s ervle t.ht tp.Ht tpSes sionB indin gLis tener ;
import javax .ser vlet. http. HttpS essio nCon text;
import org.a pach e.tom cat.c atali na.*;
import org.a pach e.tom cat.u til.S tring Mana ger;
}
if ( this Acces sTime == c reati onTi me) {
retu rn tr ue;
} el se {
retu rn fa lse;
}
}
/**
* @depr ecat ed
*/
pub lic v oid putVa lue(S tring name , Ob ject value ) {
setA ttri bute( name, valu e);
}
pub lic v oid setAt tribu te(St ring name , Obj ect v alue) {
if ( ! va lid) {
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);
}
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ;
thro w new Ille galAr gumen tExc eptio n(msg );
/**
* Stan dard impl ement ation of t he
<b>Sess ion</ b> i nterf ace. This obje ct i s
* seri aliza ble, so t hat i t can be s tore d in
persist ent s tora ge or tran sferr ed
* to a diff eren t JVM for distr ibuta ble
session supp ort.
* <p>
* <b>I MPLEM ENTA TION NOTE< /b>: An i nsta nce o f
this cl ass r epre sents both the
* inte rnal (Ses sion) and appli catio n le vel
(HttpSe ssion ) vi ew of the sessi on.
* Howe ver, beca use t he cl ass i tself is not
declare d pub lic, Java logi c out side
* of t he
<code>o rg.ap ache .tomc at.se ssion </cod e> p ackag e
cannot cast an
* Http Sessi on v iew o f thi s ins tance bac k to a
Session view .
*
* @aut hor C raig R. M cClan ahan
* @ver sion $Rev ision : 1.2 $ $D ate: 2000 /05/1 5
17:54:1 0 $
*/
final c lass Stan dardS essio n
imp lemen ts H ttpSe ssion , Ses sion {
/**
/**
* Retur n th e <co de>Ht tpSes sion< /cod e> fo r whi ch
this ob ject
* is th e fa cade.
*/
pub lic H ttpS essio n get Sessi on() {
* Bind an o bject to t his s essio n, u sing the s pecif ied n ame. If an ob ject
* of th e sa me na me is alre ady b ound to t his s essio n, th e ob ject is
* repla ced.
* <p>
* After thi s met hod e xecut es, a nd i f the obje ct im pleme nts
* <code >Htt pSess ionBi nding Liste ner< /code >, th e con taine r ca lls
* <code >val ueBou nd()< /code > on the objec t.
*
* @para m na me Na me to whic h the obj ect i s bou nd, c annot be null
* @para m va lue O bject to b e bou nd, canno t be null
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n
* inva lida ted s essio n
*
* @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d by
* <cod e>se tAttr ibute ()</c ode>
*/
pub lic v oid putVa lue(S tring name , Ob ject value ) {
retu rn ( (Http Sessi on) t his);
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- Sessi on Pu blic Meth ods
/**
* Updat e th e acc essed time info rmat ion f or th is
session . Th is m ethod
* shoul d be call ed by the conte xt w hen a requ est
comes i n for a p artic ular
* sessi on, even if th e app licat ion does not
referen ce it .
*/
pub lic v oid acces s() {
setA ttri bute( name, valu e);
}
/**
* Remov e th e obj ect b ound with the speci fied name from this sess ion. If
* the s essi on do es no t hav e an obje ct bo und w ith t his n ame, this meth od
* does noth ing.
* <p>
* After thi s met hod e xecut es, a nd i f the obje ct im pleme nts
* <code >Htt pSess ionBi nding Liste ner< /code >, th e con taine r ca lls
* <code >val ueUnb ound( )</co de> o n th e obj ect.
*
* @para m na me Na me of the objec t to remo ve fr om th is se ssio n.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n
* inva lida ted s essio n
*/
pub lic v oid remov eAttr ibute (Stri ng n ame) {
this .las tAcce ssedT ime = this .thi sAcce ssedT ime;
this .thi sAcce ssedT ime =
System. curre ntTi meMil lis() ;
this .isN ew=fa lse;
}
/**
* Perfo rm t he in terna l pro cessi ng r equir ed to
invalid ate t his sessi on,
* witho ut t rigge ring an ex cepti on i f the sess ion
has alr eady expi red.
*/
pub lic v oid expir e() {
sync hron ized (attr ibute s) {
Obje ct ob ject = att ribut es.g et(na me);
if ( objec t == null)
retur n;
attr ibute s.rem ove(n ame);
//
S ystem .out. print ln( "Remo ving attri bute " + name );
if ( objec t ins tance of Ht tpSe ssion Bindi ngLis tener ) {
((Htt pSess ionBi nding List ener) obje ct).v alueU nbou nd
( new H ttpSe ssion Bind ingEv ent(( HttpS essio n) t his, name) );
}
}
// R emov e thi s ses sion from our manag er's
active sessi ons
if ( (man ager != nu ll) & & (ma nage r ins tance of
Manager Base) )
((Ma nager Base) mana ger). remo ve(th is);
// U nbin d any obje cts a ssoci ated with this
}
session
remo veVa lue(n ame);
// remov e an y exi sting bind ing
if ( valu e != null && va lue i nsta nceof Http Sessi onBin ding Liste ner) {
Http Sessi onBin dingE vent e =
new H ttpSe ssion Bindi ngEv ent(t his, name) ;
((Ht tpSes sionB indin gList ener )valu e).va lueBo und(e );
}
valu es.p ut(na me, v alue) ;
}
/**
* @depr ecat ed
*/
pub lic O bjec t get Value (Stri ng na me) {
retu rn g etAtt ribut e(nam e);
}
package org. apac he.to mcat. sessi on;
import org.a pach e.tom cat.c ore.* ;
import org.a pach e.tom cat.u til.S tring Mana ger;
import java. io.* ;
import java. net. *;
import java. util .*;
import javax .ser vlet. *;
import javax .ser vlet. http. *;
pub lic O bjec t get Attri bute( Strin g na me) {
if ( ! va lid) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise ");
/**
* Core impl emen tatio n of an ap plica tion leve l ses sion
*
* @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om]
* @aut hor J ason Hunt er [j ch@en g.sun .com ]
* @aut hor J ames Todd [gon zo@en g.sun .com ]
*/
thro w new Ille galSt ateEx cept ion(m sg);
}
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ;
// ----- ---- ----- ----- ----- ----- ---- ----- ------- ----- ---- ---- Const ructo rs
/**
* Const ruct a ne w Ses sion assoc iate d wit h
the spe cifie d Ma nager .
*
* @para m ma nager The manag er wi th w hich
this Se ssion is assoc iated
*/
pub lic S tand ardSe ssion (Mana ger m anag er) {
retu rn v alues .get( name) ;
}
/**
* @depr ecat ed
*/
pub lic S trin g[] g etVal ueNam es() {
Enum erat ion e = ge tAttr ibute Name s();
Vect or n ames = new Vect or();
whil e (e .hasM oreEl ement s()) {
name s.add Eleme nt(e. nextE leme nt()) ;
/**
* Remov e th e obj ect b ound with the speci fied name from this sess ion. If
* the s essi on do es no t hav e an obje ct bo und w ith t his n ame, this meth od
* does noth ing.
* <p>
* After thi s met hod e xecut es, a nd i f the obje ct im pleme nts
* <code >Htt pSess ionBi nding Liste ner< /code >, th e con taine r ca lls
* <code >val ueUnb ound( )</co de> o n th e obj ect.
*
* @para m na me Na me of the objec t to remo ve fr om th is se ssio n.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n
* inva lida ted s essio n
*
* @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d by
* <cod e>re moveA ttrib ute() </cod e>
*/
pub lic v oid remov eValu e(Str ing n ame) {
}
}
// ----- ---- ----- ----- ----- ----- ---- ----- ------- ----- -- I nstan ce Va riabl es
/**
* The c olle ction of u ser d ata a ttri butes
associa ted w ith this Sessi on.
*/
pri vate Hash table attr ibute s = n ew
Hashtab le();
thro w new Ille galAr gumen tExc eptio n(msg );
pri vate Stri ngMan ager sm =
Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" );
pri vate Hash table valu es = new H asht able( );
pri vate Stri ng id ;
pri vate Serv erSes sion serve rSess ion;
pri vate Cont ext c ontex t;
pri vate long crea tionT ime = Syst em.c urren tTime Milli s();;
pri vate long this Acces sTime = cr eati onTim e;
pri vate long last Acces sed = crea tion Time;
pri vate int inact iveIn terva l = - 1;
pri vate bool ean v alid = tru e;
}
// M ark this sessi on as inva lid
setV alid (fals e);
supe r();
this .man ager = man ager;
}
public class App licat ionSe ssion impl emen ts Ht tpSes sion {
Vect or r esult s = n ew Ve ctor( );
Enum erat ion a ttrs = get Attri bute Names ();
whil e (a ttrs. hasMo reEle ments ()) {
Stri ng at tr = (Stri ng) a ttrs .next Eleme nt();
resu lts.a ddEle ment( attr) ;
}
Enum erat ion n ames = res ults. elem ents( );
whil e (n ames. hasMo reEle ments ()) {
Stri ng na me = (Stri ng) n ames .next Eleme nt();
remo veAtt ribut e(nam e);
}
/**
* The t ime this sessi on wa s cre ated , in
millise conds sin ce mi dnigh t,
* Janua ry 1 , 197 0 GMT .
*/
pri vate long crea tionT ime = 0L;
/**
* Relea se a ll ob ject refer ences , an d ini tiali ze
instanc e var iabl es, i n
* prepa rati on fo r reu se of this obj ect.
*/
pub lic v oid recyc le() {
// R eset the insta nce v ariab les assoc iated with
this Se ssion
attr ibut es.cl ear() ;
crea tion Time = 0L;
id = nul l;
last Acce ssedT ime = 0L;
mana ger = nul l;
maxI nact iveIn terva l = - 1;
isNe w = true;
isVa lid = fal se;
remo veAt tribu te(na me);
/**
* The s essi on id entif ier o f thi s Se ssion .
*/
pri vate Stri ng id = nu ll;
/**
* Bind an o bject to t his s essio n, u sing the s pecif ied n ame. If an ob ject
* of th e sa me na me is alre ady b ound to t his s essio n, th e ob ject is
* repla ced.
* <p>
* After thi s met hod e xecut es, a nd i f the obje ct im pleme nts
* <code >Htt pSess ionBi nding Liste ner< /code >, th e con taine r ca lls
* <code >val ueBou nd()< /code > on the objec t.
*
* @para m na me Na me to whic h the obj ect i s bou nd, c annot be null
* @para m va lue O bject to b e bou nd, canno t be null
*
* @exce ptio n Ill egalA rgume ntExc epti on if an a ttemp t is made to a dd a
* non- seri aliza ble o bject in a n en viron ment marke d dis trib utabl e.
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n
* inva lida ted s essio n
*/
pub lic v oid setAt tribu te(St ring name , Obj ect v alue) {
if ( (man ager != nu ll) & & (ma nage r ins tance of
Manager Base) )
((Ma nager Base) mana ger). recy cle(t his);
}
}
App licat ionS essio n(Str ing i d, Se rver Sessi on se rverS essio n,
Cont ext conte xt) {
this .ser verSe ssion = se rverS essi on;
this .con text = con text;
this .id = id;
Stri ng[] valu eName s = n ew St ring [name s.siz e()];
name s.co pyInt o(val ueNam es);
retu rn v alueN ames;
/**
* Descr ipti ve in forma tion descr ibin g thi s
Session impl emen tatio n.
*/
pri vate stat ic fi nal S tring info =
"Standa rdSes sion /1.0" ;
this .ina ctive Inter val = cont ext. getSe ssion TimeO ut();
}
if ( this .inac tiveI nterv al != -1) {
this .inac tiveI nterv al *= 60;
}
pub lic E nume ratio n get Attri buteN ames () {
if ( ! va lid) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise ");
}
Ser verSe ssio n get Serve rSess ion() {
retu rn s erver Sessi on;
thro w new Ille galSt ateEx cept ion(m sg);
/**
* The l ast acces sed t ime f or th is
Session .
*/
pri vate long last Acces sedTi me =
creatio nTime ;
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----Session Pack age Metho ds
/**
* Retur n th e <co de>is Valid </cod e> f lag f or th is
session .
*/
boo lean isVa lid() {
if ( (man ager != nu ll) & & man ager .getD istri butab le() &&
!( valu e ins tance of Se riali zabl e))
thro w new Ille galAr gumen tExc eptio n
(sm.g etStr ing(" stand ardS essio n.set Attri bute. iae" ));
sync hron ized (attr ibute s) {
remo veAtt ribut e(nam e);
attr ibute s.put (name , val ue);
if ( value inst anceo f Htt pSes sionB indin gList ener)
((Htt pSess ionBi nding List ener) valu e).va lueBo und
( new H ttpSe ssion Bind ingEv ent(( HttpS essio n) t his, name) );
}
retu rn ( this. isVal id);
}
}
}
Hash tabl e val uesCl one = (Has htab le)va lues. clone ();
/**
* Calle d by cont ext w hen r eques t co mes i n so that acces ses and
* inact ivit ies c an be deal t wit h ac cordi ngly.
*/
retu rn ( Enume ratio n)val uesCl one. keys( );
}
voi d acc esse d() {
// s et l ast a ccess ed to this Acce ssTim e as it wi ll be lef t ove r
// f rom the p revio us ac cess
last Acce ssed = thi sAcce ssTim e;
this Acce ssTim e = S ystem .curr entT imeMi llis( );
/**
* The M anag er wi th wh ich t his S essi on is
associa ted.
*/
pri vate Mana ger m anage r = n ull;
/**
* @depr ecat ed
*/
pub lic v oid remov eValu e(Str ing n ame) {
remo veAt tribu te(na me);
}
vali date ();
}
pub lic v oid remov eAttr ibute (Stri ng n ame) {
if ( ! va lid) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise ");
voi d val idat e() {
// i f we have an i nacti ve in terv al, c heck to se e if we'v e exc eeded it
if ( inac tiveI nterv al != -1) {
int thisI nterv al =
(int) (Syst em.cu rrent Time Milli s() - last Acces sed) / 10 00;
thro w new Ille galSt ateEx cept ion(m sg);
}
if ( thisI nterv al > inact iveI nterv al) {
inval idate ();
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ;
/**
* The m axim um ti me in terva l, in sec onds,
between clie nt r eques ts be fore
* the s ervl et co ntain er ma y inv alid ate
this se ssion . A nega tive time
* indic ates that the sessi on sh ould neve r
time ou t.
*/
pri vate int maxIn activ eInte rval = -1 ;
/**
* Flag indi catin g whe ther this sess ion i s
new or not.
*/
pri vate bool ean i sNew = tru e;
/**
* Set t he < code> isNew </cod e> fl ag f or th is
session .
*
* @para m is New T he ne w val ue fo r th e
<code>i sNew< /cod e> fl ag
*/
voi d set New( boole an is New) {
// ----- ---- ----- ----- ----- ----- ---- ----- ----- - Htt pSess ion Priva te Me thods
/**
* Read a se riali zed v ersio n of this sess ion o bject from the spec ified
* objec t in put s tream .
* <p>
* <b>IM PLEM ENTAT ION N OTE</ b>: The refer ence to th e own ing Manag er
* is no t re store d by this metho d, a nd mu st be set expli citl y.
*
* @para m st ream The i nput strea m to read from
*
* @exce ptio n Cla ssNot Found Excep tion if a n unk nown class is speci fied
* @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s
*/
pri vate void read Objec t(Obj ectIn putS tream stre am)
thro ws C lassN otFou ndExc eptio n, I OExce ption {
/**
* Set t he < code> isVal id</c ode> flag for this
session .
*
* @para m is Valid The new v alue for the
<code>i sVali d</c ode> flag
*/
voi d set Vali d(boo lean isVal id) {
this .isV alid = isV alid;
// HTTP SESS ION I MPLEM ENTAT ION M ETHO DS
Obje ct o = va lues. get(n ame);
pub lic S trin g get Id() {
if ( vali d) {
retu rn id ;
} el se {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise ");
if ( o in stanc eof H ttpSe ssion Bind ingLi stene r) {
Http Sessi onBin dingE vent e =
new H ttpSe ssion Bindi ngEv ent(t his,n ame);
((Ht tpSes sionB indin gList ener )o).v alueU nboun d(e);
}
thro w new Ille galSt ateEx cept ion(m sg);
}
/**
* Flag indi catin g whe ther this sess ion i s
valid o r not .
*/
pri vate bool ean i sVali d = f alse;
/**
* The s trin g man ager for t his p acka ge.
*/
pri vate Stri ngMan ager sm =
valu es.r emove (name );
StringM anage r.ge tMana ger(" org.a pache .tom cat.s e
ssion") ;
}
}
pub lic l ong getCr eatio nTime () {
if ( vali d) {
retu rn cr eatio nTime ;
} el se {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise ");
pub lic v oid setMa xInac tiveI nterv al(i nt in terva l) {
if ( ! va lid) {
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);
}
thro w new Ille galSt ateEx cept ion(m sg);
}
inac tive Inter val = inte rval;
}
}
/**
*
* @depr ecat ed
*/
pub lic i nt g etMax Inact iveIn terva l() {
if ( ! va lid) {
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);
pub lic H ttpS essio nCont ext g etSes sion Conte xt() {
retu rn n ew Se ssion Conte xtImp l();
}
}
/**
* The H TTP sessi on co ntext asso ciat ed
with th is se ssio n.
*/
pri vate stat ic Ht tpSes sionC ontex t
session Conte xt = null ;
/**
* The c urre nt ac cesse d tim e for thi s
session .
*/
pri vate long this Acces sedTi me =
creatio nTime ;
retu rn i nacti veInt erval ;
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- HttpS essio n Pr opert ies
/**
* Retur n th e tim e whe n thi s ses sion was creat ed,
in mill iseco nds since
* midni ght, Janu ary 1 , 197 0 GMT .
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on an
* inva lida ted s essio n
*/
pub lic l ong getCr eatio nTime () {
retu rn ( this. creat ionTi me);
/**
* Write a s erial ized versi on of thi s ses sion objec t to the speci fied
* objec t ou tput strea m.
* <p>
* <b>IM PLEM ENTAT ION N OTE</ b>: The ownin g Man ager will not be st ored
* in th e se riali zed r epres entat ion of th is Se ssion . Af ter calli ng
* <code >rea dObje ct()< /code >, yo u mu st se t the asso ciate d Ma nager
* expli citl y.
* <p>
* <b>IM PLEM ENTAT ION N OTE</ b>: Any attri bute that is no t Se riali zable
* will be s ilent ly ig nored . If you do n ot wa nt an y suc h at tribu tes,
* be su re t he <c ode>d istri butab le</ code> prop erty of ou r as socia ted
* Manag er i s set to < code> true< /cod e>.
*
* @para m st ream The o utput stre am t o wri te to
*
* @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s
*/
pri vate void writ eObje ct(Ob jectO utpu tStre am st ream) thro ws I OExce ption {
}
pub lic l ong getLa stAcc essed Time( ) {
if ( vali d) {
retu rn la stAcc essed ;
} el se {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise ");
}
// ----- ---- ----- ----- ----- ----- ---- ----- ------- ----- -- S essio n Pro perti es
//----- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- ----- ---/**
* Set t he c reati on ti me fo r thi s se ssion .
This me thod is c alled by t he
* Manag er w hen a n exi sting Sess ion
instanc e is reus ed.
*
* @para m ti me Th e new crea tion time
*/
pub lic v oid setCr eatio nTime (long tim e) {
thro w new Ille galSt ateEx cept ion(m sg);
}
}
this .cre ation Time = tim e;
this .las tAcce ssedT ime = time ;
this .thi sAcce ssedT ime = time ;
}
/**
* Retur n th e ses sion ident ifier for this
session .
*/
pub lic S trin g get Id() {
retu rn ( this. id);
if ( sess ionCo ntext == n ull)
sess ionCo ntext = ne w
Standar dSess ionC ontex t();
retu rn ( sessi onCon text) ;
// ----- ---- ----- ----- ----- ----- ---- ----- ----- --HttpSes sion Publ ic Me thods
resp onse .addH eader ( Coo kieTo ols. getCo okieH eader Name( cook ie),
Coo kieTo ols. getCo okieH eader Value (coo kie)) ;
cook ie.s etVer sion( 0);
resp onse .addH eader ( Coo kieTo ols. getCo okieH eader Name( cook ie),
Coo kieTo ols. getCo okieH eader Value (coo kie)) ;
retu rn 0 ;
pub lic i nt r eques tMap( Reque st re ques t ) {
Stri ng s essio nId = null ;
}
Cook ie c ookie s[]=r eques t.get Cook ies() ; // asser t !=n ull
/** Noti fica tion of co ntext shut down
*/
pub lic v oid conte xtShu tdown ( Con text ctx )
thro ws T omcat Excep tion
{
if( ctx. getDe bug() > 0 ) ctx .log ("Rem oving sess ions from " + ctx ) ;
ctx. getS essio nMana ger() .remo veSe ssion s(ctx );
}
for( int i=0; i<co okies .leng th; i++ ) {
Cook ie co okie = coo kies[ i];
if ( cooki e.get Name( ).equ als( "JSES SIONI D")) {
sessi onId = coo kie.g etVa lue() ;
sessi onId= valid ateSe ssio nId(r eques t, se ssion Id);
if (s essio nId!= null) {
r eques t.set Reque sted Sessi onIdF romCo okie( true );
}
}
}
}
Stri ng s ig="; jsess ionid =";
int foun dAt=- 1;
if( debu g>0 ) cm.l og(" XXX R URI= " + r eques t.get Reque stUR I());
if ( (fou ndAt= reque st.ge tRequ estU RI(). index Of(si g))!= -1){
sess ionId =requ est.g etReq uest URI() .subs tring (foun dAt+ sig.l ength ());
// r ewrit e URL , do I nee d to do a nythi ng mo re?
requ est.s etReq uestU RI(re ques t.get Reque stURI ().su bstr ing(0 , fou ndAt) );
sess ionId =vali dateS essio nId( reque st, s essio nId);
if ( sessi onId! =null ){
reque st.se tRequ ested Sess ionId FromU RL(tr ue);
}
}
retu rn 0 ;
import java. io.I OExce ption ;
import java. util .Enum erati on;
import java. util .Hash table ;
import java. util .Vect or;
import org.a pach e.tom cat.c atali na.*;
import javax .ser vlet. http. Cooki e;
import javax .ser vlet. http. HttpS essio n;
import org.a pach e.tom cat.u til.S tring Mana ger;
import org.w 3c.d om.Na medNo deMap ;
import org.w 3c.d om.No de;
/**
* Has t his compo nent been confi gure d yet ?
*/
pri vate bool ean c onfig ured = fal se;
/**
* The d escr iptiv e inf ormat ion a bout this impl ement ation .
*/
pri vate stat ic fi nal S tring info = " Stand ardMa nager /1.0" ;
// XXX w hat is th e cor rect behav ior if th e ses sion is in vali d ?
// We ma y st ill s et it and just retu rn se ssion inva lid.
/** Vali date and fix t he se ssion id. If t he se ssion is n ot v alid retur n nul l.
* It w ill also clean up t he se ssio n fro m loa d-bal ancin g st rings .
* @retu rn s essio nId, or nu ll if not vali d
*/
pri vate Stri ng va lidat eSess ionId (Req uest reque st, S tring ses sionI d){
// G S, W e pig gybac k the JVM id o n top of t he se ssion coo kie
// S epar ate t hem . ..
ServerSession
if ( (thi s.id != nu ll) & & (ma nage r !=
/**
* The s trin g man ager for t his p acka ge.
*/
pri vate Stri ngMan ager sm =
Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" );
/**
* Has t his compo nent been start ed y et?
*/
pri vate bool ean s tarte d = f alse;
if ( sess ionId != n ull & & ses sion Id.le ngth( )!=0) {
// G S, We are in a probl em h ere, we ma y act ually get
// m ultip le Se ssion cook ies (one for t he ro ot
// c ontex t and one for t he r eal c ontex t... or ol d se ssion
// c ookie . We must check for vali dity in th e cur rent cont ext.
Cont ext c tx=re quest .getC onte xt();
Sess ionMa nager sM = ctx. getS essio nMana ger() ;
if(n ull ! = sM. findS essio n(ct x, se ssion Id)) {
sM.ac cesse d(ctx , req uest , ses sionI d );
reque st.se tRequ ested Sess ionId (sess ionId );
if( d ebug> 0 ) c m.log (" F inal sessi on id " + sess ionId );
retur n ses sionI d;
}
}
retu rn n ull;
retu rn ( attri butes .get( name) );
/**
* Retur n an <cod e>Enu merat ion</ code > of
<code>S tring </co de> o bject s
* conta inin g the name s of the o bjec ts bo und t o
this se ssion .
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on an
* inva lida ted s essio n
*/
pub lic E nume ratio n get Attri buteN ames () {
/**
* The b ackg round thre ad.
*/
pri vate Thre ad th read = nul l;
void va lidat e() {
// i f we have an i nacti ve in terv al, c heck to se e if
// w e've exce eded it
if ( inac tiveI nterv al != -1) {
int thisI nterv al =
(int) (Syst em.cu rrent Time Milli s() - last Acces sed) / 10 00;
if ( thisI nterv al > inact iveI nterv al) {
inval idate ();
/**
* Core impl emen tatio n of a ser ver s essi on
*
* @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om]
* @aut hor J ames Todd [gon zo@en g.sun .com ]
*/
Serve rSess ionMa nager ssm =
S erver Sessi onMan ager .getM anage r();
ssm.r emove Sessi on(th is);
if ( (man ager != nu ll) & & (ma nage r
instanc eof M anag erBas e))
((Ma nager Base) mana ger). add( this) ;
}
retu rn ( attri butes .keys ());
sta tic a dvic e(Sta ndard Sessi on s) : in valid ate(s ) {
befo re {
if ( !s.is Valid ())
throw new Illeg alSta teEx cepti on
( s.sm. getSt ring( "sta ndard Sessi on."
+ th isJoi nPoin t.met hodNa me
+ ". ise") );
}
}
/**
* Retur n de scrip tive infor matio n ab out
this Se ssion imp lemen tatio n and
* the c orre spond ing v ersio n num ber, in
the for mat
*
<code>& lt;de scri ption >/ <v ersio n> ;</co d
e>.
*/
pub lic S trin g get Info( ) {
retu rn ( getAt tribu te(na me));
}
retu rn ( this. info) ;
}
public class Ser verSe ssion {
}
}
}
pri vate Stri ngMan ager sm =
Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" );
pri vate Hash table valu es = new H asht able( );
pri vate Hash table appS essio ns = new Hasht able( );
pri vate Stri ng id ;
pri vate long crea tionT ime = Syst em.c urren tTime Milli s();;
pri vate long this Acces sTime = cr eati onTim e;
pri vate long last Acces sed = crea tion Time;
pri vate int inact iveIn terva l = - 1;
syn chron ized void inva lidat e() {
Enum erat ion e num = appS essio ns.k eys() ;
Ser verSe ssio n(Str ing i d) {
this .id = id;
}
}
pub lic v oid putVa lue(S tring name , Ob ject value ) {
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("s erver Sessi on.va lue.i ae") ;
whil e (e num.h asMor eElem ents( )) {
Obje ct ke y = e num.n extEl emen t();
Appl icati onSes sion appSe ssio n =
(Appl icati onSes sion) appS essio ns.ge t(key );
appS essio n.inv alida te();
}
pub lic S trin g get Id() {
retu rn i d;
}
thro w new Ille galAr gumen tExc eptio n(msg );
/**
* Retur n th e las t tim e the clie nt s ent a
request asso ciat ed wi th th is
* sessi on, as th e num ber o f mil lise conds
since m idnig ht, Janua ry 1, 1970
* GMT. Act ions that your appli cati on
takes, such as g ettin g or setti ng
* a val ue a ssoci ated with the s essi on, d o
not aff ect t he a ccess time .
*/
pub lic l ong getLa stAcc essed Time( ) {
retu rn ( this. lastA ccess edTim e);
/**
* Retur n th e set of n ames of ob ject s bou nd to this
session . If the re
* are n o su ch ob jects , a z ero-l engt h arr ay is
returne d.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on an
* inva lida ted s essio n
*
* @depr ecat ed As of V ersio n 2.2 , th is me thod is
replace d by
* <cod e>ge tAttr ibute Names ()</c ode>
*/
pub lic S trin g[] g etVal ueNam es() {
remo veVa lue(n ame); // remov e an y exi sting bind ing
valu es.p ut(na me, v alue) ;
}
pub lic l ong getLa stAcc essed Time( ) {
retu rn l astAc cesse d;
}
pub lic O bjec t get Value (Stri ng na me) {
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("s erver Sessi on.va lue.i ae") ;
pub lic A ppli catio nSess ion g etApp lica tionS essio n(Con text cont ext,
bool ean creat e) {
Appl icat ionSe ssion appS essio n =
(App licat ionSe ssion )appS essi ons.g et(co ntext );
thro w new Ille galAr gumen tExc eptio n(msg );
}
// X XX
// s ync t o ens ure v alid?
pub lic E nume ratio n get Value Names () {
retu rn v alues .keys ();
}
appS essio n = n ew Ap plica tion Sessi on(id , thi s, co ntex t);
appS essio ns.pu t(con text, app Sessi on);
final c lass Stan dardS essio nCont ext i mple ments Http Sessi onCon text {
pri vate Vect or du mmy = new Vecto r();
/**
* Retur n th e ses sion ident ifier s of all sessi ons d efine d
* withi n th is co ntext .
*
* @depr ecat ed As of J ava S ervle t AP I 2.1 with no r eplac emen t.
* This met hod m ust r eturn an e mpty <cod e>Enu merat ion</ code >
* and will be r emove d in a fut ure versi on of the API.
*/
pub lic E nume ratio n get Ids() {
retu rn ( dummy .elem ents( ));
retu rn ( this. check Inter val);
}
/**
* Set t he c heck inter val ( in se cond s) fo r thi s Man ager.
*
* @para m ch eckIn terva l The new chec k int erval
*/
pub lic v oid setCh eckIn terva l(int che ckInt erval ) {
/**
* Set t he M anage r wit hin w hich this
Session is v alid .
*
* @para m ma nager The new M anage r
*/
pub lic v oid setMa nager (Mana ger m anag er) {
this .man ager = man ager;
/**
* Inval idat es th is se ssion and unbi nds a ny ob jects
bound t o it.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on
* an i nval idate d ses sion
*/
pub lic v oid inval idate () {
ServerSessionManager
package org. apac he.to mcat. sessi on;
import org.a pach e.tom cat.u til.* ;
import org.a pach e.tom cat.c ore.* ;
import java. io.* ;
import java. net. *;
import java. util .*;
import javax .ser vlet. http. *;
// XXX
// sync' d fo r saf ty -- no o ther thre ad sh ould be ge tting som ethin g
// from this whil e we are r eapin g. T his i sn't the m ost o ptim al
// solut ion for t his, but w e'll dete rmine some thing else lat er.
syn chron ized void reap () {
Enum erat ion e num = sess ions. keys ();
whil e (e num.h asMor eElem ents( )) {
Obje ct ke y = e num.n extEl emen t();
Serv erSes sion sessi on = (Ser verSe ssion )sess ions. get( key);
/**
*
* @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om]
* @aut hor J ason Hunt er [j ch@en g.sun .com ]
* @aut hor J ames Todd [gon zo@en g.sun .com ]
*/
pub lic v oid setMa xInac tiveI nterv al(i nt in terva l) {
inac tive Inter val = inte rval;
}
retu rn a ppSes sion;
pub lic i nt g etMax Inact iveIn terva l() {
retu rn i nacti veInt erval ;
}
sess ion.r eap() ;
sess ion.v alida te();
}
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) {
Stri ng i d = s essio n.get Id();
pri vate Stri ngMan ager sm =
Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" );
pri vate stat ic Se rverS essio nMana ger manag er; / / = n ew Se rver Sessi onMan ager( );
}
voi d rem oveA pplic ation Sessi on(Co ntex t con text) {
appS essi ons.r emove (cont ext);
}
// XXX
// sync' d fo r saf ty -- no o ther thre ad sh ould be ge tting som ethin g
// from this whil e we are r eapin g. T his i sn't the m ost o ptim al
// solut ion for t his, but w e'll dete rmine some thing else lat er.
/**
* Calle d by cont ext w hen r eques t co mes i n so that acces ses and
* inact ivit ies c an be deal t wit h ac cordi ngly.
*/
syn chron ized void reap () {
Enum erat ion e num = appS essio ns.k eys() ;
voi d acc esse d() {
// s et l ast a ccess ed to this Acce ssTim e as it wi ll be lef t ove r
// f rom the p revio us ac cess
whil e (e num.h asMor eElem ents( )) {
Obje ct ke y = e num.n extEl emen t();
Appl icati onSes sion appSe ssio n =
(Appl icati onSes sion) appS essio ns.ge t(key );
last Acce ssed = thi sAcce ssTim e;
this Acce ssTim e = S ystem .curr entT imeMi llis( );
appS essio n.val idate ();
}
}
}
}
retu rn ( this. maxIn activ eInte rval );
}
/**
* Set t he m aximu m tim e int erval , in
seconds , bet ween clie nt re quest s
* befor e th e ser vlet conta iner will
invalid ate t he s essio n. A nega tive
* time indi cates that the sessi on s hould
never t ime o ut.
*
* @para m in terva l The new maxim um
interva l
*/
pub lic v oid setMa xInac tiveI nterv al(i nt
interva l) {
this .max Inact iveIn terva l = i nter val;
// S tart the backg round reap er t hread
thre adSt art() ;
if( sess ion = = nul l) re turn;
/**
if ( sess ion i nstan ceof Sessi on)
* Spec ializ ed i mplem entat ion o f
org.apa che.t omca t.cor e.Ses sionM anage r
((Se ssion ) ses sion) .acce ss() ;
* that adap ts t o the new compo nent- base d Man ager
impleme ntati on.
// c ache the HttpS essio n - a void anot her f ind
* <p>
req. setS essio n( se ssion );
* XXX - At pres ent, use o f <co de>St anda rdMan ager< /code > is hard }
coded,
* and lifec ycle conf igura tion is no t su pport ed.
// XXX s houl d we throw exce ption or just retur n nul l ??
* <p>
pub lic H ttpS essio n fin dSess ion( Cont ext c tx, S tring id ) {
* <b>I MPLEM ENTA TION NOTE< /b>:
Manager /Sess ion
Once we commi t to the n ew
try {
Sess ion s essio n = m anage r.fi ndSes sion( id);
* para digm, I w ould sugge st mo ving the logic impl ement ed he re
back in to
* the core leve l.
more li ke a
if(s essio n!=nu ll)
T he To mcat. Next "Man ager" inte rface acts
retur n ses sion. getSe ssio n();
} ca tch (IOEx cepti on e) {
* coll ectio n cl ass, and h as mi nimal kno wledg e of the d etail ed
request
}
retu rn ( null) ;
* proc essin g se manti cs of hand ling sess ions.
}
* <p>
* XXX - At pres ent, there is n o way (vi a the Sess ionMa nager
interfa ce) f or
pub lic H ttpS essio n cre ateSe ssion (Con text ctx) {
* a Co ntext to tell the M anage r tha t we crea te wh at th e def ault
session
retu rn
manag er.cr eateS essio n(). getSe ssion ();
}
* time out f or t his w eb ap plica tion (spe cifie d in the d eploy ment
descrip tor)
/**
* shou ld be .
* Remov e al l ses sions beca use o ur a ssoci ated Conte xt is
being s hut d own.
*
* @aut hor C raig R. M cClan ahan
*
*/
* @para m ct x The cont ext t hat i s be ing s hut d own
public final cla ss St andar dSess ionMa nage r
pub lic v oid remov eSess ions( Conte xt c tx) {
imp lemen ts S essio nMana ger {
// X XX X XX a manag er ma y be shar ed by mult iple
/**
try {
* Creat e a new S essio nMana ger t hat adapt s to the
corresp ondin g Ma nager
((Lif ecycl e) ma nager ).st op();
} ca tch ( Lifec ycleE xcept ion e) {
* imple ment ation .
throw new Illeg alSta teEx cepti on("" + e) ;
*/
}
pub lic S tand ardSe ssion Manag er() {
}
mana ger = new Stan dardM anage r();
}
if ( mana ger i nstan ceof Lifec ycle ) {
try {
/**
((Lif ecycl e) ma nager ).co nfigu re(nu ll);
((Lif ecycl e) ma nager ).st art() ;
* Used by c ontex t to confi gure the sessi on ma nager 's
inactiv ity t imeo ut.
} ca tch ( Lifec ycleE xcept ion e) {
throw new Illeg alSta teEx cepti on("" + e) ;
}
}
*
* The S essi onMan ager may h ave s ome defau lt se ssion time
out, th e
* Conte xt o n the othe r han d has it' s tim eout set b y the
deploym ent
* descr ipto r (we b.xml ). Th is me thod lets the Conte xt
conforg ure t he
}
* sessi on m anage r acc ordin g to this valu e.
*
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----Instanc e Var iabl es
* @para m mi nutes The sessi on in acti vity timeo ut in minu tes.
}
*/
/**
* Grace full y ter minat e the acti ve u se of the publi c met hods of t his
* compo nent . Th is me thod shoul d be the last one c alled on a giv en
* insta nce of th is co mpone nt.
*
* @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s no t bee n
started
* @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready
* been sto pped
* @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l
error
* that nee ds to be r eport ed
*/
pub lic v oid stop( ) thr ows L ifecy cleE xcept ion {
if(- 1 != minu tes) {
/**
// T he ma nager work s wit h se conds ...
* The M anag er im pleme ntati on we are actu ally using .
mana ger.s etMax Inact iveIn terv al(mi nutes * 60 );
*/
}
pri vate Mana ger m anage r = n ull;
}
}
// V alid ate a nd up date our c urre nt co mpone nt st ate
if ( !sta rted)
thro w new Life cycle Excep tion
(sm.g etStr ing(" stand ardM anage r.not Start ed")) ;
star ted = fal se;
this .che ckInt erval = ch eckIn terv al;
// S top the b ackgr ound reape r th read
thre adSt op();
// E xpir e all acti ve se ssion s
Sess ion sessi ons[] = fi ndSes sion s();
for (int i = 0; i < ses sions .len gth; i++) {
Stan dardS essio n ses sion = (S tanda rdSes sion) sess ions [i];
if ( !sess ion.i sVali d())
conti nue;
sess ion.e xpire ();
}
/**
* Retur n de scrip tive infor matio n ab out t his M anage r imp leme ntati on an d
* the c orre spond ing v ersio n num ber, in t he fo rmat
* <code >< ;desc ripti on> ;/< ;ver sion& gt;</ code> .
*/
pub lic S trin g get Info( ) {
sess ion. inval idate ();
sess ions .remo ve(id );
retu rn ( null) ;
/**
* Retur n th e max imum numbe r of acti ve Se ssion s all owed, or -1 fo r
* no li mit.
*/
pub lic i nt g etMax Activ eSess ions( ) {
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- --- Priva te
Methods
/**
* Inval idat e all sess ions that have expi red.
*/
pri vate void proc essEx pires () {
retu rn ( this. maxAc tiveS essio ns);
long tim eNow = Sys tem.c urren tTim eMill is();
Sess ion sessi ons[] = fi ndSes sion s();
}
for (int i = 0; i < ses sions .len gth; i++) {
Stan dardS essio n ses sion = (S tanda rdSes sion) sess ions [i];
if ( !sess ion.i sVali d())
conti nue;
int maxIn activ eInte rval = se ssion .getM axIna ctive Inte rval( );
if ( maxIn activ eInte rval < 0)
conti nue;
int timeI dle = // T runca te, do no t rou nd up
(int) ((ti meNow - se ssio n.get LastA ccess edTim e()) /
/**
* Set t he m aximu m num ber o f act ives Sess ions allow ed, o r -1 for
* no li mit.
*
* @para m ma x The new maxim um nu mber of s essio ns
*/
pub lic v oid setMa xActi veSes sions (int max) {
this .max Activ eSess ions = max ;
pub lic v oid remov eSess ions( Conte xt c ontex t) {
Enum erat ion e num = sess ions. keys ();
sta tic {
mana ger = new Serv erSes sionM anag er();
}
whil e (e num.h asMor eElem ents( )) {
Obje ct ke y = e num.n extEl emen t();
Serv erSes sion sessi on = (Ser verSe ssion )sess ions. get( key);
Appl icati onSes sion appSe ssio n =
sessi on.ge tAppl icati onSe ssion (cont ext, false );
}
/**
* Retur n th e <co de>Ht tpSes sion< /cod e> as socia ted w ith t he
* speci fied sess ion i denti fier.
*
* @para m id Sess ion i denti fier for which to l ook u p a s essi on
*
* @depr ecat ed As of J ava S ervle t AP I 2.1 with no r eplac emen t.
* This met hod m ust r eturn null and will be r emove d in a
* futu re v ersio n of the A PI.
*/
pub lic H ttpS essio n get Sessi on(St ring id) {
}
}
}
pri vate Hash table sess ions = new Has htabl e();
pri vate Reap er re aper;
if ( appSe ssion != n ull) {
appSe ssion .inva lidat e();
}
pri vate Serv erSes sionM anage r() {
reap er = Reap er.ge tReap er();
reap er.s etSer verSe ssion Manag er(t his);
reap er.s tart( );
}
}
}
/**
* Used by c ontex t to confi gure the sessi on ma nager 's in acti vity timeo ut.
*
* The S essi onMan ager may h ave s ome defau lt se ssion time out , the
* Conte xt o n the othe r han d has it' s tim eout set b y the dep loyme nt
* descr ipto r (we b.xml ). Th is me thod lets the Conte xt co nfor gure the
* sessi on m anage r acc ordin g to this valu e.
*
* @para m mi nutes The sessi on in acti vity timeo ut in minu tes.
*/
pub lic v oid setSe ssion TimeO ut(in t mi nutes ) {
if(- 1 != minu tes) {
// T he ma nager work s wit h se conds ...
inac tiveI nterv al = (minu tes * 60) ;
}
}
pub lic v oid acces sed( Conte xt ct x, R eques t req , Str ing i d ) {
Appl icat ionSe ssion apS= (Appl icat ionSe ssion )find Sessi on( ctx, id);
if( apS= =null ) ret urn;
Serv erSe ssion serv S=apS .getS erve rSess ion() ;
serv S.ac cesse d();
apS. acce ssed( );
}
}
// c ache it - no n eed t o com pute it a gain
req. setS essio n( ap S );
}
}
/**
* Retur n <c ode>t rue</ code> if t he c lient does not
yet kno w abo ut t he
* sessi on, or if the clien t cho oses not to jo in
the ses sion. Fo r
* examp le, if th e ser ver u sed o nly cooki e-bas ed
session s, an d th e cli ent
* has d isab led t he us e of cooki es, then a ses sion
would b e new on each
* reque st.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on an
* inva lida ted s essio n
*/
pub lic b oole an is New() {
// V alid ate a nd up date our c urre nt co mpone nt st ate
if ( !con figur ed)
thro w new Life cycle Excep tion
(sm.g etStr ing(" stand ardM anage r.not Confi gured "));
if ( star ted)
thro w new Life cycle Excep tion
(sm.g etStr ing(" stand ardM anage r.alr eadyS tarte d")) ;
star ted = tru e;
}
pro tecte d in t ina ctive Inter val = -1;
// C ause this sess ion t o exp ire
expi re() ;
/**
* Retur n th e max imum time inter val, in
seconds , bet ween clie nt re quest s
* befor e th e ser vlet conta iner will
invalid ate t he s essio n. A nega tive
* time indi cates that the sessi on s hould
never t ime o ut.
*
* @exce ptio n Ill egalS tateE xcept ion if
this me thod is c alled on
* an i nval idate d ses sion
*/
pub lic i nt g etMax Inact iveIn terva l() {
Http Sess ion s essio n=fin dSess ion( ctx, id);
}
}
// X XX
// m ake sure that we ha ven't gon e ove r the end of ou r
// i nact ive i nterv al -- if s o, i nvali date and c reate
// a new appS essio n
pub lic v oid acces sed(C ontex t ctx , Re quest req, Stri ng id ) {
pub lic v oid setSe ssion TimeO ut(in t mi nutes ) {
/**
* Retur n th e che ck in terva l (in sec onds) for this Manag er.
*/
pub lic i nt g etChe ckInt erval () {
pub lic s tati c Ser verSe ssion Manag er g etMan ager( ) {
retu rn m anage r;
}
}
pub lic v oid remov eValu e(Str ing n ame) {
valu es.r emove (name );
}
}
* @para m se ssion The sessi on to be marke d
*/
import org.a pach e.tom cat.u til.S essio nUti l;
retu rn ( this. info) ;
}
retu rn v alues .get( name) ;
if ( appS essio n == null && cr eate ) {
voi d val idat e()
retu rn ( this. manag er);
Thi s
* calle d fo r eac h req uest by a Requ estIn terce ptor.
*
import org.a pach e.tom cat.c ore.R espon se;
import org.a pach e.tom cat.c ore.S essio nMan ager;
if ( mana ger i nstan ceof Lifec ycle ) {
* compo nent . Th is me thod shoul d be call ed af ter
<code>c onfig ure( )</co de>,
* and b efor e any of t he pu blic meth ods o f the comp onent are
utilize d.
*
* @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s no t yet
been
* conf igur ed (i f req uired for this comp onent )
* @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready
been
* star ted
* @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l
error
* that pre vents this comp onent fro m bei ng us ed
*/
pub lic v oid start () th rows Lifec ycle Excep tion {
// ---- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- - Pri vate Class
/**
* This clas s is a du mmy i mplem entat ion of th e <co de>Ht tpSes sion Conte xt</c ode>
* inte rface , to conf orm t o the requ irem ent t hat s uch a n obj ect be re turne d
* when <cod e>Ht tpSes sion. getSe ssion Cont ext() </cod e> is call ed.
*
* @aut hor C raig R. M cClan ahan
*
* @dep recat ed A s of Java Servl et AP I 2. 1 wit h no repla cemen t. The
* int erfac e wi ll be remo ved i n a f utur e ver sion of th is AP I.
*/
Vect or r esult s = n ew Ve ctor( );
Enum erat ion a ttrs = get Attri bute Names ();
whil e (a ttrs. hasMo reEle ments ()) {
Stri ng at tr = (Stri ng) a ttrs .next Eleme nt();
resu lts.a ddEle ment( attr) ;
}
Stri ng n ames[ ] = n ew St ring[ resu lts.s ize() ];
for (int i = 0; i < nam es.le ngth ; i++ )
name s[i] = (St ring) resu lts. eleme ntAt( i);
retu rn ( names );
/**
* Retur n th e Man ager withi n whi ch t his
Session is v alid .
*/
pub lic M anag er ge tMana ger() {
}
* Mark the speci fied sessi on's last acce ssed time.
should be
import org.a pach e.tom cat.c ore.C ontex t;
import org.a pach e.tom cat.c ore.R eques t;
// c onne ction open
* Prepa re f or th e beg innin g of acti ve us e of the p ublic met hods of
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- ---- Prope rties
}
}
}
pub lic l ong getCr eatio nTime () {
retu rn c reati onTim e;
}
/**
import javax .ser vlet. http. HttpS essio n;
import org.a pach e.tom cat.c atali na.*;
// c onte xts, we ju st wa nt to rem ove t he se ssion s of ctx!
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---// T he m anage r wil l sti ll ru n af ter t hat ( i.e. keep
-- Cons truct ors
databas e
}
/**
/**
* Name to r egist er fo r the back grou nd th read.
*/
pri vate Stri ng th readN ame = "Sta ndar dMana ger";
cro sscut inv alida te(St andar dSess ion s): s & (i nt ge tMaxI nact iveIn terva l() |
l ong g etCre atio nTime () |
O bject getA ttri bute( Strin g) |
E numer ation get Attri buteN ames( ) |
S tring [] ge tVal ueNam es() |
v oid i nvali date () |
b oolea n isN ew() |
v oid r emove Attr ibute (Stri ng) |
v oid s etAtt ribu te(St ring, Obje ct));
}
/**
* Retur n th e obj ect b ound with the speci fied name
in this sess ion, or
* <code >nul l</co de> i f no objec t is boun d wit h
that na me.
*
* @para m na me Na me of the value to be re turne d
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on an
* inva lida ted s essio n
*
* @depr ecat ed As of V ersio n 2.2 , th is me thod is
replace d by
* <cod e>ge tAttr ibute ()</c ode>
*/
pub lic O bjec t get Value (Stri ng na me) {
import javax .ser vlet. http. Cooki e;
*/
/**
* The b ackg round thre ad co mplet ion semap hore.
*/
pri vate bool ean t hread Done = fal se;
}
this .id = id;
import org.a pach e.tom cat.c ore.* ;
import org.a pach e.tom cat.u til.S tring Mana ger;
import java. io.* ;
import java. net. *;
import java. util .*;
import javax .ser vlet. *;
import javax .ser vlet. http. *;
node = a ttrib utes. getNa medIt em(" maxIn activ eInte rval" );
if ( node != n ull) {
try {
setMaxI nacti veIn terva l(Int eger. parse Int( node. getNo deVal ue()) );
} ca tch ( Throw able t) {
;
// XXX - Thr ow e xcept ion?
}
}
}
null) & &
(m anag er in stanc eof M anage rBas e))
((Ma nager Base)
manager ).rem ove( this) ;
package org. apac he.to mcat. sessi on;
setMaxA ctive Sess ions( Integ er.pa rseIn t(no de.ge tNode Value ()));
} ca tch ( Throw able t) {
;
// XXX - Thr ow e xcept ion?
}
}
this
if( debu g>0 ) cm.l og(" Orig sess ionId " + sess ionId );
if ( null != s essio nId) {
int idex = ses sionI d.las tInd exOf( SESSI ONID_ ROUTE _SEP );
if(i dex > 0) {
sessi onId = ses sionI d.su bstri ng(0, idex );
}
}
// ---- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----Public Metho ds
import java. io.I OExce ption ;
/**
* Confi gure this comp onent , bas ed o n the spec ified conf igur ation
* param eter s. T his m ethod shou ld b e cal led i mmedi ately aft er th e
* compo nent inst ance is cr eated , an d bef ore < code> start ()</ code>
* is ca lled .
*
* @para m pa ramet ers C onfig urati on p arame ters for t his c ompo nent
* (<B> FIXM E: Wh at ob ject type shou ld th is re ally be?)
*
* @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready
/**
* The m axim um nu mber of ac tive Sess ions allow ed, o r -1 for no li mit.
*/
pro tecte d in t max Activ eSess ions = -1 ;
}
/**
* Set t he s essio n ide ntifi er fo r th is
session .
*
* @para m id The new s essio n ide ntif ier
*/
pub lic v oid setId (Stri ng id ) {
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- - Li fecyc le
Methods
/**
been
* Stan dard impl ement ation of t he <b >Man ager< /b> i nterf ace t hat provi des
* conf igur ed an d/or start ed
* no s essio n pe rsist ence or di strib utab le ca pabil ities , but doe s sup port
* @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l
* an o ption al, confi gurab le, m aximu m nu mber of ac tive sessi ons allow ed.
error
* <p>
* in t he c onfig urati on pa ramet ers it wa s giv en
* Life cycle con figur ation of t his c ompo nent assum es an XML node
*/
* in t he fo llow ing f ormat :
pub lic v oid confi gure( Node param eter s)
* <cod e>
thro ws L ifecy cleEx cepti on {
*
<M anag er cl assNa me="o rg.ap ache .tomc at.se ssion .Stan dard Manag er"
*
check Inter val=" 60" m axAc tiveS essio ns="- 1"
// V alid ate a nd up date our c urre nt co mpone nt st ate
*
maxIn activ eInte rval= "-1" />
if ( conf igure d)
* </co de>
thro w new Life cycle Excep tion
* wher e you can adju st th e fol lowin g pa ramet ers, with defau lt v alues
(sm.g etStr ing(" stand ardM anage r.alr eadyC onfig ured "));
* in s quare bra ckets :
conf igur ed = true;
* <ul>
if ( para meter s == null)
* <li> <b>ch eckI nterv al</b > - T he in terv al (i n sec onds) betw een backg round
retu rn;
*
threa d ch ecks for e xpire d ses sion s. [ 60]
* <li> <b>ma xAct iveSe ssion s</b> - Th e ma ximum numb er of sess ions allo wed t o
// P arse and proce ss ou r con figu ratio n par amete rs
*
be ac tive at o nce, or -1 for no l imit. [-1 ]
if ( !("M anage r".eq uals( param eter s.get NodeN ame() )))
* <li> <b>ma xIna ctive Inter val</ b> - The defau lt ma ximum numb er o f sec onds of
retu rn;
*
inact ivit y bef ore w hich the s ervl et co ntain er is allo wed to ti me ou t
Name dNod eMap attri butes = pa rame ters. getAt tribu tes() ;
*
a ses sion , or -1 fo r no limit . T his v alue shoul d be over ridde n fro m
Node nod e = n ull;
*
the d efau lt se ssion time out s peci fied in th e web appl icat ion d eploy ment
*
descr ipto r, if any. [-1 ]
node = a ttrib utes. getNa medIt em(" check Inter val") ;
* </ul >
if ( node != n ull) {
*
try {
* @aut hor C raig R. M cClan ahan
setCh eckIn terva l(Int eger .pars eInt( node. getNo deVa lue() ));
* @ver sion $Rev ision : 1.1 .1.1 $ $Da te: 2000/ 05/02 21:2 8:30 $
} ca tch ( Throw able t) {
*/
;
// XXX - Thr ow e xcept ion?
}
public final cla ss St andar dMana ger
}
ext ends Mana gerBa se
imp lemen ts L ifecy cle, Runna ble {
node = a ttrib utes. getNa medIt em(" maxAc tiveS essio ns");
if ( node != n ull) {
try {
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- Ins tance Vari ables
/**
* The i nter val ( in se conds ) bet ween chec ks fo r exp ired sess ions.
*/
pri vate int check Inter val = 60;
// S eria lize the a ttrib ute c ount and the attri bute valu es
stre am.w riteO bject (new Integ er(r esult s.siz e())) ;
Enum erat ion n ames = res ults. elem ents( );
whil e (n ames. hasMo reEle ments ()) {
Stri ng na me = (Stri ng) n ames .next Eleme nt();
stre am.wr iteOb ject( name) ;
stre am.wr iteOb ject( attri bute s.get (name ));
}
}
StandardSessionManager
package org. apac he.to mcat. sessi on;
package org. apac he.to mcat. sessi on;
}
// A ccum ulate the names of s eria lizab le at tribu tes
Vect or r esult s = n ew Ve ctor( );
Enum erat ion a ttrs = get Attri bute Names ();
whil e (a ttrs. hasMo reEle ments ()) {
Stri ng at tr = (Stri ng) a ttrs .next Eleme nt();
Obje ct va lue = attr ibute s.ge t(att r);
if ( value inst anceo f Ser iali zable )
resul ts.ad dElem ent(a ttr) ;
}
/**
* Retur n th e obj ect b ound with the speci fied name
in this sess ion, or
* <code >nul l</co de> i f no objec t is boun d wit h
that na me.
*
* @para m na me Na me of the attri bute to b e ret urned
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on an
* inva lida ted s essio n
*/
pub lic O bjec t get Attri bute( Strin g na me) {
Cook ie c ookie = ne w Coo kie(" JSES SIONI D",
r eqSe ssion Id);
cook ie.s etMax Age(- 1);
cook ie.s etPat h(ses sionP ath);
cook ie.s etVer sion( 1);
pub lic v oid setCo ntext Manag er( C onte xtMan ager cm ) {
this .cm= cm;
}
// W rite the scala r ins tance var iable s (ex cept Manag er)
stre am.w riteO bject (new Long( crea tionT ime)) ;
stre am.w riteO bject (id);
stre am.w riteO bject (new Long( last Acces sedTi me));
stre am.w riteO bject (new Integ er(m axIna ctive Inter val)) ;
stre am.w riteO bject (new Boole an(i sNew) );
stre am.w riteO bject (new Boole an(i sVali d));
}
// G S, p iggyb ack t he jv m rou te o n the sess ion i d.
if(! sess ionPa th.eq uals( "/")) {
Stri ng jv mRout e = r reque st.g etJvm Route ();
if(n ull ! = jvm Route ) {
reqSe ssion Id = reqSe ssio nId + SESS IONID _ROUT E_SE P + j vmRou te;
}
}
pub lic v oid setDe bug( int i ) {
Syst em.o ut.pr intln ("Set debu g to " + i);
debu g=i;
}
// D eser ializ e the attr ibute cou nt an d att ribut e val ues
int n = ((Int eger) stre am.re adOb ject( )).in tValu e();
for (int i = 0; i < n; i++) {
Stri ng na me = (Stri ng) s trea m.rea dObje ct();
Obje ct va lue = (Obj ect) stre am.re adObj ect() ;
attr ibute s.put (name , val ue);
}
}
// G S, s et th e pat h att ribut e to the cooki e. Th is wa y
// m ulti ple s essio n coo kies can be us ed, o ne fo r eac h
// c onte xt.
Stri ng s essio nPath = rr eques t.ge tCont ext() .getP ath() ;
if(s essi onPat h.len gth() == 0 ) {
sess ionPa th = "/";
}
// GS, s epar ates the s essio n id from the jvm r oute
sta tic f inal char SESS IONID _ROUT E_SE P = ' .';
int debu g=0;
Con textM anag er cm ;
}
/**
* Retur n th e ses sion conte xt wi th w hich this
session is a ssoc iated .
*
* @depr ecat ed As of V ersio n 2.1 , th is me thod is
depreca ted a nd h as no
* repl acem ent. It w ill b e rem oved in a futu re
version of t he
* Java Ser vlet API.
*/
pub lic H ttpS essio nCont ext g etSes sion Conte xt() {
pub lic i nt b efore Body( Requ est r requ est, Respo nse r espon se ) {
Stri ng r eqSes sionI d = r espon se.g etSes sionI d();
if( debu g>0 ) cm.l og("B efore Bod y " + reqS essio nId ) ;
if( reqS essio nId== null)
retu rn 0;
/**
* Will proc ess the r eques t and dete rmin e the sess ion I d, an d se t it
* in t he Re ques t.
* It a lso m arks the sessi on as acce ssed .
*
* This impl emen tatio n onl y han dles Cook ies s essio ns, p lease ext end o r
* add new i nter cepto rs fo r oth er me thod s.
*
*/
public class Ses sionI nterc eptor exte nds Base Inter cepto r imp leme nts R eques tInte rcept or {
// D eser ializ e the scal ar in stan ce va riabl es (e xcept Man ager)
crea tion Time = ((L ong) strea m.re adObj ect() ).lon gValu e();
id = (St ring) stre am.re adObj ect( );
last Acce ssedT ime = ((Lo ng) s trea m.rea dObje ct()) .long Valu e();
maxI nact iveIn terva l = ( (Inte ger) stre am.re adObj ect() ).in tValu e();
isNe w = ((Boo lean) stre am.re adOb ject( )).bo olean Value ();
isVa lid = ((B oolea n) st ream. read Objec t()). boole anVal ue() ;
thro w new Ille galAr gumen tExc eptio n(msg );
}
StandardManage
package org. apac he.to mcat. reque st;
import org.a pach e.tom cat.c ore.* ;
import org.a pach e.tom cat.u til.* ;
import java. io.* ;
import java. net. *;
import java. util .*;
import javax .ser vlet. http. *;
pub lic S essi onInt ercep tor() {
}
}
this .isN ew = isNew ;
}
}
}
}
}
SessionInterceptor
}
// T ell our M anage r tha t thi s Se ssion has been
recycle d
pub lic H ttpS essio n cre ateSe ssion (Con text ctx) {
Stri ng s essio nId = Sess ionId Gene rator .gene rateI d();
Serv erSe ssion sess ion = new Serv erSes sion( sessi onId) ;
sess ions .put( sessi onId, sess ion) ;
1000L);
if ( timeI dle > = max Inact iveI nterv al)
sessi on.ex pire( );
}
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- Publ ic Me thods
}
/**
* Const ruct and retur n a n ew se ssio n obj ect, based on t he d efaul t
* setti ngs speci fied by th is Ma nage r's p roper ties. The ses sion
* id wi ll b e ass igned by t his m etho d, an d ava ilabl e via the getI d()
* metho d of the retur ned s essio n. If a new s essio n can not be cr eated
* for a ny r eason , ret urn < code> null </cod e>.
*
* @exce ptio n Ill egalS tateE xcept ion if a new s essio n can not be
* inst anti ated for a ny re ason
*/
pub lic S essi on cr eateS essio n() {
/**
* Sleep for the durat ion s pecif ied by th e <co de>ch eckIn terv al</c ode>
* prope rty.
*/
pri vate void thre adSle ep() {
try {
Thre ad.sl eep(c heckI nterv al * 1000 L);
} ca tch (Inte rrupt edExc eptio n e) {
;
}
}
if ( (max Activ eSess ions >= 0) &&
(s essi ons.s ize() >= m axAct iveS essio ns))
thro w new Ille galSt ateEx cept ion
(sm.g etStr ing(" stand ardM anage r.cre ateSe ssion .ise "));
/**
* Start the back groun d thr ead t hat will perio dical ly ch eck for
* sessi on t imeou ts.
*/
pri vate void thre adSta rt() {
retu rn ( super .crea teSes sion( ));
}
if ( thre ad != null )
retu rn;
thre adDo ne = false ;
thre ad = new Threa d(thi s, th read Name) ;
thre ad.s etDae mon(t rue);
thre ad.s tart( );
}
if(- 1 != inac tiveI nterv al) {
sess ion. setMa xInac tiveI nterv al(i nacti veInt erval );
}
}
retu rn s essio n.get Appli catio nSes sion( ctx, true );
/**
* Stop the backg round thre ad th at i s per iodic ally check ing for
* sessi on t imeou ts.
*/
pri vate void thre adSto p() {
}
pub lic H ttpS essio n fin dSess ion(C onte xt ct x, St ring id) {
Serv erSe ssion sSes sion= (Serv erSe ssion )sess ions. get(i d);
if(s Sess ion== null) retu rn nu ll;
if ( thre ad == null )
retu rn;
retu rn s Sessi on.ge tAppl icati onSe ssion (ctx, fals e);
}
thre adDo ne = true;
thre ad.i nterr upt() ;
try {
thre ad.jo in();
} ca tch (Inte rrupt edExc eptio n e) {
;
}
retu rn ( this. isNew );
}
thre ad = null ;
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- - Ba ckgro und
Thread
}
/**
* The b ackg round thre ad th at ch ecks for sessi on ti meout s an d
shutdow n.
*/
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 ();
}
}
}
10
Exemplo – Gerenc. de Sessões
S anda dSes n
App ca onSess on
ApplicationSession
/*
* ==== ===== ==== ===== ===== ===== ===
/*
* ==== ===== ==== ===== ===== ===== ===== ==== ===== ===== ===== ===== ==== ===== ==
*
* The Apach e So ftwar e Lic ense, Vers ion 1.1
*
* Copy right (c) 1999 The Apach e Sof twar e Fou ndati on. All r ight s
* rese rved.
*
* Redi strib utio n and use in so urce and binar y for ms, w ith o r wi thout
* modi ficat ion, are permi tted provi ded that the f ollow ing c ondi tions
* are met:
*
* 1. R edist ribu tions of s ource code mus t ret ain t he ab ove c opyr ight
*
n otice , th is li st of cond ition s an d the foll owing disc laim er.
*
* 2. R edist ribu tions in b inary form mus t rep roduc e the abov e co pyrig ht
*
n otice , th is li st of cond ition s an d the foll owing disc laim er in
*
t he do cume ntati on an d/or other mat erial s pro vided with the
*
d istri buti on.
*
* 3. T he en d-us er do cumen tatio n inc lude d wit h the redi strib utio n, if
*
a ny, m ust inclu de th e fol lowin g ac knowl egeme nt:
*
"Th is p roduc t inc ludes soft ware deve loped by t he
*
Ap ache Soft ware Found ation (ht tp:// www.a pache .org/ )."
*
A ltern atel y, th is ac knowl egeme nt m ay ap pear in th e sof twar e
itself,
*
i f and whe rever such thir d-par ty a cknow legem ents norma lly appea r.
*
* 4. T he na mes "The Jakar ta Pr oject ", " Tomca t", a nd "A pache Sof tware
*
F ounda tion " mus t not be u sed t o en dorse or p romot e pro duct s
derived
*
f rom t his softw are w ithou t pri or w ritte n per missi on. F or w ritte n
*
p ermis sion , ple ase c ontac t apa che@ apach e.org .
*
* 5. P roduc ts d erive d fro m thi s sof twar e may not be ca lled "Apa che"
*
n or ma y "A pache " app ear i n the ir n ames witho ut pr ior w ritt en
*
p ermis sion of t he Ap ache Group .
*
* THIS SOFT WARE IS P ROVID ED `` AS IS '' A ND AN Y EXP RESSE D OR IMPL IED
* WARR ANTIE S, I NCLUD ING, BUT N OT LI MITE D TO, THE IMPLI ED WA RRAN TIES
* OF M ERCHA NTAB ILITY AND FITNE SS FO R A PARTI CULAR PURP OSE A RE
* DISC LAIME D. IN NO EVEN T SHA LL TH E AP ACHE SOFTW ARE F OUNDA TION OR
* ITS CONTR IBUT ORS B E LIA BLE F OR AN Y DI RECT, INDI RECT, INCI DENT AL,
* SPEC IAL, EXEM PLARY , OR CONSE QUENT IAL DAMAG ES (I NCLUD ING, BUT NOT
* LIMI TED T O, P ROCUR EMENT OF S UBSTI TUTE GOOD S OR SERVI CES; LOSS OF
* USE, DATA , OR PROF ITS; OR BU SINES S IN TERRU PTION ) HOW EVER CAUS ED AN D
* ON A NY TH EORY OF L IABIL ITY, WHETH ER I N CON TRACT , STR ICT L IABI LITY,
* OR T ORT ( INCL UDING NEGL IGENC E OR OTHE RWISE ) ARI SING IN AN Y WA Y OUT
* OF T HE US E OF THIS SOFT WARE, EVEN IF ADVIS ED OF THE POSSI BILI TY OF
* SUCH DAMA GE.
* ==== ===== ==== ===== ===== ===== ===== ==== ===== ===== ===== ===== ==== ===== ==
*
* This soft ware cons ists of vo lunta ry c ontri butio ns ma de by man y
* indi vidua ls o n beh alf o f the Apac he S oftwa re Fo undat ion. For more
* info rmati on o n the Apac he So ftwar e Fo undat ion, pleas e see
* <htt p://w ww.a pache .org/ >.
*
* [Add ition al n otice s, if requ ired by p rior licen sing condi tion s]
*
*/
public void inva lidat e() {
serv erSe ssion .remo veApp licat ionS essio n(con text) ;
// r emov e eve rythi ng in the sess ion
Enum erat ion e num = valu es.ke ys() ;
whil e (e num.h asMor eElem ents( )) {
Stri ng na me = (Stri ng)en um.n extEl ement ();
remo veVal ue(na me);
}
vali d = false ;
}
pub lic b oole an is New() {
if ( ! va lid) {
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);
package org. apac he.to mcat. sessi on;
import java. io.I OExce ption ;
import java. io.O bject Input Strea m;
import java. io.O bject Outpu tStre am;
import java. io.S erial izabl e;
import java. util .Enum erati on;
import java. util .Hash table ;
import java. util .Vect or;
import javax .ser vlet. Servl etExc eptio n;
import javax .ser vlet. http. HttpS essio n;
import
javax.s ervle t.ht tp.Ht tpSes sionB indin gEve nt;
import
javax.s ervle t.ht tp.Ht tpSes sionB indin gLis tener ;
import javax .ser vlet. http. HttpS essio nCon text;
import org.a pach e.tom cat.c atali na.*;
import org.a pach e.tom cat.u til.S tring Mana ger;
}
if ( this Acces sTime == c reati onTi me) {
retu rn tr ue;
} el se {
retu rn fa lse;
}
}
/**
* @depr ecat ed
*/
pub lic v oid putVa lue(S tring name , Ob ject value ) {
setA ttri bute( name, valu e);
}
pub lic v oid setAt tribu te(St ring name , Obj ect v alue) {
if ( ! va lid) {
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);
}
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ;
thro w new Ille galAr gumen tExc eptio n(msg );
/**
* Stan dard impl ement ation of t he
<b>Sess ion</ b> i nterf ace. This obje ct i s
* seri aliza ble, so t hat i t can be s tore d in
persist ent s tora ge or tran sferr ed
* to a diff eren t JVM for distr ibuta ble sessi on
support .
* <p>
* <b>I MPLEM ENTA TION NOTE< /b>: An i nsta nce o f
this cl ass r epre sents both the
* inte rnal (Ses sion) and appli catio n le vel
(HttpSe ssion ) vi ew of the sessi on.
* Howe ver, beca use t he cl ass i tself is not
declare d pub lic, Java logi c out side
* of t he
<code>o rg.ap ache .tomc at.se ssion </cod e> p ackag e
cannot cast an
* Http Sessi on v iew o f thi s ins tance bac k to a
Session view .
*
* @aut hor C raig R. M cClan ahan
* @ver sion $Rev ision : 1.2 $ $D ate: 2000 /05/1 5
17:54:1 0 $
*/
final c lass Stan dardS essio n
imp lemen ts H ttpSe ssion , Ses sion {
* Bind an o bject to t his s essio n, u sing the s pecif ied n ame. If an ob ject
* of th e sa me na me is alre ady b ound to t his s essio n, th e ob ject is
* repla ced.
* <p>
* After thi s met hod e xecut es, a nd i f the obje ct im pleme nts
* <code >Htt pSess ionBi nding Liste ner< /code >, th e con taine r ca lls
* <code >val ueBou nd()< /code > on the objec t.
*
* @para m na me Na me to whic h the obj ect i s bou nd, c annot be null
* @para m va lue O bject to b e bou nd, canno t be null
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n
* inva lida ted s essio n
*
* @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d by
* <cod e>se tAttr ibute ()</c ode>
*/
pub lic v oid putVa lue(S tring name , Ob ject value ) {
retu rn ( (Http Sessi on) t his);
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- Session Publ ic M ethod s
/**
* Updat e th e acc essed time info rmat ion f or th is
session . Th is m ethod
* shoul d be call ed by the conte xt w hen a requ est
comes i n for a p artic ular
* sessi on, even if th e app licat ion does not
referen ce it .
*/
pub lic v oid acces s() {
setA ttri bute( name, valu e);
}
/**
* Remov e th e obj ect b ound with the speci fied name from this sess ion. If
* the s essi on do es no t hav e an obje ct bo und w ith t his n ame, this meth od
* does noth ing.
* <p>
* After thi s met hod e xecut es, a nd i f the obje ct im pleme nts
* <code >Htt pSess ionBi nding Liste ner< /code >, th e con taine r ca lls
* <code >val ueUnb ound( )</co de> o n th e obj ect.
*
* @para m na me Na me of the objec t to remo ve fr om th is se ssio n.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n
* inva lida ted s essio n
*/
pub lic v oid remov eAttr ibute (Stri ng n ame) {
this .las tAcce ssedT ime = this .thi sAcce ssedT ime;
this .thi sAcce ssedT ime =
System. curre ntTi meMil lis() ;
this .isN ew=fa lse;
}
/**
* Perfo rm t he in terna l pro cessi ng r equir ed to
invalid ate t his sessi on,
* witho ut t rigge ring an ex cepti on i f the sess ion
has alr eady expi red.
*/
pub lic v oid expir e() {
sync hron ized (attr ibute s) {
Obje ct ob ject = att ribut es.g et(na me);
if ( objec t == null)
retur n;
attr ibute s.rem ove(n ame);
//
S ystem .out. print ln( "Remo ving attri bute " + name );
if ( objec t ins tance of Ht tpSe ssion Bindi ngLis tener ) {
((Htt pSess ionBi nding List ener) obje ct).v alueU nbou nd
( new H ttpSe ssion Bind ingEv ent(( HttpS essio n) t his, name) );
}
}
// R emov e thi s ses sion from our manag er's activ e
session s
if ( (man ager != nu ll) & & (ma nage r ins tance of
Manager Base) )
((Ma nager Base) mana ger). remo ve(th is);
// U nbin d any obje cts a ssoci ated with this
session
remo veVa lue(n ame);
// remov e an y exi sting bind ing
if ( valu e != null && va lue i nsta nceof Http Sessi onBin ding Liste ner) {
Http Sessi onBin dingE vent e =
new H ttpSe ssion Bindi ngEv ent(t his, name) ;
((Ht tpSes sionB indin gList ener )valu e).va lueBo und(e );
}
valu es.p ut(na me, v alue) ;
}
/**
* @depr ecat ed
*/
pub lic O bjec t get Value (Stri ng na me) {
retu rn g etAtt ribut e(nam e);
}
import org.a pach e.tom cat.c ore.* ;
import org.a pach e.tom cat.u til.S tring Mana ger;
import java. io.* ;
import java. net. *;
import java. util .*;
import javax .ser vlet. *;
import javax .ser vlet. http. *;
pub lic O bjec t get Attri bute( Strin g na me) {
if ( ! va lid) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise ");
/**
* Core impl emen tatio n of an ap plica tion leve l ses sion
*
* @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om]
* @aut hor J ason Hunt er [j ch@en g.sun .com ]
* @aut hor J ames Todd [gon zo@en g.sun .com ]
*/
thro w new Ille galSt ateEx cept ion(m sg);
}
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ;
// ----- ---- ----- ----- ----- ----- ---- ----- -------- ----- ---- --- C onstr uctor s
retu rn v alues .get( name) ;
}
/**
* @depr ecat ed
*/
pub lic S trin g[] g etVal ueNam es() {
Enum erat ion e = ge tAttr ibute Name s();
Vect or n ames = new Vect or();
whil e (e .hasM oreEl ement s()) {
name s.add Eleme nt(e. nextE leme nt()) ;
}
App licat ionS essio n(Str ing i d, Se rver Sessi on se rverS essio n,
Cont ext conte xt) {
this .ser verSe ssion = se rverS essi on;
this .con text = con text;
this .id = id;
Stri ng[] valu eName s = n ew St ring [name s.siz e()];
name s.co pyInt o(val ueNam es);
retu rn v alueN ames;
}
// ----- ---- ----- ----- ----- ----- ---- ----- -------- ----- - In stanc e Var iable s
/**
* The c olle ction of u ser d ata a ttri butes
associa ted w ith this Sessi on.
*/
pri vate Hash table attr ibute s = n ew
Hashtab le();
/**
* The t ime this sessi on wa s cre ated , in
millise conds sin ce mi dnigh t,
* Janua ry 1 , 197 0 GMT .
*/
pri vate long crea tionT ime = 0L;
/**
* The s essi on id entif ier o f thi s Se ssion .
*/
pri vate Stri ng id = nu ll;
/**
* Descr ipti ve in forma tion descr ibin g thi s
Session impl emen tatio n.
*/
pri vate stat ic fi nal S tring info =
"Standa rdSes sion /1.0" ;
}
pub lic E nume ratio n get Attri buteN ames () {
if ( ! va lid) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise ");
}
Ser verSe ssio n get Serve rSess ion() {
retu rn s erver Sessi on;
}
/**
* Remov e th e obj ect b ound with the speci fied name from this sess ion. If
* the s essi on do es no t hav e an obje ct bo und w ith t his n ame, this meth od
* does noth ing.
* <p>
* After thi s met hod e xecut es, a nd i f the obje ct im pleme nts
* <code >Htt pSess ionBi nding Liste ner< /code >, th e con taine r ca lls
* <code >val ueUnb ound( )</co de> o n th e obj ect.
*
* @para m na me Na me of the objec t to remo ve fr om th is se ssio n.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n
* inva lida ted s essio n
*
* @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d by
* <cod e>re moveA ttrib ute() </cod e>
*/
pub lic v oid remov eValu e(Str ing n ame) {
// M ark this sessi on as inva lid
setV alid (fals e);
supe r();
this .man ager = man ager;
this .ina ctive Inter val = cont ext. getSe ssion TimeO ut();
if ( this .inac tiveI nterv al != -1) {
this .inac tiveI nterv al *= 60;
}
}
}
}
pri vate Stri ngMan ager sm =
Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" );
pri vate Hash table valu es = new H asht able( );
pri vate Stri ng id ;
pri vate Serv erSes sion serve rSess ion;
pri vate Cont ext c ontex t;
pri vate long crea tionT ime = Syst em.c urren tTime Milli s();;
pri vate long this Acces sTime = cr eati onTim e;
pri vate long last Acces sed = crea tion Time;
pri vate int inact iveIn terva l = - 1;
pri vate bool ean v alid = tru e;
Vect or r esult s = n ew Ve ctor( );
Enum erat ion a ttrs = get Attri bute Names ();
whil e (a ttrs. hasMo reEle ments ()) {
Stri ng at tr = (Stri ng) a ttrs .next Eleme nt();
resu lts.a ddEle ment( attr) ;
}
Enum erat ion n ames = res ults. elem ents( );
whil e (n ames. hasMo reEle ments ()) {
Stri ng na me = (Stri ng) n ames .next Eleme nt();
remo veAtt ribut e(nam e);
}
/**
* Const ruct a ne w Ses sion assoc iate d wit h
the spe cifie d Ma nager .
*
* @para m ma nager The manag er wi th w hich
this Se ssion is assoc iated
*/
pub lic S tand ardSe ssion (Mana ger m anag er) {
thro w new Ille galAr gumen tExc eptio n(msg );
public class App licat ionSe ssion impl emen ts Ht tpSes sion {
/**
* The l ast acces sed t ime f or th is S essio n.
*/
pri vate long last Acces sedTi me =
creatio nTime ;
/**
* Relea se a ll ob ject refer ences , an d ini tiali ze
instanc e var iabl es, i n
* prepa rati on fo r reu se of this obj ect.
*/
pub lic v oid recyc le() {
// R eset the insta nce v ariab les assoc iated with
this Se ssion
attr ibut es.cl ear() ;
crea tion Time = 0L;
id = nul l;
last Acce ssedT ime = 0L;
mana ger = nul l;
maxI nact iveIn terva l = - 1;
isNe w = true;
isVa lid = fal se;
remo veAt tribu te(na me);
}
/**
* Bind an o bject to t his s essio n, u sing the s pecif ied n ame. If an ob ject
* of th e sa me na me is alre ady b ound to t his s essio n, th e ob ject is
* repla ced.
* <p>
* After thi s met hod e xecut es, a nd i f the obje ct im pleme nts
* <code >Htt pSess ionBi nding Liste ner< /code >, th e con taine r ca lls
* <code >val ueBou nd()< /code > on the objec t.
*
* @para m na me Na me to whic h the obj ect i s bou nd, c annot be null
* @para m va lue O bject to b e bou nd, canno t be null
*
* @exce ptio n Ill egalA rgume ntExc epti on if an a ttemp t is made to a dd a
* non- seri aliza ble o bject in a n en viron ment marke d dis trib utabl e.
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n
* inva lida ted s essio n
*/
pub lic v oid setAt tribu te(St ring name , Obj ect v alue) {
// T ell our M anage r tha t thi s Se ssion has been
recycle d
if ( (man ager != nu ll) & & (ma nage r ins tance of
Manager Base) )
((Ma nager Base) mana ger). recy cle(t his);
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----Session Pack age Metho ds
/**
* Retur n th e <co de>is Valid </cod e> f lag f or th is
session .
*/
boo lean isVa lid() {
if ( (man ager != nu ll) & & man ager .getD istri butab le() &&
!( valu e ins tance of Se riali zabl e))
thro w new Ille galAr gumen tExc eptio n
(sm.g etStr ing(" stand ardS essio n.set Attri bute. iae" ));
sync hron ized (attr ibute s) {
remo veAtt ribut e(nam e);
attr ibute s.put (name , val ue);
if ( value inst anceo f Htt pSes sionB indin gList ener)
((Htt pSess ionBi nding List ener) valu e).va lueBo und
( new H ttpSe ssion Bind ingEv ent(( HttpS essio n) t his, name) );
}
retu rn ( this. isVal id);
}
thro w new Ille galSt ateEx cept ion(m sg);
}
Hash tabl e val uesCl one = (Has htab le)va lues. clone ();
/**
* Calle d by cont ext w hen r eques t co mes i n so that acces ses and
* inact ivit ies c an be deal t wit h ac cordi ngly.
*/
retu rn ( Enume ratio n)val uesCl one. keys( );
}
voi d acc esse d() {
// s et l ast a ccess ed to this Acce ssTim e as it wi ll be lef t ove r
// f rom the p revio us ac cess
last Acce ssed = thi sAcce ssTim e;
this Acce ssTim e = S ystem .curr entT imeMi llis( );
/**
* @depr ecat ed
*/
pub lic v oid remov eValu e(Str ing n ame) {
remo veAt tribu te(na me);
vali date ();
}
}
pub lic v oid remov eAttr ibute (Stri ng n ame) {
if ( ! va lid) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise ");
voi d val idat e() {
// i f we have an i nacti ve in terv al, c heck to se e if we'v e exc eeded it
if ( inac tiveI nterv al != -1) {
int thisI nterv al =
(int) (Syst em.cu rrent Time Milli s() - last Acces sed) / 10 00;
thro w new Ille galSt ateEx cept ion(m sg);
}
if ( thisI nterv al > inact iveI nterv al) {
inval idate ();
}
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ;
}
thro w new Ille galAr gumen tExc eptio n(msg );
}
}
// HTTP SESS ION I MPLEM ENTAT ION M ETHO DS
Obje ct o = va lues. get(n ame);
pub lic S trin g get Id() {
if ( vali d) {
retu rn id ;
} el se {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise ");
if ( o in stanc eof H ttpSe ssion Bind ingLi stene r) {
Http Sessi onBin dingE vent e =
new H ttpSe ssion Bindi ngEv ent(t his,n ame);
((Ht tpSes sionB indin gList ener )o).v alueU nboun d(e);
}
/**
* The M anag er wi th wh ich t his S essi on is
associa ted.
*/
pri vate Mana ger m anage r = n ull;
/**
* The m axim um ti me in terva l, in sec onds,
between clie nt r eques ts be fore
* the s ervl et co ntain er ma y inv alid ate
this se ssion . A nega tive time
* indic ates that the sessi on sh ould neve r
time ou t.
*/
pri vate int maxIn activ eInte rval = -1 ;
/**
* Flag indi catin g whe ther this sess ion i s
new or not.
*/
pri vate bool ean i sNew = tru e;
valu es.r emove (name );
}
pub lic l ong getCr eatio nTime () {
if ( vali d) {
retu rn cr eatio nTime ;
} el se {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise ");
pub lic v oid setMa xInac tiveI nterv al(i nt in terva l) {
if ( ! va lid) {
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);
}
thro w new Ille galSt ateEx cept ion(m sg);
}
/**
* Flag indi catin g whe ther this sess ion i s
valid o r not .
*/
pri vate bool ean i sVali d = f alse;
/**
* The s trin g man ager for t his p acka ge.
*/
pri vate Stri ngMan ager sm =
StringM anage r.ge tMana ger(" org.a pache .tom cat.s es
sion");
/**
* The H TTP sessi on co ntext asso ciat ed wi th
this se ssion .
*/
pri vate stat ic Ht tpSes sionC ontex t
session Conte xt = null ;
inac tive Inter val = inte rval;
}
}
/**
*
* @depr ecat ed
*/
pub lic i nt g etMax Inact iveIn terva l() {
if ( ! va lid) {
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);
pub lic H ttpS essio nCont ext g etSes sion Conte xt() {
retu rn n ew Se ssion Conte xtImp l();
}
/**
* Set t he < code> isNew </cod e> fl ag f or th is se ssion .
*
* @para m is New T he ne w val ue fo r th e
<code>i sNew< /cod e> fl ag
*/
voi d set New( boole an is New) {
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- - Htt pSess ion Priva te Me thods
this .isN ew = isNew ;
/**
* Read a se riali zed v ersio n of this sess ion o bject from the spec ified
* objec t in put s tream .
* <p>
* <b>IM PLEM ENTAT ION N OTE</ b>: The refer ence to th e own ing Manag er
* is no t re store d by this metho d, a nd mu st be set expli citl y.
*
* @para m st ream The i nput strea m to read from
*
* @exce ptio n Cla ssNot Found Excep tion if a n unk nown class is speci fied
* @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s
*/
pri vate void read Objec t(Obj ectIn putS tream stre am)
thro ws C lassN otFou ndExc eptio n, I OExce ption {
}
/**
* Set t he < code> isVal id</c ode> flag for this
session .
*
* @para m is Valid The new v alue for the
<code>i sVali d</c ode> flag
*/
voi d set Vali d(boo lean isVal id) {
/**
* The c urre nt ac cesse d tim e for thi s
session .
*/
pri vate long this Acces sedTi me =
creatio nTime ;
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- HttpSes sion Prop ertie s
/**
* Retur n th e tim e whe n thi s ses sion was creat ed, i n
millise conds sin ce
* midni ght, Janu ary 1 , 197 0 GMT .
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on an
* inva lida ted s essio n
*/
pub lic l ong getCr eatio nTime () {
// ----- ---- ----- ----- ----- ----- ---- ----- -------- ----- - Se ssion Prop ertie s
}
thro w new Ille galSt ateEx cept ion(m sg);
}
}
this .cre ation Time = tim e;
this .las tAcce ssedT ime = time ;
this .thi sAcce ssedT ime = time ;
}
/**
* Retur n th e ses sion ident ifier for this
session .
*/
pub lic S trin g get Id() {
retu rn ( this. id);
Se ve Sess on
void va lidat e() {
// i f we have an i nacti ve in terv al, c heck to se e if
// w e've exce eded it
if ( inac tiveI nterv al != -1) {
int thisI nterv al =
(int) (Syst em.cu rrent Time Milli s() - last Acces sed) / 10 00;
if ( thisI nterv al > inact iveI nterv al) {
inval idate ();
Serve rSess ionMa nager ssm =
S erver Sessi onMan ager .getM anage r();
ssm.r emove Sessi on(th is);
}
}
public class Ser verSe ssion {
}
pri vate Stri ngMan ager sm =
Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" );
pri vate Hash table valu es = new H asht able( );
pri vate Hash table appS essio ns = new Hasht able( );
pri vate Stri ng id ;
pri vate long crea tionT ime = Syst em.c urren tTime Milli s();;
pri vate long this Acces sTime = cr eati onTim e;
pri vate long last Acces sed = crea tion Time;
pri vate int inact iveIn terva l = - 1;
syn chron ized void inva lidat e() {
Enum erat ion e num = appS essio ns.k eys() ;
Ser verSe ssio n(Str ing i d) {
this .id = id;
}
}
whil e (e num.h asMor eElem ents( )) {
Obje ct ke y = e num.n extEl emen t();
Appl icati onSes sion appSe ssio n =
(Appl icati onSes sion) appS essio ns.ge t(key );
appS essio n.inv alida te();
}
pub lic v oid putVa lue(S tring name , Ob ject value ) {
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("s erver Sessi on.va lue.i ae") ;
pub lic S trin g get Id() {
retu rn i d;
}
thro w new Ille galAr gumen tExc eptio n(msg );
}
pub lic l ong getCr eatio nTime () {
retu rn c reati onTim e;
/**
* Set t he s essio n ide ntifi er fo r th is
session .
*
* @para m id The new s essio n ide ntif ier
*/
pub lic v oid setId (Stri ng id ) {
if ( (thi s.id != nu ll) & & (ma nage r !=
null) & &
(m anag er in stanc eof M anage rBas e))
((Ma nager Base)
manager ).rem ove( this) ;
}
pub lic l ong getLa stAcc essed Time( ) {
retu rn l astAc cesse d;
}
thro w new Ille galAr gumen tExc eptio n(msg );
}
}
/**
* Retur n de scrip tive infor matio n ab out
this Se ssion imp lemen tatio n and
* the c orre spond ing v ersio n num ber, in t he
format
*
<code>& lt;de scri ption >/ <v ersio n> ;</co de
>.
*/
pub lic S trin g get Info( ) {
/**
* Write a s erial ized versi on of thi s ses sion objec t to the speci fied
* objec t ou tput strea m.
* <p>
* <b>IM PLEM ENTAT ION N OTE</ b>: The ownin g Man ager will not be st ored
* in th e se riali zed r epres entat ion of th is Se ssion . Af ter calli ng
* <code >rea dObje ct()< /code >, yo u mu st se t the asso ciate d Ma nager
* expli citl y.
* <p>
* <b>IM PLEM ENTAT ION N OTE</ b>: Any attri bute that is no t Se riali zable
* will be s ilent ly ig nored . If you do n ot wa nt an y suc h at tribu tes,
* be su re t he <c ode>d istri butab le</ code> prop erty of ou r as socia ted
* Manag er i s set to < code> true< /cod e>.
*
* @para m st ream The o utput stre am t o wri te to
*
* @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s
*/
pri vate void writ eObje ct(Ob jectO utpu tStre am st ream) thro ws I OExce ption {
/**
* Retur n th e ses sion conte xt wi th w hich this
session is a ssoc iated .
*
* @depr ecat ed As of V ersio n 2.1 , th is me thod is
depreca ted a nd h as no
* repl acem ent. It w ill b e rem oved in a futu re
version of t he
* Java Ser vlet API.
*/
pub lic H ttpS essio nCont ext g etSes sion Conte xt() {
pub lic E nume ratio n get Value Names () {
retu rn v alues .keys ();
}
appS essio n = n ew Ap plica tion Sessi on(id , thi s, co ntex t);
appS essio ns.pu t(con text, app Sessi on);
pub lic v oid remov eValu e(Str ing n ame) {
valu es.r emove (name );
}
// X XX
// m ake sure that we ha ven't gon e ove r the end of ou r
// i nact ive i nterv al -- if s o, i nvali date and c reate
// a new appS essio n
pub lic v oid setMa xInac tiveI nterv al(i nt in terva l) {
inac tive Inter val = inte rval;
retu rn a ppSes sion;
// ----- ---- ----- ----- ----- ----- ---- ----- ----- --HttpSes sion Publ ic Me thods
/**
* Retur n th e obj ect b ound with the speci fied name
in this sess ion, or
* <code >nul l</co de> i f no objec t is boun d wit h tha t
name.
*
* @para m na me Na me of the attri bute to b e ret urned
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on an
* inva lida ted s essio n
*/
pub lic O bjec t get Attri bute( Strin g na me) {
// XXX
// sync' d fo r saf ty -- no o ther thre ad sh ould be ge tting som ethin g
// from this whil e we are r eapin g. T his i sn't the m ost o ptim al
// solut ion for t his, but w e'll dete rmine some thing else lat er.
syn chron ized void reap () {
Enum erat ion e num = appS essio ns.k eys() ;
voi d acc esse d() {
// s et l ast a ccess ed to this Acce ssTim e as it wi ll be lef t ove r
// f rom the p revio us ac cess
whil e (e num.h asMor eElem ents( )) {
Obje ct ke y = e num.n extEl emen t();
Appl icati onSes sion appSe ssio n =
(Appl icati onSes sion) appS essio ns.ge t(key );
last Acce ssed = thi sAcce ssTim e;
this Acce ssTim e = S ystem .curr entT imeMi llis( );
retu rn ( this. lastA ccess edTim e);
/**
* Retur n th e set of n ames of ob ject s bou nd to this
session . If the re
* are n o su ch ob jects , a z ero-l engt h arr ay is
returne d.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on an
* inva lida ted s essio n
*
* @depr ecat ed As of V ersio n 2.2 , th is me thod is
replace d by
* <cod e>ge tAttr ibute Names ()</c ode>
*/
pub lic S trin g[] g etVal ueNam es() {
sta tic a dvic e(Sta ndard Sessi on s) : in valid ate(s ) {
befo re {
if ( !s.is Valid ())
throw new Illeg alSta teEx cepti on
( s.sm. getSt ring( "sta ndard Sessi on."
+ th isJoi nPoin t.met hodNa me
+ ". ise") );
}
}
}
Cook ie c ookie s[]=r eques t.get Cook ies() ; // asser t !=n ull
/** Noti fica tion of co ntext shut down
*/
pub lic v oid conte xtShu tdown ( Con text ctx )
thro ws T omcat Excep tion
{
if( ctx. getDe bug() > 0 ) ctx .log ("Rem oving sess ions from " + ctx ) ;
ctx. getS essio nMana ger() .remo veSe ssion s(ctx );
}
for( int i=0; i<co okies .leng th; i++ ) {
Cook ie co okie = coo kies[ i];
if ( cooki e.get Name( ).equ als( "JSES SIONI D")) {
sessi onId = coo kie.g etVa lue() ;
sessi onId= valid ateSe ssio nId(r eques t, se ssion Id);
if (s essio nId!= null) {
r eques t.set Reque sted Sessi onIdF romCo okie( true );
}
}
}
}
Stri ng s ig="; jsess ionid =";
int foun dAt=- 1;
if( debu g>0 ) cm.l og(" XXX R URI= " + r eques t.get Reque stUR I());
if ( (fou ndAt= reque st.ge tRequ estU RI(). index Of(si g))!= -1){
sess ionId =requ est.g etReq uest URI() .subs tring (foun dAt+ sig.l ength ());
// r ewrit e URL , do I nee d to do a nythi ng mo re?
requ est.s etReq uestU RI(re ques t.get Reque stURI ().su bstr ing(0 , fou ndAt) );
sess ionId =vali dateS essio nId( reque st, s essio nId);
if ( sessi onId! =null ){
reque st.se tRequ ested Sess ionId FromU RL(tr ue);
}
}
retu rn 0 ;
// ---- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- - Pri vate Class
/**
* This clas s is a du mmy i mplem entat ion of th e <co de>Ht tpSes sion Conte xt</c ode>
* inte rface , to conf orm t o the requ irem ent t hat s uch a n obj ect be re turne d
* when <cod e>Ht tpSes sion. getSe ssion Cont ext() </cod e> is call ed.
*
* @aut hor C raig R. M cClan ahan
*
* @dep recat ed A s of Java Servl et AP I 2. 1 wit h no repla cemen t. The
* int erfac e wi ll be remo ved i n a f utur e ver sion of th is AP I.
*/
final c lass Stan dardS essio nCont ext i mple ments Http Sessi onCon text {
pri vate Vect or du mmy = new Vecto r();
/**
* Retur n th e ses sion ident ifier s of all sessi ons d efine d
* withi n th is co ntext .
*
* @depr ecat ed As of J ava S ervle t AP I 2.1 with no r eplac emen t.
* This met hod m ust r eturn an e mpty <cod e>Enu merat ion</ code >
* and will be r emove d in a fut ure versi on of the API.
*/
pub lic E nume ratio n get Ids() {
retu rn ( dummy .elem ents( ));
}
/**
* Retur n th e <co de>Ht tpSes sion< /cod e> as socia ted w ith t he
* speci fied sess ion i denti fier.
*
* @para m id Sess ion i denti fier for which to l ook u p a s essi on
*
* @depr ecat ed As of J ava S ervle t AP I 2.1 with no r eplac emen t.
* This met hod m ust r eturn null and will be r emove d in a
* futu re v ersio n of the A PI.
*/
pub lic H ttpS essio n get Sessi on(St ring id) {
}
}
/**
* Set t he M anage r wit hin w hich this
Session is v alid .
*
* @para m ma nager The new M anage r
*/
pub lic v oid setMa nager (Mana ger m anag er) {
/**
* Inval idat es th is se ssion and unbi nds a ny ob jects
bound t o it.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on
* an i nval idate d ses sion
*/
pub lic v oid inval idate () {
}
retu rn ( this. maxIn activ eInte rval );
}
voi d val idat e()
/**
* Set t he m aximu m tim e int erval , in
seconds , bet ween clie nt re quest s
* befor e th e ser vlet conta iner will
invalid ate t he s essio n. A nega tive
* time indi cates that the sessi on s hould
never t ime o ut.
*
* @para m in terva l The new maxim um i nterv al
*/
pub lic v oid setMa xInac tiveI nterv al(i nt
interva l) {
this .max Inact iveIn terva l = i nter val;
java. io.I OExce ption ;
java. util .Enum erati on;
java. util .Hash table ;
java. util .Vect or;
org.a pach e.tom cat.c atali na.*;
javax .ser vlet. http. Cooki e;
javax .ser vlet. http. HttpS essio n;
org.a pach e.tom cat.u til.S tring Mana ger;
org.w 3c.d om.Na medNo deMap ;
org.w 3c.d om.No de;
/**
* The d escr iptiv e inf ormat ion a bout this impl ement ation .
*/
pri vate stat ic fi nal S tring info = " Stand ardMa nager /1.0" ;
/**
* The m axim um nu mber of ac tive Sess ions allow ed, o r -1 for no li mit.
*/
pro tecte d in t max Activ eSess ions = -1 ;
/**
* The s trin g man ager for t his p acka ge.
*/
pri vate Stri ngMan ager sm =
Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" );
if( debu g>0 ) cm.l og(" Orig sess ionId " + sess ionId );
if ( null != s essio nId) {
int idex = ses sionI d.las tInd exOf( SESSI ONID_ ROUTE _SEP );
if(i dex > 0) {
sessi onId = ses sionI d.su bstri ng(0, idex );
}
}
/**
* Has t his compo nent been start ed y et?
*/
pri vate bool ean s tarte d = f alse;
if ( sess ionId != n ull & & ses sion Id.le ngth( )!=0) {
// G S, We are in a probl em h ere, we ma y act ually get
// m ultip le Se ssion cook ies (one for t he ro ot
// c ontex t and one for t he r eal c ontex t... or ol d se ssion
// c ookie . We must check for vali dity in th e cur rent cont ext.
Cont ext c tx=re quest .getC onte xt();
Sess ionMa nager sM = ctx. getS essio nMana ger() ;
if(n ull ! = sM. findS essio n(ct x, se ssion Id)) {
sM.ac cesse d(ctx , req uest , ses sionI d );
reque st.se tRequ ested Sess ionId (sess ionId );
if( d ebug> 0 ) c m.log (" F inal sessi on id " + sess ionId );
retur n ses sionI d;
}
}
retu rn n ull;
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- - Li fecyc le
Methods
/**
* Confi gure this comp onent , bas ed o n the spec ified conf igur ation
* param eter s. T his m ethod shou ld b e cal led i mmedi ately aft er th e
* compo nent inst ance is cr eated , an d bef ore < code> start ()</ code>
* is ca lled .
*
* @para m pa ramet ers C onfig urati on p arame ters for t his c ompo nent
* (<B> FIXM E: Wh at ob ject type shou ld th is re ally be?)
*
* @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready
/**
been
* Stan dard impl ement ation of t he <b >Man ager< /b> i nterf ace t hat provi des
* conf igur ed an d/or start ed
* no s essio n pe rsist ence or di strib utab le ca pabil ities , but doe s sup port
* @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l
* an o ption al, confi gurab le, m aximu m nu mber of ac tive sessi ons allow ed.
error
* <p>
* in t he c onfig urati on pa ramet ers it wa s giv en
* Life cycle con figur ation of t his c ompo nent assum es an XML node
*/
* in t he fo llow ing f ormat :
pub lic v oid confi gure( Node param eter s)
* <cod e>
thro ws L ifecy cleEx cepti on {
*
<M anag er cl assNa me="o rg.ap ache .tomc at.se ssion .Stan dard Manag er"
*
check Inter val=" 60" m axAc tiveS essio ns="- 1"
// V alid ate a nd up date our c urre nt co mpone nt st ate
*
maxIn activ eInte rval= "-1" />
if ( conf igure d)
* </co de>
thro w new Life cycle Excep tion
* wher e you can adju st th e fol lowin g pa ramet ers, with defau lt v alues
(sm.g etStr ing(" stand ardM anage r.alr eadyC onfig ured "));
* in s quare bra ckets :
conf igur ed = true;
* <ul>
if ( para meter s == null)
* <li> <b>ch eckI nterv al</b > - T he in terv al (i n sec onds) betw een backg round
retu rn;
*
threa d ch ecks for e xpire d ses sion s. [ 60]
* <li> <b>ma xAct iveSe ssion s</b> - Th e ma ximum numb er of sess ions allo wed t o
// P arse and proce ss ou r con figu ratio n par amete rs
*
be ac tive at o nce, or -1 for no l imit. [-1 ]
if ( !("M anage r".eq uals( param eter s.get NodeN ame() )))
* <li> <b>ma xIna ctive Inter val</ b> - The defau lt ma ximum numb er o f sec onds of
retu rn;
*
inact ivit y bef ore w hich the s ervl et co ntain er is allo wed to ti me ou t
Name dNod eMap attri butes = pa rame ters. getAt tribu tes() ;
*
a ses sion , or -1 fo r no limit . T his v alue shoul d be over ridde n fro m
Node nod e = n ull;
*
the d efau lt se ssion time out s peci fied in th e web appl icat ion d eploy ment
*
descr ipto r, if any. [-1 ]
node = a ttrib utes. getNa medIt em(" check Inter val") ;
* </ul >
if ( node != n ull) {
*
try {
* @aut hor C raig R. M cClan ahan
setCh eckIn terva l(Int eger .pars eInt( node. getNo deVa lue() ));
* @ver sion $Rev ision : 1.1 .1.1 $ $Da te: 2000/ 05/02 21:2 8:30 $
} ca tch ( Throw able t) {
*/
;
// XXX - Thr ow e xcept ion?
}
public final cla ss St andar dMana ger
}
ext ends Mana gerBa se
imp lemen ts L ifecy cle, Runna ble {
node = a ttrib utes. getNa medIt em(" maxAc tiveS essio ns");
if ( node != n ull) {
try {
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- Ins tance Vari ables
/**
* Has t his compo nent been confi gure d yet ?
*/
pri vate bool ean c onfig ured = fal se;
/** Vali date and fix t he se ssion id. If t he se ssion is n ot v alid retur n nul l.
* It w ill also clean up t he se ssio n fro m loa d-bal ancin g st rings .
* @retu rn s essio nId, or nu ll if not vali d
*/
pri vate Stri ng va lidat eSess ionId (Req uest reque st, S tring ses sionI d){
// G S, W e pig gybac k the JVM id o n top of t he se ssion coo kie
// S epar ate t hem . ..
/**
* The b ackg round thre ad.
*/
pri vate Thre ad th read = nul l;
setMaxA ctive Sess ions( Integ er.pa rseIn t(no de.ge tNode Value ()));
} ca tch ( Throw able t) {
;
// XXX - Thr ow e xcept ion?
}
}
node = a ttrib utes. getNa medIt em(" maxIn activ eInte rval" );
if ( node != n ull) {
try {
package org. apac he.to mcat. sessi on;
// ---- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----Public Metho ds
import java. io.I OExce ption ;
import javax .ser vlet. http. Cooki e;
/**
import javax .ser vlet. http. HttpS essio n;
import org.a pach e.tom cat.c atali na.*;
* Mark the speci fied sessi on's last acce ssed time.
should be
import org.a pach e.tom cat.c ore.C ontex t;
Thi s
* calle d fo r eac h req uest by a Requ estIn terce ptor.
import org.a pach e.tom cat.c ore.R eques t;
*
import org.a pach e.tom cat.c ore.R espon se;
* @para m se ssion The sessi on to be marke d
import org.a pach e.tom cat.c ore.S essio nMan ager;
*/
import org.a pach e.tom cat.u til.S essio nUti l;
pub lic v oid acces sed(C ontex t ctx , Re quest req, Stri ng id ) {
Http Sess ion s essio n=fin dSess ion( ctx, id);
if( sess ion = = nul l) re turn;
/**
if ( sess ion i nstan ceof Sessi on)
* Spec ializ ed i mplem entat ion o f
org.apa che.t omca t.cor e.Ses sionM anage r
((Se ssion ) ses sion) .acce ss() ;
* that adap ts t o the new compo nent- base d Man ager
impleme ntati on.
// c ache the HttpS essio n - a void anot her f ind
* <p>
req. setS essio n( se ssion );
* XXX - At pres ent, use o f <co de>St anda rdMan ager< /code > is hard
coded,
* and lifec ycle conf igura tion is no t su pport ed.
}
// XXX s houl d we throw exce ption or just retur n nul l ??
* <p>
pub lic H ttpS essio n fin dSess ion( Cont ext c tx, S tring id ) {
* <b>I MPLEM ENTA TION NOTE< /b>:
Manager /Sess ion
Once we commi t to the n ew
try {
Sess ion s essio n = m anage r.fi ndSes sion( id);
* para digm, I w ould sugge st mo ving the logic impl ement ed he re
back in to
* the core leve l.
more li ke a
if(s essio n!=nu ll)
T he To mcat. Next "Man ager" inte rface acts
retur n ses sion. getSe ssio n();
} ca tch (IOEx cepti on e) {
* coll ectio n cl ass, and h as mi nimal kno wledg e of the d etail ed
request
}
retu rn ( null) ;
* proc essin g se manti cs of hand ling sess ions.
}
* <p>
* XXX - At pres ent, there is n o way (vi a the Sess ionMa nager
interfa ce) f or
pub lic H ttpS essio n cre ateSe ssion (Con text ctx) {
* a Co ntext to tell the M anage r tha t we crea te wh at th e def ault
session
retu rn
manag er.cr eateS essio n(). getSe ssion ();
}
* time out f or t his w eb ap plica tion (spe cifie d in the d eploy ment
descrip tor)
/**
* shou ld be .
* Remov e al l ses sions beca use o ur a ssoci ated Conte xt is
being s hut d own.
*
* @aut hor C raig R. M cClan ahan
*
*/
* @para m ct x The cont ext t hat i s be ing s hut d own
public final cla ss St andar dSess ionMa nage r
pub lic v oid remov eSess ions( Conte xt c tx) {
imp lemen ts S essio nMana ger {
// X XX X XX a manag er ma y be shar ed by mult iple
// c onne ction open
if ( mana ger i nstan ceof Lifec ycle ) {
/**
* Prepa re f or th e beg innin g of acti ve us e of the p ublic met hods of
this
* compo nent . Th is me thod shoul d be call ed af ter
<code>c onfig ure( )</co de>,
* and b efor e any of t he pu blic meth ods o f the comp onent are
utilize d.
*
* @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s no t yet
been
* conf igur ed (i f req uired for this comp onent )
* @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready
been
* star ted
* @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l
error
* that pre vents this comp onent fro m bei ng us ed
*/
pub lic v oid start () th rows Lifec ycle Excep tion {
// V alid ate a nd up date our c urre nt co mpone nt st ate
if ( !con figur ed)
thro w new Life cycle Excep tion
(sm.g etStr ing(" stand ardM anage r.not Confi gured "));
if ( star ted)
thro w new Life cycle Excep tion
(sm.g etStr ing(" stand ardM anage r.alr eadyS tarte d")) ;
star ted = tru e;
// S tart the backg round reap er t hread
thre adSt art() ;
/**
try {
* Creat e a new S essio nMana ger t hat adapt s to the
corresp ondin g Ma nager
((Lif ecycl e) ma nager ).st op();
} ca tch ( Lifec ycleE xcept ion e) {
* imple ment ation .
throw new Illeg alSta teEx cepti on("" + e) ;
*/
}
pub lic S tand ardSe ssion Manag er() {
}
mana ger = new Stan dardM anage r();
}
if ( mana ger i nstan ceof Lifec ycle ) {
try {
/**
((Lif ecycl e) ma nager ).co nfigu re(nu ll);
((Lif ecycl e) ma nager ).st art() ;
* Used by c ontex t to confi gure the sessi on ma nager 's
inactiv ity t imeo ut.
} ca tch ( Lifec ycleE xcept ion e) {
throw new Illeg alSta teEx cepti on("" + e) ;
}
}
*
* The S essi onMan ager may h ave s ome defau lt se ssion time
out, th e
* Conte xt o n the othe r han d has it' s tim eout set b y the
deploym ent
* descr ipto r (we b.xml ). Th is me thod lets the Conte xt
conforg ure t he
}
* sessi on m anage r acc ordin g to this valu e.
*
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----Instanc e Var iabl es
* @para m mi nutes The sessi on in acti vity timeo ut in minu tes.
}
*/
pub lic v oid setSe ssion TimeO ut(in t mi nutes ) {
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- ---- Prope rties
/**
* Retur n th e che ck in terva l (in sec onds) for this Manag er.
*/
pub lic i nt g etChe ckInt erval () {
retu rn ( this. check Inter val);
}
Se ve Sess onManage
ServerSessionMana
ger
import org.a pach e.tom cat.u til.* ;
import org.a pach e.tom cat.c ore.* ;
import java. io.* ;
import java. net. *;
import java. util .*;
import javax .ser vlet. http. *;
// XXX
// sync' d fo r saf ty -- no o ther thre ad sh ould be ge tting som ethin g
// from this whil e we are r eapin g. T his i sn't the m ost o ptim al
// solut ion for t his, but w e'll dete rmine some thing else lat er.
/**
* Set t he c heck inter val ( in se cond s) fo r thi s Man ager.
*
* @para m ch eckIn terva l The new chec k int erval
*/
pub lic v oid setCh eckIn terva l(int che ckInt erval ) {
/**
* Grace full y ter minat e the acti ve u se of the publi c met hods of t his
* compo nent . Th is me thod shoul d be the last one c alled on a giv en
* insta nce of th is co mpone nt.
*
* @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s no t bee n
started
* @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready
* been sto pped
* @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l
error
* that nee ds to be r eport ed
*/
pub lic v oid stop( ) thr ows L ifecy cleE xcept ion {
// T he ma nager work s wit h se conds ...
* The M anag er im pleme ntati on we are actu ally using .
mana ger.s etMax Inact iveIn terv al(mi nutes * 60 );
*/
}
pri vate Mana ger m anage r = n ull;
}
}
// V alid ate a nd up date our c urre nt co mpone nt st ate
if ( !sta rted)
thro w new Life cycle Excep tion
(sm.g etStr ing(" stand ardM anage r.not Start ed")) ;
star ted = fal se;
this .che ckInt erval = ch eckIn terv al;
// S top the b ackgr ound reape r th read
thre adSt op();
}
// E xpir e all acti ve se ssion s
Sess ion sessi ons[] = fi ndSes sion s();
for (int i = 0; i < ses sions .len gth; i++) {
Stan dardS essio n ses sion = (S tanda rdSes sion) sess ions [i];
if ( !sess ion.i sVali d())
conti nue;
sess ion.e xpire ();
}
/**
* Retur n de scrip tive infor matio n ab out t his M anage r imp leme ntati on an d
* the c orre spond ing v ersio n num ber, in t he fo rmat
* <code >< ;desc ripti on> ;/< ;ver sion& gt;</ code> .
*/
pub lic S trin g get Info( ) {
retu rn ( this. info) ;
whil e (e num.h asMor eElem ents( )) {
Obje ct ke y = e num.n extEl emen t();
Serv erSes sion sessi on = (Ser verSe ssion )sess ions. get( key);
sess ion.r eap() ;
sess ion.v alida te();
}
/**
* Retur n th e max imum numbe r of acti ve Se ssion s all owed, or -1 fo r
* no li mit.
*/
pub lic i nt g etMax Activ eSess ions( ) {
}
retu rn ( this. maxAc tiveS essio ns);
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- --- Priva te
Methods
/**
* Inval idat e all sess ions that have expi red.
*/
pri vate void proc essEx pires () {
}
long tim eNow = Sys tem.c urren tTim eMill is();
Sess ion sessi ons[] = fi ndSes sion s();
}
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) {
Stri ng i d = s essio n.get Id();
pri vate Stri ngMan ager sm =
Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" );
pri vate stat ic Se rverS essio nMana ger manag er; / / = n ew Se rver Sessi onMan ager( );
sess ion. inval idate ();
sess ions .remo ve(id );
}
pro tecte d in t ina ctive Inter val = -1;
pub lic v oid remov eSess ions( Conte xt c ontex t) {
Enum erat ion e num = sess ions. keys ();
sta tic {
mana ger = new Serv erSes sionM anag er();
}
whil e (e num.h asMor eElem ents( )) {
Obje ct ke y = e num.n extEl emen t();
Serv erSes sion sessi on = (Ser verSe ssion )sess ions. get( key);
Appl icati onSes sion appSe ssio n =
sessi on.ge tAppl icati onSe ssion (cont ext, false );
pub lic s tati c Ser verSe ssion Manag er g etMan ager( ) {
retu rn m anage r;
}
pri vate Hash table sess ions = new Has htabl e();
pri vate Reap er re aper;
if ( appSe ssion != n ull) {
appSe ssion .inva lidat e();
}
pri vate Serv erSes sionM anage r() {
reap er = Reap er.ge tReap er();
reap er.s etSer verSe ssion Manag er(t his);
reap er.s tart( );
}
}
}
/**
* Used by c ontex t to confi gure the sessi on ma nager 's in acti vity timeo ut.
*
* The S essi onMan ager may h ave s ome defau lt se ssion time out , the
* Conte xt o n the othe r han d has it' s tim eout set b y the dep loyme nt
* descr ipto r (we b.xml ). Th is me thod lets the Conte xt co nfor gure the
* sessi on m anage r acc ordin g to this valu e.
*
* @para m mi nutes The sessi on in acti vity timeo ut in minu tes.
*/
pub lic v oid setSe ssion TimeO ut(in t mi nutes ) {
if(- 1 != minu tes) {
// T he ma nager work s wit h se conds ...
inac tiveI nterv al = (minu tes * 60) ;
}
}
pub lic v oid acces sed( Conte xt ct x, R eques t req , Str ing i d ) {
Appl icat ionSe ssion apS= (Appl icat ionSe ssion )find Sessi on( ctx, id);
if( apS= =null ) ret urn;
Serv erSe ssion serv S=apS .getS erve rSess ion() ;
serv S.ac cesse d();
apS. acce ssed( );
// c ache it - no n eed t o com pute it a gain
req. setS essio n( ap S );
}
pub lic H ttpS essio n cre ateSe ssion (Con text ctx) {
Stri ng s essio nId = Sess ionId Gene rator .gene rateI d();
Serv erSe ssion sess ion = new Serv erSes sion( sessi onId) ;
sess ions .put( sessi onId, sess ion) ;
if(- 1 != minu tes) {
/**
}
syn chron ized void reap () {
Enum erat ion e num = sess ions. keys ();
/**
*
* @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om]
* @aut hor J ason Hunt er [j ch@en g.sun .com ]
* @aut hor J ames Todd [gon zo@en g.sun .com ]
*/
}
for (int i = 0; i < ses sions .len gth; i++) {
Stan dardS essio n ses sion = (S tanda rdSes sion) sess ions [i];
if ( !sess ion.i sVali d())
conti nue;
int maxIn activ eInte rval = se ssion .getM axIna ctive Inte rval( );
if ( maxIn activ eInte rval < 0)
conti nue;
int timeI dle = // T runca te, do no t rou nd up
(int) ((ti meNow - se ssio n.get LastA ccess edTim e()) /
/**
* Set t he m aximu m num ber o f act ives Sess ions allow ed, o r -1 for
* no li mit.
*
* @para m ma x The new maxim um nu mber of s essio ns
*/
pub lic v oid setMa xActi veSes sions (int max) {
this .max Activ eSess ions = max ;
1000L);
if ( timeI dle > = max Inact iveI nterv al)
sessi on.ex pire( );
}
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- Publ ic Me thods
}
/**
* Const ruct and retur n a n ew se ssio n obj ect, based on t he d efaul t
* setti ngs speci fied by th is Ma nage r's p roper ties. The ses sion
* id wi ll b e ass igned by t his m etho d, an d ava ilabl e via the getI d()
* metho d of the retur ned s essio n. If a new s essio n can not be cr eated
* for a ny r eason , ret urn < code> null </cod e>.
*
* @exce ptio n Ill egalS tateE xcept ion if a new s essio n can not be
* inst anti ated for a ny re ason
*/
pub lic S essi on cr eateS essio n() {
/**
* Sleep for the durat ion s pecif ied by th e <co de>ch eckIn terv al</c ode>
* prope rty.
*/
pri vate void thre adSle ep() {
if ( (max Activ eSess ions >= 0) &&
(s essi ons.s ize() >= m axAct iveS essio ns))
thro w new Ille galSt ateEx cept ion
(sm.g etStr ing(" stand ardM anage r.cre ateSe ssion .ise "));
retu rn ( super .crea teSes sion( ));
}
try {
Thre ad.sl eep(c heckI nterv al * 1000 L);
} ca tch (Inte rrupt edExc eptio n e) {
;
}
}
/**
* Start the back groun d thr ead t hat will perio dical ly ch eck for
* sessi on t imeou ts.
*/
pri vate void thre adSta rt() {
}
if ( thre ad != null )
retu rn;
thre adDo ne = false ;
thre ad = new Threa d(thi s, th read Name) ;
thre ad.s etDae mon(t rue);
thre ad.s tart( );
if(- 1 != inac tiveI nterv al) {
sess ion. setMa xInac tiveI nterv al(i nacti veInt erval );
/**
* Retur n <c ode>t rue</ code> if t he c lient does not
yet kno w abo ut t he
* sessi on, or if the clien t cho oses not to jo in th e
session . Fo r
* examp le, if th e ser ver u sed o nly cooki e-bas ed
session s, an d th e cli ent
* has d isab led t he us e of cooki es, then a ses sion
would b e new on each
* reque st.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on an
* inva lida ted s essio n
*/
pub lic b oole an is New() {
StandardSessionMana
ger
// c onte xts, we ju st wa nt to rem ove t he se ssion s of ctx!
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---// T he m anage r wil l sti ll ru n af ter t hat ( i.e. keep
-- Cons truct ors
databas e
}
/**
* The b ackg round thre ad co mplet ion semap hore.
*/
pri vate bool ean t hread Done = fal se;
/**
* Name to r egist er fo r the back grou nd th read.
*/
pri vate Stri ng th readN ame = "Sta ndar dMana ger";
S andardSess onManager
*/
setMaxI nacti veIn terva l(Int eger. parse Int( node. getNo deVal ue()) );
} ca tch ( Throw able t) {
;
// XXX - Thr ow e xcept ion?
}
}
}
retu rn ( null) ;
}
}
// C ause this sess ion t o exp ire
expi re() ;
/**
* Retur n th e max imum time inter val, in
seconds , bet ween clie nt re quest s
* befor e th e ser vlet conta iner will
invalid ate t he s essio n. A nega tive
* time indi cates that the sessi on s hould
never t ime o ut.
*
* @exce ptio n Ill egalS tateE xcept ion if th is
method is ca lled on
* an i nval idate d ses sion
*/
pub lic i nt g etMax Inact iveIn terva l() {
package org. apac he.to mcat. sessi on;
import
import
import
import
import
import
import
import
import
import
/**
* The i nter val ( in se conds ) bet ween chec ks fo r exp ired sess ions.
*/
pri vate int check Inter val = 60;
// XXX w hat is th e cor rect behav ior if th e ses sion is in vali d ?
// We ma y st ill s et it and just retu rn se ssion inva lid.
package org. apac he.to mcat. sessi on;
}
Vect or r esult s = n ew Ve ctor( );
Enum erat ion a ttrs = get Attri bute Names ();
whil e (a ttrs. hasMo reEle ments ()) {
Stri ng at tr = (Stri ng) a ttrs .next Eleme nt();
resu lts.a ddEle ment( attr) ;
}
Stri ng n ames[ ] = n ew St ring[ resu lts.s ize() ];
for (int i = 0; i < nam es.le ngth ; i++ )
name s[i] = (St ring) resu lts. eleme ntAt( i);
retu rn ( names );
retu rn ( this. manag er);
appS essio n.val idate ();
}
}
cro sscut inv alida te(St andar dSess ion s): s & (i nt ge tMaxI nact iveIn terva l() |
l ong g etCre atio nTime () |
O bject getA ttri bute( Strin g) |
E numer ation get Attri buteN ames( ) |
S tring [] ge tVal ueNam es() |
v oid i nvali date () |
b oolea n isN ew() |
v oid r emove Attr ibute (Stri ng) |
v oid s etAtt ribu te(St ring, Obje ct));
retu rn ( attri butes .keys ());
/**
* Retur n th e Man ager withi n whi ch t his
Session is v alid .
*/
pub lic M anag er ge tMana ger() {
}
}
pub lic i nt r eques tMap( Reque st re ques t ) {
Stri ng s essio nId = null ;
}
}
/**
* Retur n th e obj ect b ound with the speci fied name
in this sess ion, or
* <code >nul l</co de> i f no objec t is boun d wit h tha t
name.
*
* @para m na me Na me of the value to be re turne d
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on an
* inva lida ted s essio n
*
* @depr ecat ed As of V ersio n 2.2 , th is me thod is
replace d by
* <cod e>ge tAttr ibute ()</c ode>
*/
pub lic O bjec t get Value (Stri ng na me) {
retu rn ( getAt tribu te(na me));
this .man ager = man ager;
pub lic i nt g etMax Inact iveIn terva l() {
retu rn i nacti veInt erval ;
/**
* Calle d by cont ext w hen r eques t co mes i n so that acces ses and
* inact ivit ies c an be deal t wit h ac cordi ngly.
*/
retu rn 0 ;
// S eria lize the a ttrib ute c ount and the attri bute valu es
stre am.w riteO bject (new Integ er(r esult s.siz e())) ;
Enum erat ion n ames = res ults. elem ents( );
whil e (n ames. hasMo reEle ments ()) {
Stri ng na me = (Stri ng) n ames .next Eleme nt();
stre am.wr iteOb ject( name) ;
stre am.wr iteOb ject( attri bute s.get (name ));
}
retu rn ( attri butes .get( name) );
/**
* Retur n an <cod e>Enu merat ion</ code > of
<code>S tring </co de> o bject s
* conta inin g the name s of the o bjec ts bo und t o thi s
session .
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod
is call ed on an
* inva lida ted s essio n
*/
pub lic E nume ratio n get Attri buteN ames () {
}
voi d rem oveA pplic ation Sessi on(Co ntex t con text) {
appS essi ons.r emove (cont ext);
}
// A ccum ulate the names of s eria lizab le at tribu tes
Vect or r esult s = n ew Ve ctor( );
Enum erat ion a ttrs = get Attri bute Names ();
whil e (a ttrs. hasMo reEle ments ()) {
Stri ng at tr = (Stri ng) a ttrs .next Eleme nt();
Obje ct va lue = attr ibute s.ge t(att r);
if ( value inst anceo f Ser iali zable )
resul ts.ad dElem ent(a ttr) ;
}
}
}
}
}
resp onse .addH eader ( Coo kieTo ols. getCo okieH eader Name( cook ie),
Coo kieTo ols. getCo okieH eader Value (coo kie)) ;
cook ie.s etVer sion( 0);
resp onse .addH eader ( Coo kieTo ols. getCo okieH eader Name( cook ie),
Coo kieTo ols. getCo okieH eader Value (coo kie)) ;
pub lic v oid setCo ntext Manag er( C onte xtMan ager cm ) {
this .cm= cm;
}
// W rite the scala r ins tance var iable s (ex cept Manag er)
stre am.w riteO bject (new Long( crea tionT ime)) ;
stre am.w riteO bject (id);
stre am.w riteO bject (new Long( last Acces sedTi me));
stre am.w riteO bject (new Integ er(m axIna ctive Inter val)) ;
stre am.w riteO bject (new Boole an(i sNew) );
stre am.w riteO bject (new Boole an(i sVali d));
}
retu rn ( this. info) ;
}
// X XX
// s ync t o ens ure v alid?
}
if ( sess ionCo ntext == n ull)
sess ionCo ntext = ne w
Standar dSess ionC ontex t();
retu rn ( sessi onCon text) ;
}
/**
* Retur n th e las t tim e the clie nt s ent a
request asso ciat ed wi th th is
* sessi on, as th e num ber o f mil lise conds
since m idnig ht, Janua ry 1, 1970
* GMT. Act ions that your appli cati on
takes, such as g ettin g or setti ng
* a val ue a ssoci ated with the s essi on, d o
not aff ect t he a ccess time .
*/
pub lic l ong getLa stAcc essed Time( ) {
retu rn v alues .get( name) ;
if ( appS essio n == null && cr eate ) {
pub lic v oid setDe bug( int i ) {
Syst em.o ut.pr intln ("Set debu g to " + i);
debu g=i;
}
StandardManage
r
}
retu rn ( this. creat ionTi me);
}
}
pub lic O bjec t get Value (Stri ng na me) {
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("s erver Sessi on.va lue.i ae") ;
pub lic A ppli catio nSess ion g etApp lica tionS essio n(Con text cont ext,
bool ean creat e) {
Appl icat ionSe ssion appS essio n =
(App licat ionSe ssion )appS essi ons.g et(co ntext );
// G S, p iggyb ack t he jv m rou te o n the sess ion i d.
if(! sess ionPa th.eq uals( "/")) {
Stri ng jv mRout e = r reque st.g etJvm Route ();
if(n ull ! = jvm Route ) {
reqSe ssion Id = reqSe ssio nId + SESS IONID _ROUT E_SE P + j vmRou te;
}
}
Cook ie c ookie = ne w Coo kie(" JSES SIONI D",
r eqSe ssion Id);
cook ie.s etMax Age(- 1);
cook ie.s etPat h(ses sionP ath);
cook ie.s etVer sion( 1);
pub lic S essi onInt ercep tor() {
}
// D eser ializ e the attr ibute cou nt an d att ribut e val ues
int n = ((Int eger) stre am.re adOb ject( )).in tValu e();
for (int i = 0; i < n; i++) {
Stri ng na me = (Stri ng) s trea m.rea dObje ct();
Obje ct va lue = (Obj ect) stre am.re adObj ect() ;
attr ibute s.put (name , val ue);
}
this .id = id;
if ( (man ager != nu ll) & & (ma nage r
instanc eof M anag erBas e))
((Ma nager Base) mana ger). add( this) ;
remo veVa lue(n ame); // remov e an y exi sting bind ing
valu es.p ut(na me, v alue) ;
}
// GS, s epar ates the s essio n id from the jvm r oute
sta tic f inal char SESS IONID _ROUT E_SE P = ' .';
int debu g=0;
Con textM anag er cm ;
// G S, s et th e pat h att ribut e to the cooki e. Th is wa y
// m ulti ple s essio n coo kies can be us ed, o ne fo r eac h
// c onte xt.
Stri ng s essio nPath = rr eques t.ge tCont ext() .getP ath() ;
if(s essi onPat h.len gth() == 0 ) {
sess ionPa th = "/";
}
}
ServerSessio
n
/**
* Core impl emen tatio n of a ser ver s essi on
*
* @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om]
* @aut hor J ames Todd [gon zo@en g.sun .com ]
*/
pub lic i nt b efore Body( Requ est r requ est, Respo nse r espon se ) {
Stri ng r eqSes sionI d = r espon se.g etSes sionI d();
if( debu g>0 ) cm.l og("B efore Bod y " + reqS essio nId ) ;
if( reqS essio nId== null)
retu rn 0;
/**
* Will proc ess the r eques t and dete rmin e the sess ion I d, an d se t it
* in t he Re ques t.
* It a lso m arks the sessi on as acce ssed .
*
* This impl emen tatio n onl y han dles Cook ies s essio ns, p lease ext end o r
* add new i nter cepto rs fo r oth er me thod s.
*
*/
public class Ses sionI nterc eptor exte nds Base Inter cepto r imp leme nts R eques tInte rcept or {
}
//----- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- ----- ---/**
* Set t he c reati on ti me fo r thi s se ssion .
This me thod is c alled by t he
* Manag er w hen a n exi sting Sess ion
instanc e is reus ed.
*
* @para m ti me Th e new crea tion time
*/
pub lic v oid setCr eatio nTime (long tim e) {
S andardManager
package org. apac he.to mcat. reque st;
import org.a pach e.tom cat.c ore.* ;
import org.a pach e.tom cat.u til.* ;
import java. io.* ;
import java. net. *;
import java. util .*;
import javax .ser vlet. http. *;
// D eser ializ e the scal ar in stan ce va riabl es (e xcept Man ager)
crea tion Time = ((L ong) strea m.re adObj ect() ).lon gValu e();
id = (St ring) stre am.re adObj ect( );
last Acce ssedT ime = ((Lo ng) s trea m.rea dObje ct()) .long Valu e();
maxI nact iveIn terva l = ( (Inte ger) stre am.re adObj ect() ).in tValu e();
isNe w = ((Boo lean) stre am.re adOb ject( )).bo olean Value ();
isVa lid = ((B oolea n) st ream. read Objec t()). boole anVal ue() ;
retu rn i nacti veInt erval ;
}
pub lic l ong getLa stAcc essed Time( ) {
if ( vali d) {
retu rn la stAcc essed ;
} el se {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise ");
Sess on n ercep o
SessionIntercept
or
this .isV alid = isV alid;
}
thro w new Ille galSt ateEx cept ion(m sg);
}
}
package org. apac he.to mcat. sessi on;
/**
/**
* Retur n th e <co de>Ht tpSes sion< /cod e> fo r whi ch
this ob ject
* is th e fa cade.
*/
pub lic H ttpS essio n get Sessi on() {
}
package org. apac he.to mcat. sessi on;
import org.a pach e.tom cat.c ore.* ;
import org.a pach e.tom cat.u til.S tring Mana ger;
import java. io.* ;
import java. net. *;
import java. util .*;
import javax .ser vlet. *;
import javax .ser vlet. http. *;
StandardSessio
n
}
retu rn s essio n.get Appli catio nSes sion( ctx, true );
}
}
pub lic H ttpS essio n fin dSess ion(C onte xt ct x, St ring id) {
Serv erSe ssion sSes sion= (Serv erSe ssion )sess ions. get(i d);
if(s Sess ion== null) retu rn nu ll;
retu rn s Sessi on.ge tAppl icati onSe ssion (ctx, fals e);
}
/**
* Stop the backg round thre ad th at i s per iodic ally check ing for
* sessi on t imeou ts.
*/
pri vate void thre adSto p() {
if ( thre ad == null )
retu rn;
thre adDo ne = true;
thre ad.i nterr upt() ;
try {
thre ad.jo in();
} ca tch (Inte rrupt edExc eptio n e) {
;
}
retu rn ( this. isNew );
}
thre ad = null ;
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- - Ba ckgro und
Thread
}
/**
* The b ackg round thre ad th at ch ecks for sessi on ti meout s an d
shutdow n.
*/
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 ();
}
11
Por que o interesse é transversal ?
O desenvolvimento desta aplicação
começou com dois interesses:
Display
*
Figure
FigureElement
moveBy(int, int)
makePoint(..)
makeLine(..)
Point
getX()
getY()
setX(int)
setY(int)
2
Line
getP1()
getP2()
setP1(Point)
setP2(Point)
1.
2.
Representar os elementos gráficos
Atualizar o Display quando esses
elementos se movem
O primeiro interesse é modelado pelas
classes.
O segundo não pode ser modelado
por classes, pois é um comportamento
que deve ocorrer quando um
determinado evento acontece. Ele é
um interesse transversal
12
Por que o interesse é “transversal” ?
Display
*
Figure
Uma decisão de projeto seria chamar
FigureElement
moveBy(int, int)
makePoint(..)
makeLine(..)
o método de atualização do Display
(displayUpdating()) quando algum método
set é invocado.
Point
getX()
getY()
setX(int)
setY(int)
2
Line
getP1()
getP2()
setP1(Point)
setP2(Point)
O interesse de atualização do
Display entrecorta
transversalmente a funcionalidade
Display Updating
13
Exemplo da Atualização do Display
class Line {
private Point p1, p2;
Point getP1() { return p1; }
Point getP2() { return p2; }
void setP1(Point p1) {
this.p1 = p1;
}
void setP2(Point p2) {
this.p2 = p2;
}
}
class Point
Adicionar o
comportamento
para atualizar
o display.
{
private int x = 0, y = 0;
int getX() { return x; }
int getY() { return y; }
void setX(int x) {
this.x = x;
}
void setY(int y) {
this.y = y;
}
}
14
Exemplo da Atualização do Display
class Line {
private Point p1, p2;
Point getP1() { return p1; }
Point getP2() { return p2; }
void setP1(Point p1) {
this.p1 = p1;
Display.Updating()
}
void setP2(Point p2) {
this.p2 = p2;
Display.Updating()
}
}
class Point
Adicionar o
comportamento
para atualizar
o display.
{
private int x = 0, y = 0;
int getX() { return x; }
int getY() { return y; }
void setX(int x) {
this.x = x;
Display.Updating()
}
void setY(int y) {
this.y = y;
Display.Updating();
}
}
15
O que é um Interesse Transversal ?
A
<<uses>>
B
Um interesse A é dependente do interesse B quando há em tempo
de execução ou de construção (build) uma dependência entre eles.
• Sendo assim:
– Um interesse é transversal quando o sentido da dependência (uses) entre
dois interesses não está no mesmo sentido dos requisitos da parte que
usa.
16
O que é um Interesse Transversal ?
• Exemplo: Tracing
• Requisito:
– Toda vez que qualquer método for executado,
imprima uma mensagem informando a entrada
e a saída desse método A existência das chamadas
ao método beginningMethod() e
public class Employee
finishingMethod() dentro dos
{
…
métodos funcionais ocorre apenas
public void setName(String n)
para cumprir o requisito do
{
Tracing.beginningMethod(“setName”); Tracing. Sendo assim, o sentido do
this.name = n;
requisito não está no mesmo sentido
Tracing.finishingMethod (“setName”);
da dependência causada pela
}
…
implementação.
}
17
Programação Orientada a Aspectos
• Abordagem assimétrica proposta por Kiczales et al em 1997
• Idéia principal
– Sistemas são melhor programados especificando separadamente os
interesses transversais dos interesses funcionais
(base/componentes), e depois “compondo” esses interesses em um
único sistema (weaving)
• Interesses transversais relatados por Kiczales
– sincronização, gerenciamento de transação, concorrência,
persistência, logging, distribuição, segurança, alocação de recurso,
tratamento de exceções, gerenciamento de memória, etc
• Alguns interesses são de “desenvolvimento” enquanto outros são
de “produção”
18
Desenvolvimento OA
Aspectos
Funcionalidade
Tempo de projeto
Weaver
Tempo de compilação
Tempo de execução
(Sistema completo)
19
Conceitos Básicos da POA
• Quando se utiliza a programação orientada a aspectos,
alguns conceitos precisam ser entendidos:
– Pontos de Junção (Join Points)
– Conjuntos de junção ou de pontos de junção (pointcuts)
– Adendos (Advices)
– Aspectos (Aspects)
– Composição (weaving)
20
Pontos de Junção (Join Points)
• São pontos bem definidos na EXECUÇÃO do programa “base”
– Chamada ou execução de métodos;
– Acesso (leitura e escrita) a determinados atributos;
– Construção de objetos (new)
– Lançamento de exceções
• O pontos de junção tem esse nome pois é onde ocorre a “junção”
ou “composição” com os interesses transversais
• Quem realmente realiza essa junção é o Weaver.
21
Pontos de Junção
L.moveBy(2, 2)
a Line
a Point
a method execution
returning or throwing
a method call
returning or
throwing
a method execution
returning or throwing
22
Pontos de Junção
a Line
dispatch
Execução
de
método
Chamada
de
método
23
Join Points – Fluxo de Controle
a Point
a Line
a Point
24
Join Points – Fluxo de Controle
a
Point
a Line
a
Point
• Note que todo ponto de junção pertence a um contexto de
execução (representado pelos círculos).
• Pode-se acessar essas informações de contexto
• objetos
• parâmetros
• valores de variáveis (atributos)
25
Advices (Adendos)
• É o comportamento do aspecto
• É um trecho de código que pode ser executado
em um ponto de junção
• Três tipos básicos:
– Before()
• Ocorre antes do ponto de junção
– After()
• Ocorre depois do ponto de junção
– Around()
• O código do adendo toma o controle do ponto de junção
26
Conjuntos de Junção (pointcuts)
• É uma construção linguística que permite
identificar os pontos de junção e capturar o
contexto de execução desse ponto de junção,
ex:
– Parâmetros
– Objetos alvo
• Ex em AspectJ
– call (public void Employee.setName(String));
– execution (public void Employee.setName(String))
27
Composição
•
Em tempo de compilação
–
O código fonte da parte funcional e dos aspectos é composto antes que o compilador
produza o bytecode. AspectJ 1.0.x
•
Em tempo de linkedição
–
A composição ocorre depois que os códigos base e aspectuais foram transformados em
bytecode. AspectJ 1.1.x
•
•
Load-time
–
A composição ocorre quando as classes são carregadas pelo ClassLoader.
–
Ocorre também no nível de bytecode. AspectJ 1.2.x
–
Utiliza uma variável de ambiente ASPECTPATH
Run-time
–
A composição ocorre com o sistema em operação – aspectos são criados em tempo de
execução e passam a atuar a partir desse momento
28
Aspect/J
Programação Orientada a
Aspectos para Java
AspectJ
•
Extensão orientada a aspectos para Java que apóia a programação orientada a
aspectos de propósito geral;
•
Desenvolvida pelo Centro de Pesquisa da Xerox em Palo Alto, NY.
•
Compilador é o “ajc”
•
Pode ser utilizada em vários ambientes
–
Eclipse, JBuilder, Emacs e Forte
•
Pode ser utilizada com o “Ant”
•
Possui ferramenta para documentação ajdoc
•
A última versão estável é a 1.2.1, desenvolvida em novembro de 2004
•
A versão mais nova é a 1.5 a qual permite trabalhar com anotações “annotations” do
Java 5.0
30
Outras Linguagens OA
• Linguagens específicas de domínio para AOP
– COOL (sincronização) , RIDL (portais), D2-AL
(distribuição) e TyRuBa (sincronização), JST
(sincronização), Luthier-MOP (concorrência).
• Linguagens de propósito geral
– AspectJ, HyperJ, aspectC++, aspectC#, AspectS, ...
31
AspectJ
• Além dos conceitos básicos da POA, AspectJ acrescenta alguns
mecanismos próprios, por exemplo:
– Designadores de Conjuntos de Junção
– Declarações inter-tipo (Inter-Type Declaration)
32
Conjuntos de Junção (pointcuts)
•
São construções do AspectJ que permitem identificar/agrupar/capturar
quaisquer tipos de pontos de junção
•
Os conjuntos de junção mais comuns são:
– call
captura chamadas a métodos/construtores
– execution captura execução de métodos/construtores
•
– set
captura modificação do valor de um atributo
– get
captura leitura do valor de um atributo
Exemplo
– call (Point.setX(int))
– captura chamadas ao método setX( ) de um objeto Ponto a partir de
qualquer lugar.
33
Conjuntos de Junção
• Podem ser compostos utilizando filtros de
composição semântica e/ou caracteres
coringa
–
–
–
–
–
call (Point.setX(int) || Point.setY(int))
execution (void Figure.make*(..))
execution (public * Figure.*(*,..))
execution (PersistentRoot+.new(..))
set (int Figure.point);
34
Conjuntos de Junção
• O programador pode definir os seus conjuntos de junção e
nomeá-los:
Identificador do
Conjunto de junção
pointcut move():
call(void FigureElement.setXY(int,int)) ||
call(void Point.setX(int)) ||
call(void Point.setY(int)) ||
call(void Line.setP1(Point)) ||
call(void Line.setP2(Point));
Join Points
35
Diferença entre Call e Execution
• Call
– O entrecorte ocorre no contexto de execução
do objeto em que a chamada está sendo
feita
• Execution
– O entrecorte ocorre no contexto de execução
do objeto que faz a chamada
36
Diferença entre Call e Execution
class Line {
private Point p1, p2;
Point getP1() { return p1; }
Point getP2() { return p2; }
void setP1(Point p1) {
this.p1 = p1;
}
void setP2(Point p2) {
this.p2 = p2;
}
• Se for especificado
call (* Line.set*());
• o objeto target é o myLine
• o objeto this é o objeto main
}
• Se for especificado
public class Main {
execution (* Line.set*());
public static void main(..){
Point p1 = new Point(10,30);
Point p2 = new Point(20,40);
Line myLine = new Line(p1,p2);
Point p3 = new Point(30,50);
myLine.setP1(p3);
• o objeto target é o myLine
• o objeto this também é o objeto myLine
}
37
Exemplo de Aspecto
public aspect MyAspect{
pointcut myPointcut() : execution (* Cliente.set*(..));
before() : myPointcut() {
//faz alguma coisa
}
after() : myPointcut(){
//faz outras coisas
}
}
38
Exemplo da Atualização do Display
Display
*
Figure
FigureElement
moveBy(int, int)
makePoint(..)
makeLine(..)
Point
getX()
getY()
setX(int)
setY(int)
Interesse:
Atualizar o Display quando
um elemento da Figura
se move.
2
Line
getP1()
getP2()
setP1(Point)
setP2(Point)
Display Updating
39
Exemplo da Atualização do Display
class Line {
private Point p1, p2;
Point getP1() { return p1; }
Point getP2() { return p2; }
void setP1(Point p1) {
this.p1 = p1;
}
void setP2(Point p2) {
this.p2 = p2;
}
}
class Point
Adicionar o
comportamento
para atualizar
o display.
{
private int x = 0, y = 0;
int getX() { return x; }
int getY() { return y; }
void setX(int x) {
this.x = x;
}
void setY(int y) {
this.y = y;
}
}
40
Exemplo da Atualização do Display
class Line {
private Point p1, p2;
Point getP1() { return p1; }
Point getP2() { return p2; }
void setP1(Point p1) {
this.p1 = p1;
Display.Updating()
}
void setP2(Point p2) {
this.p2 = p2;
Display.Updating()
}
}
class Point
Adicionar o
comportamento
para atualizar
o display.
{
private int x = 0, y = 0;
int getX() { return x; }
int getY() { return y; }
void setX(int x) {
this.x = x;
Display.Updating()
}
void setY(int y) {
this.y = y;
Display.Updating();
}
}
41
Exemplo da Atualização do Display
class Line {
private Point p1, p2;
Point getP1() { return p1; }
Point getP2() { return p2; }
aspect DisplayUpdating
{
pointcut move():
void setP1(Point p1) {
this.p1 = p1;
call(void FigureElement+.set*(..));
}
void setP2(Point p2) {
this.p2 = p2;
after(): move() {
Display.update();
}
}
}
}
class Point
{
private int x = 0, y = 0;
int getX() { return x; }
int getY() { return y; }
void setX(int x) {
this.x = x;
}
void setY(int y) {
this.y = y;
}
}
42
Captura de Contexto
• Há situações em que deve-se ter acesso às informações do contexto de
execução do ponto de junção
public aspect DisplayUpdating_v2 {
pointcut setXY(FigureElement fe, int x, int y):
call(void FigureElement.setXY(int, int))
&& target(fe)
&& args(x, y);
after(FigureElement fe, int x, int y): setXY(fe, x, y)
{
System.out.println(fe + " moved to (" + x + ", " + y +
").");
}
}
43
Declarações inter-tipo
• As declarações inter-tipo (inter-type declaration)
modificam a estrutura estática do código base
introduzindo membros e até relacionamentos
• Opera estaticamente em tempo de compilação,
diferentemente dos adendos
• Ex de introdução de membros
aspect PointObserving
{
private Vector Point.observers = new Vector();
public static void Point.addObserver(Point p, Screen s)
{
p.observers.addElement(s);
}
44
Reflexividade - thisJoinPoint
• Por meio do “thisJoinPoint” tem-se acesso algumas
informações reflexivas no corpo do adendo, por exemplo:
– thisJoinPoint ponto de junção
– thisJoinPoint.getTarget() objeto alvo do ponto de junção
– thisJoinPoint.getThis() objeto onde ocorreu o ponto de
junção
– thisJoinPoint.getArgs() argumentos do ponto de junção
45
Adendo Around()
• Toma o controle do ponto de junção para si, podendo
devolver ou não.
• O advice “around” muitas vezes é utilizado para
substituir o comportamento de um determinado método
em tempo de execução
• Sendo assim, ele deve ter o mesmo tipo de retorno do
método que pode ser substituído
• Esse adendo utiliza o método estático “proceed()” para
retornar o controle ao método original
46
Considerações Finais
• A POA é uma técnica de programação que permite
desenvolver o código base separado do código
transversal
– Entrelaçamento e espalhamento
• Suas principais características são a quantificação e a
inconsciência
• AspectJ é um extensão da linguagem Java de propósito
geral que apóia o desenvolvimento de software
orientado a aspectos
47
Principais Eventos
• Internacional
– Conferência AOSD (Aspect Oriented
Software Development)
• Nacional
– WASP (Workshop de desenvolvimento de
software orientado a aspectos)
• Uberlândia em conjunto com o SBES
48
Bibliografia
• Gradecki e Lesiecki, Mastering AspectJ, 2003
• Kiselev, Aspect Oriented Programming with
AspectJ, 2003.
• Special Issue of the ACM on Aspect Oriented
Programming (5 papers) 2001.
49
Contato
• Rosana T. Vaccare Braga
– ICMC-Universidade de São Paulo
– São Carlos – SP – Labes (Laboratório de
Engenharia de Software)
– [email protected]
– http://www.icmc.usp.br/~rtvb
50
© Copyright 2026 Paperzz