Aspect-Oriented Programming (AOP) methodology

Report
Aspect-Oriented Programming (AOP)
and Aspect-oriented software
development (AOSD)
面向方面的程序设计 (AOP)
和面向方面的软件开发方法 (AOSD)
郝克刚
西北大学计算机科学系
(为研究生们作的报告) 2003.10
2015/7/17
1
软件技术新动向:面向方面方法的兴起



二十年的实践证明:面向对象的开发方法具有很强的生
命力,已为广大的软件业界所普遍采用。
但是,对多数复杂的系统,在多种需求关注点和实现的
模块(构件、类)之间的对应中,往往出现交叉分割
(横切)的现象。即需求关注点在实现中的分散和实现
构件内容的混杂。从而导致了软件开发和维护的一系列
困难(Poor traceability, Lower productivity, Less code
reuse, Poor code quality, More difficult evolution 。)
面向方面方法就是针对这些问题而产生的。它一出现就
得到业界的广泛关注。很可能,它将成为软件开发方法
发展的重要一步,引起新一轮软件开发方法和支持工具
研究和开发的热潮。
2015/7/17
2
讲座大纲:


2015/7/17
AOP AOSD 的飞速发展
 基本概念和内容
 AspectJ 的基本思路
(-- 语言的概念和结构)
研究和开发的方向和课题
3
international conferences on AOP










Workshop on Aspect Oriented Programming(ECOOP 1997) June 1997
Int’l Workshop on Aspect Oriented Programming(ICSE 1998) April 1998.
Workshop on Aspect Oriented Programming(ECOOP 1998), Jan 1998.
Int’l Workshop on Aspect Oriented Programming(ECOOP 1999), June 1999.
Workshop on Advanced Separations of Concerns(OOPSLA 2000), Oct. 2000.
Workshop on Aspects and Dimensions of Concerns(ECOOP 2000), June
2000.
Workshop on Multi-Dimentional Separation of Concerns in Software
Engineering(ICSE 2000), June 2000.
Workshop on Advanced Separations of Concerns(ECOOP 2001), June. 2001.
Workshop on Advanced Separations of Concerns in Object Orieted Systems
(OOPSLA 2001), Oct. 2001.
Workshop on Advanced Separation of Concerns in Software
Engineering(ICSE 2001), May 2001.
2015/7/17
4
international conferences on AOSD



the 1st international conference on Aspect-oriented
software development . Enschede, The Netherlands, on
April 22-26, 2002. .
2nd international conference on Aspect-oriented
software development . Boston, Massachusetts, USA,
March 17 - 21, 2003.
the 3rd International Conference on Aspect-Oriented
Software Development . Lancaster UK, March 22-26
2004.
2015/7/17
5
Workshop on Aspect-Orientation (German)



AOP-GI 2001:
Workshop on Aspect-Orientation, May 3-4, 2001,
University of Paderborn. (German only)
AOSD-GI 2002:
Second Workshop on Aspect-Oriented Software
Development of the GI, February 21-22, 2002,
University of Bonn.
AOSD-GI 2003:
Third Workshop on Aspect-Oriented Software
Development of the GI, March 4-5 2003,
University of Essen.
2015/7/17
6
Research Projects:

Supported Systems:
AspectC++, AspectJ, AspectR, AspectS,…



Research Prototypes:
Applications:
Methods & Foundations:
2015/7/17
7
Web sites:



http://aosd.net
http://www.aspectc.org/
Xerox PARC's research on AOP :



http://aspectj.org
http://www.parc.xerox.com/csl/groups/sda
……
2015/7/17
8
A Bibliography of Aspect-Oriented
Software Development
Version 1.0 (502) RIACS Technical Report
02.06 August 2002
 Version 1. 1 (694) RIACS Technical Report
03.01 January 2003
 Version 1.22
{Research Institute for Advanced Computer
Science},

2015/7/17
9
The fundamental goal of AOSD


The fundamental goal of AOSD -- effective
separation of concerns-- was enunciated about
30 years ago, most notably by Dijkstra and
Parnas.
The first two decades or so of research on
separation of concerns focused primarily on
providing new kinds of modules, able to separate
concerns in new ways. This led to some key
advances, including abstract data types and
object-oriented programming, which have had
dramatic impact on software engineering
research and practice.
2015/7/17
10
The time is right for practitioners to begin using
AOSD technology



The approaches suffered from a limitation, however: they
could encapsulate concerns that aligned with the dominant
decomposition of the software into modules such as
objects or classes, but not concerns that cut across
multiple modules.
The advent and promulgation of aspect-oriented
programming awakened broader interest in the area, on
the part of researchers and practitioners alike.
The time is right for practitioners to begin using AOSD
technology, for researchers to solve some of the
challenging problems that remain, and for researchers and
practitioners to work together to make AOSD a
mainstream software development technology.
2015/7/17
11
Evolution of software programming methodology
machine-level coding
 higher-level languages
 structured languages
 Object-oriented programming (OOP)



Each new methodology presents new ways to decompose
problems: machine code, machine-independent code,
procedures, classes, and so on.
Each new methodology allowed a more natural mapping of
system requirements to programming constructs.
2015/7/17
12
the next big step



OOP has shown its strength when it comes
to modeling common behavior.
However, OOP does not adequately address
behaviors that span over many -- often
unrelated -- modules.
In contrast, AOP methodology fills this void.
AOP quite possibly represents the next big
step in the evolution of programming
methodologies.
2015/7/17
13
View the system as a set of concerns
(关注点,考虑)
A typical system may
consist of several kinds of
concerns, including:
business logic, performance,
data persistence, logging and
debugging, authentication,
security, multithread safety,
error checking, and so on.
 development-process
concerns, such as:
comprehensibility,
maintainability, traceability,
and evolution ease .

2015/7/17
14
Concern decomposition:
The prism(棱镜) analogy
2015/7/17
15
Modularity problems



