304. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 12/5/2017 12:06:46 PM Central Standard Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

304.1 Files compared

# Location File Last Modified
1 IV-eHMP_CIF.zip\IMAG_Source\VISA\Java\ImagingVistaRealm\main\src\java\gov\va\med\imaging\tomcat\vistarealm AbstractVistaRealmImpl.java Mon Dec 4 21:35:12 2017 UTC
2 IV-eHMP_CIF.zip\IMAG_Source\VISA\Java\ImagingVistaRealm\main\src\java\gov\va\med\imaging\tomcat\vistarealm AbstractVistaRealmImpl.java Tue Dec 5 13:23:32 2017 UTC

304.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 4 3454
Changed 3 6
Inserted 0 0
Removed 0 0

304.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

304.4 Active regular expressions

No regular expressions were active.

304.5 Comparison detail

  1   package go v.va.med.i maging.tom cat.vistar ealm;
  2  
  3   import jav a.beans.Pr opertyChan geEvent;
  4   import jav a.beans.Pr opertyChan geListener ;
  5   import jav a.io.IOExc eption;
  6   import jav a.lang.man agement.Ma nagementFa ctory;
  7   import jav a.security .Principal ;
  8   import jav a.util.Arr ayList;
  9   import jav a.util.Col lection;
  10   import jav a.util.Col lections;
  11   import jav a.util.Has hMap;
  12   import jav a.util.Has htable;
  13   import jav a.util.Ite rator;
  14   import jav a.util.Lis t;
  15   import jav a.util.Map ;
  16  
  17   import jav ax.managem ent.Instan ceAlreadyE xistsExcep tion;
  18   import jav ax.managem ent.Instan ceNotFound Exception;
  19   import jav ax.managem ent.MBeanR egistratio nException ;
  20   import jav ax.managem ent.MBeanS erver;
  21   import jav ax.managem ent.Malfor medObjectN ameExcepti on;
  22   import jav ax.managem ent.NotCom pliantMBea nException ;
  23   import jav ax.managem ent.Object Instance;
  24   import jav ax.managem ent.Object Name;
  25  
  26   import org .apache.ca talina.Wra pper;
  27   import org .apache.ca talina.Con tainer;
  28   import org .apache.ca talina.Con text;
  29   import org .apache.ca talina.Lif ecycle;
  30   import org .apache.ca talina.Lif ecycleEven t;
  31   import org .apache.ca talina.Lif ecycleExce ption;
  32   import org .apache.ca talina.Lif ecycleList ener;
  33   import org .apache.ca talina.Rea lm;
  34   import org .apache.ca talina.con nector.Req uest;
  35   import org .apache.ca talina.con nector.Res ponse;
  36   import org .apache.to mcat.util. descriptor .web.Login Config;
  37   import org .apache.to mcat.util. descriptor .web.Secur ityCollect ion;
  38   import org .apache.to mcat.util. descriptor .web.Secur ityConstra int;
  39   import org .apache.ca talina.rea lm.Constan ts;
  40   import org .apache.lo gging.log4 j.LogManag er;
  41   import org .apache.lo gging.log4 j.Logger;
  42  
  43   /*
  44    * This cl ass implem ents all o f the REal m methods  except the  authentic ate method s.
  45    * the aut henticate  methods ar e implemen ted by the  derived c lasses.
  46    */
  47   public abs tract clas s Abstract VistaRealm Impl
  48   implements  Realm, or g.apache.c atalina.Li fecycle, A bstractVis taRealm, j avax.manag ement.MBea nRegistrat ion
  49   {
  50           //  propertie s that def ine the Vi stA site w e are prot ecting
  51           pr ivate Stri ng siteNum ber = null ; // this  MUST be in itialized  to null
  52           pr ivate Stri ng siteAbb reviation  = null;
  53           pr ivate Stri ng siteNam e = null;
  54  
  55           //  cache tun ing proper ties
  56           pr ivate bool ean usingP rincipalCa che = true ;
  57           pr ivate long  principal CacheLifes pan = 1200 00; // how  long shou ld Princip al
  58                                                                                                                     // map ping insta nces live  in
  59                                                                                                                     // the  cache
  60           pr ivate bool ean refres hPrincipal CacheEntry OnUse = fa lse; // if  true then
  61                                                                                                                                               //  the date  of
  62                                                                                                                                               //  the Princ ipal
  63                                                                                                                                               //  entry wil l be
  64                                                                                                                                               //  set to
  65           //  current t ime whenev er it is a ccessed
  66  
  67           //  Read-only  Realm pro perties
  68           pr ivate long  lastPrinc ipalCacheS weepDate =  0L;
  69  
  70           //  maps a us ername aga inst an ex isting Pri ncipal ins tance
  71           //  gets, put s, etc are  synchroni zed BUT th ere are so me operati ons that
  72           //  explicitl y synchron ize on pri ncipalCach e to assur e atomic o perations
  73           pr ivate Map< FullyQuali fiedPrinci palName, P rincipalCa cheValue>  principalC ache = 
  74                    Coll ections.sy nchronized Map(new Ha shMap<Full yQualified PrincipalN ame, Princ ipalCacheV alue>());
  75  
  76           //  maps a Co ntext to a
  77           //  map from  URL/HttpMe thod to th e array of  applicabl e Security Constraint
  78           pr ivate Map< Context, M ap<Securit yConstrain tCacheKey,  SecurityC onstraintC acheValue> > security Constraint Cache = 
  79                    Coll ections.sy nchronized Map(new Ha shMap<Cont ext, Map<S ecurityCon straintCac heKey, Sec urityConst raintCache Value>>()) ;
  80  
  81           //  An identi fier that  helps conn ect log me ssages eac h security  request i s assigned  a (proces s) unique  identifier
  82           //  that is l ogged alon g with inf o messages .  the ID  should not  be confus ed with a  VIX transa ction iden tifier.
  83           //  The realm  ID is onl y valid fo r the loca l server.   The VIX t ransaction  ID is val id for the  transacti on
  84           //  from end  to end.
  85           pr ivate Thre adLocal<St ring> real mSecurityI dentifier  = null;
  86  
  87           pr otected vo id setReal mSecurityI dentifier( )
  88           {
  89                    real mSecurityI dentifier  = new Thre adLocal<St ring>();
  90                    real mSecurityI dentifier. set("ID" +  System.cu rrentTimeM illis() +  (new Objec t().hashCo de()));
  91           }
  92           
  93           pr otected St ring getRe almSecurit yIdentifie r()
  94           {
  95                    retu rn realmSe curityIden tifier ==  null ? nul l : realmS ecurityIde ntifier.ge t();
  96           }
  97           
  98           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========
  99           //  Required  implementa tions
  100           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========
  101           pr otected ab stract Log ger getLog ger();
  102  
  103           /* *
  104        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#is Initialize d()
  105        */
  106           pu blic abstr act boolea n isInitia lized();
  107  
  108           /* *
  109        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#ge tRealmImpl ementation Name()
  110        */
  111           pu blic Strin g getRealm Implementa tionName()
  112           {
  113                    retu rn this.ge tClass().g etName();
  114           }
  115  
  116           /* *
  117        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#ge tVersion()
  118        */
  119           pu blic float  getVersio n()
  120           {
  121                    retu rn 1.0f;
  122           }
  123  
  124           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========
  125           //  MBeanRegi stration M ethods
  126           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========
  127           pr ivate Obje ctName des iredMBeanN ame;
  128           pr ivate Obje ctName reg isteredMBe anName;
  129           
  130           //  create th e name tha t we would  like to b e register ed as
  131           pr ivate sync hronized O bjectName  getDesired MBeanName(
  132           th rows Malfo rmedObject NameExcept ion, NullP ointerExce ption
  133           {
  134                    if(d esiredMBea nName == n ull)
  135                    {
  136                             Hashta ble<String , String>  keys = new  Hashtable <String, S tring>();
  137                             keys.p ut("realm" , getRealm ());
  138                             desire dMBeanName  = new Obj ectName("g ov.va.med. imaging.to mcat.vista realm", ke ys);
  139                    }
  140                    
  141                    retu rn desired MBeanName;
  142           }
  143           
  144           /* *
  145        * @se e javax.ma nagement.M BeanRegist ration#pre Register(j avax.manag ement.MBea nServer, j avax.manag ement.Obje ctName)
  146        */
  147       @Overr ide
  148       public  ObjectNam e preRegis ter(MBeanS erver serv er, Object Name name)  
  149       throws  Exception
  150       {
  151           
  152           tr y
  153           { 
  154                    getL ogger().in fo(
  155                             "Realm  instance  '" + getDe siredMBean Name().toS tring() + 
  156                             "' bei ng registe red as '"  + (name ==  null ? ge tDesiredMB eanName(). toString()  : name.to String()) 
  157                             "'." )
  158           } 
  159           ca tch (Excep tion e){}
  160           
  161           if (name != n ull)                  // if we a re passed  a name the n use it
  162                    retu rn name;
  163           el se    
  164                    retu rn getDesi redMBeanNa me();
  165       }
  166  
  167           /* *
  168        * @se e javax.ma nagement.M BeanRegist ration#pos tRegister( java.lang. Boolean)
  169        */
  170       @Overr ide
  171       public  void post Register(B oolean reg istrationD one)
  172       {
  173           tr y{ getLogg er().info( "Realm ins tance '" +  getDesire dMBeanName ().toStrin g() + "' i s now regi stered.");  } 
  174           ca tch (Excep tion e){}
  175       }
  176  
  177           /* *
  178        * @se e javax.ma nagement.M BeanRegist ration#pre Deregister ()
  179        */
  180       @Overr ide
  181       public  void preD eregister( ) throws E xception
  182       {
  183           tr y{ getLogg er().info( "Realm ins tance '" +  getDesire dMBeanName ().toStrin g() + "' b eing de-re gistered." ); } 
  184           ca tch (Excep tion e){}
  185       }
  186  
  187           /* *
  188        * @se e javax.ma nagement.M BeanRegist ration#pos tDeregiste r()
  189        */
  190       @Overr ide
  191       public  void post Deregister ()
  192       {
  193           tr y{ getLogg er().info( "Realm ins tance '" +  getDesire dMBeanName ().toStrin g() + "' h as been de -registere d."); } 
  194           ca tch (Excep tion e){}
  195       }
  196  
  197       // === ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== ==
  198       // the  realm is  registered  with the  MBeanserve r when the  realm is  started
  199       // and  de-regist ered when  the realm  is stopped
  200       // === ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== ==
  201           pr otected vo id mBeanRe gistration ()
  202           {
  203                    // r egister th e manageme nt interfa ce if the  MBeanServe r exists
  204                    MBea nServer mb s = Manage mentFactor y.getPlatf ormMBeanSe rver();
  205                    if ( mbs != nul l)
  206                    {
  207                             try
  208                             {
  209                                      ObjectIn stance oi  = mbs.regi sterMBean( this, null );
  210                                      register edMBeanNam e = oi.get ObjectName ();
  211                                      getLogge r().info(  "Realm '"  + getDesir edMBeanNam e().toStri ng() + "'  registered  as '" + r egisteredM BeanName +  "'." );
  212                                      
  213                             } catc h (Instanc eAlreadyEx istsExcept ion e)
  214                             {
  215                                      getLogge r().error( e);
  216                             } catc h (MBeanRe gistration Exception  e)
  217                             {
  218                                      getLogge r().error( e);
  219                             } catc h (NotComp liantMBean Exception  e)
  220                             {
  221                                      getLogge r().error( e);
  222                             } catc h (Malform edObjectNa meExceptio n e)
  223                {
  224                                      getLogge r().error( e);
  225                } catch  (NullPoint erExceptio n e)
  226                {
  227                                      getLogge r().error( e);
  228                }
  229                    }
  230           }
  231  
  232           pr otected vo id mBeanUn Registrati on()
  233           {
  234                    MBea nServer mb s = Manage mentFactor y.getPlatf ormMBeanSe rver();
  235                    if ( mbs != nul l)
  236                    {
  237                             try
  238                             {
  239                                      if (regi steredMBea nName != n ull) 
  240                                      {
  241                                               mbs.unregi sterMBean( registered MBeanName) ;
  242                                               getLogger( ).info( "R ealm '" +  registered MBeanName  + "' de-re gistered."  );
  243                                               registered MBeanName  = null;
  244                                      }
  245                             } catc h (Instanc eNotFoundE xception x )
  246                             {
  247                                      getLogge r().error( x);
  248                             } catc h (MBeanRe gistration Exception  x)
  249                             {
  250                                      getLogge r().error( x);
  251                             }
  252                    }
  253           }
  254       
  255       
  256           /*
  257            *  ========= ========== ========== ========== ========== ========== ========== ========== =======
  258            *  Informati on string,  toString( )
  259            *  ========= ========== ========== ========== ========== ========== ========== ========== =======
  260            * /
  261           /* *
  262            *  Return de scriptive  informatio n about th is Realm i mplementat ion and th e
  263            *  correspon ding versi on number,  in the fo rmat <desc ription>/< version>.
  264            * /
  265           pu blic Strin g getInfo( )
  266           {
  267                    retu rn getReal mImplement ationName( ) + "/" +  getVersion ();
  268           }
  269  
  270           /* *
  271            *  @see java .lang.Obje ct#toStrin g()
  272            *  
  273            *  Returns a  String li ke: VistaR ealm [660- SLC Salt L ake City,  UT
  274              * vista:sl c. DNS        . DNS     : PORT ]
  275            * /
  276           @O verride
  277           pu blic Strin g toString ()
  278           {
  279                    Stri ngBuilder  sb = new S tringBuild er();
  280  
  281                    sb.a ppend(this .getInfo() );
  282                    sb.a ppend(" [" );
  283                    sb.a ppend(this .getSiteAb breviation ());
  284                    sb.a ppend("-") ;
  285                    sb.a ppend(this .getSiteNu mber());
  286                    sb.a ppend(" ") ;
  287                    sb.a ppend(this .getSiteNa me());
  288                    sb.a ppend("]") ;
  289  
  290                    retu rn sb.toSt ring();
  291           }
  292  
  293           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========
  294           //  JavaBean  Property A ccessors
  295           //  These pro perties ma y be set f rom the se rver confi guration.
  296           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========
  297           /* *
  298        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#ge tSiteAbbre viation()
  299        */
  300           pu blic Strin g getSiteA bbreviatio n()
  301           {
  302                    retu rn siteAbb reviation;
  303           }
  304  
  305           pu blic void  setSiteAbb reviation( String loc alSiteAbbr eviation)
  306           {
  307                    this .siteAbbre viation =  localSiteA bbreviatio n;
  308           }
  309  
  310           /* *
  311        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#ge tSiteName( )
  312        */
  313           pu blic Strin g getSiteN ame()
  314           {
  315                    retu rn siteNam e;
  316           }
  317  
  318           pu blic void  setSiteNam e(String l ocalSiteNa me)
  319           {
  320                    this .siteName  = localSit eName;
  321           }
  322  
  323           /* *
  324        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#ge tSiteNumbe r()
  325        */
  326           pu blic Strin g getSiteN umber()
  327           {
  328                    retu rn siteNum ber;
  329           }
  330  
  331           pu blic Strin g getRealm ()
  332           {
  333                    retu rn getSite Number();
  334           }
  335           
  336           //  because o f the way  a Realm is  initializ ed by Tomc at
  337           //  the immut able prope rties cann ot be decl ared final , so
  338           //  we prohib it changes  after the  first in  code
  339           pu blic void  setSiteNum ber(String  localSite Number)
  340           {
  341                    if ( this.siteN umber == n ull)
  342                             this.s iteNumber  = localSit eNumber;
  343                    else
  344                             getLog ger().erro r(
  345                                      "The sit e number m ay not be  changed on ce it has  been set,  attempt to  change fr om '" + th is.siteNum ber + "' t o '"
  346                                               + localSit eNumber +  "' is bein g ignored. ");
  347           }
  348  
  349           //  ========= ========== ========== ========== ========== ========== ========== ========== =========
  350           //  Cache Tun ing Proper ties
  351           //  ========= ========== ========== ========== ========== ========== ========== ========== =========
  352           /* *
  353        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#is UsingPrinc ipalCache( )
  354        */
  355           pu blic Boole an isUsing PrincipalC ache()
  356           {
  357                    retu rn this.us ingPrincip alCache;
  358           }
  359  
  360           /* *
  361        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#se tUsingPrin cipalCache (java.lang .Boolean)
  362        */
  363           pu blic void  setUsingPr incipalCac he(Boolean  usingPrin cipalCache )
  364           {
  365                    // i f the cach e is being  turned of f then cle ar it
  366                    if ( this.using PrincipalC ache && !u singPrinci palCache)
  367                             clearP rincipalCa che();
  368  
  369                    this .usingPrin cipalCache  = usingPr incipalCac he;
  370           }
  371  
  372           /* *
  373        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#ge tPrincipal CacheLifes pan()
  374        */
  375           pu blic Long  getPrincip alCacheLif espan()
  376           {
  377                    retu rn this.pr incipalCac heLifespan ;
  378           }
  379  
  380           /* *
  381        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#se tPrincipal CacheLifes pan(java.l ang.Long)
  382        */
  383           pu blic void  setPrincip alCacheLif espan(Long  principal CacheLifes pan)
  384           {
  385                    this .principal CacheLifes pan = prin cipalCache Lifespan;
  386           }
  387  
  388           /* *
  389        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#is RefreshPri ncipalCach eEntryOnUs e()
  390        */
  391           pu blic Boole an isRefre shPrincipa lCacheEntr yOnUse()
  392           {
  393                    retu rn this.re freshPrinc ipalCacheE ntryOnUse;
  394           }
  395  
  396           /* *
  397        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#se tRefreshPr incipalCac heEntryOnU se(java.la ng.Boolean )
  398        */
  399           pu blic void  setRefresh PrincipalC acheEntryO nUse(Boole an refresh PrincipalC acheEntryO nUse)
  400           {
  401                    this .refreshPr incipalCac heEntryOnU se = refre shPrincipa lCacheEntr yOnUse;
  402           }
  403  
  404           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ===
  405           //  Read-Only  propertie s, used by  JMX for m onitoring
  406           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ===
  407           /* *
  408        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#ge tPrincipal CacheSize( )
  409        */
  410           pu blic int g etPrincipa lCacheSize ()
  411           {
  412                    retu rn princip alCache.si ze();
  413           }
  414  
  415           /* *
  416        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#ge tSecurityC onstraintC acheSize()
  417        */
  418           pu blic int g etSecurity Constraint CacheSize( )
  419           {
  420                    retu rn this.se curityCons traintCach e.size();
  421           }
  422  
  423           /* *
  424            *  Get the n umber of c ached secu rity const raints for  the named  context.
  425            *  
  426            *  @param co ntext
  427            *  @return
  428            * /
  429           pu blic int g etContextS ecurityCon straintsCa cheSize(St ring conte xt)
  430           {
  431                    if ( context ==  null)
  432                             return  0;
  433  
  434                    for  (Context s ervicedCon text : sec urityConst raintCache .keySet())
  435                    {
  436                             if (co ntext.equa ls(service dContext.g etName()))
  437                             {
  438                                      Map<Secu rityConstr aintCacheK ey, Securi tyConstrai ntCacheVal ue> contex tSecurityC onstraintC ache = sec urityConst raintCache
  439                                               .get(servi cedContext );
  440                                      return c ontextSecu rityConstr aintCache. size();
  441                             }
  442                    }
  443  
  444                    retu rn 0;
  445           }
  446  
  447           /* *
  448        * @se e gov.va.m ed.imaging .tomcat.vi starealm.A bstractVis taRealm#ge tLastPrinc ipalCacheS weepDate()
  449        */
  450           pu blic long  getLastPri ncipalCach eSweepDate ()
  451           {
  452                    retu rn this.la stPrincipa lCacheSwee pDate;
  453           }
  454  
  455           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========
  456           //  Lifecycle  Listeners
  457           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========
  458           pr ivate List <Lifecycle Listener>  lifecycleL isteners =  new Array List<Lifec ycleListen er>();
  459  
  460           pu blic void  addLifecyc leListener (Lifecycle Listener l istener)
  461           {
  462                    life cycleListe ners.add(l istener);
  463           }
  464  
  465           pu blic void  removeLife cycleListe ner(Lifecy cleListene r listener )
  466           {
  467                    life cycleListe ners.remov e(listener );
  468           }
  469  
  470           pu blic Lifec ycleListen er[] findL ifecycleLi steners()
  471           {
  472                    Life cycleListe ner[] a =  new Lifecy cleListene r[lifecycl eListeners .size()];
  473                    life cycleListe ners.toArr ay(a);
  474  
  475                    retu rn a;
  476           }
  477  
  478           pr ivate void  notifyLif ecycleList eners(Life cycleEvent  event)
  479           {
  480                    for  (Lifecycle Listener l istener :  lifecycleL isteners)
  481                             listen er.lifecyc leEvent(ev ent);
  482           }
  483  
  484           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========
  485           //  Tomcat Li fecycleLis tener Impl ementation
  486           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========
  487           /* *
  488            *  This is w here the r ealm initi alization  occurs.
  489            *  
  490            *  Get the r ealm start ed, this i ncludes re storing th e realm st ate from
  491            *  context p roperties.
  492            * /
  493           @O verride
  494           pu blic void  start() th rows Lifec ycleExcept ion
  495           {
  496                    // S erver serv er = Serve rFactory.g etServer() ;
  497                    // l ogger.info ("VistaRea lm startin g on serve r " + serv er.getInfo ());
  498  
  499                    noti fyLifecycl eListeners (new Lifec ycleEvent( this, Life cycle.BEFO RE_START_E VENT, null ));
  500  
  501                    // r egister ou rselves wi th the JMX  MBean ser ver if it  exists
  502                    mBea nRegistrat ion();
  503  
  504                    if ( isInitiali zed())
  505                    {
  506                             getLog ger().info ("Realm["  + this.get RealmName( ) + "] ini tialized w ith author ization si te " + thi s.toString () + ".");
  507  
  508                             notify LifecycleL isteners(n ew Lifecyc leEvent(th is, Lifecy cle.START_ EVENT, nul l));
  509                             getLog ger().info ("Realm ["  + this.ge tRealmName () + "] is  started." );
  510                             notify LifecycleL isteners(n ew Lifecyc leEvent(th is, Lifecy cle.AFTER_ START_EVEN T, null));
  511                    } el se
  512                             getLog ger().warn ("[" + thi s.getRealm Name() + " ] is NOT i nitialized , use JMX  interface  to set req uired fiel ds and ini tialize.") ;
  513  
  514           }
  515           
  516  
  517           /* *
  518            *  We are st opping, no tify our l isteners a nd unregis ter oursel ves with t he
  519            *  MBean ser ver
  520            * /
  521           @O verride
  522           pu blic void  stop() thr ows Lifecy cleExcepti on
  523           {
  524                    getL ogger().in fo("Realm[ " + this.g etRealmNam e() + "] s topping.") ;
  525                    noti fyLifecycl eListeners (new Lifec ycleEvent( this, Life cycle.BEFO RE_STOP_EV ENT, null) );
  526                    mBea nUnRegistr ation();
  527                    noti fyLifecycl eListeners (new Lifec ycleEvent( this, Life cycle.AFTE R_STOP_EVE NT, null)) ;
  528           }
  529  
  530           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ==========
  531           //  Realm Pro perty chan ge Listene r
  532           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========= 
  533           /* *
  534            *  PropertyC hangeListe ner manage ment and n otificatio n
  535            * /
  536           pr ivate List <PropertyC hangeListe ner> prope rtyChangeL isteners =  new Array List<Prope rtyChangeL istener>() ;
  537  
  538           pu blic void  addPropert yChangeLis tener(Prop ertyChange Listener l istener)
  539           {
  540                    prop ertyChange Listeners. add(listen er);
  541           }
  542  
  543           pu blic void  removeProp ertyChange Listener(P ropertyCha ngeListene r listener )
  544           {
  545                    prop ertyChange Listeners. remove(lis tener);
  546           }
  547  
  548           pr otected vo id notifyP ropertyCha ngeListene rs(Propert yChangeEve nt event)
  549           {
  550                    for  (Iterator< PropertyCh angeListen er> proper tyChangeLi stenerIter  = propert yChangeLis teners.ite rator(); p ropertyCha ngeListene rIter
  551                             .hasNe xt();)
  552                             (prope rtyChangeL istenerIte r.next()). propertyCh ange(event );
  553           }
  554  
  555           pr otected vo id notifyP ropertyCha ngeListene rs(String  propertyNa me, Object  oldValue,  Object ne wValue)
  556           {
  557                    noti fyProperty ChangeList eners(new  PropertyCh angeEvent( this, prop ertyName,  oldValue,  newValue)) ;
  558           }
  559  
  560           
  561           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========
  562           //  Realm imp lementatio n
  563           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========
  564  
  565           /* *
  566            *  Is the gi ven role o ne of the  roles know n to this  Realm
  567            * /
  568           pu blic boole an isKnown Role(Strin g roleName )
  569           {
  570                    retu rn VistaRe almRoles.i sKnownRole Name(roleN ame);
  571           }
  572           
  573           /* *
  574            *  This must  be overri dden becau se the Rea lmBase imp lementatio n expects  an
  575            *  instance  of Generic Principal
  576            *  
  577            *  @see org. apache.cat alina.Real m.hasRole( Principal  principal,  String ro le)
  578            * /
  579           @O verride
  580           pu blic boole an hasRole (Wrapper w rapper, Pr incipal pr incipal, S tring role )
  581           {
  582                    getL ogger().de bug("hasRo le (" + (p rincipal ! = null ? p rincipal.g etName() :  "UNKNOWN" ) + ", " +  role + ") ");
  583                    try
  584                    {
  585                             return  ((VistaRe almPrincip al) princi pal).hasRo le(role);
  586                    } 
  587                    catc h (ClassCa stExceptio n ccX)
  588                    {
  589                             getLog ger().erro r("Expecti ng an inst ance of Vi staRealmPr incipal an d got an i nstance of  " + princ ipal.getCl ass().getN ame()
  590                                      + ", whi ch VistaRe alm does n ot underst and");
  591                             return  false;
  592                    }
  593           }
  594           
  595  
  596           /* *
  597            *  A Contain er is an o bject that  can execu te request s received  from a
  598            *  client, a nd return  responses  based on t hose reque sts. Engin e -
  599            *  Represent ation of t he entire  Catalina s ervlet eng ine. Host  -
  600            *  Represent ation of a  virtual h ost contai ning a num ber of Con texts. Con text -
  601            *  Represent ation of a  single Se rvletConte xt, which  will typic ally conta in
  602            *  one or mo re Wrapper s for the  supported  servlets.  Wrapper -  Representa tion
  603            *  of an ind ividual se rvlet defi nition.
  604            * /
  605           pr ivate Cont ainer cont ainer = nu ll;
  606  
  607           pu blic void  setContain er(Contain er contain er)
  608           {
  609                    this .container  = contain er;
  610           }
  611  
  612           pu blic Conta iner getCo ntainer()
  613           {
  614                    retu rn this.co ntainer;
  615           }
  616  
  617           /* *
  618            *  The realm  name is t he site nu mber.
  619            *  
  620            *  @return
  621            * /
  622           pu blic Strin g getRealm Name()
  623           {
  624                    retu rn getSite Number();
  625           }
  626  
  627           /*
  628            *  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== ======
  629            *  Principal  Cache Imp lementatio n
  630            *  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== ======
  631            * /
  632  
  633           /* *
  634            *  Execute a  periodic  task, such  as reload ing, etc.
  635            *  
  636            *  Executed  periodical ly to relo ad from da tabase, cl ear cache,  etc ...
  637            *  
  638            *  @see org. apache.cat alina.Real m.backgrou ndProcess( )
  639            * /
  640           @O verride
  641           pu blic void  background Process()
  642           {
  643                    long  now = Sys tem.curren tTimeMilli s();
  644  
  645                    // l ogically r unning evi ction will  have no e ffect if
  646                    // t he cache i s not bein g used, bu t having t his test h ere both
  647                    // s aves time  and allows  us to tur n off proc essing if  there is a n
  648                    // e rror in it .
  649                    if ( isUsingPri ncipalCach e())
  650                             evictO ldPrincipa lCacheEntr ies(now);
  651           }
  652  
  653           /* *
  654            *  This may  be called  from MBean  managemen t to force  an evicti on NOTE: t his
  655            *  method do es not che ck if the  cache is b eing used,  but simpl y runs the
  656            *  eviction  pass.
  657            * /
  658           pu blic void  evictOldPr incipalCac heEntries( )
  659           {
  660                    long  now = Sys tem.curren tTimeMilli s();
  661  
  662                    evic tOldPrinci palCacheEn tries(now) ;
  663           }
  664  
  665           /* *
  666            *  Clear all  principal  cache ent ries
  667            * /
  668           pu blic void  clearPrinc ipalCache( )
  669           {
  670                    prin cipalCache .clear();
  671           }
  672  
  673           /* *
  674            *  
  675            *  @param no w
  676            * /
  677           pr ivate void  evictOldP rincipalCa cheEntries (long now)
  678           {
  679                    last PrincipalC acheSweepD ate = now;
  680                    // e viction ag e is the d ate in the  past when  a cache e ntry must  have
  681                    // n een touche d/opened a fter to re main in th e cache
  682                    long  evictionA ge = now -  this.getP rincipalCa cheLifespa n();
  683  
  684                    // s ynchronize  on the pr incipalCac he so that  we do not  get a
  685                    // C oncurrentM odificatio nException
  686                    // i n the iter ator
  687                    sync hronized ( principalC ache)
  688                    {
  689                             for (I terator<Fu llyQualifi edPrincipa lName> ite r = princi palCache.k eySet().it erator();  iter.hasNe xt();)
  690                             {
  691                                      FullyQua lifiedPrin cipalName  fqPrincipa l = iter.n ext();
  692  
  693                                      Principa lCacheValu e principa lCacheValu e = princi palCache.g et(fqPrinc ipal);
  694                                      if (prin cipalCache Value.getD ate() < ev ictionAge)
  695                                               iter.remov e();
  696                             }
  697                    }
  698           }
  699           
  700           pr otected Pr incipalCac heValue ge tPrincipal CacheEntry (FullyQual ifiedPrinc ipalName f qPrincipal )
  701           {
  702                    retu rn princip alCache.ge t(fqPrinci pal);
  703           }
  704           
  705           pr otected vo id addPrin cipalCache EntryIfUni que(FullyQ ualifiedPr incipalNam e fqpn, Pr incipalCac heValue pr incipalCac heValue)
  706           {
  707                    getL ogger().in fo("Cachin g fully qu alified pr incipal na me '" + fq pn.toStrin g() + "'." );
  708                    // s ynchronize  on the pr incipal ca che so tha t the get,  the check  for exist ence
  709                    // a nd the put  are atomi c
  710                    sync hronized(p rincipalCa che)
  711                    {
  712                             // If  the princi pal is not  already c ached then  cache it.  
  713                             // Don 't PUT ove r an exist ing instan ce.
  714                             if( pr incipalCac he.get(fqp n) == null  )
  715                             {
  716                                      // clone  the Princ ipal objec t and cach e the clon e
  717                                      // DO NO T CACHE th e instance  that the  applicatio ns see bec ause they
  718                                      // may c hange the  values in  the Princi pal !!!!!
  719                                      principa lCache.put ( fqpn, pr incipalCac heValue );
  720                             }
  721                    }
  722           }
  723  
  724           /* *
  725            *  @param co ntext
  726            *  @param co nstraintKe y
  727            *  @return
  728            * /
  729           pr otected Se curityCons traint[] g etCachedSe curityCons traint(Con text conte xt, Securi tyConstrai ntCacheKey  constrain tKey)
  730           {
  731                    // f irst see i f there is  a securit y constrai nt map for  this cont ext
  732                    Map< SecurityCo nstraintCa cheKey, Se curityCons traintCach eValue> co ntextCache  = getCont extSecurit yConstrain tCache(con text);
  733                    if ( contextCac he != null )
  734                    {
  735                             Securi tyConstrai ntCacheVal ue cacheVa lue = cont extCache.g et(constra intKey);
  736                             if (ca cheValue ! = null)
  737                                      return c acheValue. getConstra ints();
  738                    }
  739  
  740                    retu rn null;
  741           }
  742  
  743           pr ivate Map< SecurityCo nstraintCa cheKey, Se curityCons traintCach eValue> ge tContextSe curityCons traintCach e(Context  context)
  744           {
  745                    retu rn securit yConstrain tCache.get (context);
  746           }
  747  
  748           pr ivate Map< SecurityCo nstraintCa cheKey, Se curityCons traintCach eValue> ge tOrCreateC ontextSecu rityConstr aintCache( Context co ntext)
  749           {
  750                    Map< SecurityCo nstraintCa cheKey, Se curityCons traintCach eValue> re sult = sec urityConst raintCache .get(conte xt);
  751                    if ( result ==  null)
  752                    {
  753                             result  = Collect ions.synch ronizedMap (new HashM ap<Securit yConstrain tCacheKey,  SecurityC onstraintC acheValue> ());
  754  
  755                             securi tyConstrai ntCache.pu t(context,  result);
  756                    }
  757                    retu rn result;
  758           }
  759  
  760           /* *
  761            *  @param co ntext
  762            *  @param co nstraintKe y
  763            *  @param re sults
  764            * /
  765           pr otected vo id putToSe curityCons traintsCac he(Context  context,  SecurityCo nstraintCa cheKey con straintKey ,
  766                    Coll ection<Sec urityConst raintMatch > matching SecurityCo nstraints)
  767           {
  768                    Secu rityConstr aint[] sec urityConst raintsArra y = new Se curityCons traint[mat chingSecur ityConstra ints.size( )];
  769  
  770                    int  index = 0;
  771                    for  (SecurityC onstraintM atch match ingSecurit yConstrain t : matchi ngSecurity Constraint s)
  772                             securi tyConstrai ntsArray[i ndex++] =  matchingSe curityCons traint.get SecurityCo nstraint() ;
  773  
  774                    putT oSecurityC onstraints Cache(cont ext, const raintKey,  securityCo nstraintsA rray);
  775           }
  776  
  777           pr ivate void  putToSecu rityConstr aintsCache (Context c ontext, Se curityCons traintCach eKey const raintKey,
  778                    Secu rityConstr aint[] sec urityConst raints)
  779           {
  780                    // f irst see i f there is  a securit y constrai nt map for  this cont ext
  781                    Map< SecurityCo nstraintCa cheKey, Se curityCons traintCach eValue> co ntextCache  = getOrCr eateContex tSecurityC onstraintC ache(conte xt);
  782                    cont extCache.p ut(constra intKey, ne w Security Constraint CacheValue (securityC onstraints ));
  783           }
  784           
  785           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========
  786           //  Preemptiv eAuthoriza tion Imple mentation
  787           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========
  788           /* *
  789            *  A non-aut horitative , pre-empt ive determ ination of  whether t he current ly logged  in user
  790            *  has privi leges to t he selecte d resource .
  791            *  
  792        * @se e gov.va.m ed.imaging .tomcat.vi starealm.P reemptiveA uthorizati on#isAutho rized(java .lang.Obje ct, java.l ang.String , java.lan g.String)
  793        */
  794       @Overr ide
  795       public  Preemptiv eAuthoriza tion.Resul t isAuthor ized(
  796                    Prin cipal prin cipal, 
  797                    Obje ct context
  798                    Stri ng context RequestPat h, 
  799                    Stri ng request Method)
  800       {
  801           ge tLogger(). info("Pree mptively c hecking au thorizatio n '" + pri ncipal.get Name() + " ' to '" +  requestMet hod + ":"  + contextR equestPath  + "'.");
  802           if (! (contex t instance of Context ) )
  803           {
  804                    getL ogger().wa rn("Attemp t to pre-e mptively d etermine a uthorizati on with a  context of  type othe r than Tom cat standa rd Context ");
  805                    retu rn Preempt iveAuthori zation.Res ult.Unknow n;
  806           }
  807           Co ntext tomc atContext  = (Context )context;
  808           
  809                    Stri ng request ContextPat h = tomcat Context.ge tName();
  810                    Stri ng request PathInfo =  requestCo ntextPath  + contextR equestPath ;
  811                    
  812           ge tLogger(). info("Pree mptively c hecking au thorizatio n, getting  security  constraint s.");
  813                    Secu rityConstr aint[] sec urityConst raints = f indSecurit yConstrain ts(tomcatC ontext, re questPathI nfo, reque stMethod,  contextReq uestPath);
  814  
  815           ge tLogger(). info("Pree mptively c hecking au thorizatio n, checkin g resource  permmissi ons.");
  816                    retu rn hasReso urcePermis sion(tomca tContext,  securityCo nstraints,  requestPa thInfo, pr incipal) ?
  817                                      Preempti veAuthoriz ation.Resu lt.True :  Preemptive Authorizat ion.Result .False;
  818       }
  819  
  820           
  821           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========
  822           //  Realm Imp lementatio n
  823           //  Other tha n authenti cate(), wh ich is don e by deriv ed classes
  824           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========
  825  
  826           /*
  827            *  Perform a ccess cont rol based  on the spe cified aut horization  constrain t.
  828            *  
  829            *  Servlet s pecificati on section s implemen ted: 12.8
  830            *  
  831            *  Specially  notable r equirement s: "An aut horization  constrain t that nam es
  832            *  no roles  indicates  that acces s to the c onstrained  requests  must not b e
  833            *  permitted  under any  circumsta nces."
  834            *  
  835            *  Section 1 2.8.1: "Wh en a url-p attern and  http-meth od pair oc curs in
  836            *  multiple  security c onstraints , the cons traints (o n the patt ern and
  837            *  method) a re defined  by combin ing the in dividual c onstraints . The rule s
  838            *  for combi ning const raints in  which the  same patte rn and met hod occur  are
  839            *  as follow s:
  840            *  
  841            *  The combi nation of  authorizat ion constr aints that  name role s or that
  842            *  imply rol es via the  name “*”  shall yiel d the unio n of the r ole names  in
  843            *  the indiv idual cons traints as  permitted  roles. A  security c onstraint  that
  844            *  does not  contain an  authoriza tion const raint shal l combine  with
  845            *  authoriza tion const raints tha t name or  imply role s to allow
  846            *  unauthent icated acc ess. The s pecial cas e of an au thorizatio n constrai nt
  847            *  that name s no roles  shall com bine with  any other  constraint s to overr ide
  848            *  their aff ects and c ause acces s to be pr ecluded.
  849            *  
  850            *  The combi nation of  user-data- constraint s that app ly to a co mmon
  851            *  urlpatter n and http -method sh all yield  the union  of connect ion types
  852            *  accepted  by the ind ividual co nstraints  as accepta ble connec tion types . A
  853            *  security  constraint  that does  not conta in a user- data-const raint shal l
  854            *  combine w ith other  user data- constraint s to cause  the unpro tected
  855            *  connectio n type to  be an acce pted conne ction type ."
  856            *  
  857            *  
  858            *  @param re quest
  859            *              Request  we are pro cessing
  860            *  @param re sponse
  861            *              Response  we are cr eating
  862            *  @param se curityCons traints
  863            *              applicab le securit y constrai nts as det ermined by  the
  864            *              web-reso urce-colle ction, see  findSecur ityConstra ints()
  865            *              security -constrain t elements  that were  returned  in the pre vious
  866            *              findSecu rityConstr aints() ca ll
  867            *              i.e. thi s is the l ist of app licable se curity con straints i n
  868            *              descendi ng order o f applicab ility
  869            *  @param co ntext
  870            *              The Cont ext to whi ch client  of this cl ass is att ached.
  871            *  
  872            *  @return < code>true< /code> if  this const raint is s atisfied a nd
  873            *          p rocessing  should con tinue, or  <code>fals e</code> o therwise.
  874            *  
  875            *  @exceptio n IOExcept ion
  876            *                  if a n input/ou tput error  occurs
  877            * /
  878           pu blic boole an hasReso urcePermis sion(
  879                             Reques t request,  
  880                             Respon se respons e, 
  881                             Securi tyConstrai nt[] secur ityConstra ints, 
  882                    Cont ext contex t) 
  883           th rows IOExc eption
  884           {
  885                    bool ean result  = false;          //  assume no  access
  886                    
  887                    Stri ng request Uri = requ est.getReq uestURI();
  888                    getL ogger().in fo("hasRes ourcePermi ssion (" +  request.g etRequestU RI() + ",  " + contex t.getName( ) + "," +  securityCo nstraints. length
  889                             + ") r sID='" + g etRealmSec urityIdent ifier() +  "'.");
  890  
  891                    // d ump debugg ing messag es, check  the debug  level firs t to avoid  executing  a bunch o f code
  892                    if ( getLogger( ).isDebugE nabled())
  893                             for (S ecurityCon straint c  : security Constraint s)
  894                             {
  895                                      getLogge r().debug( "  Securit yConstrain t '" + c.g etDisplayN ame() + "'  roles");
  896                                      for (Str ing roleNa me : c.fin dAuthRoles ())
  897                                               getLogger( ).debug("     role '"  + roleNam e + "'");
  898                             }
  899  
  900                    // U ser princi pal may ha ve been pr eviously a uthenticat ed
  901                    // i f the user  has not b een authen ticated th en access  will only  be
  902                    // g ranted whe re no secu rity-const raint is a pplicable
  903                    Prin cipal prin cipal = re quest.getP rincipal() ;
  904                    
  905                    resu lt = hasRe sourcePerm ission(
  906                                      context,  
  907                                      security Constraint s, 
  908                                      requestU ri, 
  909                                      principa l);
  910                    
  911                    // p ermission  is granted , log an a uthorizati on message
  912                    if(r esult)
  913                    {
  914                             getLog ger().info ("hasResou rcePermiss ion (" + r equestUri  + "...) rs ID='" + ge tRealmSecu rityIdenti fier()
  915                                      + "' - p ermission  GRANTED");
  916                    }
  917                    // i f permissi on was den ied for an y reason,  send a 403  response,  else just  log an au thorizatio n message
  918                    else
  919                    {
  920                             String  deniedMes sage = 
  921                                      "Access  to resourc e '" + req uestUri + 
  922                                      "' by us er '" + (p rincipal = = null ? " <unknown>"  : princip al.getName ()) + 
  923                                      "' is de nied.  " +  
  924                                      "Securit y realm un ique ID '"  + getReal mSecurityI dentifier( ) + "'.";
  925  
  926                             getLog ger().info (deniedMes sage);
  927                             respon se.sendErr or(403, de niedMessag e);
  928                    }
  929                    
  930                    retu rn result;
  931           }
  932  
  933           /* *
  934        * @pa ram securi tyConstrai nts
  935        * @pa ram contex t
  936        * @pa ram result
  937        * @pa ram reques tUri
  938        * @pa ram princi pal
  939        * @re turn
  940        */
  941       privat e boolean  hasResourc ePermissio n(
  942                    Cont ext contex t, 
  943                    Secu rityConstr aint[] sec urityConst raints, 
  944                    Stri ng request Uri,
  945                Principa l principa l)
  946       {
  947           bo olean resu lt = false ;
  948           
  949                // no se curity-con straints a pplicable  therefore  no restric tion
  950                    if(  securityCo nstraints  == null ||  securityC onstraints .length ==  0 )
  951                    {
  952                             getLog ger().debu g("hasReso urcePermis sion (" +  requestUri  + "...) r sID='" + g etRealmSec urityIdent ifier()
  953                                      + "' - n o security  constrain ts provide d, permiss ion GRANTE D");
  954                             result  = true;
  955                    }
  956                    else
  957                    {
  958                             // if  the login- config ele ment exist s and the  authorizat ion method  is FORM
  959                             // the re is some  special h andling of  error and  login URL s
  960                             if( is SpecialFor mAuthReque st(context .getLoginC onfig(), r equestUri)  )
  961                             {
  962                                      getLogge r().info(" hasResourc ePermissio n (" + req uestUri +  "...) rsID ='" + getR ealmSecuri tyIdentifi er()
  963                                               + "' - byp assing sec urity cons traints fo r special  form-based  authentic ation reso urces, per mission GR ANTED");
  964                                      result =  true;
  965                             }
  966  
  967                             // cre ate an ins tance of S ecurityCon straintLis t, which i s capable  of
  968                             // int elligently  combining  the autho rization c onstraints  of many S ecurityCon straint
  969                             Securi tyConstrai ntAuthoriz ationList< SecurityCo nstraint>  scList = 
  970                                      new Secu rityConstr aintAuthor izationLis t<Security Constraint >(security Constraint s);
  971  
  972                              // if  the user  is not aut henticated  then the  only way i n is if th e applicat ion
  973                             // all ows unauth enticated  access
  974                             if( pr incipal ==  null )
  975                             {
  976                                      result =  scList.is AllowUnaut henticated Access();
  977                                      getLogge r().info(" hasResourc ePermissio n (" + req uestUri +  "...) rsID ='" + getR ealmSecuri tyIdentifi er()
  978                                               + "' - no  principal,  permissio n " + (res ult ? "is  GRANTED" :  "is NOT G RANTED")
  979                                               + " on una uthenticat ed access. ");
  980                             }
  981                             else
  982                             {
  983                                      // we ca n only han dle our ow n Principa l realizat ions
  984                                      if( !(pr incipal in stanceof V istaRealmP rincipal)  )
  985                                      {
  986                                               // an erro r because  we should  never get  any other  kind of pr incipal,
  987                                               // and we  need the r ole inform ation stor ed in it
  988                                               getLogger( ).error("A ttempt to  determine  resource p ermissions , hasResou rcePermiss ion(), wit h an unkno wn princip al type.") ;
  989                                      }
  990                                      else
  991                                      {
  992                                               result = s cList.isAn yRoleAllow edAccess(  ((VistaRea lmPrincipa l)principa l).getRole s() );
  993                                      }
  994                             }
  995                    }
  996                return r esult;
  997       }
  998  
  999           /* *
  1000            *  If the au thorizatio n method i s FORM and  the reque sted page  is one of  the
  1001            *  "special"  pages (er ror and lo gin) then  allow acce ss.
  1002            *  
  1003            *  @param co nfig
  1004            *  @param re questURI
  1005            * /
  1006           pr ivate bool ean isSpec ialFormAut hRequest(L oginConfig  config, S tring requ estURI)
  1007           {
  1008                    Stri ng authMet hod = conf ig.getAuth Method();
  1009                    if ( config !=  null && Co nstants.FO RM_METHOD. equals(aut hMethod))
  1010                    {
  1011                             String  loginPage  = config. getLoginPa ge();
  1012                             if (lo ginPage.eq uals(reque stURI))
  1013                             {
  1014                                      getLogge r().debug( " Allow ac cess to lo gin page "  + loginPa ge);
  1015                                      return t rue;
  1016                             }
  1017  
  1018                             // thi s is littl e strange  'cause it  means that  the error  page wont 't
  1019                             // be  returned t o
  1020                             // a u ser before  login. I' m leaving  it like th is on the  assertion
  1021                             // tha t this is  more
  1022                             // sec ure by not  allowing  any clues  about the  applicatio n to escap e
  1023                             // in  the error  page
  1024                             String  errorPage  = config. getErrorPa ge();
  1025                             if (er rorPage.eq uals(reque stURI))
  1026                             {
  1027                                      getLogge r().debug( " Allow ac cess to er ror page "  + errorPa ge);
  1028                                      return t rue;
  1029                             }
  1030  
  1031                             if (re questURI.e ndsWith(Co nstants.FO RM_ACTION) )
  1032                             {
  1033                                      getLogge r().debug( " Allow ac cess to us ername/pas sword subm ission");
  1034                                      return t rue;
  1035                             }
  1036                    }
  1037  
  1038                    retu rn false;
  1039           }
  1040  
  1041           /* *
  1042            *  Enforce a ny user da ta constra int requir ed by the  security c onstraint
  1043            *  guarding  this reque st URI. Re turn <code >true</cod e> if this  constrain t
  1044            *  was not v iolated an d processi ng should  continue,  or <code>f alse</code >
  1045            *  if we hav e created  a response  already.
  1046            *  
  1047            *  NOTE: thi s is essen tially a c opy of the  code in
  1048            *  org.apach e.catalina .realm.Bas icRealm. D eriving fr om that cl ass would  have
  1049            *  been a be tter solut ion howeve r it makes  assumptio ns related  to passwo rd
  1050            *  matching  that our a uthenticat ion store  will not s upport.
  1051            *  The secti on of the  web config uration th at this co de reflect s looks so mething li ke:
  1052            *  
  1053            *  <security -constrain t>
  1054            *       <dis play-name> XCA Respon ding Gatew ay</displa y-name>
  1055            *       <web -resource- collection >
  1056            *                <web-r esource-na me>Everyth ing</web-r esource-na me>
  1057            *                <descr iption>All  resources  within th e XCA Resp onding Gat eway are p rotected</ descriptio n>
  1058            *                <url-p attern>/*< /url-patte rn>
  1059            *       </we b-resource -collectio n>
  1060            *       <aut h-constrai nt>
  1061            *                <descr iption></d escription >
  1062            *                <role- name>xca</ role-name>
  1063            *                <role- name>devel oper</role -name>
  1064            *       </au th-constra int>
  1065            *       <use r-data-con straint>
  1066            *                <descr iption>Req uires encr yption</de scription>
  1067            *                <trans port-guara ntee>CONFI DENTIAL</t ransport-g uarantee>
  1068            *       </us er-data-co nstraint>
  1069            *  </securit y-constrai nt>
  1070            *  
  1071            *  @param re quest
  1072            *              Request  we are pro cessing
  1073            *  @param re sponse
  1074            *              Response  we are cr eating
  1075            *  @param co nstraints
  1076            *              Security  constrain t being ch ecked
  1077            *  @exceptio n IOExcept ion
  1078            *                  if a n input/ou tput error  occurs
  1079            * /
  1080           pu blic boole an hasUser DataPermis sion(Reque st request , Response  response,  SecurityC onstraint[ ] constrai nts) 
  1081           th rows IOExc eption
  1082           {
  1083                    getL ogger().de bug("hasUs erDataPerm ission(" +  request.g etRequestU RI() + ")  rsID='" +  getRealmSe curityIden tifier() +  "'");
  1084  
  1085                    // A re there a ny securit y-constrai nt element s ?
  1086                    if(  constraint s == null  || constra ints.lengt h == 0 )
  1087                    {
  1088                             getLog ger().info ("  hasUse rDataPermi ssion (" +  request.g etRequestU RI() + ")  rsID='" +  getRealmSe curityIden tifier()
  1089                                      + "', no  security  constraint s provided , returnin g true");
  1090                             return  true;
  1091                    }
  1092  
  1093                    // f or each se curity-con straint el ement in t he web con figuration
  1094                    for(  SecurityC onstraint  constraint  : constra ints )
  1095                    {
  1096                             // get  the user- data-const raints ele ment conte nt
  1097                             String  userConst raint = co nstraint.g etUserCons traint();
  1098                             if (us erConstrai nt == null )
  1099                             {
  1100                                      getLogge r().info("   hasUserD ataPermiss ion (" + r equest.get RequestURI () + ") rs ID='" + ge tRealmSecu rityIdenti fier()
  1101                                               + "', appl icable sec urity cons traint pro vided with  no user c onstraint,  returning  true");
  1102                                      return t rue;
  1103                             }
  1104                             if( Co nstants.NO NE_TRANSPO RT.equals( userConstr aint) )
  1105                             {
  1106                                      getLogge r().info("   hasUserD ataPermiss ion (" + r equest.get RequestURI () + ") rs ID='" + ge tRealmSecu rityIdenti fier()
  1107                                               + "', appl icable sec urity cons traint pro vided with  no transp ort securi ty require d, returni ng true");
  1108                                      return t rue;
  1109                             }
  1110                    }
  1111                    
  1112                    // T he request  is to a s ecure area  that requ ires eithe r INTEGRAL  or CONFID ENTIAL
  1113                    // t ransport g uarantee.  If the req uest is no t already  secure the n redirect  it
  1114                    // t o the secu re port.
  1115                    if(  request.is Secure() )
  1116                             return  true;
  1117                    else
  1118                    {
  1119                             // Val idate the  request ag ainst the  user data  constraint
  1120                             /*
  1121                              * if(  request.g etRequest( ).isSecure () ) { log ger.debug( " User dat a
  1122                              * con straint al ready sati sfied for  request ["  + request .getReques tURI() +
  1123                              * "]" ); return  true; }
  1124                              */
  1125                             
  1126                             // Ini tialize va riables we  need to d etermine t he appropr iate actio n
  1127                             int re directPort  = request .getConnec tor().getR edirectPor t();
  1128  
  1129                             // Is  redirectin g disabled ?
  1130                             if (re directPort  <= 0)
  1131                             {
  1132                                      getLogge r().info("   hasUserD ataPermiss ion (" + r equest.get RequestURI () + ") rs ID='" + ge tRealmSecu rityIdenti fier()
  1133                                               + "', SSL  redirect i s disabled , returnin g false (H TTP 403)") ;
  1134                                      response .sendError (403, requ est.getReq uestURI()) ;
  1135                                      return f alse;
  1136                             }
  1137  
  1138                             // Red irect to t he corresp onding SSL  port
  1139                             String Buffer fil e = new St ringBuffer ();
  1140                             String  protocol  = "https";
  1141                             String  host = re quest.getS erverName( );
  1142                             // Pro tocol
  1143                             file.a ppend(prot ocol).appe nd("://"). append(hos t);
  1144                             // Hos t with por t
  1145                             if (re directPort  != 443)
  1146                                      file.app end(":").a ppend(redi rectPort);
  1147  
  1148                             // URI
  1149                             file.a ppend(requ est.getReq uestURI()) ;
  1150                             String  requested SessionId  = request. getRequest edSessionI d();
  1151                             if ((r equestedSe ssionId !=  null) &&  request.is RequestedS essionIdFr omURL())
  1152                             {
  1153                                      file.app end(";jses sionid=");
  1154                                      file.app end(reques tedSession Id);
  1155                             }
  1156  
  1157                             String  queryStri ng = reque st.getQuer yString();
  1158                             if (qu eryString  != null)
  1159                             {
  1160                                      file.app end('?');
  1161                                      file.app end(queryS tring);
  1162                             }
  1163                             getLog ger().debu g("  Redir ecting req uest [" +  request.ge tRequestUR I() + "] t o [" + fil e.toString () + "]");
  1164                             respon se.sendRed irect(file .toString( ));
  1165  
  1166                             getLog ger().info ("  hasUse rDataPermi ssion (" +  request.g etRequestU RI() + ")  rsID='" +  getRealmSe curityIden tifier()
  1167                                               + " return ing false" );
  1168                             return  false;
  1169                    }
  1170                    
  1171           }
  1172  
  1173           /*
  1174            *  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ====
  1175            * /
  1176           /* *
  1177            *  Return th e Security Constraint s configur ed to guar d the requ est URI fo r
  1178            *  this requ est, or <c ode>null</ code> if t here is no  such cons traint.
  1179            *  
  1180            *  <security -constrain t> <web-re source-col lection> < web-resour ce-name>
  1181            *  <descript ion> <url- pattern> < http-metho d> <auth-c onstraint>  <role-nam e>
  1182            *  <user-dat a-constrai nt> <trans port-guara ntee>
  1183            *  
  1184            *  The web-r esource-co llection e lement is  used to id entify a s ubset of t he
  1185            *  resources  and HTTP  methods on  those res ources wit hin a web  applicatio n to
  1186            *  which a s ecurity co nstraint a pplies. If  no HTTP m ethods are  specified ,
  1187            *  then the  security c onstraint  applies to  all HTTP  methods.
  1188            *  
  1189            *  The url-p attern ele ment conta ins the ur l pattern  of the map ping. Must
  1190            *  follow th e rules sp ecified in  Section 1 1.2 of the  Servlet A PI
  1191            *  Specifica tion. Esse ntially th at means;  "/xxx/*" m atches any thing star ting
  1192            *  with /xxx  "*.xxx" m atches any thing endi ng with .x xx anythin g else mat ches
  1193            *  exactly.
  1194            *  
  1195            *  The http- method con tains an H TTP method  (GET | PO ST |...).  No http-me thod
  1196            *  matches a ny method
  1197            *  
  1198            *  @param re quest
  1199            *              Request  we are pro cessing
  1200            *  @param co ntext
  1201            *              Context  the Reques t is mappe d to
  1202            * /
  1203           pu blic Secur ityConstra int[] find SecurityCo nstraints( Request re quest, Con text conte xt)
  1204           {
  1205                    // f indSecurit yConstrain ts is the  first call  made for  each trans action,
  1206                    // c reate the  unique ID
  1207                    setR ealmSecuri tyIdentifi er();
  1208  
  1209                    // T he mapping  to applic able Secur ityConstra int is don e on the r equestURI  and the re quest meth od.
  1210                    // T he request PathInfo w ill contai n the path , includin g the cont ext.
  1211                    // e .g. /Vix/s ecure/Tran sactionLog .jspx 
  1212                    // w here: "Vix " is the c ontext nam e
  1213                    // a nd "secure /Transacti onLog.jspx " is the s ervlet pat h and addi tional pat h info
  1214                    // t he query s tring is N OT include d
  1215                    // T he request Method is  (probably)  an HTTP r equest met hod.
  1216                    Stri ng request PathInfo =  request.g etRequestU RI();
  1217                    Stri ng request Method = r equest.get Method();
  1218                    
  1219                    // r equestCont extPath is  the path  to the Con text
  1220                    Stri ng request ContextPat h = reques t.getConte xtPath();
  1221                    
  1222                    // g et the por tion of th e URL whic h is mappe d in the w eb context
  1223                    // u nder <secu rity-const raint> <we b-resource -collectio n> <url-pa ttern>
  1224                    Stri ng context RequestPat h = reques tPathInfo;
  1225                    
  1226                    // A s far as I 've been a ble to tel l, this ne xt test wi ll always  be true,
  1227                    // t hat is the  requestPa thInfo alw ays starts  with the  context.
  1228                    // T he context RequestPat h is the p ath withou t the cont ext part o f the path .
  1229                    if ( requestPat hInfo.star tsWith(req uestContex tPath))
  1230                             contex tRequestPa th = reque stPathInfo .substring (requestCo ntextPath. length());
  1231                    
  1232                    
  1233                    retu rn findSec urityConst raints(con text, requ estPathInf o, request Method, co ntextReque stPath);
  1234           }
  1235  
  1236           /* *
  1237            *  Return an  Array of  SecurityCo nstraint a pplicable  to the res ource as s pecified b y the
  1238            *  Context,  the reques t path and  the metho d.
  1239            *  
  1240        * @pa ram contex t - the ap plication  Context
  1241        * @pa ram reques tPathInfo  - the requ est path ( from the s ervlet req uest)
  1242        * @pa ram reques tMethod -  the reques t method,  probably a n HTTP met hod
  1243        * @pa ram contex tRequestPa th - the p ath within  the conte xt of the  requested  resource
  1244        *                                the c ontext nam e appended  to the co ntextReque stPath sho uld be the  requestPa thInfo
  1245        * 
  1246        * @re turn
  1247        */
  1248       privat e Security Constraint [] findSec urityConst raints(
  1249                    Cont ext contex t, 
  1250                    Stri ng request PathInfo, 
  1251                    Stri ng request Method,
  1252                String c ontextRequ estPath)
  1253       {
  1254                // The S ecurityCon straintKey  uses the  requestPat hInfo (wit h the cont ext path)  so tha the  cached
  1255                    // k eys includ e the cont ext (other wise we'd  apply a pr emission i n one web  app to the  same path
  1256                    // i n another  web app.
  1257                    Secu rityConstr aintCacheK ey constra intKey = n ew Securit yConstrain tCacheKey( requestPat hInfo, req uestMethod );
  1258  
  1259                    getL ogger().de bug(
  1260                                      "findSec urityConst raints(" +  context.g etName() +  ", " + co nstraintKe y.toString () + 
  1261                                      ") rsID= '" + getRe almSecurit yIdentifie r() + "'." );
  1262  
  1263                    Secu rityConstr aint[] res ult = null ;
  1264                    // i f security  constrain t caching  is turned  on then lo ok there f irst
  1265                    // t he cached  security c onstraints  are index ed by the  context an d the cons traintKey,  which
  1266                    // i s a combin ation of r equest pat h and requ est method .
  1267                    resu lt = getCa chedSecuri tyConstrai nt(context , constrai ntKey);
  1268                    getL ogger().de bug("findS ecurityCon straints("  + constra intKey.toS tring() +  ") rsID='"  + getReal mSecurityI dentifier( )
  1269                             + "' l ocated " +  (result = = null ? 0  : result. length) +  " constrai nts in cac he");
  1270                    
  1271                    // t he constra ints for t his URL we re not cac hed
  1272                    if(  result ==  null )
  1273                    {
  1274                             // Are  there any  defined s ecurity co nstraints?
  1275                             // if  not then r eturn null , i.e. if  there are  no securit y constrai nts
  1276                             // the n
  1277                             // the re are no  applicable  security  constraint s
  1278                             Securi tyConstrai nt[] conte xtSecurity Constraint s = contex t.findCons traints();
  1279                             getLog ger().debu g(
  1280                                               "findSecur ityConstra ints(" + c onstraintK ey.toStrin g() + 
  1281                                               ") rsID='"  + getReal mSecurityI dentifier( ) +
  1282                                      "'  " +  (contextSe curityCons traints ==  null ? 0  : contextS ecurityCon straints.l ength) + 
  1283                                      " securi ty constra ints defin ed for ent ire contex t '" + con text.getNa me() + 
  1284                                      "', all  requests w ill be gra nted if no  security  constraint s are defi ned.");
  1285                             
  1286                             // som e security  constrain ts are def ined, find  the ones  applicable  to this r equest 
  1287                             if( co ntextSecur ityConstra ints != nu ll || cont extSecurit yConstrain ts.length  > 0 )
  1288                             {
  1289                                      getLogge r().debug( "findSecur ityConstra ints findi ng securit y constrai nts applic able to pa th [" + co ntextReque stPath + " ] from "
  1290                                               + contextS ecurityCon straints.l ength + "  constraint s in conte xt");
  1291  
  1292                                      // selec ts the sec urity cons traints th at match t he path in fo, and me thod
  1293                                      ArrayLis t<Security Constraint Match> con textMatche dSecurityC onstraints  = 
  1294                                               getMatchin gSecurityC onstraints (contextSe curityCons traints, c ontextRequ estPath, r equestMeth od);
  1295  
  1296                                      if (cont extMatched SecurityCo nstraints  == null ||  contextMa tchedSecur ityConstra ints.size( ) < 1)
  1297                                               getLogger( ).debug("N o applicab le securit y constrai nts found  for '" + c onstraintK ey.toStrin g() + "'." );
  1298                                      else
  1299                                               Collection s.sort(con textMatche dSecurityC onstraints );
  1300  
  1301                                      getLogge r().debug( "For '" +  constraint Key.toStri ng() + "'  adding " +  contextMa tchedSecur ityConstra ints.size( ) + " secu rity const raints to  cache");
  1302  
  1303                                      putToSec urityConst raintsCach e(context,  constrain tKey, cont extMatched SecurityCo nstraints) ;
  1304  
  1305                                      getLogge r().debug( "findSecur ityConstra ints(" + c onstraintK ey.toStrin g() + ") r sID='" + g etRealmSec urityIdent ifier() +  "' - retur ning "
  1306                                               + contextM atchedSecu rityConstr aints.size () + " sec urity cons traints.") ;
  1307  
  1308                                      // retur ns null if  the List  is null or  zero leng th
  1309                                      result =  resultsTo Array(cont extMatched SecurityCo nstraints) ;
  1310                             }
  1311                    }
  1312                    
  1313                    // i f the resu lt is empt y then we  need to re turn null.   An empty  array is  not the sa me as a nu ll array ( they are h andled dif ferently).
  1314                    if(( result ==  null) || ( result.len gth <= 0))
  1315                             return  null;
  1316                    
  1317                    retu rn result;
  1318       }
  1319  
  1320           /* *
  1321        * @pa ram reques tPathInfo
  1322        * @pa ram reques tMethod
  1323        * @pa ram securi tyConstrai nts
  1324        * @re turn
  1325        */
  1326       privat e ArrayLis t<Security Constraint Match> get MatchingSe curityCons traints(
  1327           Se curityCons traint[] s ecurityCon straints, 
  1328           St ring reque stPathInfo
  1329           St ring reque stMethod)
  1330       {
  1331                ArrayLis t<Security Constraint Match> res ults = 
  1332                    new  ArrayList< SecurityCo nstraintMa tch>();
  1333                
  1334                    // f or each of  the <secu rity-const raint> ele ments (in  the web ap p
  1335                    // d eployment  descriptor )
  1336                    for  (SecurityC onstraint  securityCo nstraint :  securityC onstraints )
  1337                    {
  1338                             getLog ger().debu g("  Evalu ating <sec urity-cons traint> '"  + securit yConstrain t + "' aga inst " + r equestMeth od + "-" +  requestPa thInfo);
  1339  
  1340                             // Fin d the web- resource-c ollection  elements w ithin the  security
  1341                             // con straints
  1342                             // A w eb-resourc e-collecti on element  includes  the url-pa ttern and
  1343                             // htt p-method e lements. T he request
  1344                             // mus t match ag ainst both  url-patte rn and htt p-method.
  1345                             Securi tyCollecti on[] webRe sourceColl ections =  securityCo nstraint.f indCollect ions();
  1346  
  1347                             if (we bResourceC ollections  == null)
  1348                             {
  1349                                      getLogge r().debug( "  <securi ty-constra int> '" +  securityCo nstraint +  "' has no  web resou rces defin ed, ignori ng ...");
  1350                                      continue ;
  1351                             }
  1352  
  1353                             // log ger.debug( " Checking  constrain t '" + sec urityConst raint +
  1354                             // "'  against "  + requestM ethod + "  " + pathIn fo + " -->  " +
  1355                             // sec urityConst raint.incl uded(pathI nfo, reque stMethod)) ;
  1356  
  1357                             // sea rch for an y exact ma tches to t he request URI
  1358                             for (S ecurityCol lection we bResourceC ollection  : webResou rceCollect ions)
  1359                             {
  1360                                      getLogge r().debug( "    Check ing <web-r esource-co llection>  '" + webRe sourceColl ection + " ' against  " + reques tMethod +  "-"
  1361                                               + requestP athInfo);
  1362  
  1363                                      // get t he url-pat tern eleme nts within  the
  1364                                      // web-r esource-co llection
  1365                                      String[]  urlPatter ns = webRe sourceColl ection.fin dPatterns( );
  1366  
  1367                                      if (urlP atterns ==  null)
  1368                                               continue;
  1369  
  1370                                      // for e ach patter n in the w eb-resourc e-collecti on
  1371                                      // In th e Web appl ication de ployment d escriptor,  the follo wing
  1372                                      // synta x is used  to define
  1373                                      // mappi ngs:
  1374                                      // • A s tring begi nning with  a ‘/’ cha racter and  ending wi th a
  1375                                      // ‘/*’  suffix is  used
  1376                                      // for p ath mappin g.
  1377                                      // • A s tring begi nning with  a ‘*.’ pr efix is us ed as an
  1378                                      // exten sion mappi ng.
  1379                                      // • A s tring cont aining onl y the ’/’  character  indicates  the
  1380                                      // "defa ult" servl et of
  1381                                      // the a pplication . In this  case the s ervlet pat h is the r equest
  1382                                      // URI m inus the c ontext
  1383                                      // path  and the pa th info is  null.
  1384                                      // • All  other str ings are u sed for ex act matche s only.
  1385                                      //
  1386                                      // Exact  match tak es precede nce over p ath and ex tension.
  1387                                      // Path  match take s preceden ce over ex tension.
  1388                                      // Defau lt servlet  matches a nything el se.
  1389                                      for (int  urlPatter nIndex = 0 ; urlPatte rnIndex <  urlPattern s.length;  urlPattern Index++)
  1390                                      {
  1391                                               String url Pattern =  urlPattern s[urlPatte rnIndex];
  1392                                               boolean pa tternIsDef aultMatch  = "/".equa ls(urlPatt ern);
  1393                                               boolean pa tternIsPat hMatch = u rlPattern. startsWith ("/") && u rlPattern. endsWith(" /*");
  1394                                               boolean pa tternIsAny PathMatch  = "/*".equ als(urlPat tern);
  1395                                               boolean pa tternIsExt ensionMatc h = urlPat tern.start sWith("*." );
  1396                                               boolean pa tternIsExa ctMatch =  !patternIs DefaultMat ch && !pat ternIsAnyP athMatch & & !pattern IsPathMatc h
  1397                                                       &&  !patternI sExtension Match;
  1398  
  1399                                               getLogger( ).debug("     Checkin g <url-pat tern> '" +  urlPatter n + (patte rnIsDefaul tMatch ? " ' as defau lt match"  : "")
  1400                                                       +  (patternIs AnyPathMat ch ? "' as  any path  match" : " ") + (patt ernIsExact Match ? "'  as exact  match" : " ")
  1401                                                       +  (patternIs PathMatch  ? "' as pa th match"  : "") + (p atternIsEx tensionMat ch ? "' as  extension  match" :  "")
  1402                                                       +  "' against  " + reque stMethod +  " " + req uestPathIn fo);
  1403  
  1404                                               if (patter nIsDefault Match && w ebResource Collection .findMetho d(requestM ethod))
  1405                                               {
  1406                                                       ge tLogger(). debug("Def ault match  '" + urlP attern + " ' found");
  1407                                                       re sults.add( SecurityCo nstraintMa tch.create DefaultSec urityConst raintMatch (securityC onstraint,  urlPatter n));
  1408                                               } else if  (patternIs AnyPathMat ch && webR esourceCol lection.fi ndMethod(r equestMeth od))
  1409                                               {
  1410                                                       ge tLogger(). debug("Any  path patt ern match  '" + urlPa ttern + "'  found");
  1411                                                       re sults.add( SecurityCo nstraintMa tch.create PathSecuri tyConstrai ntMatch(se curityCons traint, ur lPattern)) ;
  1412                                               }
  1413                                               // if the  url-patter n is an ex act match  for the re quest URI
  1414                                               // then ad d it direc tly to the  results a rray
  1415                                               else if (p atternIsEx actMatch & & requestP athInfo.eq uals(urlPa ttern) &&  webResourc eCollectio n.findMeth od(request Method))
  1416                                               {
  1417                                                       ge tLogger(). debug("Exa ct pattern  match '"  + urlPatte rn + "' fo und");
  1418                                                       re sults.add( SecurityCo nstraintMa tch.create ExactSecur ityConstra intMatch(s ecurityCon straint, u rlPattern) );
  1419                                               } else if  (patternIs PathMatch)
  1420                                               {
  1421                                                       St ring[] url PatternPat hComponent s = urlPat tern.split ("/");
  1422                                                       St ring[] req uestCompon ents = req uestPathIn fo.split(" /");
  1423                                                       in t patternL ength = ur lPatternPa thComponen ts.length;
  1424                                                       in t requestC omponentsL ength = re questCompo nents.leng th;
  1425  
  1426                                                       //  if the re quest has  fewer elem ents than  the patter n
  1427                                                       //  then it c annot matc h
  1428                                                       bo olean matc hes = requ estCompone ntsLength  >= pattern Length;
  1429                                                       fo r (int pat ternCompon entIndex =  0; matche s && patte rnComponen tIndex < p atternLeng th
  1430                                                                && ( !"*".equal s(urlPatte rnPathComp onents[pat ternCompon entIndex]) ); ++patte rnComponen tIndex)
  1431                                                       {
  1432                                                                Stri ng pattern Component  = urlPatte rnPathComp onents[pat ternCompon entIndex];
  1433                                                                Stri ng request Component  = requestC omponents[ patternCom ponentInde x];
  1434  
  1435                                                                getL ogger().de bug("       Checking  <url-patte rn> path c omponent ' " + patter nComponent  + "' to r equest com ponent '"
  1436                                                                         + requ estCompone nt + "'");
  1437  
  1438                                                                // i f path com ponent doe sn't match , set matc hes to
  1439                                                                // f alse
  1440                                                                matc hes = patt ernCompone nt.equals( requestCom ponent);
  1441                                                       }
  1442                                                       //  if we mat ched all o f the patt ern compon ents
  1443                                                       if  (matches)
  1444                                                       {
  1445                                                                getL ogger().de bug("Path  pattern ma tch '" + u rlPattern  + "' found ");
  1446                                                                resu lts.add(Se curityCons traintMatc h.createPa thSecurity Constraint Match(secu rityConstr aint, urlP attern));
  1447                                                       }
  1448                                               } else if  (patternIs ExtensionM atch)
  1449                                               {
  1450                                                       in t extensio nIndex = u rlPattern. indexOf('. ');
  1451                                                       St ring exten sion = url Pattern.su bstring(ex tensionInd ex);
  1452                                                       if  (requestP athInfo.en dsWith(ext ension) &&  webResour ceCollecti on.findMet hod(reques tMethod))
  1453                                                       {
  1454                                                                getL ogger().de bug("Exten sion patte rn match ' " + urlPat tern + "'  found");
  1455                                                                resu lts.add(Se curityCons traintMatc h.createEx tensionSec urityConst raintMatch (securityC onstraint,  urlPatter n));
  1456                                                       }
  1457                                               }
  1458                                      }
  1459                             }
  1460                    }
  1461                return r esults;
  1462       }
  1463  
  1464           /* *
  1465            *  Convert a n ArrayLis t to a Sec urityContr aint [].
  1466            * /
  1467           pr ivate Secu rityConstr aint[] res ultsToArra y(ArrayLis t<Security Constraint Match> res ults)
  1468           {
  1469                    if ( results ==  null || r esults.siz e() < 1)
  1470                             return  null;
  1471  
  1472                    Secu rityConstr aint[] arr ay = new S ecurityCon straint[re sults.size ()];
  1473  
  1474                    int  index = 0;
  1475                    for  (SecurityC onstraintM atch match  : results )
  1476                    {
  1477                             array[ index] = m atch.getSe curityCons traint();
  1478                             ++inde x;
  1479                    }
  1480  
  1481                    retu rn array;
  1482           }
  1483           
  1484           
  1485           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========
  1486           //  Inner cla sses
  1487           //  Cache key s and valu es
  1488           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========
  1489  
  1490           cl ass FullyQ ualifiedPr incipalNam e
  1491           {
  1492                    priv ate final  String rea lm;
  1493                    priv ate final  String nam e;
  1494  
  1495                    publ ic FullyQu alifiedPri ncipalName (VistaReal mPrincipal  principal )
  1496                    {
  1497                             this.r ealm = pri ncipal.get Realm();
  1498                             this.n ame = prin cipal.getA ccessCode( );
  1499                    }
  1500  
  1501                    publ ic FullyQu alifiedPri ncipalName (String re alm, Strin g name)
  1502                    {
  1503                             this.r ealm = rea lm;
  1504                             this.n ame = name ;
  1505                    }
  1506  
  1507                    publ ic String  getRealm()
  1508                    {
  1509                             return  realm;
  1510                    }
  1511  
  1512                    publ ic String  getName()
  1513                    {
  1514                             return  name;
  1515                    }
  1516  
  1517                    @Ove rride
  1518                    publ ic String  toString()
  1519                    {
  1520                             return  getRealm( ) + "/" +  getName();
  1521                    }
  1522  
  1523                    @Ove rride
  1524                    publ ic int has hCode()
  1525                    {
  1526                             final  int prime  = 31;
  1527                             int re sult = 1;
  1528                             result  = prime *  result +  ((name ==  null) ? 0  : name.has hCode());
  1529                             result  = prime *  result +  ((realm ==  null) ? 0  : realm.h ashCode()) ;
  1530                             return  result;
  1531                    }
  1532  
  1533                    @Ove rride
  1534                    publ ic boolean  equals(Ob ject obj)
  1535                    {
  1536                             if (th is == obj)
  1537                                      return t rue;
  1538                             if (ob j == null)
  1539                                      return f alse;
  1540                             if (ge tClass() ! = obj.getC lass())
  1541                                      return f alse;
  1542                             final  FullyQuali fiedPrinci palName ot her = (Ful lyQualifie dPrincipal Name) obj;
  1543                             if (na me == null )
  1544                             {
  1545                                      if (othe r.name !=  null)
  1546                                               return fal se;
  1547                             } else  if (!name .equals(ot her.name))
  1548                                      return f alse;
  1549                             if (re alm == nul l)
  1550                             {
  1551                                      if (othe r.realm !=  null)
  1552                                               return fal se;
  1553                             } else  if (!real m.equals(o ther.realm ))
  1554                                      return f alse;
  1555                             return  true;
  1556                    }
  1557           }
  1558  
  1559           /* *
  1560            *  
  1561            * /
  1562           cl ass Princi palCacheVa lue
  1563           {
  1564                    priv ate long d ate = Syst em.current TimeMillis ();
  1565                    priv ate VistaR ealmPrinci pal princi pal = null ;
  1566  
  1567                    Prin cipalCache Value(Vist aRealmPrin cipal prin cipal)
  1568                    {
  1569                             // thi s.principa l = princi pal.clone( );
  1570                             this.p rincipal =  principal ;
  1571                    }
  1572  
  1573                    publ ic long ge tDate()
  1574                    {
  1575                             return  this.date ;
  1576                    }
  1577  
  1578                    publ ic VistaRe almPrincip al getPrin cipal()
  1579                    {
  1580                             return  this.prin cipal;
  1581                    }
  1582  
  1583                    /**
  1584                     * S et the inc eption dat e on this  cache entr y to the c urrent dat e
  1585                     */
  1586                    void  touch()
  1587                    {
  1588                             this.d ate = Syst em.current TimeMillis ();
  1589                    }
  1590           }
  1591  
  1592           /* *
  1593            *  
  1594              * @author        
BECKEC
  1595            *  
  1596            * /
  1597           cl ass Securi tyConstrai ntCacheKey
  1598           {
  1599                    priv ate String  requestUr i;
  1600                    priv ate String  httpMetho d;
  1601  
  1602                    publ ic Securit yConstrain tCacheKey( String req uestUri, S tring http Method)
  1603                    {
  1604                             super( );
  1605                             this.r equestUri  = requestU ri;
  1606                             this.h ttpMethod  = httpMeth od;
  1607                    }
  1608  
  1609                    publ ic String  getHttpMet hod()
  1610                    {
  1611                             return  this.http Method;
  1612                    }
  1613  
  1614                    publ ic String  getRequest Uri()
  1615                    {
  1616                             return  this.requ estUri;
  1617                    }
  1618  
  1619                    @Ove rride
  1620                    publ ic int has hCode()
  1621                    {
  1622                             final  int PRIME  = 31;
  1623                             int re sult = 1;
  1624                             result  = PRIME *  result +  ((this.htt pMethod ==  null) ? 0  : this.ht tpMethod.h ashCode()) ;
  1625                             result  = PRIME *  result +  ((this.req uestUri ==  null) ? 0  : this.re questUri.h ashCode()) ;
  1626                             return  result;
  1627                    }
  1628  
  1629                    @Ove rride
  1630                    publ ic boolean  equals(Ob ject obj)
  1631                    {
  1632                             if (th is == obj)
  1633                                      return t rue;
  1634                             if (ob j == null)
  1635                                      return f alse;
  1636                             if (ge tClass() ! = obj.getC lass())
  1637                                      return f alse;
  1638                             final  SecurityCo nstraintCa cheKey oth er = (Secu rityConstr aintCacheK ey) obj;
  1639                             if (th is.httpMet hod == nul l)
  1640                             {
  1641                                      if (othe r.httpMeth od != null )
  1642                                               return fal se;
  1643                             } else  if (!this .httpMetho d.equals(o ther.httpM ethod))
  1644                                      return f alse;
  1645                             if (th is.request Uri == nul l)
  1646                             {
  1647                                      if (othe r.requestU ri != null )
  1648                                               return fal se;
  1649                             } else  if (!this .requestUr i.equals(o ther.reque stUri))
  1650                                      return f alse;
  1651                             return  true;
  1652                    }
  1653  
  1654                    @Ove rride
  1655                    publ ic String  toString()
  1656                    {
  1657                             return  this.getC lass().get SimpleName () + ":" +  this.http Method + " -" + this. requestUri ;
  1658                    }
  1659           }
  1660  
  1661           /* *
  1662            *  
  1663              * @author        
BECKEC
  1664            *  
  1665            * /
  1666           cl ass Securi tyConstrai ntCacheVal ue
  1667           {
  1668                    priv ate long d ate = Syst em.current TimeMillis ();
  1669                    priv ate Securi tyConstrai nt[] const raints;
  1670  
  1671                    publ ic Securit yConstrain tCacheValu e(Security Constraint [] constra ints)
  1672                    {
  1673                             super( );
  1674                             // mak e a copy o f the arra y so that  if someone  else mess es with it ,
  1675                             // our  copy is s till valid
  1676                             this.c onstraints  = new Sec urityConst raint[cons traints.le ngth];
  1677                             System .arraycopy (constrain ts, 0, thi s.constrai nts, 0, co nstraints. length);
  1678                    }
  1679  
  1680                    publ ic Securit yConstrain t[] getCon straints()
  1681                    {
  1682                             return  this.cons traints;
  1683                    }
  1684  
  1685                    publ ic long ge tDate()
  1686                    {
  1687                             return  this.date ;
  1688                    }
  1689  
  1690                    void  touch()
  1691                    {
  1692                             this.d ate = Syst em.current TimeMillis ();
  1693                    }
  1694           }
  1695  
  1696           /*  (non-Java doc)
  1697            *  @see java .lang.Obje ct#hashCod e()
  1698            * /
  1699           @O verride
  1700           pu blic int h ashCode()
  1701           {
  1702                    fina l int prim e = 31;
  1703                    int  result = 1 ;
  1704                    resu lt = prime  * result  + ((this.s iteNumber  == null) ?  0 : this. siteNumber .hashCode( ));
  1705                    retu rn result;
  1706           }
  1707  
  1708           /*  (non-Java doc)
  1709            *  @see java .lang.Obje ct#equals( java.lang. Object)
  1710            * /
  1711           @O verride
  1712           pu blic boole an equals( Object obj )
  1713           {
  1714                    if ( this == ob j)
  1715                             return  true;
  1716                    if ( obj == nul l)
  1717                             return  false;
  1718                    if ( getClass()  != obj.ge tClass())
  1719                             return  false;
  1720                    Abst ractVistaR ealmImpl o ther = (Ab stractVist aRealmImpl ) obj;
  1721                    if ( this.siteN umber == n ull)
  1722                    {
  1723                             if (ot her.siteNu mber != nu ll)
  1724                                      return f alse;
  1725                    }
  1726                    else  if (!this .siteNumbe r.equals(o ther.siteN umber))
  1727                             return  false;
  1728                    retu rn true;
  1729           }
  1730   }