modular
Shared by: linxiaoqin
-
Stats
- views:
- 0
- posted:
- 1/27/2013
- language:
- Hebrew
- pages:
- 22
Document Sample


מודולריות של תוכנה
עמירם יהודאי
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 1
מערכות גדולות
כל מערכת גדולה מורכבת מתתי מערכות.
רק כך ניתן לתכנן ולבנות מערכות כאלה.
דוגמא: מכונית מורכבת ממנוע, שילדה, הילוכים,...
כל תת מערכת כזאת מורכבת אף היא מרכיבים.
מבנה היררכי, עד לרכיבים פשוטים.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 2
הפרדת עניינים
החלוקה לתתי מערכות צריכה לאפשר למתכנני כל
תת מערכת לפתח אותה בנפרד.
מתכנן המנוע אינו צריך לדעת את הפרטים של
השילדה.
אבל עליו להכיר מאפיינים מסוימים של השילדה
(אולי את המשקל?).
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 3
מערכות תוכנה
מערכות תוכנה הן מערכות הנדסיות כמו מכונית.
למערכות תוכנה יש מאפיינים ייחודיים לעומת
מערכות אחרות.
אבל יש גם הרבה מן המשותף.
בין המערכות המורכבות ביותר שמפותחות כיום,
מערכות תוכנה תופסות מקום בולט.
גם מערכת תוכנה מורכבת חייבת להיות בנויה
כאוסף תתי מערכות.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 4
תוכנה
תוכנה נכתבת כקוד בשפת תכנות מסוימת.
ניתן למדוד את גודל התוכנה ע"י ספירת שורות
הקוד.
( תהליך הפיתוח כולל פעילויות נוספות, ומייצר
מסמכים בנוסף לקוד).
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 5
מודול תוכנה
היחידה הקטנה ביותר שיש לה קיום עצמאי.
מערכת תוכנה מורכבת ממודולים.
( במערכת בינונית או גדולה, המודולים מסודרים
במבנה היררכי של תתי מערכות וכו').
מודול הוא קטע תכנית שניתן להפעילו (ממודול
אחר) באופן או אופנים מוגדרים היטב.
בפעולת כלל המערכת בכל רגע פועל מודול
מסוים, הוא יכול להפעיל מודול אחר ולהמתין
לתוצאתו, וכך הלאה.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 6
מודולריות
מהו מודול "טוב"?
איך בונים מערכת "מודולרית"?
לפני שננסה להבין מהי מודולריות, נציין כי
מודולריות היא תכונה של מערכת מסוימת.
אבל גם תכונה של
שיטה לפיתוח תוכנה שמובילה למערכות מודולריות.
שפת תכנות.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 7
קריטריונים למודולריות
פירוק מודולרי: ניתן לפרק בעיה לבעיות פשוטות
יותר ולפתור אותן בנפרד.
הרכבה מודולרית: ניתן לקחת מודולים שפותחו
בנפרד ולהרכיבם למערכת.
הבנה מודולרית: ניתן להבין כל מודול בנפרד.
רציפות: שינוי קטן בדרישות מהמערכת ידרוש
שינוי במספר קטן של מודולים.
הגנה : ארוע לא תקין בזמן ביצוע מודול ישפיע רק
על מודול זה, או אחדים נוספים.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 8
מודולים והקשרים ביניהם
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 9
כללים למודולריות
המבנה המודולרי של המערכת צריך לשקף את המבנה
של עולם הבעיה.
מעט ממשקים: כל מודול יתקשר עם מספר קטן של
מודולים.
ממשקים קטנים: כמות המידע שמודולים יעבירו ביניהם
קטנה.
ממשקים מפורשים: רק מידע שמודול הגדיר במפורש
כמיוצא יהיה זמין למודולים האחרים.
הסתרת מידע: רק חלק קטן מהמידע של מודול יהיה זמין
למודולים האחרים.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 01
שימוש חוזר בתוכנה
היכולת להשתמש במודול שפותח עבור מערכת
מסוימת גם במערכות אחרות בעתיד.
אמצעי חשוב לשיפור תפוקת מפתחי תוכנה.
מבנה מודולרי טוב מוביל ליצירת מודולים שניתן
יהיה להשתמש בהם מחדש בהמשך.
החזון: תעשיה של רכיבי תוכנה שניתן לקטלג,
למכור, ולקנות.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 11
סוגי מודולים
בשיטות פיתוח (ושפות תכנות) "קלסיות", מודול
הוא "פונקציה" – קטע קוד שמבצע פעולה
מסוימת.
פיתוח בשיטת "פירוק פונקציונלי"
שיטות אלה אינן משיגות מודולריות טובה:
יש ביניהן תלות חזקה בגלל תלות בנתונים.
המודולים הנוצרים קטנים למדי.
שינוי בתוכנה גורם לשינוי בפעולות.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 21
פיתוח מונחה עצמים
כיום מוסכם ששיטות המפרקות מערכת לישויות
שלה (לא לפעולות) מובילות למבנה מודולרי עדיף.
" אל תשאל מה המערכת עושה, אלא למי היא
עושה זאת".
עצם: "ישות" מתחום הבעיה: מודל של עצם ממשי.
מחלקה: מודול המתאר עצמים מסוג מסוים.
תהליך הפיתוח עוסק במידול המערכת, איתור
הישויות והיחסים ביניהם.
זאת השיטה הרווחת כיום.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 31
חלוקת אחריות בין עצמים
תיכון באמצעות חוזה ).(Design by Contract
מודול לקוח מבקש שירות ממודול ספק.
כל מודול מגדיר חוזה בינו לבין לקוחותיו.
הלקוח חייב לקיים את תנאי הקדם של השירות.
אם תנאי הקדם קוים, הספק מבטיח לקיים את
תנאי האחר – כלומר לספק את השרות שהובטח.
ניתן לבסס גישה זאת באופן פורמלי.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 41
אפיון חלופי של מרכיבי מערכת תוכנה
מערכת תוכנה עוסקת במגוון "עניינים".
עניין הוא יעד מסוים, מושג, או תחום עיסוק.
ענייני הליבה של מערכת - פונקציונליות עיקרית.
בגישה מונחת עצמים ענייני ליבה מטופלים ע"י
מודול אחד או שניים.
" עניינים נחתכים" – חלים על כל המערכת, ולא
ניתן לטפל בהם במודול יחיד.
דוגמאות:
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 51
מודולריות טובה
ניתוח תחבירי של XML
ניתוח תחבירי של XMLב org.apache.tomcat
באדום שורות קוד רלבנטיות
5002/4/1
61 מופיע כולו במודול אחד
ל"ר ברק שהם ז"יום עיון לזכרו של ד
מודולריות טובה
התאמת תבנית של URL
התאמת תבנית של XMLב org.apache.tomcat
באדום שורות קוד רלבנטיות
5002/4/1
מופיע בשני מודולים
ל"ר ברק שהם ז"יום עיון לזכרו של ד 71
רישום לוג אינו מודולרי .....
רישום לוג ב org.apache.tomcat
באדום שורות קוד שמטפלות ברישום לוג
מפוזר במספר רב של מודולים
חלק קטן בכל מודול
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 81
השלכות הפגיעה במודולריות
קטעי קוד חוזרים במקומות שונים.
קשה להבין את הקוד: מבנה הקוד לא משקף את
חלוקת העניינים.
קשה לשנות את הקוד: צריך למצוא את כל קטעי
הקוד הרלבנטיים ולתקנם באופן עיקבי.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 91
...... אילו רק יכולנו
App ca onSess on
ApplicationSession S andardSess on
StandardSession
/* public void inva lidat e() { package org. apac he.to mcat. sessi on; /**
* ==== ===== ==== ===== ===== ===== ===== ==== ===== ===== ===== ===== ==== ===== == serv erSe ssion .remo veApp licat ionS essio n(con text) ; /** * Bind an o bject to t his s essio n, u sing the s pecif ied n ame. If an ob ject
* * Retur n th e <co de>Ht tpSes sion< /cod e> fo r whi ch th is * of th e sa me na me is alre ady b ound to t his s essio n, th e ob ject is
* The Apach e So ftwar e Lic ense, Vers ion 1.1 // r emov e eve rythi ng in the sess ion import java. io.I OExce ption ; object * repla ced.
* import java. io.O bject Input Strea m; * is th e fa cade. * <p>
* Copy right (c) 1999 The Apach e Sof twar e Fou ndati on. All r ight s Enum erat ion e num = valu es.ke ys() ; import java. io.O bject Outpu tStre am; */ * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts
* rese rved. whil e (e num.h asMor eElem ents( )) { import java. io.S erial izabl e; pub lic H ttpS essio n get Sessi on() { * <code >Htt pSess ionBi nding Liste ner< /code >, th e con taine r ca lls
* Stri ng na me = (Stri ng)en um.n extEl ement (); import java. util .Enum erati on; * <code >val ueBou nd()< /code > on the objec t.
* Redi strib utio n and use in so urce and binar y for ms, w ith o r wi thout remo veVal ue(na me); import java. util .Hash table ; retu rn ( (Http Sessi on) t his); *
* modi ficat ion, are permi tted provi ded that the f ollow ing c ondi tions } import java. util .Vect or; * @para m na me Na me to whic h the obj ect i s bou nd, c annot be null
* are met: import javax .ser vlet. Servl etExc eptio n; } * @para m va lue O bject to b e bou nd, canno t be null
* vali d = false ; import javax .ser vlet. http. HttpS essio n; *
* 1. R edist ribu tions of s ource code mus t ret ain t he ab ove c opyr ight } import javax .ser vlet. http. HttpS essio nBin dingE vent; * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n
* n otice , th is li st of cond ition s an d the foll owing disc laim er. import javax .ser vlet. http. HttpS essio nBin dingL isten er; // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- - * inva lida ted s essio n
* pub lic b oole an is New() { import javax .ser vlet. http. HttpS essio nCon text; Session Publ ic M ethod s *
* 2. R edist ribu tions in b inary form mus t rep roduc e the abov e co pyrig ht if ( ! va lid) { import org.a pach e.tom cat.c atali na.*; * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d by
* n otice , th is li st of cond ition s an d the foll owing disc laim er in Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); import org.a pach e.tom cat.u til.S tring Mana ger; * <cod e>se tAttr ibute ()</c ode>
* t he do cume ntati on an d/or other mat erial s pro vided with the /** */
* d istri buti on. thro w new Ille galSt ateEx cept ion(m sg); * Updat e th e acc essed time info rmat ion f or th is se ssion . pub lic v oid putVa lue(S tring name , Ob ject value ) {
* } /** This me thod
* 3. T he en d-us er do cumen tatio n inc lude d wit h the redi strib utio n, if * Stan dard impl ement ation of t he <b >Ses sion< /b> * shoul d be call ed by the conte xt w hen a requ est c omes in setA ttri bute( name, valu e);
* a ny, m ust inclu de th e fol lowin g ac knowl egeme nt: if ( this Acces sTime == c reati onTi me) { interfa ce. This obje ct is for a p artic ular
* "Th is p roduc t inc ludes soft ware deve loped by t he retu rn tr ue; * seri aliza ble, so t hat i t can be s tore d in * sessi on, even if th e app licat ion does not r efere nce i t. }
* Ap ache Soft ware Found ation (ht tp:// www.a pache .org/ )." } el se { persist ent s tora ge or tran sferr ed */
* A ltern atel y, th is ac knowl egeme nt m ay ap pear in th e sof twar e retu rn fa lse; * to a diff eren t JVM for distr ibuta ble sessi on pub lic v oid acces s() {
itself, } support . /**
* i f and whe rever such thir d-par ty a cknow legem ents norma lly appea r. } * <p> this .las tAcce ssedT ime = this .thi sAcce ssedT ime; * Remov e th e obj ect b ound with the speci fied name from this sess ion. If
* * <b>I MPLEM ENTA TION NOTE< /b>: An i nsta nce o f thi s this .thi sAcce ssedT ime = Syst em.c urren tTime Milli s(); * the s essi on do es no t hav e an obje ct bo und w ith t his n ame, this meth od
* 4. T he na mes "The Jakar ta Pr oject ", " Tomca t", a nd "A pache Sof tware class r epres ents both the this .isN ew=fa lse; * does noth ing.
* F ounda tion " mus t not be u sed t o en dorse or p romot e pro duct s /** * inte rnal (Ses sion) and appli catio n le vel } * <p>
derived * @depr ecat ed (HttpSe ssion ) vi ew of the sessi on. * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts
* f rom t his softw are w ithou t pri or w ritte n per missi on. F or w ritte n */ * Howe ver, beca use t he cl ass i tself is not d eclar ed * <code >Htt pSess ionBi nding Liste ner< /code >, th e con taine r ca lls
* p ermis sion , ple ase c ontac t apa che@ apach e.org . public, Java log ic ou tside /** * <code >val ueUnb ound( )</co de> o n th e obj ect.
* pub lic v oid putVa lue(S tring name , Ob ject value ) { * of t he <c ode> org.a pache .tomc at.se ssio n</co de> * Perfo rm t he in terna l pro cessi ng r equir ed to inva lidat e *
* 5. P roduc ts d erive d fro m thi s sof twar e may not be ca lled "Apa che" setA ttri bute( name, valu e); package cann ot c ast a n this se ssion , * @para m na me Na me of the objec t to remo ve fr om th is se ssio n.
* n or ma y "A pache " app ear i n the ir n ames witho ut pr ior w ritt en } * Http Sessi on v iew o f thi s ins tance bac k to a * witho ut t rigge ring an ex cepti on i f the sess ion h as *
* p ermis sion of t he Ap ache Group . Session view . already expi red. * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n
* pub lic v oid setAt tribu te(St ring name , Obj ect v alue) { * */ * inva lida ted s essio n
* THIS SOFT WARE IS P ROVID ED `` AS IS '' A ND AN Y EXP RESSE D OR IMPL IED if ( ! va lid) { * @aut hor C raig R. M cClan ahan pub lic v oid expir e() { */
* WARR ANTIE S, I NCLUD ING, BUT N OT LI MITE D TO, THE IMPLI ED WA RRAN TIES Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); * @ver sion $Rev ision : 1.2 $ $D ate: 2000 /05/1 5 pub lic v oid remov eAttr ibute (Stri ng n ame) {
* OF M ERCHA NTAB ILITY AND FITNE SS FO R A PARTI CULAR PURP OSE A RE 17:54:1 0 $ // R emov e thi s ses sion from our manag er's activ e
* DISC LAIME D. IN NO EVEN T SHA LL TH E AP ACHE SOFTW ARE F OUNDA TION OR thro w new Ille galSt ateEx cept ion(m sg); */ session s sync hron ized (attr ibute s) {
* ITS CONTR IBUT ORS B E LIA BLE F OR AN Y DI RECT, INDI RECT, INCI DENT AL, } if ( (man ager != nu ll) & & (ma nage r ins tance of Obje ct ob ject = att ribut es.g et(na me);
* SPEC IAL, EXEM PLARY , OR CONSE QUENT IAL DAMAG ES (I NCLUD ING, BUT NOT final c lass Stan dardS essio n Manager Base) ) if ( objec t == null)
* LIMI TED T O, P ROCUR EMENT OF S UBSTI TUTE GOOD S OR SERVI CES; LOSS OF if ( name == n ull) { imp lemen ts H ttpSe ssion , Ses sion { ((Ma nager Base) mana ger). remo ve(th is); retur n;
* USE, DATA , OR PROF ITS; OR BU SINES S IN TERRU PTION ) HOW EVER CAUS ED AN D Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ; attr ibute s.rem ove(n ame);
* ON A NY TH EORY OF L IABIL ITY, WHETH ER I N CON TRACT , STR ICT L IABI LITY, // U nbin d any obje cts a ssoci ated with this sess ion // S ystem .out. print ln( "Remo ving attri bute " + name );
* OR T ORT ( INCL UDING NEGL IGENC E OR OTHE RWISE ) ARI SING IN AN Y WA Y OUT thro w new Ille galAr gumen tExc eptio n(msg ); // ----- ---- ----- ----- ----- ----- ---- ----- ----- --- Vect or r esult s = n ew Ve ctor( ); if ( objec t ins tance of Ht tpSe ssion Bindi ngLis tener ) {
* OF T HE US E OF THIS SOFT WARE, EVEN IF ADVIS ED OF THE POSSI BILI TY OF } ------- ----- - Co nstru ctors Enum erat ion a ttrs = get Attri bute Names (); ((Htt pSess ionBi nding List ener) obje ct).v alueU nbou nd
* SUCH DAMA GE. whil e (a ttrs. hasMo reEle ments ()) { ( new H ttpSe ssion Bind ingEv ent(( HttpS essio n) t his, name) );
* ==== ===== ==== ===== ===== ===== ===== ==== ===== ===== ===== ===== ==== ===== == remo veVa lue(n ame); // remov e an y exi sting bind ing Stri ng at tr = (Stri ng) a ttrs .next Eleme nt(); }
* /** resu lts.a ddEle ment( attr) ; }
* This soft ware cons ists of vo lunta ry c ontri butio ns ma de by man y if ( valu e != null && va lue i nsta nceof Http Sessi onBin ding Liste ner) { * Const ruct a ne w Ses sion assoc iate d wit h the }
* indi vidua ls o n beh alf o f the Apac he S oftwa re Fo undat ion. For more Http Sessi onBin dingE vent e = specifi ed Ma nage r. Enum erat ion n ames = res ults. elem ents( ); }
* info rmati on o n the Apac he So ftwar e Fo undat ion, pleas e see new H ttpSe ssion Bindi ngEv ent(t his, name) ; * whil e (n ames. hasMo reEle ments ()) {
* <htt p://w ww.a pache .org/ >. * @para m ma nager The manag er wi th w hich this Stri ng na me = (Stri ng) n ames .next Eleme nt();
* ((Ht tpSes sionB indin gList ener )valu e).va lueBo und(e ); Session is a ssoc iated remo veAtt ribut e(nam e); /**
* [Add ition al n otice s, if requ ired by p rior licen sing condi tion s] } */ } * Remov e th e obj ect b ound with the speci fied name from this sess ion. If
* pub lic S tand ardSe ssion (Mana ger m anag er) { * the s essi on do es no t hav e an obje ct bo und w ith t his n ame, this meth od
*/ valu es.p ut(na me, v alue) ; // M ark this sessi on as inva lid * does noth ing.
} supe r(); setV alid (fals e); * <p>
this .man ager = man ager; * 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
package org. apac he.to mcat. sessi on; * @depr ecat ed } * <code >val ueUnb ound( )</co de> o n th e obj ect.
*/ *
import org.a pach e.tom cat.c ore.* ; pub lic O bjec t get Value (Stri ng na me) { /** * @para m na me Na me of the objec t to remo ve fr om th is se ssio n.
import org.a pach e.tom cat.u til.S tring Mana ger; retu rn g etAtt ribut e(nam e); // ----- ---- ----- ----- ----- ----- ---- ----- ----- --- * Relea se a ll ob ject refer ences , an d ini tiali ze in stanc e *
import java. io.* ; } ------- Inst ance Vari ables variabl es, i n * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n
import java. net. *; * prepa rati on fo r reu se of this obj ect. * inva lida ted s essio n
import java. util .*; pub lic O bjec t get Attri bute( Strin g na me) { */ *
import javax .ser vlet. *; if ( ! va lid) { /** pub lic v oid recyc le() { * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d by
import javax .ser vlet. http. *; Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); * The c olle ction of u ser d ata a ttri butes * <cod e>re moveA ttrib ute() </cod e>
associa ted w ith this Sessi on. // R eset the insta nce v ariab les assoc iated with this */
/** thro w new Ille galSt ateEx cept ion(m sg); */ Session pub lic v oid remov eValu e(Str ing n ame) {
* Core impl emen tatio n of an ap plica tion leve l ses sion } pri vate Hash table attr ibute s = n ew H ashta ble() ; attr ibut es.cl ear() ;
* crea tion Time = 0L; remo veAt tribu te(na me);
* @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om] if ( name == n ull) { id = nul l;
Sess on n ercep or S andardManager
StandardManager S andardSess onManager
StandardSessionManager
* @aut hor J ason Hunt er [j ch@en g.sun .com ] Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ; /** last Acce ssedT ime = 0L; }
* @aut hor J ames Todd [gon zo@en g.sun .com ] * The t ime this sessi on wa s cre ated , in mana ger = nul l;
*/ thro w new Ille galAr gumen tExc eptio n(msg ); millise conds sin ce mi dnigh t, maxI nact iveIn terva l = - 1;
} * Janua ry 1 , 197 0 GMT . isNe w = true; /**
public class App licat ionSe ssion impl emen ts Ht tpSes sion { */ isVa lid = fal se; * Bind an o bject to t his s essio n, u sing the s pecif ied n ame. If an ob ject
retu rn v alues .get( name) ; pri vate long crea tionT ime = 0L; * of th e sa me na me is alre ady b ound to t his s essio n, th e ob ject is
pri vate Stri ngMan ager sm = } // T ell our M anage r tha t thi s Se ssion has been recyc led * repla ced.
Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" ); if ( (man ager != nu ll) & & (ma nage r ins tance of * <p>
pri vate Hash table valu es = new H asht able( ); /** /** Manager Base) ) * After thi s met hod e xecut es, a nd i f the obje ct im pleme nts
pri vate Stri ng id ; * @depr ecat ed * The s essi on id entif ier o f thi s Se ssion . ((Ma nager Base) mana ger). recy cle(t his); * <code >Htt pSess ionBi nding Liste ner< /code >, th e con taine r ca lls
pri vate Serv erSes sion serve rSess ion; */ */ * <code >val ueBou nd()< /code > on the objec t.
pri vate Cont ext c ontex t; pub lic S trin g[] g etVal ueNam es() { pri vate Stri ng id = nu ll; } *
pri vate long crea tionT ime = Syst em.c urren tTime Milli s();; Enum erat ion e = ge tAttr ibute Name s(); * @para m na me Na me to whic h the obj ect i s bou nd, c annot be null
pri vate long this Acces sTime = cr eati onTim e; Vect or n ames = new Vect or(); * @para m va lue O bject to b e bou nd, canno t be null package org. apac he.to mcat. sessi on; package org. apac he.to mcat. sessi on; // ---- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- Pub lic
pri vate long last Acces sed = crea tion Time; /** // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- Sess ion * // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- - Li fecyc le Me thods Methods
pri vate int inact iveIn terva l = - 1; whil e (e .hasM oreEl ement s()) { * Descr ipti ve in forma tion descr ibin g thi s Package Meth ods * @exce ptio n Ill egalA rgume ntExc epti on if an a ttemp t is made to a dd a import java. io.I OExce ption ;
pri vate bool ean v alid = tru e; name s.add Eleme nt(e. nextE leme nt()) ; Session impl emen tatio n. * non- seri aliza ble o bject in a n en viron ment marke d dis trib utabl e. import java. util .Enum erati on; import java. io.I OExce ption ;
} */ * @exce ptio n Ill egalS tateE xcept ion if th is me thod is ca lled on a n import java. util .Hash table ; /**
import javax .ser vlet. http. Cooki e;
App licat ionS essio n(Str ing i d, Se rver Sessi on se rverS essio n, pri vate stat ic fi nal S tring info = /** * inva lida ted s essio n import java. util .Vect or; * Confi gure this comp onent , bas ed o n the spec ified conf igur ation
/**
Cont ext conte xt) { Stri ng[] valu eName s = n ew St ring [name s.siz e()]; "Standa rdSes sion /1.0" ; * Retur n th e <co de>is Valid </cod e> f lag f or th is se ssion . */ import org.a pach e.tom cat.c atali na.*; * param eter s. T his m ethod shou ld b e cal led i mmedi ately aft er th e import javax .ser vlet. http. HttpS essio n;
this .ser verSe ssion = se rverS essi on; */ pub lic v oid setAt tribu te(St ring name , Obj ect v alue) { import javax .ser vlet. http. Cooki e; * compo nent inst ance is cr eated , an d bef ore < code> start ()</ code> * Mark the speci fied sessi on's last acce ssed time. Thi s sh ould be
import org.a pach e.tom cat.c atali na.*;
this .con text = con text; name s.co pyInt o(val ueNam es); boo lean isVa lid() { import javax .ser vlet. http. HttpS essio n; * is ca lled .
* calle d fo r eac h req uest by a Requ estIn terce ptor.
this .id = id; /** if ( (man ager != nu ll) & & man ager .getD istri butab le() && import org.a pach e.tom cat.u til.S tring Mana ger; * import org.a pach e.tom cat.c ore.C ontex t;
retu rn v alueN ames; * The l ast acces sed t ime f or th is S essio n. retu rn ( this. isVal id); !( valu e ins tance of Se riali zabl e)) import org.w 3c.d om.Na medNo deMap ; * @para m pa ramet ers C onfig urati on p arame ters for t his c ompo nent *
import org.a pach e.tom cat.c ore.R eques t;
this .ina ctive Inter val = cont ext. getSe ssion TimeO ut(); */ thro w new Ille galAr gumen tExc eptio n import org.w 3c.d om.No de; * (<B> FIXM E: Wh at ob ject type shou ld th is re ally be?)
* @para m se ssion The sessi on to be marke d
} pri vate long last Acces sedTi me = crea tionT ime; } (sm.g etStr ing(" stand ardS essio n.set Attri bute. iae" )); * import org.a pach e.tom cat.c ore.R espon se;
if ( this .inac tiveI nterv al != -1) { * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready been */
import org.a pach e.tom cat.c ore.S essio nMan ager;
this .inac tiveI nterv al *= 60; pub lic E nume ratio n get Attri buteN ames () { sync hron ized (attr ibute s) { /** * conf igur ed an d/or start ed
pub lic v oid acces sed(C ontex t ctx , Re quest req, Stri ng id ) {
} if ( ! va lid) { /** /** remo veAtt ribut e(nam e); * Stan dard impl ement ation of t he <b >Man ager< /b> i nterf ace t hat provi des * @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l err or import org.a pach e.tom cat.u til.S essio nUti l;
} Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); * The M anag er wi th wh ich t his S essi on is * Set t he < code> isNew </cod e> fl ag f or th is se ssion . attr ibute s.put (name , val ue); * no s essio n pe rsist ence or di strib utab le ca pabil ities , but doe s sup port * in t he c onfig urati on pa ramet ers it wa s giv en Http Sess ion s essio n=fin dSess ion( ctx, id);
associa ted. * if ( value inst anceo f Htt pSes sionB indin gList ener) * an o ption al, confi gurab le, m aximu m nu mber of ac tive sessi ons allow ed. */
if( sess ion = = nul l) re turn;
Ser verSe ssio n get Serve rSess ion() { thro w new Ille galSt ateEx cept ion(m sg); */ * @para m is New T he ne w val ue fo r th e <co de>is New</ code> ((Htt pSess ionBi nding List ener) valu e).va lueBo und * <p> pub lic v oid confi gure( Node param eter s)
retu rn s erver Sessi on; } pri vate Mana ger m anage r = n ull; flag ( new H ttpSe ssion Bind ingEv ent(( HttpS essio n) t his, name) ); * Life cycle con figur ation of t his c ompo nent assum es an XML node thro ws L ifecy cleEx cepti on { if ( sess ion i nstan ceof Sessi on)
/**
} */ } * in t he fo llow ing f ormat :
((Se ssion ) ses sion) .acce ss() ;
Hash tabl e val uesCl one = (Has htab le)va lues. clone (); voi d set New( boole an is New) { * <cod e> // V alid ate a nd up date our c urre nt co mpone nt st ate * Spec ializ ed i mplem entat ion o f org .apa che.t omcat .core .Sess ionM anage r
/** /** } * <M anag er cl assNa me="o rg.ap ache .tomc at.se ssion .Stan dard Manag er" if ( conf igure d)
* that adap ts t o the new compo nent- base d Man ager imple menta tion .
* Calle d by cont ext w hen r eques t co mes i n so that acces ses and retu rn ( Enume ratio n)val uesCl one. keys( ); * The m axim um ti me in terva l, in sec onds, betw een this .isN ew = isNew ; * check Inter val=" 60" m axAc tiveS essio ns="- 1" thro w new Life cycle Excep tion
// c ache the HttpS essio n - a void anot her f ind
* inact ivit ies c an be deal t wit h ac cordi ngly. } client reque sts befor e * maxIn activ eInte rval= "-1" /> (sm.g etStr ing(" stand ardM anage r.alr eadyC onfig ured ")); * <p>
*/ * the s ervl et co ntain er ma y inv alid ate t his } // ----- ---- ----- ----- ----- ----- ---- ----- ----- - Htt pSess ion Priva te Me thods * </co de> conf igur ed = true; req. setS essio n( se ssion );
* XXX - At pres ent, use o f <co de>St anda rdMan ager< /code > is hard code d,
session . A nega tive time * wher e you can adju st th e fol lowin g pa ramet ers, with defau lt v alues if ( para meter s == null)
}
voi d acc esse d() { /** * indic ates that the sessi on sh ould neve r tim e * in s quare bra ckets : retu rn; * and lifec ycle conf igura tion is no t su pport ed.
// s et l ast a ccess ed to this Acce ssTim e as it wi ll be lef t ove r * @depr ecat ed out. /** /** * <ul>
* <p>
// f rom the p revio us ac cess */ */ * Set t he < code> isVal id</c ode> flag for this sessi on. * Read a se riali zed v ersio n of this sess ion o bject from the spec ified * <li> <b>ch eckI nterv al</b > - T he in terv al (i n sec onds) betw een backg round // P arse and proce ss ou r con figu ratio n par amete rs
// XXX s houl d we throw exce ption or just retur n nul l ??
last Acce ssed = thi sAcce ssTim e; pri vate int maxIn activ eInte rval = -1 ; * * objec t in put s tream . * threa d ch ecks for e xpire d ses sion s. [ 60] if ( !("M anage r".eq uals( param eter s.get NodeN ame() ))) * <b>I MPLEM ENTA TION NOTE< /b>: Once we commi t to the n ew
this Acce ssTim e = S ystem .curr entT imeMi llis( ); pub lic v oid remov eValu e(Str ing n ame) { * @para m is Valid The new v alue for the * <p> * <li> <b>ma xAct iveSe ssion s</b> - Th e ma ximum numb er of sess ions allo wed t o retu rn; Manager /Sess ion pub lic H ttpS essio n fin dSess ion( Cont ext c tx, S tring id ) {
remo veAt tribu te(na me); <code>i sVali d</c ode> flag * <b>IM PLEM ENTAT ION N OTE</ b>: The refer ence to th e own ing Manag er * be ac tive at o nce, or -1 for no l imit. [-1 ] Name dNod eMap attri butes = pa rame ters. getAt tribu tes() ;
* para digm, I w ould sugge st mo ving the logic impl ement ed he re b ack i nto try {
vali date (); } /** */ * is no t re store d by this metho d, a nd mu st be set expli citl y. * <li> <b>ma xIna ctive Inter val</ b> - The defau lt ma ximum numb er o f sec onds of Node nod e = n ull;
} * Flag indi catin g whe ther this sess ion i s new or voi d set Vali d(boo lean isVal id) { * * inact ivit y bef ore w hich the s ervl et co ntain er is allo wed to ti me ou t * the core leve l. T he To mcat. Next "Man ager" inte rface acts mor e lik e a Sess ion s essio n = m anage r.fi ndSes sion( id);
pub lic v oid remov eAttr ibute (Stri ng n ame) { not. * @para m st ream The i nput strea m to read from * a ses sion , or -1 fo r no limit . T his v alue shoul d be over ridde n fro m node = a ttrib utes. getNa medIt em(" check Inter val") ;
* coll ectio n cl ass, and h as mi nimal kno wledg e of the d etail ed r eques t if(s essio n!=nu ll)
voi d val idat e() { if ( ! va lid) { */ this .isV alid = isV alid; * * the d efau lt se ssion time out s peci fied in th e web appl icat ion d eploy ment if ( node != n ull) {
// i f we have an i nacti ve in terv al, c heck to se e if we'v e exc eeded it Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); pri vate bool ean i sNew = tru e; } * @exce ptio n Cla ssNot Found Excep tion if a n unk nown class is speci fied * descr ipto r, if any. [-1 ] try { * proc essin g se manti cs of hand ling sess ions. retur n ses sion. getSe ssio n();
if ( inac tiveI nterv al != -1) { * @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s * </ul > setCh eckIn terva l(Int eger .pars eInt( node. getNo deVa lue() ));
* <p> } ca tch (IOEx cepti on e) {
int thisI nterv al = thro w new Ille galSt ateEx cept ion(m sg); */ * } ca tch ( Throw able t) {
(int) (Syst em.cu rrent Time Milli s() - last Acces sed) / 10 00; } /** // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- - pri vate void read Objec t(Obj ectIn putS tream stre am) * @aut hor C raig R. M cClan ahan ; // XXX - Thr ow e xcept ion? * XXX - At pres ent, there is n o way (vi a the Sess ionMa nager int erfac e) }
* Flag indi catin g whe ther this sess ion i s val id HttpSes sion Prop ertie s thro ws C lassN otFou ndExc eptio n, I OExce ption { * @ver sion $Rev ision : 1.1 .1.1 $ $Da te: 2000/ 05/02 21:2 8:30 $ } for
retu rn ( null) ;
if ( thisI nterv al > inact iveI nterv al) { if ( name == n ull) { or not. */ }
* a Co ntext to tell the M anage r tha t we crea te wh at th e def ault sess ion
inval idate (); Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.va lue. iae") ; */ // D eser ializ e the scal ar in stan ce va riabl es (e xcept Man ager) }
} pri vate bool ean i sVali d = f alse; /** crea tion Time = ((L ong) strea m.re adObj ect() ).lon gValu e(); public final cla ss St andar dMana ger node = a ttrib utes. getNa medIt em(" maxAc tiveS essio ns"); * time out f or t his w eb ap plica tion (spe cifie d in the d eploy ment
} thro w new Ille galAr gumen tExc eptio n(msg ); * Retur n th e tim e whe n thi s ses sion was creat ed, i n id = (St ring) stre am.re adObj ect( ); ext ends Mana gerBa se if ( node != n ull) { descrip tor)
} } millise conds sin ce last Acce ssedT ime = ((Lo ng) s trea m.rea dObje ct()) .long Valu e(); imp lemen ts L ifecy cle, Runna ble { try { pub lic H ttpS essio n cre ateSe ssion (Con text ctx) {
* shou ld be .
/** * midni ght, Janu ary 1 , 197 0 GMT . maxI nact iveIn terva l = ( (Inte ger) stre am.re adObj ect() ).in tValu e(); setMa xActi veSes sions (Int eger. parse Int(n ode.g etNo deVal ue()) );
retu rn manag er.cr eateS essio n(). getSe ssion ();
// HTTP SESS ION I MPLEM ENTAT ION M ETHO DS Obje ct o = va lues. get(n ame); * The s trin g man ager for t his p acka ge. * isNe w = ((Boo lean) stre am.re adOb ject( )).bo olean Value (); } ca tch ( Throw able t) { *
*/ * @exce ptio n Ill egalS tateE xcept ion if th is me thod is isVa lid = ((B oolea n) st ream. read Objec t()). boole anVal ue() ; // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- Ins tance Vari ables ; // XXX - Thr ow e xcept ion? }
* @aut hor C raig R. M cClan ahan
pub lic S trin g get Id() { if ( o in stanc eof H ttpSe ssion Bind ingLi stene r) { pri vate Stri ngMan ager sm = called on an }
if ( vali d) { Http Sessi onBin dingE vent e = * inva lida ted s essio n // D eser ializ e the attr ibute cou nt an d att ribut e val ues } */
retu rn id ; new H ttpSe ssion Bindi ngEv ent(t his,n ame); StringM anage r.ge tMana ger(" org.a pache .tom cat.s essio n") */ int n = ((Int eger) stre am.re adOb ject( )).in tValu e(); /** /**
} el se { ; pub lic l ong getCr eatio nTime () { for (int i = 0; i < n; i++) { * The i nter val ( in se conds ) bet ween chec ks fo r exp ired sess ions. node = a ttrib utes. getNa medIt em(" maxIn activ eInte rval" );
* Remov e al l ses sions beca use o ur a ssoci ated Conte xt is bei ng sh ut
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); ((Ht tpSes sionB indin gList ener )o).v alueU nboun d(e); Stri ng na me = (Stri ng) s trea m.rea dObje ct(); */ if ( node != n ull) { public final cla ss St andar dSess ionMa nage r
down.
} retu rn ( this. creat ionTi me); Obje ct va lue = (Obj ect) stre am.re adObj ect() ; pri vate int check Inter val = 60; try {
imp lemen ts S essio nMana ger {
thro w new Ille galSt ateEx cept ion(m sg); /** attr ibute s.put (name , val ue); setMa xInac tiveI nterv al(I ntege r.par seInt (node .get NodeV alue( ))); *
} valu es.r emove (name ); * The H TTP sessi on co ntext asso ciat ed wi th th is } } } ca tch ( Throw able t) {
* @para m ct x The cont ext t hat i s be ing s hut d own
} } session . /** ; // XXX - Thr ow e xcept ion?
*/ } * Has t his compo nent been confi gure d yet ? } */
pub lic l ong getCr eatio nTime () { pub lic v oid setMa xInac tiveI nterv al(i nt in terva l) { pri vate stat ic Ht tpSes sionC ontex t se ssion Conte xt /** */ } // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- --
pub lic v oid remov eSess ions( Conte xt c tx) {
if ( vali d) { if ( ! va lid) { = null; * Retur n th e ses sion conte xt wi th w hich this sessi on is pri vate bool ean c onfig ured = fal se; Constru ctors
retu rn cr eatio nTime ; Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); associa ted. /** }
} el se { * * Write a s erial ized versi on of thi s ses sion objec t to the speci fied // X XX X XX a manag er ma y be shar ed by mult iple
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); /** * @depr ecat ed As of V ersio n 2.1 , th is me thod is de preca ted * objec t ou tput strea m. /**
} * The c urre nt ac cesse d tim e for thi s ses sion. and has no * <p> * The d escr iptiv e inf ormat ion a bout this impl ement ation . // c onte xts, we ju st wa nt to rem ove t he se ssion s of ctx!
/**
thro w new Ille galSt ateEx cept ion(m sg); */ * repl acem ent. It w ill b e rem oved in a futu re ve rsion of * <b>IM PLEM ENTAT ION N OTE</ b>: The ownin g Man ager will not be st ored */
// T he m anage r wil l sti ll ru n af ter t hat ( i.e. keep dat abase
} inac tive Inter val = inte rval; pri vate long this Acces sedTi me = crea tionT ime; the * in th e se riali zed r epres entat ion of th is Se ssion . Af ter calli ng pri vate stat ic fi nal S tring info = " Stand ardMa nager /1.0" ; /** * Creat e a new S essio nMana ger t hat adapt s to the c orres pond ing
} } * Java Ser vlet API. * <code >rea dObje ct()< /code >, yo u mu st se t the asso ciate d Ma nager * Prepa re f or th e beg innin g of acti ve us e of the p ublic met hods of th is Manager // c onne ction open
*/ * expli citl y. * compo nent . Th is me thod shoul d be call ed af ter < code> conf igure ()</c ode>,
* imple ment ation . if ( mana ger i nstan ceof Lifec ycle ) {
/** pub lic i nt g etMax Inact iveIn terva l() { pub lic H ttpS essio nCont ext g etSes sion Conte xt() { * <p> /** * and b efor e any of t he pu blic meth ods o f the comp onent are util ized.
* if ( ! va lid) { * <b>IM PLEM ENTAT ION N OTE</ b>: Any attri bute that is no t Se riali zable * The m axim um nu mber of ac tive Sess ions allow ed, o r -1 for no li mit. * */ try {
* @depr ecat ed Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); // ----- ---- ----- ----- ----- ----- ---- ----- ----- --- if ( sess ionCo ntext == n ull) * will be s ilent ly ig nored . If you do n ot wa nt an y suc h at tribu tes, */ * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s no t yet been
pub lic S tand ardSe ssion Manag er() { ((Lif ecycl e) ma nager ).st op();
*/ ------- Sess ion Prope rties sess ionCo ntext = ne w Sta ndar dSess ionCo ntext (); * be su re t he <c ode>d istri butab le</ code> prop erty of ou r as socia ted pro tecte d in t max Activ eSess ions = -1 ; * conf igur ed (i f req uired for this comp onent )
thro w new Ille galSt ateEx cept ion(m sg); retu rn ( sessi onCon text) ; * Manag er i s set to < code> true< /cod e>. * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready been } ca tch ( Lifec ycleE xcept ion e) {
pub lic H ttpS essio nCont ext g etSes sion Conte xt() { } * * star ted
mana ger = new Stan dardM anage r(); throw new Illeg alSta teEx cepti on("" + e) ;
retu rn n ew Se ssion Conte xtImp l(); /** } * @para m st ream The o utput stre am t o wri te to /** * @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l err or
} retu rn i nacti veInt erval ; * Set t he c reati on ti me fo r thi s se ssion . Th is * * The s trin g man ager for t his p acka ge. * that pre vents this comp onent fro m bei ng us ed if ( mana ger i nstan ceof Lifec ycle ) { }
} method is ca lled by t he * @exce ptio n IOE xcept ion i f an inpu t/out put e rror occur s */ */
try { }
pub lic l ong getLa stAcc essed Time( ) { } * Manag er w hen a n exi sting Sess ion insta nce i s // ----- ---- ----- ----- ----- ----- ---- ----- ----- --- */ pri vate Stri ngMan ager sm = pub lic v oid start () th rows Lifec ycle Excep tion {
if ( vali d) { reused. HttpSes sion Publ ic Me thods pri vate void writ eObje ct(Ob jectO utpu tStre am st ream) thro ws I OExce ption { Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" ); ((Lif ecycl e) ma nager ).co nfigu re(nu ll);
retu rn la stAcc essed ; * // V alid ate a nd up date our c urre nt co mpone nt st ate
((Lif ecycl e) ma nager ).st art() ; }
} el se { //----- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- ----- ---- * @para m ti me Th e new crea tion time // W rite the scala r ins tance var iable s (ex cept Manag er) if ( !con figur ed)
Stri ng ms g = s m.get Strin g("a pplic ation Sessi on.se ssio n.ise "); */ /** stre am.w riteO bject (new Long( crea tionT ime)) ; /** thro w new Life cycle Excep tion } ca tch ( Lifec ycleE xcept ion e) {
pub lic v oid setCr eatio nTime (long tim e) { * Retur n th e obj ect b ound with the speci fied name in th is stre am.w riteO bject (id); * Has t his compo nent been start ed y et? (sm.g etStr ing(" stand ardM anage r.not Confi gured "));
throw new Illeg alSta teEx cepti on("" + e) ; /**
thro w new Ille galSt ateEx cept ion(m sg); session , or stre am.w riteO bject (new Long( last Acces sedTi me)); */ if ( star ted)
} this .cre ation Time = tim e; * <code >nul l</co de> i f no objec t is boun d wit h tha t nam e. stre am.w riteO bject (new Integ er(m axIna ctive Inter val)) ; pri vate bool ean s tarte d = f alse; thro w new Life cycle Excep tion } * Used by c ontex t to confi gure the sessi on ma nager 's in acti vity
} this .las tAcce ssedT ime = time ; * stre am.w riteO bject (new Boole an(i sNew) ); (sm.g etStr ing(" stand ardM anage r.alr eadyS tarte d")) ; timeout .
}
this .thi sAcce ssedT ime = time ; * @para m na me Na me of the attri bute to b e ret urned stre am.w riteO bject (new Boole an(i sVali d)); star ted = tru e;
*
* /**
} * @exce ptio n Ill egalS tateE xcept ion if th is me thod is // A ccum ulate the names of s eria lizab le at tribu tes * The b ackg round thre ad. // S tart the backg round reap er t hread * The S essi onMan ager may h ave s ome defau lt se ssion time out , the
}
called on an Vect or r esult s = n ew Ve ctor( ); */ thre adSt art() ;
* Conte xt o n the othe r han d has it' s tim eout set b y the dep loyme nt
* inva lida ted s essio n Enum erat ion a ttrs = get Attri bute Names (); pri vate Thre ad th read = nul l;
/** */ whil e (a ttrs. hasMo reEle ments ()) { } * descr ipto r (we b.xml ). Th is me thod lets the Conte xt co nfor gure the
* Retur n th e ses sion ident ifier for this pub lic O bjec t get Attri bute( Strin g na me) { Stri ng at tr = (Stri ng) a ttrs .next Eleme nt();
* sessi on m anage r acc ordin g to this valu e.
session . Obje ct va lue = attr ibute s.ge t(att r); /** // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- Ins tance
*/ retu rn ( attri butes .get( name) ); if ( value inst anceo f Ser iali zable ) * The b ackg round thre ad co mplet ion semap hore. /** Variabl es *
pub lic S trin g get Id() { resul ts.ad dElem ent(a ttr) ; */ * Grace full y ter minat e the acti ve u se of the publi c met hods of t his
* @para m mi nutes The sessi on in acti vity timeo ut in minu tes.
} } pri vate bool ean t hread Done = fal se; * compo nent . Th is me thod shoul d be the last one c alled on a giv en
retu rn ( this. id); * insta nce of th is co mpone nt. */
// S eria lize the a ttrib ute c ount and the attri bute valu es *
/** pub lic v oid setSe ssion TimeO ut(in t mi nutes ) {
} /** stre am.w riteO bject (new Integ er(r esult s.siz e())) ; /** * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s no t bee n sta rted
* Retur n an <cod e>Enu merat ion</ code > of Enum erat ion n ames = res ults. elem ents( ); * Name to r egist er fo r the back grou nd th read. * @exce ptio n Ill egalS tateE xcept ion if th is co mpone nt ha s al ready * The M anag er im pleme ntati on we are actu ally using . if(- 1 != minu tes) {
<code>S tring </co de> o bject s whil e (n ames. hasMo reEle ments ()) { */ * been sto pped
*/ // T he ma nager work s wit h se conds ...
/** * conta inin g the name s of the o bjec ts bo und t o thi s Stri ng na me = (Stri ng) n ames .next Eleme nt(); pri vate Stri ng th readN ame = "Sta ndar dMana ger"; * @exce ptio n Lif ecycl eExce ption if this compo nent detec ts a fata l err or
* Set t he s essio n ide ntifi er fo r th is se ssion . session . stre am.wr iteOb ject( name) ; * that nee ds to be r eport ed pri vate Mana ger m anage r = n ull; mana ger.s etMax Inact iveIn terv al(mi nutes * 60 );
* * stre am.wr iteOb ject( attri bute s.get (name )); */
}
* @para m id The new s essio n ide ntif ier * @exce ptio n Ill egalS tateE xcept ion if th is me thod is } // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- ---- Prope rties pub lic v oid stop( ) thr ows L ifecy cleE xcept ion {
*/ called on an }
pub lic v oid setId (Stri ng id ) { * inva lida ted s essio n // V alid ate a nd up date our c urre nt co mpone nt st ate
}
*/ } /** if ( !sta rted)
if ( (thi s.id != nu ll) & & (ma nage r != null) && pub lic E nume ratio n get Attri buteN ames () { * Retur n th e che ck in terva l (in sec onds) for this Manag er. thro w new Life cycle Excep tion
(m anag er in stanc eof M anage rBas e)) cro sscut inv alida te(St andar dSess ion s): s & (i nt ge tMaxI nact iveIn terva l() | */ (sm.g etStr ing(" stand ardM anage r.not Start ed")) ;
((Ma nager Base) mana ger). remo ve(th is); retu rn ( attri butes .keys ()); l ong g etCre atio nTime () | pub lic i nt g etChe ckInt erval () { star ted = fal se;
O bject getA ttri bute( Strin g) |
this .id = id; } E numer ation get Attri buteN ames( ) | retu rn ( this. check Inter val); // S top the b ackgr ound reape r th read
S tring [] ge tVal ueNam es() | thre adSt op();
ServerSess on
if ( (man ager != nu ll) & & (ma nage r ins tance of v oid i nvali date () | }
Manager Base) ) /** b oolea n isN ew() | // E xpir e all acti ve se ssion s
((Ma nager Base) mana ger). add( this) ; * Retur n th e obj ect b ound with the speci fied name in th is v oid r emove Attr ibute (Stri ng) | Sess ion sessi ons[] = fi ndSes sion s();
session , or v oid s etAtt ribu te(St ring, Obje ct)); /** for (int i = 0; i < ses sions .len gth; i++) {
} * <code >nul l</co de> i f no objec t is boun d wit h tha t nam e. * Set t he c heck inter val ( in se cond s) fo r thi s Man ager. Stan dardS essio n ses sion = (S tanda rdSes sion) sess ions [i];
* sta tic a dvic e(Sta ndard Sessi on s) : in valid ate(s ) { * if ( !sess ion.i sVali d())
* @para m na me Na me of the value to be re turne d befo re { * @para m ch eckIn terva l The new chec k int erval conti nue;
/** * if ( !s.is Valid ()) */ sess ion.e xpire ();
* Retur n de scrip tive infor matio n ab out t his * @exce ptio n Ill egalS tateE xcept ion if th is me thod is throw new Illeg alSta teEx cepti on pub lic v oid setCh eckIn terva l(int che ckInt erval ) { }
Session impl emen tatio n and called on an ( s.sm. getSt ring( "sta ndard Sessi on."
ServerSessionManager
ServerSess onManager
* the c orre spond ing v ersio n num ber, in t he * inva lida ted s essio n + th isJoi nPoin t.met hodNa me this .che ckInt erval = ch eckIn terv al; }
format * + ". ise") );
* * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d } }
<code>& lt;de scri ption >/ <v ersio n> ;</co de>. by } // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- --- Priva te Me thods
*/ * <cod e>ge tAttr ibute ()</c ode>
pub lic S trin g get Info( ) { */ /**
pub lic O bjec t get Value (Stri ng na me) { * Retur n de scrip tive infor matio n ab out t his M anage r imp leme ntati on an d /**
retu rn ( this. info) ; * the c orre spond ing v ersio n num ber, in t he fo rmat * Inval idat e all sess ions that have expi red.
retu rn ( getAt tribu te(na me)); } * <code >< ;desc ripti on> ;/< ;ver sion& gt;</ code> . */
} */ pri vate void proc essEx pires () {
} pub lic S trin g get Info( ) {
// ---- ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- - Pri vate Class long tim eNow = Sys tem.c urren tTim eMill is();
/** retu rn ( this. info) ; Sess ion sessi ons[] = fi ndSes sion s();
* Retur n th e las t tim e the clie nt s ent a requ est /**
associa ted w ith this * Retur n th e set of n ames of ob ject s bou nd to this /** package org. apac he.to mcat. sessi on; } for (int i = 0; i < ses sions .len gth; i++) {
* sessi on, as th e num ber o f mil lise conds sinc e session . If the re * This clas s is a du mmy i mplem entat ion of th e <co de>Ht tpSes sion Conte xt</c ode> Stan dardS essio n ses sion = (S tanda rdSes sion) sess ions [i];
midnigh t, Ja nuar y 1, 1970 * are n o su ch ob jects , a z ero-l engt h arr ay is retu rned. * inte rface , to conf orm t o the requ irem ent t hat s uch a n obj ect be re turne d import org.a pach e.tom cat.u til.* ; if ( !sess ion.i sVali d())
* GMT. Act ions that your appli cati on ta kes, * * when <cod e>Ht tpSes sion. getSe ssion Cont ext() </cod e> is call ed. import org.a pach e.tom cat.c ore.* ; /** conti nue;
such as gett ing or se tting * @exce ptio n Ill egalS tateE xcept ion if th is me thod is * import java. io.* ; * Retur n th e max imum numbe r of acti ve Se ssion s all owed, or -1 fo r int maxIn activ eInte rval = se ssion .getM axIna ctive Inte rval( );
* a val ue a ssoci ated with the s essi on, d o not called on an * @aut hor C raig R. M cClan ahan import java. net. *; * no li mit. if ( maxIn activ eInte rval < 0)
affect the a cces s tim e. * inva lida ted s essio n * import java. util .*; */ conti nue;
*/ * * @dep recat ed A s of Java Servl et AP I 2. 1 wit h no repla cemen t. The import javax .ser vlet. http. *; pub lic i nt g etMax Activ eSess ions( ) { int timeI dle = // T runca te, do no t rou nd up
pub lic l ong getLa stAcc essed Time( ) { * @depr ecat ed As of V ersio n 2.2 , th is me thod is re place d * int erfac e wi ll be remo ved i n a f utur e ver sion of th is AP I. (int) ((ti meNow - se ssio n.get LastA ccess edTim e()) / 10 00L);
by */ /** retu rn ( this. maxAc tiveS essio ns); if ( timeI dle > = max Inact iveI nterv al)
retu rn ( this. lastA ccess edTim e); * <cod e>ge tAttr ibute Names ()</c ode> * sessi on.ex pire( );
*/ final c lass Stan dardS essio nCont ext i mple ments Http Sessi onCon text { * @aut hor J ames Dunc an Da vidso n [du ncan @eng. sun.c om] } }
} pub lic S trin g[] g etVal ueNam es() { * @aut hor J ason Hunt er [j ch@en g.sun .com ] }
* @aut hor J ames Todd [gon zo@en g.sun .com ]
Vect or r esult s = n ew Ve ctor( ); pri vate Vect or du mmy = new Vecto r(); */ /**
/** Enum erat ion a ttrs = get Attri bute Names (); * Set t he m aximu m num ber o f act ives Sess ions allow ed, o r -1 for /**
* Retur n th e Man ager withi n whi ch t his S essio n whil e (a ttrs. hasMo reEle ments ()) { /** public class Ser verSe ssion Manag er im plem ents Sessi onMan ager { * no li mit. * Sleep for the durat ion s pecif ied by th e <co de>ch eckIn terv al</c ode>
is vali d. Stri ng at tr = (Stri ng) a ttrs .next Eleme nt(); * Retur n th e ses sion ident ifier s of all sessi ons d efine d * * prope rty.
*/ resu lts.a ddEle ment( attr) ; * withi n th is co ntext . pri vate Stri ngMan ager sm = * @para m ma x The new maxim um nu mber of s essio ns */
pub lic M anag er ge tMana ger() { } * Stri ngMa nager .getM anage r("or g.ap ache. tomca t.ses sion" ); */ pri vate void thre adSle ep() {
Stri ng n ames[ ] = n ew St ring[ resu lts.s ize() ]; * @depr ecat ed As of J ava S ervle t AP I 2.1 with no r eplac emen t. pri vate stat ic Se rverS essio nMana ger manag er; / / = n ew Se rver Sessi onMan ager( ); pub lic v oid setMa xActi veSes sions (int max) {
retu rn ( this. manag er); for (int i = 0; i < nam es.le ngth ; i++ ) * This met hod m ust r eturn an e mpty <cod e>Enu merat ion</ code > try {
name s[i] = (St ring) resu lts. eleme ntAt( i); * and will be r emove d in a fut ure versi on of the API. pro tecte d in t ina ctive Inter val = -1; this .max Activ eSess ions = max ; Thre ad.sl eep(c heckI nterv al * 1000 L);
} retu rn ( names ); */ } ca tch (Inte rrupt edExc eptio n e) {
pub lic E nume ratio n get Ids() { sta tic { } ;
} mana ger = new Serv erSes sionM anag er(); }
/** retu rn ( dummy .elem ents( )); }
* Set t he M anage r wit hin w hich this Sess ion i s // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- ---- Publ ic Me thods }
valid. /** } pub lic s tati c Ser verSe ssion Manag er g etMan ager( ) {
* * Inval idat es th is se ssion and unbi nds a ny ob jects boun d retu rn m anage r;
* @para m ma nager The new M anage r to it. } /** /**
*/ * /** * Const ruct and retur n a n ew se ssio n obj ect, based on t he d efaul t * Start the back groun d thr ead t hat will perio dical ly ch eck for
pub lic v oid setMa nager (Mana ger m anag er) { * @exce ptio n Ill egalS tateE xcept ion if th is me thod is * Retur n th e <co de>Ht tpSes sion< /cod e> as socia ted w ith t he pri vate Hash table sess ions = new Has htabl e(); * setti ngs speci fied by th is Ma nage r's p roper ties. The ses sion * sessi on t imeou ts.
called on * speci fied sess ion i denti fier. pri vate Reap er re aper; * id wi ll b e ass igned by t his m etho d, an d ava ilabl e via the getI d() */
this .man ager = man ager; * an i nval idate d ses sion * * metho d of the retur ned s essio n. If a new s essio n can not be cr eated pri vate void thre adSta rt() {
*/ * @para m id Sess ion i denti fier for which to l ook u p a s essi on pri vate Serv erSes sionM anage r() { * for a ny r eason , ret urn < code> null </cod e>.
} pub lic v oid inval idate () { * reap er = Reap er.ge tReap * if ( thre ad != null )
* @depr ecat ed As of J ava S ervle t AP I 2.1 with no r eplac emen t. * @exce ptio n Ill egalS tateE xcept ion if a new s essio n can not be retu rn;
// C ause this sess ion t o exp ire * This met hod m ust r eturn null and will be r emove d in a * inst anti ated for a ny re ason
/** expi re() ; * futu re v ersio n of the A PI. */ thre adDo ne = false ;
* Retur n th e max imum time inter val, in s econd s, */ pub lic S essi on cr eateS essio n() { thre ad = new Threa d(thi s, th read Name) ;
between clie nt r eques ts } pub lic H ttpS essio n get Sessi on(St ring id) { thre ad.s etDae mon(t rue);
* befor e th e ser vlet conta iner will inva lidat e if ( (max Activ eSess ions >= 0) && thre ad.s tart( );
the ses sion. A negat ive retu rn ( null) ; (s essi ons.s ize() >= m axAct iveS essio ns))
* time indi cates that the sessi on s hould neve r /** thro w new Ille galSt ateEx cept ion }
time ou t. * Retur n <c ode>t rue</ code> if t he c lient does not yet k now } (sm.g etStr ing(" stand ardM anage r.cre ateSe ssion .ise "));
* about t he
* @exce ptio n Ill egalS tateE xcept ion if th is * sessi on, or if the clien t cho oses not to jo in th e } retu rn ( super .crea teSes sion( )); /**
method is ca lled on session . Fo r * Stop the backg round thre ad th at i s per iodic ally check ing for
* an i nval idate d ses sion * examp le, if th e ser ver u sed o nly cooki e-bas ed se ssion s, } * sessi on t imeou ts.
*/ and the clie nt */
pub lic i nt g etMax Inact iveIn terva l() { * has d isab led t he us e of cooki es, then a ses sion would be pri vate void thre adSto p() {
new on each
retu rn ( this. maxIn activ eInte rval ); * reque st. if ( thre ad == null )
* retu rn;
} * @exce ptio n Ill egalS tateE xcept ion if th is me thod is
called on an thre adDo ne = true;
* inva lida ted s essio n thre ad.i nterr upt() ;
/** */ try {
* Set t he m aximu m tim e int erval , in seco nds, pub lic b oole an is New() { thre ad.jo in();
between clie nt r eques ts } ca tch (Inte rrupt edExc eptio n e) {
* befor e th e ser vlet conta iner will inva lidat e retu rn ( this. isNew ); ;
the ses sion. A negat ive }
* time indi cates that the sessi on s hould neve r }
time ou t. thre ad = null ;
*
* @para m in terva l The new maxim um i nterv al }
*/
pub lic v oid setMa xInac tiveI nterv al(i nt in terva l)
{ // ----- ---- ----- ----- ----- ----- ---- ----- ----- ----- ----- - Ba ckgro und T hread
this .max Inact iveIn terva l = i nter val;
/**
} * The b ackg round thre ad th at ch ecks for sessi on ti meout s an d shu tdown .
*/
pub lic v oid run() {
// L oop until the termi natio n se mapho re is set
whil e (! threa dDone ) {
thre adSle ep();
proc essEx pires ();
1/4/2005 ל"ר ברק שהם ז"יום עיון לזכרו של ד 20
}
}
}
פיתוח מונחה אספקטים
פיתוח תוכנה שמתייחס למספר עניינים נחתכים.
אספקט – סוג חדש של מודול לטיפול בעניין נחתך.
נקודות מפגש – מקומות בזרימת התוכנית שבהם
רוצים להוסיף התנהגויות )(Join Point
עיצה – קוד שצריך להתבצע לפני/אחרי/במקום
נקודת המפגש )(Advice
מציין נקודת חיתוך – מתאר משפחה של נקודות
מפגש )(Pointcut designator
אריגה – תהליך השילוב בין מודולי הליבה
לאספקטים, ליצירת המערכת העובדת.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 12
תכנות מונחה אספקטים
מספר גישות שונות, ושפות תכנות חלופיות.
השפה הבשלה ביותר – , AspectJהרחבה של
ג'אווה.
פעילות מחקרית נרחבת.
יישומים, גם בתעשייה.
כנסים, עיתונים, ...
פעילות בישראל.
5002/4/1 ל"ר ברק שהם ז"יום עיון לזכרו של ד 22
Get documents about "