Scatter (分散)
tangle (混杂)
crosscut(横切、交叉分割)
2015/7/17
16
bad modularity
/*
* ==== ===== ==== ===== ===== ===== ===== ==== ===== ===== ===== ===== ==== ===== ==
*
* 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 [email protected] 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);
}
if ( this Acces sTime == c reati onTi me) {
retu rn tr ue;
} el se {
retu rn fa lse;
}
;
/**
* Stan dard impl ement ation of t he <b >Ses sion< /b>
interfa ce. This obje ct is
* 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 thi s
class r epres ents 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 d eclar ed
public, Java log ic ou tside
* of t he <c ode> org.a pache .tomc at.se ssio n</co de>
package cann ot c ast a n
* 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 {
/**
* Updat e th e acc essed time info rmat ion f or th is se ssion .
This me thod
* shoul d be call ed by the conte xt w hen a requ est c omes in
for a p artic ular
* sessi on, even if th e app licat ion does not r efere nce i t.
*/
pub lic v oid acces s() {
this .las tAcce ssedT ime = this .thi sAcce ssedT ime;
this .thi sAcce ssedT ime = Syst em.c urren tTime Milli s();
this .isN ew=fa lse;
}
// 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);
* @depr ecat ed
*/
// U nbin d any obje cts a ssoci ated with this sess ion
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);
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- --------- ----- - Co nstru ctors
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);
}
/**
* Const ruct a ne w Ses sion assoc iate d wit h the
specifi ed Ma nage r.
*
* @para m ma nager The manag er wi th w hich this
Session is a ssoc iated
*/
pub lic S tand ardSe ssion (Mana ger m anag er) {
// M ark this sessi on as inva lid
setV alid (fals e);
supe r();
this .man ager = man ager;
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ;
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) );
}
}
/**
* Perfo rm t he in terna l pro cessi ng r equir ed to inva lidat e
this se ssion ,
* witho ut t rigge ring an ex cepti on i f the sess ion h as
already expi red.
*/
pub lic v oid expir e() {
/**
}
* Remov e the obj ect b ound with the s peci 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) {
}
* Bind an ob ject to t his s essio n, us ing 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) {
}
}
thro w new Ille galAr gumen tExc eptio n(msg );
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" ));
}
/**
remo veVa lue(n ame);
// remov e an y exi sting bind ing
/**
* The l ast acces sed t ime f or th is S essio n.
*/
pri vate long last Acces sedTi me = crea tionT ime;
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 [email protected] g.sun .com ]
* @aut hor J ames Todd [gon [email protected] g.sun .com ]
*/
/**
* 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, betw een
client reque sts befor e
* the s ervl et co ntain er ma y inv alid ate t his
session . A nega tive time
* indic ates that the sessi on sh ould neve r tim e
out.
*/
pri vate int maxIn activ eInte rval = -1 ;
thro w new Ille galSt ateEx cept ion(m sg);
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;
name s.co pyInt o(val ueNam es);
retu rn v alueN ames;
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;
}
*/
voi d set New( boole an is New) {
// ----- ---- ----- ----- ----- ----- ---- ----- ----- - Htt pSess ion Priva te Me thods
}
/**
* Set t he < code> isVal id</c ode> flag for this sessi on.
*
* @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) {
thro w new Ille galSt ateEx cept ion(m sg);
this .isV alid = isV alid;
/**
* The s trin g man ager for t his p acka ge.
*/
pri vate Stri ngMan ager sm =
retu rn ( Enume ratio n)val uesCl one. keys( );
// 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() ;
/**
* 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
called on an
* inva lida ted s essio n
*/
pub lic l ong getCr eatio nTime () {
StringM anage r.ge tMana ger(" org.a pache .tom cat.s essio n")
;
// 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);
}
retu rn ( this. creat ionTi me);
}
/**
* The H TTP sessi on co ntext asso ciat ed wi th th is
session .
*/
pri vate stat ic Ht tpSes sionC ontex t se ssion Conte xt
= null;
/**
* The c urre nt ac cesse d tim e for thi s ses sion.
*/
pri vate long this Acces sedTi me = crea tionT ime;
}
/**
* Retur n th e ses sion conte xt wi th w hich this sessi on is
associa ted.
*
* @depr ecat ed As of V ersio n 2.1 , th is me thod is de preca ted
and has no
* repl acem ent. It w ill b e rem oved in a futu re ve rsion of
the
* Java Ser vlet API.
*/
pub lic H ttpS essio nCont ext g etSes sion Conte xt() {
/**
* 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 {
if ( sess ionCo ntext == n ull)
sess ionCo ntext = ne w Sta ndar dSess ionCo ntext ();
retu rn ( sessi onCon text) ;
Hash tabl e val uesCl one = (Has htab le)va lues. clone ();
}
/**
* 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 {
}
}
/**
* 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.
*/
// ----- ---- ----- ----- ----- ----- ---- ----- ----- --------- Sess ion Prope rties
}
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;
/**
* Set t he c reati on ti me fo r thi s se ssion . Th is
method is ca lled by t he
* Manag er w hen a n exi sting Sess ion insta nce i s
reused.
*
* @para m ti me Th e new crea tion time
*/
pub lic v oid setCr eatio nTime (long tim e) {
this .cre ation Time = tim e;
this .las tAcce ssedT ime = time ;
this .thi sAcce ssedT ime = time ;
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);
/**
* Retur n th e ses sion ident ifier for this
session .
*/
pub lic S trin g get Id() {
retu rn ( this. id);
}
((Ht tpSes sionB indin gList ener )o).v alueU nboun d(e);
}
thro w new Ille galSt ateEx cept ion(m sg);
}
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 ");
/**
* Set t he s essio n ide ntifi er fo r th is se ssion .
*
* @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) mana ger). remo ve(th is);
thro w new Ille galSt ateEx cept ion(m sg);
// ----- ---- ----- ----- ----- ----- ---- ----- ----- --HttpSes sion Publ ic Me thods
// 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));
/**
* Retur n th e obj ect b ound with the speci fied name in th is
session , or
* <code >nul l</co de> i f no objec t is boun d wit h tha t nam e.
*
* @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
called on an
* inva lida ted s essio n
*/
pub lic O bjec t get Attri bute( Strin g na me) {
// 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) ;
}
retu rn ( attri butes .get( name) );
// 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 ));
}
/**
* 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
called on an
* inva lida ted s essio n
*/
pub lic E nume ratio n get Attri buteN ames () {
}
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 ());
}
this .id = id;
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 ");
if ( (man ager != nu ll) & & (ma nage r ins tance of
Manager Base) )
((Ma nager Base) mana ger). add( this) ;
}
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();
}
}
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 ");
}
//----- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- ----- ----
/**
* Retur n de scrip tive infor matio n ab out t his
Session impl emen tatio n and
* the c orre spond ing v ersio n num ber, in t he
format
*
<code>& lt;de scri ption &gt;/ &lt;v ersio n&gt ;</co de>.
*/
pub lic S trin g get Info( ) {
tangling – code in one region
addresses multiple concerns
}
}
thro w new Ille galSt ateEx cept ion(m sg);
}
}
(分散)
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- HttpSes sion Prop ertie s
/**
* Flag indi catin g whe ther this sess ion i s val id
or not.
*/
pri vate bool ean i sVali d = f alse;
Stri ng[] valu eName s = n ew St ring [name s.siz e()];
}
flag
*/
pri vate bool ean i sNew = tru e;
}
public class App licat ionSe ssion impl emen ts Ht tpSes sion {
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) );
}
/**
* 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 <co de>is New</ code>
/**
* Flag indi catin g whe ther this sess ion i s new or
not.
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;
}
this .isN ew = isNew ;
}
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ;
scattering – spread around
/**
* Retur n th e obj ect b ound with the speci fied name in th is
session , or
* <code >nul l</co de> i f no objec t is boun d wit h tha t nam e.
*
* @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
called on an
* 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>ge tAttr ibute ()</c ode>
*/
pub lic O bjec t get Value (Stri ng na me) {
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") );
}
}
(混杂)
}
retu rn ( getAt tribu te(na me));
retu rn ( this. info) ;
thro w new Ille galSt ateEx cept ion(m sg);
}
}
// ---- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- - Pri vate Class
}
}
/**
* Retur n th e las t tim e the clie nt s ent a requ est
associa ted w ith this
* sessi on, as th e num ber o f mil lise conds sinc e
midnigh t, Ja nuar y 1, 1970
* GMT. Act ions that your appli cati on ta kes,
such as gett ing or se tting
* a val ue a ssoci ated with the s essi on, d o not
affect the a cces s tim e.
*/
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 retu rned.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is
called on an
* 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>ge tAttr ibute Names ()</c ode>
*/
pub lic S trin g[] g etVal ueNam es() {
/**
* 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();
}
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 S essio n
is vali d.
*/
pub lic M anag er ge tMana ger() {
retu rn ( this. manag er);
}
/**
* 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( ));
}
/**
* Set t he M anage r wit hin w hich this Sess ion i s
valid.
*
* @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 boun d
to it.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is
called on
* an i nval idate d ses sion
*/
pub lic v oid inval idate () {
}
package org. apac he.to mcat. sessi 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
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. *;
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 [email protected] g.sun .com ]
*/
Serve rSess ionMa nager ssm =
S erver Sessi onMan ager .getM anage r();
/**
* Retur n th e max imum time inter val, in s econd s,
between clie nt r eques ts
* befor e th e ser vlet conta iner will inva lidat e
the ses sion. A negat ive
* time indi cates that the sessi on s hould neve r
time ou t.
*
* @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() {
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;
}
}
retu rn ( this. maxIn activ eInte rval );
}
retu rn ( null) ;
/**
* Retur n <c ode>t rue</ code> if t he c lient does not yet k now
about 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 se ssion s,
and the clie nt
* has d isab led t he us e of cooki es, then a ses sion would be
new on each
* reque st.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is
called on an
* inva lida ted s essio n
*/
pub lic b oole an is New() {
retu rn ( this. isNew );
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;
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 );
}
retu rn v alues .get( name) ;
if ( appS essio n == null && cr eate ) {
}
// X XX
// s ync t o ens ure v alid?
/**
* 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) {
// C ause this sess ion t o exp ire
expi re() ;
}
}
}
scattering and tangling (S&T)
tend to appear together; they
describe different facets of
the same problem
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;
pub lic i nt g etMax Inact iveIn terva l() {
retu rn i nacti veInt erval ;
}
}
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 ();
}
}
}
}
voi d val idat e()
2015/7/17
17
good modularity
/*
* ==== ===== ==== ===== ===== ===== ===== ==== ===== ===== ===== ===== ==== ===== ==
*
* 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 [email protected] 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);
}
if ( this Acces sTime == c reati onTi me) {
retu rn tr ue;
} el se {
retu rn fa lse;
}
;
/**
* Stan dard impl ement ation of t he <b >Ses sion< /b>
interfa ce. This obje ct is
* 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 thi s
class r epres ents 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 d eclar ed
public, Java log ic ou tside
* of t he <c ode> org.a pache .tomc at.se ssio n</co de>
package cann ot c ast a n
* 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 $
*/
// 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 sess ion
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);
}
}
final c lass Stan dardS essio n
imp lemen ts H ttpSe ssion , Ses sion {
* @depr ecat ed
*/
// M ark this sessi on as inva lid
setV alid (fals e);
// ----- ---- ----- ----- ----- ----- ---- ----- ----- --------- ----- - Co nstru ctors
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);
}
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) );
}
}
}
/**
pub lic v oid putVa lue(S tring name , Ob ject value ) {
setA ttri bute( name, valu e);
}
* Remov e the obj ect b ound with the s peci 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) {
/**
* Perfo rm t he in terna l pro cessi ng r equir ed to inva lidat e
this se ssion ,
* witho ut t rigge ring an ex cepti on i f the sess ion h as
already expi red.
*/
pub lic v oid expir e() {
* Bind an ob ject to t his s essio n, us ing 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) {
}
/**
/**
* Const ruct a ne w Ses sion assoc iate d wit h the
specifi ed Ma nage r.
*
* @para m ma nager The manag er wi th w hich this
Session is a ssoc iated
*/
pub lic S tand ardSe ssion (Mana ger m anag er) {
}
/**
* 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 <co de>is New</ code>
flag
supe r();
this .man ager = man ager;
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ;
*/
voi d set New( boole an is New) {
}
thro w new Ille galAr gumen tExc eptio n(msg );
this .isN ew = isNew ;
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" ));
}
}
remo veVa lue(n ame);
// remov e an y exi sting bind ing
/**
* The l ast acces sed t ime f or th is S essio n.
*/
pri vate long last Acces sedTi me = crea tionT ime;
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) ;
}
/**
* 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;
/**
* Set t he < code> isVal id</c ode> flag for this sessi on.
*
* @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) {
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) );
}
this .isV alid = isV alid;
}
}
/**
* @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 [email protected] g.sun .com ]
* @aut hor J ames Todd [gon [email protected] g.sun .com ]
*/
/**
* The m axim um ti me in terva l, in sec onds, betw een
client reque sts befor e
* the s ervl et co ntain er ma y inv alid ate t his
session . A nega tive time
* indic ates that the sessi on sh ould neve r tim e
out.
*/
pri vate int maxIn activ eInte rval = -1 ;
thro w new Ille galSt ateEx cept ion(m sg);
/**
* Flag indi catin g whe ther this sess ion i s new or
}
if ( name == n ull) {
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ;
not.
*/
pri vate bool ean i sNew = tru e;
// ----- ---- ----- ----- ----- ----- ---- ----- ----- - Htt pSess ion Priva te Me thods
// ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- HttpSes sion Prop ertie s
/**
* 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 {
/**
* 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
called on an
* inva lida ted s essio n
*/
pub lic l ong getCr eatio nTime () {
retu rn ( this. creat ionTi me);
thro w new Ille galAr gumen tExc eptio n(msg );
}
public class App licat ionSe ssion impl emen ts Ht tpSes sion {
retu rn v alues .get( name) ;
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;
private bool ean valid = tr ue;
}
/**
* @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;
}
/**
* Flag indi catin g whe ther this sess ion i s val id
or 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 essio n")
;
}
name s.co pyInt o(val ueNam es);
this .ina ctive Inter val = cont ext. getSe ssion TimeO ut();
retu rn v alueN ames;
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 H TTP sessi on co ntext asso ciat ed wi th th is
session .
*/
pri vate stat ic Ht tpSes sionC ontex t se ssion Conte xt
= null;
Hash tabl e val uesCl one = (Has htab le)va lues. clone ();
retu rn ( Enume ratio n)val uesCl one. keys( );
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- --------- Sess ion Prope rties
// HTTP SESS ION I MPLEM ENTAT ION M ETHO DS
/**
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 ");
* @depr ecat ed
*/
pub lic v oid remov eValu e(Str ing n ame) {
remo veAt tribu te(na me);
}
thro w new Ille galSt ateEx cept ion(m sg);
}
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 ");
}
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 ");
/**
* Set t he c reati on ti me fo r thi s se ssion . Th is
method is ca lled by t he
* Manag er w hen a n exi sting Sess ion insta nce i s
reused.
*
* @para m ti me Th e new crea tion time
*/
pub lic v oid setCr eatio nTime (long tim e) {
this .cre ation Time = tim e;
this .las tAcce ssedT ime = time ;
this .thi sAcce ssedT ime = time ;
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 galSt ateEx cept ion(m sg);
}
thro w new Ille galAr gumen tExc eptio n(msg );
}
}
/**
*
* @depr ecat ed
*/
Obje ct o = va lues. get(n ame);
/**
* 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 {
}
// ----- ---- ----- ----- ----- ----- ---- ----- ----- --HttpSes sion Publ ic Me thods
/**
* The c urre nt ac cesse d tim e for thi s ses sion.
*/
pri vate long this Acces sedTi me = crea tionT ime;
}
/**
* 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.
*/
// 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);
}
}
if ( sess ionCo ntext == n ull)
sess ionCo ntext = ne w Sta ndar dSess ionCo ntext ();
retu rn ( sessi onCon text) ;
Stri ng[] valu eName s = n ew St ring [name s.siz e()];
}
// 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() ).
isVa lid = ((B oolea n) st ream. read Objec t()). boole anVal ue() ;
/**
* Retur n th e ses sion conte xt wi th w hich this sessi on is
associa ted.
*
* @depr ecat ed As of V ersio n 2.1 , th is me thod is de preca ted
and has no
* repl acem ent. It w ill b e rem oved in a futu re ve rsion of
the
* Java Ser vlet API.
*/
pub lic H ttpS essio nCont ext g etSes sion Conte xt() {
/**
* Retur n th e ses sion ident ifier for this
session .
*/
pub lic S trin g get Id() {
/**
* Retur n th e obj ect b ound with the speci fied name in th is
session , or
* <code >nul l</co de> i f no objec t is boun d wit h tha t nam e.
*
* @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
called on an
* inva lida ted s essio n
*/
pub lic O bjec t get Attri bute( Strin g na me) {
// 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 ( attri butes .get( name) );
}
// 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 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
called on an
* inva lida ted s essio n
*/
pub lic E nume ratio n get Attri buteN ames () {
// 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 .keys ());
}
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);
pub lic H ttpS essio nCont ext g etSes sion Conte xt() {
retu rn n ew Se ssion Conte xtImp l();
}
retu rn ( this. id);
}
((Ht tpSes sionB indin gList ener )o).v alueU nboun d(e);
}
valu es.r emove (name );
}
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 ");
/**
* Set t he s essio n ide ntifi er fo r th is se ssion .
*
* @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) mana ger). remo ve(th is);
thro w new Ille galSt ateEx cept ion(m sg);
}
this .id = id;
inac tive Inter val = inte rval;
}
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 ");
retu rn i nacti veInt erval ;
}
}
//----- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- ----- ----
/**
* Retur n th e obj ect b ound with the speci fied name in th is
session , or
* <code >nul l</co de> i f no objec t is boun d wit h tha t nam e.
*
* @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
called on an
* 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>ge tAttr ibute ()</c ode>
*/
pub lic O bjec t get Value (Stri ng na me) {
if ( (man ager != nu ll) & & (ma nage r ins tance of
Manager Base) )
((Ma nager Base) mana ger). add( this) ;
}
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));
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") );
}
}
retu rn ( getAt tribu te(na me));
}
}
thro w new Ille galSt ateEx cept ion(m sg);
}
/**
* Retur n de scrip tive infor matio n ab out t his
Session impl emen tatio n and
* the c orre spond ing v ersio n num ber, in t he
format
*
<code>& lt;de scri ption &gt;/ &lt;v ersio n&gt ;</co de>.
*/
pub lic S trin g get Info( ) {
retu rn ( this. info) ;
}
/**
* 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 retu rned.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is
called on an
* 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>ge tAttr ibute Names ()</c ode>
*/
pub lic S trin g[] g etVal ueNam es() {
/**
* Retur n th e Man ager withi n whi ch t his S essio n
is vali d.
*/
pub lic M anag er ge tMana ger() {
}
// ---- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- - 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 );
retu rn ( this. manag er);
}
ynchron ized void inva lidat e() {
Enum erat ion e num = appS essio ns.k eys() ;
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. *;
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 );
/**
* Set t he M anage r wit hin w hich this Sess ion i s
valid.
*
* @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;
appS essio n.inv alida te();
}
/**
* 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 [email protected] g.sun .com ]
*/
}
}
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") ;
thro w new Ille galAr gumen tExc eptio n(msg );
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;
remo veVa lue(n ame); // remov e an y exi sting bind ing
valu es.p ut(na me, v alue) ;
}
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") ;
thro w new Ille galAr gumen tExc eptio n(msg );
/**
* Retur n th e max imum time inter val, in s econd s,
between clie nt r eques ts
* befor e th e ser vlet conta iner will inva lidat e
the ses sion. A negat ive
* time indi cates that the sessi on s hould neve r
time ou t.
*
* @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() {
retu rn ( this. maxIn activ eInte rval );
}
Ser verSe ssio n(Str ing i d) {
this .id = id;
retu rn v alues .get( name) ;
}
}
pub lic S trin g get Id() {
retu rn i d;
}
pub lic E nume ratio n get Value Names () {
retu rn v alues .keys ();
}
pub lic l ong getCr eatio nTime () {
retu rn c reati onTim e;
}
pub lic v oid remov eValu e(Str ing n ame) {
valu es.r emove (name );
}
pub lic l ong getLa stAcc essed Time( ) {
retu rn l astAc cesse d;
}
pub lic v oid setMa xInac tiveI nterv al(i nt in terva l) {
inac tive Inter val = inte rval;
}
}
/**
* 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() {
/**
* Inval idat es th is se ssion and unbi nds a ny ob jects boun d
to it.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is
called on
* an i nval idate d ses sion
*/
pub lic v oid inval idate () {
retu rn ( dummy .elem ents( ));
// C ause this sess ion t o exp ire
expi re() ;
}
}
/**
* Retur n <c ode>t rue</ code> if t he c lient does not yet k now
about 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 se ssion s,
and the clie nt
* has d isab led t he us e of cooki es, then a ses sion would be
new on each
* reque st.
*
* @exce ptio n Ill egalS tateE xcept ion if th is me thod is
called on an
* inva lida ted s essio n
*/
pub lic b oole an is New() {
/**
* 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) {
retu rn ( null) ;
}
}
retu rn ( this. isNew );
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 );
}
pub lic i nt g etMax Inact iveIn terva l() {
retu rn i nacti veInt erval ;
}
// 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.
if ( appS essio n == null && cr eate ) {
// X XX
// s ync t o ens ure v alid?
syn chron ized void reap () {
Enum erat ion e num = appS essio ns.k eys() ;
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);
}
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 );
// 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
appS essio n.val idate ();
}
retu rn a ppSes sion;
}
}
}
voi d rem oveA pplic ation Sessi on(Co ntex t con text) {
appS essi ons.r emove (cont ext);
}
/**
* 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.
*/
privat e lon g la stAcc essed = cr eatio nTim e;
pri vate int inact iveIn terva l = - 1;
void a ccess ed() {
// 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( );
localized – implementation
of a concern appears in one
part of program
final c lass Stan dardS essio nCont ext i mple ments Http Sessi onCon text {
pri vate Vect or du mmy = new Vecto r();
package org. apac he.to mcat. sessi on;
separated – implementation
of a concern can be treated
as relatively separate entity
if (ina ctive Inte rval != -1 ) {
int thisI nterv al =
(int) (Syst em.cu rrent Time Milli s() lastAcc essed ) / 1000;
modular – above + has a
clear, well defined interface
to rest of system
if ( thisI nterv al > inact iveI nterv al) {
inval idate ();
Serve rSess ionMa nager ssm =
S erver Sessi onMan ager .getM anage r();
vali date ();
}
ssm.r emove Sessi on(th is);
voi d val idat e()
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;
if ( thisI nterv al > inact iveI nterv al) {
inval idate ();
}
}
}
public long get LastA ccess edTim e() {
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 ");
thro w new Ille galSt ateEx cept ion(m sg);
privat e lon g la stAcc essed Time = cre atio nTime ;
/**
* Retur n th e las t tim e the clie nt s ent a requ est
associa ted w ith this
* sessi on, as th e num ber o f mil lise conds sinc e mid night ,
January 1, 1 970
* GMT. Act ions that your appli cati on ta kes, such as
getting or s etti ng
* a val ue a ssoci ated with the s essi on, d o not affe ct th e
access time.
*/
pub lic l ong getLa stAcc essed Time( ) {
}
retu rn ( this. lastA ccess edTim e);
}
}
public long get LastA ccess edTim e() {
retu rn l astAc cesse d;
}
this .las tAcce ssedT ime = time ;
privat e lon g la stAcc essed = cr eatio nTim e;
void a ccess ed() {
// 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( );
}
2015/7/17
18
Crosscutting concerns in a system
(横切、交叉划分、跨断)






core module-level requirements and system-level
requirements.
Many system-level requirements tend to be orthogonal
(mutually independent) to each other and to the
module-level requirements.
System-level requirements also tend to crosscut many
core modules.
For example, authentication, logging, resource pooling,
administration, performance, and storage management.
Each crosscuts several subsystems.
For example, a storage-management concern affects
every stateful business object.
2015/7/17
19
Crosscutting concern problems





the requirement space is an n-dimensional
space, whereas the implementation space is
one-dimensional.
Such a mismatch results in an awkward
requirements-to-implementation map.
Symptoms(症状): Code tangling ; Code
scattering.
Implications(导致): Poor traceability,
Lower productivity, Less code reuse, Poor
code quality, More difficult evolution.
The current response: mix-in classes,
design patterns, and domain-specific
solutions.
2015/7/17
20
The fundamentals of AOP

The modularization unit in AOP is called an aspect, just as a
common concern's implementation in OOP is called a class.

AOP involves three distinct development steps: Aspectual
decomposition , Concern implementation, Aspectual
recomposition.
2015/7/17
21
example


public class CreditCardProcessor {
public void debit(CreditCard card, Currency amount)
throws InvalidCardException, NotEnoughAmountException,
CardExpiredException {
// Debiting logic(取款)
}
public void credit(CreditCard card, Currency amount)
throws InvalidCardException {
// Crediting logic (存款)
}
}
public interface Logger {
public void log(String message);
}
2015/7/17
22
weaving rules



Log each public operation's beginning
Log each public operation's completion
Log any exception thrown by each
public operation
2015/7/17
23
the weaver would produce composed code :
public class CreditCardProcessorWithLogging {
Logger _logger;
public void debit(CreditCard card, Money amount)
throws InvalidCardException, NotEnoughAmountException,
CardExpiredException {
_logger.log("Starting reditCardProcessor.credit(CreditCard,
Money) "+ "Card: " + card + " Amount: " + amount);
// Debiting logic
_logger.log("Completing CreditCardProcessor.credit(CreditCard,
Money) "+ "Card: " + card + " Amount: " + amount);
}
2015/7/17
24
public void credit(CreditCard card, Money amount)
throws InvalidCardException {
System.out.println("Debiting");
_logger.log("Starting CreditCardProcessor.debit
(CreditCard,Money) “ + "Card: " + card + " Amount: " +
amount);
// Crediting logic
_logger.log("Completing CreditCardProcessor.credit
(CreditCard, Money) “ + "Card: " + card + " Amount: " +
amount);
}
}
2015/7/17
25
Anatomy(解剖)of AOP languages


The AOP language specification

Implementation of concerns

Weaving rules specificationn: a language for
specifying rules for composing different
implementation pieces to form the final system.
AOP language implementation

Combine the individual concerns

Convert the resulting information into executable
code
2015/7/17
26
implement the weaver in various ways
source-to-source translation



a Java-based AOP implementation




preprocess source code for individual aspects to
produce weaved source code
feed this converted code to the base language
compiler to produce final executable code.
convert individual aspects first into Java source code,
then let the Java compiler convert it into byte code.
The same approach can perform weaving at the byte
code leve
a VM implementation
2015/7/17
27
AOP benefits
AOP helps overcome the problems caused by code tangling
and code scattering. Here are other specific benefits AOP
offers:

Modularized implementation of crosscutting concerns

Easier-to-evolve systems
Late binding of design decisions
More code reuse


In general, a loosely coupled implementation represents the
key to higher code reuse. AOP enables more loosely
coupled implementations than OOP.
2015/7/17
28
AspectJ
Learn AspectJ to better
understand aspectoriented programming
2015/7/17
29
AspectJ: An AOP implementation for Java
AspectJ, from Xerox PARC, is a general-purpose
aspect-oriented Java extension.
AspectJ uses Java as the language for implementing
individual concerns, and it specifies extensions to Java
for weaving rules. These rules are specified in terms
of :


1.
2.
3.
4.

join points (联结点、交汇点 )define specific points in a
program's execution,
Pointcuts (切入点、指定切入点)is the language construct
that specifies join points,
Advice(告知) defines pieces of an aspect implementation
to be executed at pointcuts,
aspects (方面)combines these primitives.
AspectJ's weaver -- an aspect compiler -- combines
different aspects together.
2015/7/17
30
AspectJ overview



AspectJ is a language specification as well as an AOP
language implementation.
The language specification defines various constructs
and their semantics to support aspect-oriented concepts.
AspectJ's language constructs extend the Java
programming language.
The language implementation offers tools for compiling,
debugging, and documenting code. AspectJ provides an
aspect weaver in the form of a compiler, an aspectaware debugger and documentation generator, and a
standalone aspect browser to visualize how an advice
crosscuts a system's parts.
2015/7/17
31
AspectJ language overview
To support AOP, AspectJ adds to the Java language
concepts:
 Joinpoints: Points in a program's execution. For
example, joinpoints could define calls to specific
methods in a class
 Pointcuts: Program constructs to designate
joinpoints and collect specific context at those
points
 Advices: Code that runs upon meeting certain
conditions. For example, an advice could log a
message before executing a joinpoint
2015/7/17
32
a simple class containing methods to
print a message: HelloWorld

// HelloWorld.java
public class HelloWorld {
public static void say(String message) {
System.out.println(message);
}
public static void sayToPerson(String message,
String name) {
System.out.println(name + ", " + message);
}
}
2015/7/17
33
adding greeting and gratitude
manners.

// MannersAspect.java
public aspect MannersAspect {
pointcut callSayMessage() : call(public static
void HelloWorld.say*(..));
before() : callSayMessage() {
System.out.println("Good day!");
}
}
after() : callSayMessage() {
System.out.println("Thank you!");
}
2015/7/17
34
adding greeting and gratitude
The MannersAspect.java
manners.
file declares a
MannersAspect aspect.

The aspect defines a
// MannersAspect.java
pointcut
public aspect MannersAspectcallSayMessage()
{
that captures calls to all
pointcut callSayMessage()public
: call(public
static
static methods
with
names that start with say.
void HelloWorld.say*(..));
It would capture say() and
before() : callSayMessage()
{
sayToPerson()
in a
HelloWorld
System.out.println("Good
day!");class.
Then you define two
}
advices for before and
after reaching the
after() : callSayMessage()callSayMessage()
{
pointcut:
printing
"Good day!" and
System.out.println("Thank
you!");
"Thank you!"
}
}
2015/7/17
35
AspectJ language concepts and
constructs --1



Joinpoints Joinpoints, a central concept in AspectJ, are
well-defined points in a program's execution.
Candidate joinpoints include
 calls to a method,
 a conditional check,
 a loop's beginning,
 or an assignment.
Joinpoints also have a context associated with them. For
example, a method-call joinpoint could have the target
object and its argument as part of the context.
2015/7/17
36
AspectJ language concepts and
constructs --2



Pointcuts, program constructs to designate joinpoints,
let you specify a joinpoint collection. Pointcuts also let
you expose context at the joinpoint to an advice
implementation.
AspectJ makes the following pointcuts available:
 Method call and execution
 Constructor call and execution
 Read/write access to a field
 Exception handler execution
 Object and class initialization execution
HelloWorld example: pointcut callSayMessage() :
call(public static void HelloWorld.say*(..));
2015/7/17
37
Table 1. Call to methods and constructors
pointcuts -- call pointcuts
call(public void
MyClass.myMethod(String)
)
Call to myMethod() in MyClass
taking a String argument,
returning void, and with public
access
call(void
MyClass.myMethod(..))
Call to myMethod() in MyClass
taking any arguments, with void
return type, and any access
modifiers
call(*
MyClass.myMethod(..))
Call to myMethod() in MyClass
taking any arguments returning
any type
call(*
MyClass.myMethod*(..))
Call to any method with name
starting in "myMethod" in MyClass
call(*
MyClass.myMethod*(String
,..))
Call to any method with name
starting in "myMethod" in MyClass
and the first argument is of
String type
2015/7/17
38
call(* *.myMethod(..)) Call to myMethod() in any
class in default package
call(MyClass.new())
Call to any MyClass'
constructor taking no
arguments
call(MyClass.new(..))
Call to any MyClass'
constructor with any
arguments
call(MyClass+.new(..)) Call to any MyClass or its
subclass's constructor.
(Subclass indicated by use
of '+' wildcard)
call(public *
All public methods in all
com.mycompany..*.*(..)) classes in any package with
com.mycompany the root
package
2015/7/17
39
Table 2. Execution of methods and constructors
pointcuts -- execution pointcuts
execution(public void Execution of myMethod() in MyClass
MyClass.myMethod(Strin taking a String argument, returning
g))
void, and with public access
execution(void
MyClass.myMethod(..))
Execution of myMethod() in MyClass
taking any arguments, with void
return type, and any access modifiers
execution(*
MyClass.myMethod(..))
Execution of myMethod() in MyClass
taking any arguments returning any
type
execution(*
Execution of any method with name
MyClass.myMethod*(..)) starting in "myMethod" in MyClass
execution(*
Execution of any method with name
MyClass.myMethod*(Stri starting in "myMethod" in MyClass and
ng,..))
the first argument is of String type
2015/7/17
40
execution(*
*.myMethod(..))
Execution of myMethod() in
any class in default package
execution(MyClass.ne Execution of any MyClass'
w())
constructor taking no
arguments
execution(MyClass.ne Execution of any MyClass'
w(..))
constructor with any
arguments
execution(MyClass+.n Execution of any MyClass or
ew(..))
its subclass's constructor.
(Subclass indicated by use
of '+' wildcard)
execution(public *
All public methods in all
com.mycompany..*.*(. classes in any package with
.))
com.mycompany the root
package
2015/7/17
41
Table 3. Field-access pointcuts
get(PrintStream
System.out)
Execution of read-access to field
out of type PrintStream in
System class
set(int MyClass.x)
Execution of write-access to field x
of type int in MyClass
Table 4. Exception-handler pointcuts
handler(RemoteExcepti Execution of catch-block
on)
handling RemoteException type
handler(IOException+) Execution of catch-block
handling IOException or its
subclasses
handler(CreditCard*) Execution of catch-block
handling exception types with
names that start with
CreditCard
2015/7/17
42
Table 5. Class-initialization pointcuts
staticinitialization(
MyClass)
Execution of static block of
MyClass
Staticinitialization(
MyClass+)
Execution of static block
of MyClass or its
subclasses
Table 6. Lexical-structure-based pointcuts
within(MyClass)
Any pointcut inside MyClass's
lexical scope
within(MyClass*)
Any pointcut inside lexical scope
of classes with a name that
starts with "MyClass"
withincode(*
Any pointcut inside lexical scope
MyClass.myMethod(..)) of any myMethod() of MyClass
2015/7/17
43
Table 7. Control-flow-based pointcuts
cflow(call(*
All the joinpoints in control flow of call to
MyClass.myMethod( any myMethod() in MyClass including call
..))
to the specified method itself
cflowbelow(call(* All the joinpoints in control flow of call to
MyClass.myMethod( any myMethod() in MyClass excluding call
..))
to the specified method itself
Table 8. Self-, target-, and arguments-type pointcuts
this(JComponent
+)
All the joinpoints where this is instanceof
JComponent
target(MyClass)
All the joinpoints where the object on which
the method is called is of type MyClass
args(String,..,
int)
All the joinpoints where the first argument is
of String type and the last argument is of int
type
args(RemoteExce
ption)
All the joinpoints where the type of argument
or exception handler type is RemoteException
2015/7/17
44
Table 9. Conditional-test pointcuts
if(EventQueue.isDispat All the joinpoints where
chThread())
EventQueue.isDispatchThread()
evaluates to true
• Named and anonymous pointcuts
• Use ||, &&, and ! operators with pointcuts
For example,
call(* MyClass.m1()) || call(* MyClass.m2())
call(* MyClass.m1()) && cflow(call(* MyClass.m2())
!call(* MyClass.m1())
2015/7/17
45
Exposing context

AspectJ offers target(), this(), and
args() pointcuts to collect the context.
For example,
pointcut
publicOperationCardAmountArgs(Credi
tCard card, Money amount):
execution(public *
CreditCardProcessor.*(..)) &&
args(card, amount);

2015/7/17
46
AspectJ language concepts and
constructs --3
• Advices specify the executable code when reaching
certain pointcuts.
• AspectJ provides three ways to associate an advice with
a joinpoint:
• A before advice runs just before the joinpoint,
• whereas an after advice runs just after.
• An around advice surrounds a joinpoint and has
control if the joinpoint's execution should proceed.
2015/7/17
47
before() : call(public * MyClass.*(..)) {
System.out.println("Before: " + thisJoinPoint + " " +
System.currentTimeMillis());
}
--------------------------------------------------------------------------after() : call(public * MyClass.*(..)) {
System.out.println("After: " + thisJoinPoint + " " +
System.currentTimeMillis());
}
---------------------------------------------------------------------------
void around(Connection conn) : call(Connection.close()) && target(conn) {
if (enablePooling) {
connectionPool.put(conn);
} else {
proceed();
}
}
2015/7/17
48
AspectJ language concepts and
constructs --4
• Aspects act as AspectJ's unit of modularization. It puts
together pointcuts and advices.
• Aspects resemble classes: an aspect can contain
methods and fields, extend other classes or aspects, and
implement interfaces. However, you cannot create an
object for an aspect using new.
• AspectJ does not allow classes to contain advices; only
aspects can contain advices.
• A concrete aspect extending an abstract aspect can then
provide concrete definitions of abstract pointcuts.
2015/7/17
49
AspectJ examples



Example 1: Detect a Swing UI (user
interface) update from a nonevent
dispatch thread
Example 2: Authentication
Example 3: Add Japanese manners to
HelloWorld
2015/7/17
50
Research Projects:

Supported Systems:
AspectC++, AspectJ, AspectR, AspectS,…



Research Prototypes:
Applications:
Methods & Foundations:
2015/7/17
51
Supported Systems:





ANGIE Generation Now! provides a new frame processor
language to implement generators, e.g., aspect weavers.
AspectC++ is an aspect-oriented extension to the C++
programming language.
AspectJ is a seamless aspect-oriented extension to Java that
enables the modular implementation of a wide range of
crosscutting concerns.
AspectR is aspect-oriented programming for Ruby that
allows you to wrap code around existing methods in your
classes.
AspectS is an early prototype that enables aspect-oriented
programming in the Squeak/Smalltalk environment.
2015/7/17
52







AspectWerkz is a dynamic, lightweight and high-performant
AOP/AOSD framework for Java.
Caesar is an aspect-oriented programming language that
focusses on multi-view decomposition and aspect reusability.
DemeterJ and DJ facilitate the structure-shy encapsulation
of traversal-related behavioral concerns.
Hyper/J supports "multi-dimensional" separation and
integration of concerns in standard Java software.
JAC is a Java framework for aspect-oriented distributed
programming.
JAsCo is an aspect-oriented programming language tailored
for component basedsoftware development.
JMangler is a framework for load-time transformation of
Java programs, whichsupports conflict-free composition of
independently developed aspects(implemented as JMangler
transformer components) and their joint application to
existing base classes.
53
2015/7/17







MixJuice is an extension to Java, based on the differencebased module mechanism.
Mozart Programming System is an advanced development
platform for intelligent, distributed applications.
Object Everywhere - An article describing an AOP
Framework based on COM with Delphi.
PROSE is an AOP platform based on the Java Virtual
Machine that allows dynamic weaving and un-weaving.
SmartTools is an Aspect- and XML-oriented Semantic
Framework Generator.
UMLAUT is a framework that weaves multi-dimensional high
level UML design models into detailed design models suitable
for either implementation, simulation or validation.
xlinkit checks the consistency of, and generates links between,
distributed documents; it builds on a long line of research into
the management of consistency across multiple views.
2015/7/17
54
Research Prototypes







Apostle is an AspectJ-like aspect-oriented extension to
Smalltalk.
ArchJava extends Java with explicit software architecture
constructs, separating out structural concerns that would
otherwise crosscut the system.
Aspect Browser is a graphical tool that uses the map
metaphor to assist finding, exploring, and manipulating
crosscutting concerns in software.
Aspect Mining Tool (AMT) is a tool for identification and
exploring latent concerns in software systems.
AspectC is a simple AspectJ-like AOP extension to C.
AspectC# explores adding AspectJ-style aspect support to C#.
Aspect.pm is a set of Perl libraries for aspect-oriented
programming.
2015/7/17
55







ComposeJ is an extension of the java language that adds
composition filters to Java classes through inlining.
Concern Graphs are a manipulable representation of concerns
that can be extracted from an existing code base.
ConcernJ integrates the concepts of aspects, classes and
Composition Filters into 'concerns'; this prototype
demonstrates the transformation of (languageindependent)
concern specifications and java classes into executable
composition filters and java files.
EAOP is an approach to AOP for Java with expressive
crosscuts, explicit aspect composition, aspects of aspects, and
dynamic aspect management.
ISL is an aspect-oriented service which allows to ynamically
express nonfunctional properties in terms of "interactions".
JADE is an extension to Java that allows for noninvasive
composition.
2015/7/17
56






JMunger is a tool to insert Java code into existing classes at
load time.
MetaclassTalk is a reflective extension of Smalltalk that
provides a MOP which can be used for AOP.
Object Teams is a programming model that combines well
explored concepts like role objects, collaborations, method
interception, virtual types and dynamic aspect activation,
introducing only a fairly small number of language
constructs. The model is realized within the host languages
Lua, Ruby and Java.
Pythius is an open-source project to support aspect-oriented
programming techniques in Python.
QSOUL/Aop is an Aspect Oriented Logic Meta
Programming tool in Squeak/Smalltalk.
Weave.NET aims to provide a language independent
mechanism for supporting the AspectJ notion of AOP that is
also consistent with the component model of the .NET
Framework.
57
2015/7/17
Applications




a-kernel is an effort to apply AOP techniques to operating
system kernel code.
FACET is a framework for a customizable real-time event
channel that uses aspects.
Lasagne is an aspect-oriented architecture for contextsensitive and run-time weaving of aspects--prototypes have
been developed in Java and Correlate.
PacoSuite is a visual component composition environment
which supports aspect oriented software development using
the JAsCo programming language.
2015/7/17
58



QuO is a middleware framework and toolkit which includes
aspect-oriented languages for developing quality of service
enabled, adaptive distributed object applications.
SoC+MAS is a research project whose main focus is the
application of advanced separation of concerns techniques to
handle the complexity of designing and implementing multiagent OO software.
SADES is a customizable and extensible object database
evolution system implemented using AOP techniques.
2015/7/17
59
Methods & Foundations





Afanti is a project aimed at developing techniques and tools to
support testing and analysis of aspect-oriented software.
AOPim is a method for the progressive implementation of
persistent, distributed, and concurrent applications using
aspect-oriented programming.
Aspect-Oriented Component Engineering uses the concept
of horizontal slices through vertically-decomposed
components called aspects to characterize crosscutting
properties of components.
Aspect-Oriented Frameworks is research on frameworks for
aspect-oriented software development.
Aspect-Oriented Software Engineering aims to develop
support for aspects throughout the development life cycle-specific application areas include middleware, componentbased systems and databases.
2015/7/17
60






Assessment: Does AOP Work? uses case study and
experimental methods to evaluate AOP techniques and tools.
Composition Filters model is a modular extension to the
object-oriented model that allows the modular specification of
aspects in a composable way.
Cosmos is a concern-space modeling schema that supports
the modeling of multidimensional concern spaces for
purposes of software composition, decomposition, analysis,
and understanding.
D2AL provides a methodology, an aspect language and tools
that support the development of robust and efficient
distributed applications.
Demeter Aspects points to Demeter subprojects about the
foundations of the separation of crosscutting concerns.
DisCo is a formal specification method that supports
advanced separation of concerns for distributed reactive
systems.
2015/7/17
61






Dynamic Aspect-Oriented Platform defines a distributed
platform that provides dynamic composition between
components and aspects as plug-ins.
Event-based AOP is a formal framework for AOP featuring
expressive crosscut definitions.
Filter Objects Project is a project on first-class dynamicallypluggable filter objects and related modeling methods and
notations.
Implicit Context is an approach to improving the reusability
and evolvability of systems through the reduction of
extraneous embedded knowledge.
Phoenix is an an Aspect-Oriented Approach for Software
Reengineering using Transformations.
Prospects is a project aimed at investigating how aspect
oriented components can be used to derive useful models of
specific concerns.
2015/7/17
62






Quality Controlled Component-based Software
Development (QCCS) is a project that is developing a
methodology and supporting tools for the creation of
components with contracts and based on AOSD.
Semantics of Aspect-Oriented Programming (SAOP) is an
effort to study constructs for AOP (e.g. method call
interception), in particular their language design, their formal
semantics, and their relation to program transformation.
Synbad is an architecture design approach for identifying and
composing architectural aspects.
Theme/UML is an aspect-oriented extension to the UML.
Vanderbilt/ISIS is working in the area of applying core AOP
principles toward domain-specific visual modeling languages.
XBel is a framework for reasoning about compositions of
concerns on the requirements level.
2015/7/17
63
Early Aspects:
Aspect-Oriented Requirements Engineering
and Architecture Design


In a fashion similar to object-orientation, aspectorientation is following a cycle of natural
progression from programming to other
software development stages.
Employing an aspect-oriented approach from
the very early development stages can help
capture crosscutting properties early on in the
software life cycle; hence, improving the quality
of the products and reducing adaptation,
evolution and maintenance costs.
2015/7/17
64






processes and techniques for aspect-orientation at early
software development stages;
formalisms and notations for specifying aspects at early
software development stages;
aspect composition issues and mechanisms including
those relating to composition with existing separation of
concerns mechanisms such as viewpoints, architectural
patterns and architecture trade-off analysis, and
composition with life cycle concerns;
role of aspects to improve requirements evolution and
architecture adaptability;
concern validation at early software development
stages;
mapping and influence of requirements and domain
aspects to architecture design and later software
development stages;
65
2015/7/17




aspect dependencies and interactions at early
software development stages;
integration of aspects with modeling
mechanisms such as UML;
role of early aspects in the development of test
cases to be used during verification and
validation;
tool support and automation for aspectorientation at early software development stages
2015/7/17
66
well-planned usage



While aspect oriented techniques can often produce
better programs,
sometimes aspect oriented mechanisms lead to
unpredictable or incorrect results.
Hence, a well-planned usage of such new
mechanisms is a premise for the successful
application of aspect-orientation.
2015/7/17
67
DisCo (Distributed Co-operation)
DisCo is a formal specification method for reactive
systems. It incorporates a specification language, a
methodology for developing specifications using the
language, and tool support for the methodology.
Currently the support tools include an animation facility
for executing specifications, a tool for visualizing
execution histories as scenarios, and a link to a
mechanical theorem prover for verification.
 DisCo is currently funded by the Academy of
Finland,Tise (Tampere graduate school in Information
Science And Engineering) and Tekes(The Technology
Development Center of Finland).
68
2015/7/17




DisCo Home Page http://disco.cs.tut.fi/
Mika Katara and Tommi Mikkonen. AspectOriented Specification Architectures for
Distributed Real-Time Systems. In Sten F.
Andler, Michael G. Hinchey, and Jeff Offutt,
editors, Proceedings of the Seventh IEEE
International Conference on Engineering of
Complex Computer Systems, ICECCS 2001,
pages 180-190, Skövde, Sweden, June 2001.
IEEE Computer Society Press.
Pertti Kellomäki. Composing Distributed
Systems from Reusable Aspects of Behavior.
In Proceedings of ICDCS'02 Workshops. IEEE
Press, 2002.
2015/7/17
69
AspectGAMMA


GAMMA is an abstract language, based on
multiset rewriting on a shared dataspace,
designed to support parallel execution of a
program on parallel and/or distributed
architectures.
AspectGAMMA is an extension to the
GAMMA formalism. Aspects + GAMMA =
AspectGAMMA A Formal Framework for
Aspect-Oriented Specification.
2015/7/17
70
Object teams

Stephan Herrmann. Object teams: Improving
modularity for crosscutting collaborations. In
Proc. Net Object Days 2002.
Split Object

Daniel Bardou. Towards a Platform for
Experimenting with Split Objects in Java and
AspectJ Proceedings of the Third German AOSDWorkshopof the SIG Object-Oriented Software
Development, March 4-5, 2003. Essen, Germany
2015/7/17
71
Semantics of aspect-oriented programming


R. L¨ammel. A Semantical Approach to MethodCall Interception. In Proc. of the 1st International
Conference on Aspect-Oriented Software
Development (AOSD 2002), pages 41–55, Twente,
The Netherlands, Apr. 2002. ACM Press.
R. L¨ammel. Adding Superimposition To a
Language Semantics (FOAL'03)
2015/7/17
72
FOAL: Foundations of Aspect-Oriented
Languages



Proceedings mar, 2003, Boston,
http://www.cs.iastate.edu/~leavens/FOAL/cfp-2003.shtml
semantics of aspect-oriented languages, specification
and verification or such languages, type systems, static
analysis, theory of testing, theory of aspect composition,
theory of aspect translation (compilation) and rewriting,
and applications of such theories in practice (such as
language design studies).
The workshop aims to foster work in foundations,
including formal studies, promote the exchange of ideas,
and encourage workers in the semantics and formal
methods communities to do research in the area of
aspect-oriented programming languages.
73
2015/7/17
Aspect-Oriented Modeling with UML



Workshop on Aspect-Oriented Modeling with UML
(AOSD-2002 , mar),
{http://lglwww.epfl.ch/workshops/aosd-uml/papers.html}
Second International Workshop on Aspect-Oriented
Modeling with UML sep, 2002,
{http://lglwww.epfl.ch/workshops/uml2002/},
Third International Workshop on Aspect Oriented mar,
2003, Boston
{http://lglwww.epfl.ch/workshops/aosd2003/},
This workshop is dedicated to the definition of aspectoriented modeling techniques, methods and tools based
on UML. Suggested issues are:
2015/7/17
74






How can we apply UML artifacts to AOSD?
Are the existing notations and modeling techniques of
UML sufficient to model aspects, or do we need to
extend UML to support AOSD?
Is UML the appropriate modeling language on which to
base modeling for AOSD?
Is UML capable of expressing "Core" components and
"Aspectual" components as well as associations linking
them together?
If we have to extend the UML, are the extension
mechanisms provided by UML adequate? What could
then be a UML profile for AOSD?
Or would it be possible to rely only on a restricted
subset of the UML for AOSD? What would this subset
be?
2015/7/17
75
结束语




面向方面的软件开发方法,作为一种新的方法,
新的动向,应当给予高度的关注和重视。
跟踪当代世界新技术潮流,学习,消化,研究,
然后创新,应用,产业化,这是我们的技术路线
和方针,也是我们的义不容辞的责任。
新技术是实践中产生的,但是需要进一步的深化、
理论上的提高和研究。这为我们提供了广阔的空
间。
目前这方面我们同国外的差距并不大,开展这方
面的研究不失是一个好的方向。
2015/7/17
76

本讲稿放在如下网站:
http://210.27.37.253/~kghao/jianggao/
谢谢大家!
郝克刚 西北大学计算机科学系
软件工程研究所
2015/7/17
77

similar documents