797. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 10/18/2018 2:02:21 PM Central Daylight 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.

797.1 Files compared

# Location File Last Modified
1 VIX_SIV_v3_0_patch_201_build_8.zip\v3.0_patch_201_build_8\VISA\Java\VistaDataSourceCommon\main\src\java\gov\va\med\imaging\vistadatasource\session VistaSession.java Thu Oct 11 13:30:19 2018 UTC
2 VIX_SIV_v3_0_patch_201_build_8.zip\v3.0_patch_201_build_8\VISA\Java\VistaDataSourceCommon\main\src\java\gov\va\med\imaging\vistadatasource\session VistaSession.java Wed Oct 17 19:07:53 2018 UTC

797.2 Comparison summary

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

797.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

797.4 Active regular expressions

No regular expressions were active.

797.5 Comparison detail

  1   /**
  2    * 
  3     Package:  MAG - Vis tA Imaging
  4     WARNING:  Per VHA D irective 2 004-038, t his routin e should n ot be modi fied.
  5     Date Cre ated: Feb  7, 2008
  6     Site Nam e:  Washin gton OI Fi eld Office , Silver S pring, MD
  7       Developer:     PI I
  8     Descript ion: 
  9  
  10           ;;  +-------- ---------- ---------- ---------- ---------- ---------- ---------- +
  11           ;;  Property  of the US  Government .
  12           ;;  No permis sion to co py or redi stribute t his softwa re is give n.
  13           ;;  Use of un released v ersions of  this soft ware requi res the us er
  14           ;;   to execu te a writt en test ag reement wi th the Vis tA Imaging
  15           ;;   Developm ent Office  of the De partment o f Veterans  Affairs,
  16           ;;   telephon e (301) 73 4-0100.
  17           ;;
  18           ;;  The Food  and Drug A dministrat ion classi fies this  software a s
  19           ;;  a Class I I medical  device.  A s such, it  may not b e changed
  20           ;;  in any wa y.  Modifi cations to  this soft ware may r esult in a n
  21           ;;  adulterat ed medical  device un der 21CFR8 20, the us e of which
  22           ;;  is consid ered to be  a violati on of US F ederal Sta tutes.
  23           ;;  +-------- ---------- ---------- ---------- ---------- ---------- ---------- +
  24  
  25    */
  26   package go v.va.med.i maging.vis tadatasour ce.session ;
  27  
  28   import gov .va.med.im aging.core .interface s.exceptio ns.Credent ialsExpire dException ;
  29   import gov .va.med.im aging.core .interface s.exceptio ns.Invalid UserCreden tialsExcep tion;
  30   import gov .va.med.im aging.core .interface s.exceptio ns.MethodE xception;
  31   import gov .va.med.im aging.Stri ngUtil;
  32   import gov .va.med.im aging.core .interface s.exceptio ns.Connect ionExcepti on;
  33   import gov .va.med.im aging.core .interface s.exceptio ns.Securit yCredentia lsExpiredE xception;
  34   import gov .va.med.im aging.data source.exc eptions.In validCrede ntialsExce ption;
  35   import gov .va.med.im aging.exch ange.busin ess.Site;
  36   import gov .va.med.im aging.exch ange.enums .ImagingSe curityCont extType;
  37   import gov .va.med.im aging.prot ocol.vista .VistaComm onTranslat or;
  38   import gov .va.med.im aging.prot ocol.vista .VistaLogi nMethod;
  39   import gov .va.med.im aging.prot ocol.vista .exception s.BseFaile dException ;
  40   import gov .va.med.im aging.prot ocol.vista .exception s.MissingC redentials Exception;
  41   import gov .va.med.im aging.prot ocol.vista .exception s.UnableTo CreateCont extExcepti on;
  42   import gov .va.med.im aging.prot ocol.vista .exception s.VistaCon nectionExc eption;
  43   import gov .va.med.im aging.prot ocol.vista .exception s.VistaPar singExcept ion;
  44   import gov .va.med.im aging.tran sactioncon text.Trans actionCont ext;
  45   import gov .va.med.im aging.tran sactioncon text.Trans actionCont extFactory ;
  46   import gov .va.med.im aging.url. vista.Stri ngUtils;
  47   import gov .va.med.im aging.url. vista.Vist aConnectio n;
  48   import gov .va.med.im aging.url. vista.Vist aQuery;
  49   import gov .va.med.im aging.url. vista.exce ptions.Inv alidVistaC redentials Exception;
  50   import gov .va.med.im aging.url. vista.exce ptions.Vis taMethodEx ception;
  51   import gov .va.med.im aging.vist adatasourc e.VistaCom monQueryFa ctory;
  52   import gov .va.med.im aging.vist adatasourc e.session. bse.VistaS essionBSEC ache;
  53   import gov .va.med.im aging.vist adatasourc e.session. bse.VistaS iteBseStat us;
  54   import gov .va.med.im aging.vist adatasourc e.session. configurat ion.VistaS essionConf iguration;
  55  
  56   import jav a.io.IOExc eption;
  57   import jav a.net.URL;
  58  
  59   import org .apache.lo gging.log4 j.LogManag er;
  60   import org .apache.lo gging.log4 j.Logger;
  61  
  62   /**
  63    * Represe nts a logg ed-in sess ion of a V ista user.
  64    * Impleme ntation of  the funct ions and p rocess nec essary to  login to V ista.  
  65    * Impleme nts the lo cal connec tion and t he remote  connection  methods
  66    * 
  67    * @author   PI I
  68    *
  69    */
  70   public cla ss VistaSe ssion
  71   {
  72           pr ivate fina l static L ogger logg er = LogMa nager.getL ogger(Vist aSession.c lass);
  73           
  74           // private fi nal static  String MA G_WINDOWS_ CONTEXT =  "MAG WINDO WS";
  75           pr ivate fina l static S tring CAPR I_CONTEXT  = "DVBA CA PRI GUI";
  76  
  77           pr ivate fina l static i nt FAILED_ SIGNON_MAX _COUNT = 1 0;           // maxim um number  of times t o retry an  RPC_SIGNO N
  78           pr ivate fina l static i nt FAILED_ SIGNON_MIN _WAIT_TIME  = 1000; / / maximum  number of  ms to wait  between r etrying th e RPC_SIGN ON
  79           pr ivate fina l static i nt FAILED_ SIGNIN_MAX _WAIT_TIME  = 3000; / / maximum  number of  ms to wait  between r etrying th e RPC_SIGN ON
  80           
  81           //  default c ontext to  use if non e specifie d in trans action con text
  82           pr ivate fina l static I magingSecu rityContex tType defa ultSecurit yContextTy pe = Imagi ngSecurity ContextTyp e.MAG_WIND OWS;
  83           
  84           //  ========= ========== ========== ========== ========== ========== ========== ========== =======
  85           //  Instance  Members
  86           //  ========= ========== ========== ========== ========== ========== ========== ========== =======
  87           
  88           pr ivate int  failedSign onRetryMax  = FAILED_ SIGNON_MAX _COUNT;               // for the  server, j ust leave  this value  at the de fault
  89           pr ivate int  defaultSit eBrokerCon ncetionTim eout = 25;  // 25 sec onds as de fault
  90                                              
  91           //  vistaLogi nComplete  will be tr ue after t he user ha s been aut henticated
  92           pr ivate bool ean vistaL oginComple te = false ;
  93           pr ivate fina l VistaCon nection vi staConnect ion;
  94           pr ivate fina l Site sit e;
  95           pr ivate long  loginTime  = 0L;
  96           pr ivate long  lastUsedT ime = 0L;
  97           pr ivate long  lastInter nalTime =  0L; // the  last RPC  call both  internal a nd externa l calls
  98           pr ivate bool ean localL ogin = fal se;
  99           pr ivate bool ean sessio nCreated =  false;
  100           pr ivate bool ean vistaR adLoggedIn  = false;
  101           pr ivate int  siteBroker Connection Timeout =  0; // meas ured in se conds
  102           pr ivate long  sessionIn dex = 0L;  // keeps a  unique nu mber repre senting th is session , incremem ents as se ssions are  created
  103  
  104           pr ivate Stri ng securit yContext;
  105           pr ivate Stri ng version  = null;
  106           
  107           pu blic stati c VistaSes sion getOr Create(URL  url, Site  site) 
  108           th rows IOExc eption, Co nnectionEx ception, M ethodExcep tion, Secu rityCreden tialsExpir edExceptio n
  109           {
  110                    retu rn getOrCr eate(url,  site, null , null);
  111           }
  112           
  113           pu blic stati c VistaSes sion getOr Create(URL  url, Site  site, Ima gingSecuri tyContextT ype imagin gSecurityC ontext) 
  114           th rows IOExc eption, Co nnectionEx ception, M ethodExcep tion, Secu rityCreden tialsExpir edExceptio n
  115           {
  116                    retu rn getOrCr eate(url,  site, null , imagingS ecurityCon text);
  117           }
  118           
  119           pu blic stati c VistaSes sion getOr Create(URL  url, Site  site, Str ing versio n) 
  120           th rows IOExc eption, Co nnectionEx ception, M ethodExcep tion, Secu rityCreden tialsExpir edExceptio n
  121           {
  122                    retu rn getOrCr eate(url,  site, vers ion, null) ;
  123           }
  124           
  125           /* *
  126            *  
  127            *  @param ur l
  128            *  @param si te
  129            *  @return
  130            *  @throws I OException  
  131            *  @throws M ethodExcep tion 
  132            *  @throws C onnectionE xception 
  133            * /
  134           pu blic stati c VistaSes sion getOr Create(URL  url, Site  site, Str ing versio n, Imaging SecurityCo ntextType  imagingSec urityConte xt) 
  135           th rows IOExc eption, Co nnectionEx ception, M ethodExcep tion, Secu rityCreden tialsExpir edExceptio n
  136           {
  137                    Stri ng securit yContextTo Set = null ;
  138                    if(i magingSecu rityContex t != null)
  139                             securi tyContextT oSet = ima gingSecuri tyContext. getSecurit yContext() ;
  140                    else
  141                             securi tyContextT oSet = get ImagingSec urityConte xtType().g etSecurity Context();
  142                    logg er.info("g etOrCreate (" + url.t oExternalF orm() + ")  with secu rity Conte xt (" + se curityCont extToSet +  ") and ve rsion (" +  version +  ").");
  143                    Vist aSession s ession = V istaSessio nCache.get Singleton( ).get(url,  securityC ontextToSe t, version );
  144                    logg er.info("g etOrCreate (" + url.t oExternalF orm() + ")  " + 
  145                                      (session  == null ?  "did not  find" : "f ound") + "  session i n cache" ) ;
  146                    
  147                    if(s ession ==  null)
  148                    {
  149                             sessio n = new Vi staSession (url, site , security ContextToS et, versio n);
  150                    
  151                             if(ses sion != nu ll)
  152                             {
  153                                      logger.i nfo("getOr Create(" +  url.toExt ernalForm( ) + ") con necting ne w VistaSes sion.");
  154                                      connectA ndLogin(ur l, session );                   
  155                             }
  156                    }
  157                    
  158                    logg er.info("g etOrCreate (" + url.t oExternalF orm() + ")  " + 
  159                                      (session  == null ?  "did not  instantiat e" : "inst antiated")  + " Vista Session."  );
  160                    
  161                    if(s ession !=  null)
  162                             Transa ctionConte xtFactory. get().setV istaSessio nIndex(ses sion.getSe ssionIndex ());                 
  163                    
  164                    retu rn session ;
  165           }
  166           
  167           /* *
  168            *  Return a  welcome me ssage for  the specif ied site.  This metho d does not  require t he user to  be authen ticated to  VistA
  169            *  
  170            *  @param ur l
  171            *  @param si te
  172            *  @return T he welcome  message d irectly fr om VistA w ithout mod ification
  173            *  @throws I OException
  174            *  @throws V istaMethod Exception
  175            *  @throws I nvalidVist aCredentia lsExceptio n
  176            * /
  177           pu blic stati c String g etWelcomeM essage(URL  url, Site  site)
  178           th rows IOExc eption, Vi staMethodE xception,  InvalidVis taCredenti alsExcepti on
  179           {
  180                    Vist aSession s ession = n ull;
  181                    try
  182                    {
  183                             sessio n = new Vi staSession (url, site , null, nu ll);
  184                             logger .info("get WelcomeMes sage(" + u rl.toExter nalForm()  + ") conne cting Vist aConnectio n." );
  185                             long s tartTime =  System.cu rrentTimeM illis();
  186                             sessio n.connect( );
  187                             logger .info("get WelcomeMes sage(" + u rl.toExter nalForm()  + ") conne cted to Vi sta in '"  + (System. currentTim eMillis()  - startTim e) + "' ms , now logg ing in..." );
  188                             try
  189                    {
  190                                      // anoth er sacrifi ce to Vist a, logging  in too qu ickly afte r connecti ng sometim es causes  problems
  191                         Thread.sle ep(100);
  192                    } 
  193                             catch  (Interrupt edExceptio n e){}
  194                             
  195                             // don 't need to  login, ju st want to  call rpc
  196                             VistaQ uery welco meMessageQ uery = Vis taCommonQu eryFactory .createWel comeMessag eQuery();
  197                             return  session.c all(welcom eMessageQu ery);
  198                    }
  199                    fina lly
  200                    {
  201                             // rig ht now we  are discon necting th e session  immediatel y, not reu sing it in  any way
  202                             // thi s is not v ery effici ent but it  is simple
  203                             if(ses sion != nu ll)
  204                             {
  205                                      session. disconnect (true);                                  
  206                             }
  207                    }
  208           }
  209           
  210           pu blic stati c void aut henticateU ser(URL ur l, Site si te)
  211           th rows Inval idUserCred entialsExc eption, Cr edentialsE xpiredExce ption, Met hodExcepti on, IOExce ption, Con nectionExc eption
  212           {
  213                    Vist aSession s ession = n ull;
  214                    try
  215                    {
  216                             Imagin gSecurityC ontextType  securityC ontext = g etImagingS ecurityCon textType() ;
  217                             sessio n = new Vi staSession (url, site , security Context.ge tSecurityC ontext(),  null);
  218                             logger .info("aut henticateU ser(" + ur l.toExtern alForm() +  ") connec ting Vista Connection ." );
  219                             long s tartTime =  System.cu rrentTimeM illis();
  220                             sessio n.connect( );
  221                             logger .info("aut henticateU ser(" + ur l.toExtern alForm() +  ") connec ted to Vis ta in '" +  (System.c urrentTime Millis() -  startTime ) + "' ms,  now loggi ng in...") ;
  222                             try
  223                    {
  224                                      // anoth er sacrifi ce to Vist a, logging  in too qu ickly afte r connecti ng sometim es causes  problems
  225                         Thread.sle ep(100);
  226                    } 
  227                             catch  (Interrupt edExceptio n e){}
  228                             
  229                             sessio n.localLog in();
  230                             
  231                             Transa ctionConte xt transac tionContex t = Transa ctionConte xtFactory. get();
  232                             transa ctionConte xt.setSite Name(site. getSiteNam e());
  233                             transa ctionConte xt.setSite Number(sit e.getSiteN umber());
  234                             
  235                             VistaQ uery userI nformation Query = Vi staCommonQ ueryFactor y.createGe tUserInfor mationQuer y();
  236                             try
  237                             {
  238                                      String u serInforma tion = ses sion.call( userInform ationQuery );
  239                                      if(userI nformation  == null)
  240                                               throw new  MethodExce ption("No  user infor mation ret rieved");
  241                                      String[]  userInfor mationPart s = String Utils.Spli t(userInfo rmation,St ringUtils. NEW_LINE);
  242                                      String d uz = null;
  243                                      try 
  244                                      {
  245                                               duz = user Informatio nParts[0]. trim();
  246                                               transactio nContext.s etDuz(duz) ;
  247                                               transactio nContext.s etFullName (userInfor mationPart s[1].trim( ));
  248                             } 
  249                             catch  (Exception  ex) 
  250                                      {
  251                                      throw ne w MethodEx ception("U nable to r etrieve ei ther user  DUZ and/or  Full Name . " + ex);
  252                             }
  253                             VistaQ uery ssnQu ery = Vist aCommonQue ryFactory. createGetU serSsnQuer y(duz);
  254                             try 
  255                             {
  256                                      String r tn = null;
  257                                      rtn = se ssion.call (ssnQuery) ;
  258                                      
  259                                      if (rtn  == null ||  rtn.equal s("")) 
  260                                 {
  261                                      throw ne w MethodEx ception("U nable to r etrieve us er SSN.");
  262                                 }
  263                                      String [ ] ssnParts  = StringU tils.Split (rtn, Stri ngUtils.CA RET);
  264                                 tr
  265                                      {
  266                                      transact ionContext .setSsn(ss nParts[8]) ;
  267                                 } 
  268                                 ca tch (Excep tion ex) 
  269                                      {
  270                                      throw ne w MethodEx ception("U nable to r etrieve us er SSN. "  + ex);
  271                                 }
  272                             }
  273                             catch( Exception  ex) 
  274                             {
  275                                      throw ne w MethodEx ception(ex );                            
  276                             }
  277                             } 
  278                             catch  (InvalidVi staCredent ialsExcept ion e)
  279                             {
  280                                      throw ne w InvalidU serCredent ialsExcept ion(e);
  281                             } 
  282                             
  283                             catch  (VistaMeth odExceptio n e)
  284                             {
  285                                      throw ne w MethodEx ception(e) ;
  286                             }
  287                             sessio n.vistaLog inComplete  = true;
  288                    sess ion.loginT ime = Syst em.current TimeMillis ();
  289                    sess ion.localL ogin = tru e;
  290                    tran sactionCon text.setLo ginMethod( VistaLogin Method.loc al.toStrin g());
  291                    logg er.info("L ocal login  successfu l." ); 
  292                    sess ion.getSit eBrokerTim eout();
  293                    }
  294                    catc h(MissingC redentials Exception  mcX)
  295                    {
  296                             throw  new Invali dUserCrede ntialsExce ption(mcX) ;
  297                    }
  298                    fina lly
  299                    {
  300                             // dis connect th e session  but leave  it open to  possibly  be used la ter
  301                             if(ses sion != nu ll)
  302                             {
  303                                      session. close();                                   
  304                             }
  305                    }
  306           }
  307           
  308           pr ivate stat ic void co nnectAndLo gin(URL ur l, VistaSe ssion sess ion)
  309           th rows IOExc eption, Me thodExcept ion, Conne ctionExcep tion
  310           {
  311                    logg er.info("c onnectAndL ogin(" + u rl.toExter nalForm()  + ") conne cting Vist aConnectio n." );
  312                    long  startTime  = System. currentTim eMillis();
  313                    sess ion.connec t();
  314                    logg er.info("c onnectAndL ogin(" + u rl.toExter nalForm()  + ") conne cted to Vi sta in '"  + (System. currentTim eMillis()  - startTim e) + "' ms , now logg ing in..." );
  315                    try
  316           {
  317                             // ano ther sacri fice to Vi sta, loggi ng in too  quickly af ter connec ting somet imes cause s problems
  318                Thread.s leep(100);
  319           } 
  320                    catc h (Interru ptedExcept ion e){}
  321                    logg er.info("c onnectAndL ogin(" + u rl.toExter nalForm()  + ") Vista Connection  connected , logging  in." );
  322                    sess ion.login( );
  323                    logg er.info("c onnectAndL ogin(" + u rl.toExter nalForm()  + ") Vista Connection  connected , logged i n." );    
  324           }
  325           
  326           pr ivate Vist aSession(U RL url, Si te site, S tring secu rityContex t, String  version)
  327           {
  328                    this .site = si te;
  329                    this .vistaConn ection = n ew VistaCo nnection(u rl);
  330                    this .lastUsedT ime = getC reateTime( );
  331                    this .securityC ontext = s ecurityCon text;
  332                    this .version =  version;
  333                    setS essionInde x();
  334                    logg er.info("C reated Vis taSession  (" + getSe ssionIndex () + ") wi th securit y context  (" + secur ityContext  + ") and  version ("  + version  + ")");
  335           }
  336           
  337           pr ivate Vist aSession(U RL url, Si te site)
  338           {
  339                    this (url, site , null, nu ll);
  340           }
  341           
  342           //  current i ndex count , incremen ts as new  VistaSessi on objects  are creat ed
  343           pr ivate stat ic long cu rrentSessi onIndex =  0L;   
  344           pr ivate sync hronized v oid setSes sionIndex( )
  345           {                                  
  346                    if(c urrentSess ionIndex > = Long.MAX _VALUE)
  347                             curren tSessionIn dex = 0L;
  348                    else
  349                             curren tSessionIn dex++;
  350                    this .sessionIn dex = curr entSession Index;         
  351           }
  352           
  353           pu blic final  Site getS ite() 
  354           {
  355                    retu rn site;
  356           }
  357  
  358           /* *
  359            *  @return t he securit yContext
  360            * /
  361           pu blic Strin g getSecur ityContext () {
  362                    retu rn securit yContext;
  363           }
  364  
  365           /* *
  366            *  Gets the  version co nnected to  VistA (th e patch le vel)
  367            *  @return
  368            * /
  369           pu blic Strin g getVersi on()
  370           {
  371                    retu rn version ;
  372           }
  373  
  374           /* *
  375            *  Make this  private b ecause we  want calli ng clients  to use th e
  376            *  methods t hat this c lass provi des for Vi staConnect ion access .
  377            *  @return
  378            * /
  379           pr ivate Vist aConnectio n getVista Connection () 
  380           {
  381                    retu rn vistaCo nnection;
  382           }
  383           
  384           pu blic URL g etURL()
  385           {
  386                    retu rn getVist aConnectio n().getURL ();
  387           }
  388  
  389           pu blic long  getCreateT ime()
  390       {
  391                    retu rn getVist aConnectio n().getCre ateTime();
  392       }
  393  
  394           pu blic long  getConnect Time()
  395       {
  396           re turn getVi staConnect ion() == n ull ? 0L :  getVistaC onnection( ).getConne ctTime();
  397       }
  398  
  399           pu blic long  getLoginTi me()
  400       {
  401           re turn login Time;
  402       }
  403           
  404           pu blic long  getLastUse dTime()
  405       {
  406           re turn lastU sedTime;
  407       }
  408  
  409           pu blic void  setLastUse dTime()
  410       {
  411           th is.lastUse dTime = Sy stem.curre ntTimeMill is();
  412       }
  413  
  414           pu blic boole an isLocal Login()
  415       {
  416           re turn local Login;
  417       }
  418  
  419           /* *
  420            *  The last  time an RP C was made , either i nternal or  external  call
  421            *  
  422            *  @return t he lastInt ernalTime
  423            * /
  424           pu blic long  getLastInt ernalTime( )
  425           {
  426                    retu rn lastInt ernalTime;
  427           }
  428  
  429           /* *
  430            *  The time  the site h as indicat ed a conne ction can  stay alive  between c alls
  431            *  
  432            *  @return t he siteBro kerConnect ionTimeout
  433            * /
  434           pu blic int g etSiteBrok erConnecti onTimeout( )
  435           {
  436                    retu rn siteBro kerConnect ionTimeout ;
  437           }
  438  
  439           /* *
  440            *  
  441            *  @throws I OException
  442            * /
  443           pu blic void  connect() 
  444           th rows IOExc eption
  445           {
  446                    if(!  getVistaC onnection( ).isConnec ted())
  447                             getVis taConnecti on().conne ct();
  448           }
  449  
  450           pu blic boole an isConne cted()
  451           {
  452                    retu rn getVist aConnectio n().isConn ected();
  453           }
  454           
  455           pu blic boole an isLogge dIn()
  456           {
  457                    retu rn vistaLo ginComplet e;
  458           }
  459           
  460           /* *
  461            *  A close()  just puts  this inst ance in a  cache
  462            *  It may be  picked up  again if  the same u ser makes  another re quest, or
  463            *  it will t ime out an d really d isconnect  if they do  not.
  464            *  This is t he method  that shoul d be calle d after a  completing  a client
  465            *  request,  not discon nect().
  466            * /
  467           pu blic void  close()
  468           {
  469                    if(g etVistaCon nection(). isFailedCa ll())
  470                    {
  471                             logger .warn("Vis taSession  (" + getSe ssionIndex () + ") ha d a failed  call, dis connecting  immediate ly");
  472                             discon nect(true) ;
  473                    }
  474                    else
  475                             VistaS essionCach e.getSingl eton().put (this);
  476           }
  477           
  478           /* *
  479            *  Certain e xceptions  from M cau se the bro ker to be  in a faile d state wh ere no mor e RPC call s can be m ade on the
  480            *  connectio n. This me thod close s the curr ent VistA  connection  and opens  a new one
  481            *  
  482            *  This proc edure didn 't work an d I didn't  have time  to figure  out what  is wrong w ith it
  483            * /
  484           /*
  485           pu blic void  recoverCon nectionAft erFailedMe thod()
  486           th rows Metho dException , Connecti onExceptio n, IOExcep tion
  487           {
  488                    logg er.warn("R ecovering  VistaConne ction afte r failed R PC method  on VistaSe ssion (" +  getSessio nIndex() +  ").");
  489                    try
  490                    {
  491                             discon nect(true) ;
  492                    }
  493                    catc h(Exceptio n ex) {}
  494                    logg er.warn("r ecoverConn ectionAfte rFailedMet hod - reco nnecting t o VistA");
  495                    conn ectAndLogi n(this.get URL(), thi s);            
  496           }* /
  497           
  498           /* *
  499            *  This meth od should  be called  internally  on the bu siness met hods.
  500            *  It may be  safely ca lled multi ple times,  calls sub sequent to  the first  are
  501            *  ignored.
  502            *  
  503            *  @throws C onnectionE xception
  504            *  @throws M ethodExcep tion
  505            * /
  506           pu blic void  login()
  507           th rows Conne ctionExcep tion, Meth odExceptio n, Securit yCredentia lsExpiredE xception
  508           {
  509                    if(v istaLoginC omplete)
  510                             return ;
  511                    
  512                    // g et the Sit e that we  are connec ted to
  513                    Site  site = ge tSite();
  514                    Stri ng connect edSiteNumb er = site. getSiteNum ber();
  515                    
  516                    // G et the tra nsaction c ontext to  determine  where the  user was a uthenticat ed
  517                    Tran sactionCon text trans actionCont ext = Tran sactionCon textFactor y.get();
  518  
  519                    Stri ng authent icatedSecu rityRealm  = transact ionContext .getRealm( );
  520                    bool ean authen ticatedByV ista = tra nsactionCo ntext.isAu thenticate dByVista() ;
  521                    
  522                    // i f the site  that we a re connect ed to is t he same si te number  as that of  the
  523                    // r ealm that  the user a uthenticat ed against  then try  to do a lo cal login
  524                    logg er.info("D etermining  local/rem ote login,  Connected  site numb er is '" +  connected SiteNumber  + 
  525                                      "', auth enticated  security r ealm is '"  + authent icatedSecu rityRealm 
  526                                      "', and  authentica ted by Vis tA is '" +  authentic atedByVist a  + "'.") ;
  527                    if(( connectedS iteNumber. equals(aut henticated SecurityRe alm)) &&
  528                             (authe nticatedBy Vista) &&  !isBseToke nOnly())                               
  529                    {
  530                             logger .info("Att empting lo cal login  for user ' " + transa ctionConte xt.getName () +
  531                                               "' on site  '" + conn ectedSiteN umber + "' , authenti cated to r ealm '" +  authentica tedSecurit yRealm + " '.");
  532                             try
  533                {
  534                                      logger.i nfo("Attem pting loca l login fo r user '"  + transact ionContext .getName()  + "'.");
  535                         localLogin ();
  536                             vistaL oginComple te = true;
  537                             this.l oginTime =  System.cu rrentTimeM illis();
  538                             localL ogin = tru e;
  539                             transa ctionConte xt.setLogi nMethod(Vi staLoginMe thod.local .toString( ));
  540                             logger .info("Loc al login s uccessful. " ); 
  541                             getSit eBrokerTim eout();
  542                             return ;
  543                } 
  544                             catch( MissingCre dentialsEx ception mc X)
  545                             {
  546                                      // the c redentials  were not  included,  don't worr y about it  and allow  a remote  logins
  547                                      logger.i nfo("Crede ntials for  a local l ogin were  not provid ed, will a ttempt rem ote login. ");
  548                             }
  549                             catch( InvalidCre dentialsEx ception ic X)
  550                             {
  551                                      // if we  get here  then the c redentials  were trie d and they  failed, d o not cont inue!                                
  552                                      throw ne w InvalidU serCredent ialsExcept ion(icX);
  553                             }
  554                             catch(  Exception  x )
  555                {
  556                                      // if th e local lo gin fails  then defau lt to a re mote login
  557                                      logger.w arn("Unabl e to login  using loc al credent ials for u ser '" + t ransaction Context.ge tName() +
  558                                                       "' , default  to remote  login.");
  559                }
  560                    }
  561                    else
  562                             logger .info("Con nected sit e number a nd authent icated sec urity real m are not  equal or n ot authent icated by  Vista, doi ng remote  login." );  
  563                    
  564                    bool ean bseLog inEnabled  = getVista SessionCon figuration ().isBseRe moteLoginE nabled();
  565                    bool ean capriL oginEnable d = getVis taSessionC onfigurati on().isCap riRemoteLo ginEnabled ();
  566                    
  567                    if(b seLoginEna bled)
  568                    {
  569                             if(isB seCredenti alsInConte xt(transac tionContex t))
  570                             {
  571                                      logger.i nfo("BSE c redentials  in contex t, BSE tok en '" + tr ansactionC ontext.get BrokerSecu rityToken( ) + "'.");
  572                                      if(isSit eBseTryabl e())
  573                                      {                                  
  574                                               logger.inf o("Attempt ing BSE lo gin for us er '" + tr ansactionC ontext.get Name() + " '.");
  575                                               try
  576                                               {
  577                                                       if (connected SiteNumber .equals(au thenticate dSecurityR ealm) && i sBseTokenO nly()){
  578                                                                logg er.info("A ttempting  BSE local  login for  user '" +  transactio nContext.g etName() +  "'.");
  579                                                                this .localBseL ogin();
  580                                                                loca lLogin = t rue;
  581                                                                logg er.info("L ocal BSE l ogin succe ssful." );  
  582                                                                
  583                                                       }
  584                                                       el se{
  585                                                                logg er.info("A ttempting  BSE remote  login for  user '" +  transacti onContext. getName()  + "'.");
  586                                                                this .remoteBse Login();
  587                                                                loca lLogin = f alse;
  588                                                                logg er.info("R emote BSE  login succ essful." )
  589                                                                
  590                                                       }
  591                                                       th is.loginTi me = Syste m.currentT imeMillis( );
  592                                                       vi staLoginCo mplete = t rue;
  593                                                       tr ansactionC ontext.set LoginMetho d(VistaLog inMethod.b se.toStrin g());
  594                                                       lo gger.info( "BSE login  successfu l." ); 
  595                                                       //  only gets  here if e verything  worked pro perly - if  BSE not i nstalled o r token ex ception, w on't get h ere
  596                                                       up dateSiteBs eStatus(Vi staSiteBse Status.bse Available) ;
  597                                                       ge tSiteBroke rTimeout() ;
  598                                                       re turn;
  599                                               }
  600                                               catch(Inva lidVistaCr edentialsE xception i vcX)
  601                                               {
  602                                                       //  don't do  anything w ith the er ror, its a lready bee n logged
  603                                                       //  will want  to contin ue with CA PRI login  if possibl e
  604                                                       up dateSiteBs eStatus(Vi staSiteBse Status.bse Failed);
  605                                               }
  606                                               catch( Exc eption x )
  607                                 {
  608                                                       //  don't do  anything w ith the er ror, its a lready bee n logged
  609                                                       //  will want  to contin ue with CA PRI login  if possibl e
  610                                                       up dateSiteBs eStatus(Vi staSiteBse Status.bse Unknown);
  611                                 }
  612  
  613                                      }
  614                                      else
  615                                      {
  616                                               logger.inf o("BSE cre dentials a vailable b ut site ha s been cac hed with s tatus indi cating sho uld not tr y BSE, wil l not use  BSE login. ");
  617                                      }
  618                             }                         
  619                             else
  620                             {
  621                                      logger.i nfo("BSE l ogin enabl ed but con text does  not have s ecurity to ken, canno t continue  BSE login .");
  622                             }
  623                    }
  624                    
  625                    if(c apriLoginE nabled)
  626                    {
  627                             logger .info("Att empting re mote CAPRI  login for  user '" +  transacti onContext. getName()  + "'.");
  628                             remote Login();
  629                             this.l oginTime =  System.cu rrentTimeM illis();
  630                             localL ogin = fal se;
  631                             vistaL oginComple te = true;
  632                             transa ctionConte xt.setLogi nMethod(Vi staLoginMe thod.capri .toString( ));
  633                             logger .info("Rem ote CAPRI  login succ essful." )
  634                             getSit eBrokerTim eout();
  635                             return ;
  636                    }
  637                    
  638                    thro w new Meth odExceptio n("Unable  to connect  remotely  or locally .");
  639           }
  640           
  641           pr ivate bool ean isBseT okenOnly()  
  642           {
  643                    Tran sactionCon text trans actionCont ext = Tran sactionCon textFactor y.get();
  644                    Stri ng brokerS ecurityTok en = trans actionCont ext.getBro kerSecurit yToken();
  645                    if ( brokerSecu rityToken  != null)
  646                    {
  647                             String [] tokenPa rse = Stri ngUtils.Sp lit(broker SecurityTo ken, Strin gUtils.CAR ET);
  648                             if (to kenParse.l ength == 1 )
  649                             {
  650                                      return t rue;
  651                             }
  652                    }
  653                    
  654                    retu rn false;
  655           }
  656  
  657           pr ivate void  getSiteBr okerTimeou t()
  658           {
  659                    if(g etVistaSes sionConfig uration(). isBrokerKe epAliveEna bled())
  660                    {
  661                             logger .info("Get ting broke r timeout  from site  '" + getSi te().getSi teNumber()  + "'");
  662                             
  663                             try
  664                             {
  665                                      VistaQue ry query =  VistaComm onQueryFac tory.creat eGetVistaT imeout();
  666                                      
  667                                      String m sg = getVi staConnect ion().call (query);
  668                                      logger.i nfo("Got b roker time out value  of '" + ms g + "', se tting valu e.");
  669                                      int brok erTime = I nteger.par seInt(msg) ;
  670                                      // take  half the v alue to en sure the k eep alive  event occu rs before  the timeou t
  671                                      this.sit eBrokerCon nectionTim eout = (br okerTime /  2);
  672                                      logger.i nfo("Set b roker time out time t o '" + thi s.siteBrok erConnecti onTimeout  + "'.");
  673                             }
  674                             catch( IOExceptio n ioX)
  675                             {
  676                                      logger.w arn("IOExc eption get ting broke r timeout,  using def ault '" +  defaultSit eBrokerCon ncetionTim eout + "'. " + ioX);
  677                                      this.sit eBrokerCon nectionTim eout = def aultSiteBr okerConnce tionTimeou t;
  678                             }
  679                             catch( InvalidVis taCredenti alsExcepti on ivcX)
  680                             {
  681                                      logger.w arn("Inval idVistaCre dentialsEx ception ge tting brok er timeout , using de fault '" +  defaultSi teBrokerCo nncetionTi meout + "' ." + ivcX) ;
  682                                      this.sit eBrokerCon nectionTim eout = def aultSiteBr okerConnce tionTimeou t;  
  683                             }
  684                             catch( VistaMetho dException  vmX)
  685                             {
  686                                      logger.w arn("Vista MethodExce ption gett ing broker  timeout,  using defa ult '" + d efaultSite BrokerConn cetionTime out + "'."  + vmX);
  687                                      this.sit eBrokerCon nectionTim eout = def aultSiteBr okerConnce tionTimeou t;
  688                             }
  689                             catch( Exception  ex)
  690                             {
  691                                      logger.w arn("Excep tion getti ng broker  timeout, u sing defau lt '" + de faultSiteB rokerConnc etionTimeo ut + "'."  + ex);
  692                                      this.sit eBrokerCon nectionTim eout = def aultSiteBr okerConnce tionTimeou t;
  693                             }
  694                    }
  695           }
  696           
  697           pr ivate void  updateSit eBseStatus (VistaSite BseStatus  status)
  698           {
  699                    Stri ng siteNum ber = getS ite().getS iteNumber( );
  700                    logg er.debug(" Updating t he site st atus for s ite '" + s iteNumber  + "' to st atus '" +  status + " '.");
  701                    Vist aSessionBS ECache.get VistaSessi onBseCache ().updateS iteStatus( siteNumber , status);
  702           }
  703           
  704           /* *
  705            *  Checks th e VistaSes sionBSECac he to dete rmine if t he site co nnecting t o has been  connected  to before  with BSE.
  706            *  If so and  there was  a failure , this wil l return f alse to in dicate it  failed and  should no t be attem pted again .
  707            *  If a BSE  connection  was previ ously made  or not tr ied yet, t hen this w ill return  true to i ndicate BS E should b e attempte d
  708            *  
  709            *  <br>
  710            *  <b>Note:< /b> This m ethod does  not deter mine if cr edentials  are availa ble to mak e the BSE  attempt (t hat is don e elsewher e).
  711            *  
  712            *  @return T rue if BSE  should be  attempted , false if  it has pr eviously f ailed.
  713            * /
  714           pr ivate bool ean isSite BseTryable ()
  715           {
  716                    Stri ng siteNum ber = getS ite().getS iteNumber( );
  717                    logg er.info("D etermining  cached BS E status f or site '"  + siteNum ber + "'." );
  718                    Vist aSiteBseSt atus siteS tatus = Vi staSession BSECache.g etVistaSes sionBseCac he().getSi teStatus(s iteNumber) ;
  719                    Stri ng statusM sg = "";
  720                    bool ean result  = true;
  721                    if(s iteStatus  == VistaSi teBseStatu s.bseFaile d)
  722                    {
  723                             status Msg = "BSE  was previ ously atte mpted to t his site a nd failed,  will not  attempt ag ain.";
  724                             result  = false;
  725                    }
  726                    else
  727                    {
  728                             status Msg = "BSE  was previ ously succ essful or  has not be en attempt ed to this  site, wil l attempt  BSE.";
  729                             result  = true;
  730                    }
  731                    logg er.info("C ached BSE  status for  site '" +  siteNumbe r + "' is  '" + siteS tatus + "' . " + stat usMsg);
  732                    retu rn result;
  733           }
  734           
  735           pr ivate Vist aSessionCo nfiguratio n getVista SessionCon figuration ()
  736           {
  737                    retu rn VistaSe ssionConfi guration.g etConfigur ation();
  738           }
  739           
  740           /* *
  741            *  Call an R PC on the  Vista inst ance to wh ich we are  connected .
  742            *  
  743            *  @throws I OException  
  744            *  @throws I nvalidVist aCredentia lsExceptio
  745            *  @throws V istaMethod Exception 
  746            *  @throws V istaExcept ion 
  747            * /
  748           pu blic synch ronized St ring call( VistaQuery  vistaQuer y) 
  749           th rows IOExc eption, In validVista Credential sException , VistaMet hodExcepti on
  750           {
  751                    disp layVistaQu ery(vistaQ uery);
  752                    Stri ng result  = getVista Connection ().call(vi staQuery);
  753                    disp layVistaQu eryResult( vistaQuery , result);
  754                    this .lastUsedT ime = Syst em.current TimeMillis ();
  755                    this .lastInter nalTime =  System.cur rentTimeMi llis();
  756                    retu rn result;
  757           }
  758           
  759           /* *
  760            *  Checks to  see if th e user for  the sessi on is full y signed o n.  If an  RPC call w as made th at caused  an excepti on on
  761            *  the M sid e, this co uld kill t he session  on the Vi stA databa se which w ould mean  no RPC cal ls can be  made.  Thi
  762            *  method ca lls an RPC  that shou ld only wo rk if the  session on  the VistA  side is s till good.   If the s ession is  still 
  763            *  good this  will retu rn true, i f there wa s a proble m this wil l return f alse. 
  764            *  
  765            *  If the re sult is fa lse then t he session  should be  thrown aw ay since i t is no lo nger usabl e.
  766            *  
  767            *  All neces sary excep tion handl ing is don e in this  method, th ey only re sult is tr ue or fals e. 
  768            *  @return
  769            * /
  770           pu blic boole an isUserF ullySigned On()
  771           {
  772                    try
  773                    {
  774                             logger .debug("Ch ecking if  user for V istA sessi on (" + ge tSessionIn dex() + ")  is still  signed on  to site '"  + getSite ().getSite Number() +  "'.");
  775                             VistaQ uery keepA liveQuery  = VistaCom monQueryFa ctory.crea teGetUserI nformation Query();
  776                             getVis taConnecti on().call( keepAliveQ uery);
  777                             this.l astInterna lTime = Sy stem.curre ntTimeMill is();
  778                             //logg er.debug(" Result fro m keep ali ve call '"  + rtn + " '.");
  779                             logger .debug("Us er is full y signed o n, connect ion can be  used");
  780                             return  true;
  781                    }
  782                    catc h(InvalidV istaCreden tialsExcep tion ivcX)
  783                    {
  784                             logger .warn("Inv alidVistaC redentials Exception  checking u ser sessio n (" + get SessionInd ex() + ")  still sign ed on", iv cX);
  785                             return  false;
  786                    }
  787                    catc h(IOExcept ion ioX)
  788                    {
  789                             logger .warn("IOE xception c hecking us er session  (" + getS essionInde x() + ") s till signe d on", ioX );
  790                             return  false;
  791                    }
  792                    catc h(VistaMet hodExcepti on vmX)
  793                    {
  794                             logger .warn("Vis taMethodEx ception ch ecking use r session  (" + getSe ssionIndex () + ") st ill signed  on", vmX) ;
  795                             return  false;
  796                    }
  797                    catc h(Exceptio n ex)
  798                    {
  799                             logger .warn("Exc eption che cking user  session ( " + getSes sionIndex( ) + ") sti ll signed  on", ex);
  800                             return  false;
  801                    }
  802           }
  803           
  804           /* *
  805            *  Make the  appropriat e RPC call  to keep t he broker  connection  alive. If  there is  any sort o
  806            *  exception , this met hod will r eturn fals e
  807            *  
  808            *  @return T rue if the  keep aliv e was succ essful, fa lse if the re was an  error (sho uld force  a disconne ct immedia tely)
  809            * /
  810           pu blic boole an keepAli ve()
  811           {
  812                    long  identityH ashcode =  getSession Index();
  813                    try
  814                    {
  815                             logger .debug("Ke eping Vist A session  (" + ident ityHashcod e + ") ali ve to site  '" + getS ite().getS iteNumber( ) + "'.");
  816                             VistaQ uery keepA liveQuery  = VistaCom monQueryFa ctory.crea teKeepAliv eQuery();
  817                             String  rtn = get VistaConne ction().ca ll(keepAli veQuery);
  818                             this.l astInterna lTime = Sy stem.curre ntTimeMill is();
  819                             logger .debug("Re sult from  keep alive  call '" +  rtn + "'. ");
  820                             logger .debug("Vi stA sessio n still al ive");
  821                             return  true;
  822                    }
  823                    catc h(InvalidV istaCreden tialsExcep tion ivcX)
  824                    {
  825                             logger .warn("Inv alidVistaC redentials Exception  keeping Vi stA sessio n (" + ide ntityHashc ode + ") a live", ivc X);
  826                             return  false;
  827                    }
  828                    catc h(IOExcept ion ioX)
  829                    {
  830                             logger .warn("IOE xception k eeping Vis tA session  (" + iden tityHashco de + ") al ive", ioX) ;
  831                             return  false;
  832                    }
  833                    catc h(VistaMet hodExcepti on vmX)
  834                    {
  835                             logger .warn("Vis taMethodEx ception ke eping Vist A session  (" + ident ityHashcod e + ") ali ve", vmX);
  836                             return  false;
  837                    }
  838                    catc h(Exceptio n ex)
  839                    {
  840                             logger .warn("Exc eption kee ping VistA  session ( " + identi tyHashcode  + ") aliv e", ex);
  841                             return  false;
  842                    }
  843           }
  844           
  845           pr ivate void  displayVi staQuery(V istaQuery  vistaQuery )
  846           {
  847                    logg er.info("R PC [" + vi staQuery.g etRpcName( ) + "] req uest: "+ S tringUtils .displayEn codedChars (vistaQuer y.toString ()));
  848           }
  849           
  850           pr ivate void  displayVi staQueryRe sult(Vista Query vist aQuery, St ring resul t)
  851           {
  852                    //WF P-change c ode to pus h the trun cation wor k into the  .displayE ncodedChar s() method .
  853                    if(r esult.leng th() > 320 ){
  854                             logger .info("RPC  [" + vist aQuery.get RpcName()  +  "] resp onse:\n"
  855                                               +StringUti ls.display EncodedCha rs(result) .substring (0, 320)
  856                                               + "...](tr uncated)") ;
  857                    }
  858                    else {
  859                             logger .info("RPC  [" + vist aQuery.get RpcName()  +  "] resp onse:\n"
  860                                               +StringUti ls.display EncodedCha rs(result) );                        
  861                    }
  862                    logg er.debug(" RPC [" + v istaQuery. getRpcName () +  "] r esponse:\n "
  863                                               +StringUti ls.display EncodedCha rs(result) );
  864           }
  865  
  866           
  867           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ===
  868           //  Internal  methods
  869           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ===
  870           
  871           vo id disconn ect(boolea n disconne ctImmediat ely)
  872           {
  873                    // i f a sessio n was crea ted on the  VistA dat abase for  the user,  close the  session
  874                    if(i sSessionCr eated() &&  !disconne ctImmediat ely)
  875                    {
  876                             magLog off();
  877                    }
  878                    if(d isconnectI mmediately )
  879                             getVis taConnecti on().disco nnectImmed iately();
  880                    else
  881                             getVis taConnecti on().disco nnect();
  882           }
  883           
  884           /* *
  885            *  Close the  Imaging s ession on  VistA
  886            * /
  887           pr ivate void  magLogoff ()
  888           {
  889                    logg er.info("D isconnecti ng VistA c onnection,  closing I maging ses sion");
  890                    Vist aQuery mag LogoffQuer y = VistaC ommonQuery Factory.cr eateMagLog offQuery() ;
  891                    try 
  892                    {
  893                             getVis taConnecti on().call( magLogoffQ uery);
  894                    }
  895                    catc h(IOExcept ion ioX)
  896                    {
  897                             logger .warn("Exc eption clo sing Imagi ng session  during lo goff, igno ring probl em", ioX);
  898                    }
  899                    catc h(VistaMet hodExcepti on vmX)
  900                    {
  901                             logger .warn("Exc eption clo sing Imagi ng session  during lo goff, igno ring probl em", vmX);
  902                    }
  903                    catc h(InvalidV istaCreden tialsExcep tion ivcX)
  904                    {
  905                             logger .warn("Exc eption clo sing Imagi ng session  during lo goff, igno ring probl em", ivcX) ;
  906                    }
  907           }
  908           
  909           /* *
  910            *  Creates a  "local" b roker conn ection to  the suppli ed site. 
  911            *  A local c onnection  is one tha t is estab lished wit h the user s
  912            *  access an d verify c odes rathe r than duz /site numb er/site na me
  913            *  other tha n that the  connectio ns are the  same.
  914            * /
  915           pr ivate void  localLogi n()
  916           th rows Conne ctionExcep tion, Meth odExceptio n, Missing Credential sException
  917           {
  918                    Tran sactionCon text trans actionCont ext = Tran sactionCon textFactor y.get();
  919                    logg er.info("l ocalConnec t Transact ionContext  (" + 
  920                                      (transac tionContex t != null  ? transact ionContext .getDispla yIdentity( ) : "null  transactio n context" ) + 
  921                                      ").");
  922                    
  923                    bool ean succes s = false;
  924                    try 
  925                    {
  926                             // cre ate the lo ginQuery f irst becau se it will  validate  that we ha ve the
  927                             // nec essary fie lds in the  transacti on context  to log in
  928                             VistaQ uery signo nQuery = V istaCommon QueryFacto ry.createL ocalSignon VistaQuery (transacti onContext) ;
  929                             
  930                             // con nect to th e Vista se rver and a ttempt to  call the s ignon RPC
  931                             // thi s method m ay retry b oth the co nnection a nd the sig non call
  932                             // mul tiple time s.
  933                             connec tAndSignon ( signonQu ery );
  934  
  935                             // Sen d the Acce ss and Ver ify codes,  this meth od will th row Invali dCredentia lsExceptio n
  936                             // if  the AV cod es were no t accepted .  
  937                             presen tAccessVer ifyCredent ials(trans actionCont ext);
  938                             
  939                             //
  940                             //setC ontext(MAG _WINDOWS_C ONTEXT);
  941                             setCon text(secur ityContext );
  942                             
  943                             // if  we get all  the way t o here the n we have  successful ly connect ed
  944                             succes s = true;
  945                    }
  946                    catc h(MissingC redentials Exception  mcX)
  947                    {
  948                             logger .error(mcX );
  949                             throw  mcX;
  950                    }
  951                    catc h(InvalidC redentials Exception  icX) 
  952                    {
  953                             logger .error(icX );
  954                             throw  icX;
  955                    }
  956                    catc h(NumberFo rmatExcept ion nfX) 
  957                    {
  958                             logger .error( "U nable to p roperly pa rse Vista  response." , nfX );
  959                             throw  new VistaP arsingExce ption(nfX) ;
  960                    }
  961                    catc h(ArrayInd exOutOfBou ndsExcepti on aioobX)  
  962                    {
  963                             logger .error( "U nable to p roperly pa rse Vista  response." , aioobX ) ;
  964                             throw  new VistaP arsingExce ption(aioo bX);
  965                    }
  966                    catc h(Exceptio n ex) 
  967                    {
  968                             logger .error(ex) ;
  969                             throw  new VistaP arsingExce ption(ex);
  970                    }
  971                    fina lly 
  972                    {
  973                             if( !s uccess &&  getVistaCo nnection()  != null) 
  974                             {
  975                                      try 
  976                                      {
  977                                               logger.inf o( "Connec tion faile d in RpcBr oker.local Connect(),  disconnec ting..." ) ;
  978                                               // if the  VistaConne ction is s till conne cted then  the error  occurred a fter the c onnectAndS ignon and  it needs t o be disco nnected
  979                                               // althoug h maybe no t immediat ely.  If t here was a n error du ring the c onnectAndS ignon then  it is dis connected  immediatel y in there
  980                                               // and thi s disconne ct should  not be cal led on a V istaConnec tion that  is not con nected
  981                                               if(getVist aConnectio n().isConn ected())
  982                                                       ge tVistaConn ection().d isconnect( );
  983                                      }
  984                                      catch(Ex ception eX
  985                                      {
  986                                               logger.war n( "Except ion during  handling  disconnect , continui ng ....",  eX );
  987                                      }
  988                             }
  989                             logger .info("loc alConnect( ) complete ");
  990                    }
  991           }
  992           
  993           pr ivate void  remoteBse Login()
  994           th rows Conne ctionExcep tion, Meth odExceptio n, Invalid VistaCrede ntialsExce ption, Sec urityCrede ntialsExpi redExcepti on
  995           {
  996                    bool ean succes s = false;                           // wil l be true  only when  the connec tion and l ogin RPCs  have compl eted succe ssfully
  997                    Tran sactionCon text trans actionCont ext = Tran sactionCon textFactor y.get();
  998                    
  999                    logg er.info("r emoteBseLo gin Transa ctionConte xt (" + Tr ansactionC ontextFact ory.get(). getDisplay Identity()  + ").");
  1000                    
  1001                    // p erform a l ogin
  1002                    Vist aQuery vm  = VistaCom monQueryFa ctory.crea teBseSigno nVistaQuer y(transact ionContext );
  1003                    
  1004                    try
  1005                    {
  1006                             // con nect to th e Vista se rver and a ttempt to  call the s ignon RPC
  1007                             // thi s method m ay retry b oth the co nnection a nd the sig non call
  1008                             // mul tiple time s.
  1009                             String  vistaResu lt = conne ctAndSigno n(vm);
  1010                             valida teBSELogin Response(v istaResult );                   
  1011                             // set  the divis ion for th e user (if  they have  one assig ned)
  1012                                      
  1013                             // can 't run thi s unless h as proper  context                       
  1014                             try 
  1015                             {
  1016                                      //setCon text(MAG_W INDOWS_CON TEXT);
  1017                                      setConte xt(securit yContext);
  1018                                      
  1019                                      setUserD ivision(tr ansactionC ontext.get UserDivisi on());           
  1020                                      // JMW 4 /22/09 - d on't need  to get DUZ  here, if  context se t ok don't  need DUZ
  1021                                      //remote Duz = getD UZ(transac tionContex t.getSsn() );
  1022                                      
  1023                                      success  = true;
  1024                             }
  1025                             catch( UnableToCr eateContex tException  utccX) 
  1026                             {
  1027                                      logger.w arn("Unabl eToCreateC ontextExce ption '" +  getVistaC onnection( ).getURL()  + "', BSE  does not  allow addi ng context , cannot c ontinue co nnection") ;
  1028                                      throw ne w MethodEx ception(ut ccX);                                  
  1029                             }
  1030                    }
  1031                    catc h(BseFaile dException  bsefX)
  1032                    {
  1033                             // som e sort of  BSE error  that was n ot expecte d, NOT a t oken expir ed excepti on
  1034                             throw  new Invali dVistaCred entialsExc eption(bse fX);
  1035                    }
  1036                    catc h(Security Credential sExpiredEx ception sc eX)
  1037                    {
  1038                             logger .error(sce X);
  1039                             throw  sceX;
  1040                    }
  1041                    catc h(InvalidV istaCreden tialsExcep tion ivcX)
  1042                    {
  1043                             logger .warn("Inv alid crede ntials whe n doing re mote BSE l ogin", ivc X);
  1044                             throw  ivcX;
  1045                    }
  1046                    catc h (Excepti on ex)
  1047                    {
  1048                             logger .error(ex) ;
  1049                             throw  new Method Exception( ex);
  1050                    }
  1051                    fina lly 
  1052                    {
  1053                             if( !  success &&  getVistaC onnection( ) != null 
  1054                                      try 
  1055                                      {
  1056                                               logger.inf o("Unable  to connect  remotely  with BSE,  disconnect ing");
  1057                                               // if the  VistaConne ction is s till conne cted then  the error  occurred a fter the c onnectAndS ignon and  it needs t o be disco nnected
  1058                                               // althoug h maybe no t immediat ely.  If t here was a n error du ring the c onnectAndS ignon then  it is dis connected  immediatel y in there
  1059                                               // and thi s disconne ct should  not be cal led on a V istaConnec tion that  is not con nected
  1060                                               if(getVist aConnectio n().isConn ected())
  1061                                                       ge tVistaConn ection().d isconnect( );
  1062                                      }
  1063                                      catch(Ex ception eX ) {}
  1064                    }
  1065           }
  1066           
  1067  
  1068           pr ivate void  localBseL ogin()
  1069           th rows Conne ctionExcep tion, Meth odExceptio n, Invalid VistaCrede ntialsExce ption, Sec urityCrede ntialsExpi redExcepti on
  1070           {
  1071                    bool ean succes s = false;                           // wil l be true  only when  the connec tion and l ogin RPCs  have compl eted succe ssfully
  1072                    Tran sactionCon text trans actionCont ext = Tran sactionCon textFactor y.get();
  1073                    
  1074                    logg er.info("l ocalBseLog in Transac tionContex t (" + Tra nsactionCo ntextFacto ry.get().g etDisplayI dentity()  + ").");
  1075                    
  1076                    logg er.debug(" Transactio nContext:  " + transa ctionConte xt.toStrin g());
  1077                    // p erform a l ogin
  1078                    Vist aQuery vm  = VistaCom monQueryFa ctory.crea teLocalBse SignonVist aQuery(tra nsactionCo ntext, get Site());
  1079                    
  1080                    try
  1081                    {
  1082                             // con nect to th e Vista se rver and a ttempt to  call the s ignon RPC
  1083                             // thi s method m ay retry b oth the co nnection a nd the sig non call
  1084                             // mul tiple time s.
  1085                             String  vistaResu lt = conne ctAndSigno n(vm);
  1086                             valida teBSELogin Response(v istaResult );                   
  1087                             // set  the divis ion for th e user (if  they have  one assig ned)
  1088                                      
  1089                             // can 't run thi s unless h as proper  context                       
  1090                             try 
  1091                             {
  1092                                      //setCon text(MAG_W INDOWS_CON TEXT);
  1093                                      setConte xt(securit yContext);
  1094                                      
  1095                                      setUserD ivision(tr ansactionC ontext.get UserDivisi on());           
  1096                                      // JMW 4 /22/09 - d on't need  to get DUZ  here, if  context se t ok don't  need DUZ
  1097                                      //remote Duz = getD UZ(transac tionContex t.getSsn() );
  1098                                      
  1099                                      success  = true;
  1100                             }
  1101                             catch( UnableToCr eateContex tException  utccX) 
  1102                             {
  1103                                      logger.w arn("Unabl eToCreateC ontextExce ption '" +  getVistaC onnection( ).getURL()  + "', BSE  does not  allow addi ng context , cannot c ontinue co nnection") ;
  1104                                      throw ne w MethodEx ception(ut ccX);                                  
  1105                             }
  1106                    }
  1107                    catc h(BseFaile dException  bsefX)
  1108                    {
  1109                             // som e sort of  BSE error  that was n ot expecte d, NOT a t oken expir ed excepti on
  1110                             throw  new Invali dVistaCred entialsExc eption(bse fX);
  1111                    }
  1112                    catc h(Security Credential sExpiredEx ception sc eX)
  1113                    {
  1114                             logger .error(sce X);
  1115                             throw  sceX;
  1116                    }
  1117                    catc h(InvalidV istaCreden tialsExcep tion ivcX)
  1118                    {
  1119                             logger .warn("Inv alid crede ntials whe n doing lo cal BSE lo gin", ivcX );
  1120                             throw  ivcX;
  1121                    }
  1122                    catc h (Excepti on ex)
  1123                    {
  1124                             logger .error(ex) ;
  1125                             throw  new Method Exception( ex);
  1126                    }
  1127                    fina lly 
  1128                    {
  1129                             if( !  success &&  getVistaC onnection( ) != null 
  1130                                      try 
  1131                                      {
  1132                                               logger.inf o("Unable  to connect  locally w ith BSE, d isconnecti ng");
  1133                                               // if the  VistaConne ction is s till conne cted then  the error  occurred a fter the c onnectAndS ignon and  it needs t o be disco nnected
  1134                                               // althoug h maybe no t immediat ely.  If t here was a n error du ring the c onnectAndS ignon then  it is dis connected  immediatel y in there
  1135                                               // and thi s disconne ct should  not be cal led on a V istaConnec tion that  is not con nected
  1136                                               if(getVist aConnectio n().isConn ected())
  1137                                                       ge tVistaConn ection().d isconnect( );
  1138                                      }
  1139                                      catch(Ex ception eX ) {}
  1140                    }
  1141           }
  1142  
  1143           
  1144           /* *
  1145            *  Creates a  "remote"  broker con nection to  the suppl ied site.  Credential s must inc lude DUZ,  SSN, Name,  and Site.
  1146            *  
  1147            *  @param si te VistA s ite to con nect to. M ust includ e valid Vi stA server  and VistA  port info rmation.
  1148            *  @param cr edentials  Credential s to use t o connect  to. This o bject must  include t he DUZ, SS N, name an d site
  1149            *  @throws C onnectionF ailedExcep tion Occur s if the s ystem cann ot connect  to the Vi stA Server  
  1150            *  @throws M ethodExcep tion Occur s if there  is an exc eption exe cuting an  rpc during  the conne ction
  1151            * /
  1152           pr ivate void  remoteLog in() 
  1153           th rows Conne ctionExcep tion, Meth odExceptio n
  1154           {
  1155                    bool ean succes s = false;                           // wil l be true  only when  the connec tion and l ogin RPCs  have compl eted succe ssfully
  1156                    Tran sactionCon text trans actionCont ext = Tran sactionCon textFactor y.get();
  1157                    
  1158                    logg er.info("r emoteConne ct Transac tionContex t (" + Tra nsactionCo ntextFacto ry.get().g etDisplayI dentity()  + ").");
  1159                    
  1160                    Stri ng remoteD uz = null;
  1161                    
  1162                    // p erform a l ogin               
  1163                    // W hen doing  a CAPRI lo gin, an em pty XUS SI GNON SETUP  rpc must  be called  first to p rime the
  1164                    // s ystem.  No t really s ure why, b ut thats h ow it is -  don't app ly logic w here it do esn't belo ng!
  1165                    Vist aQuery []  queries =  new VistaQ uery[2];
  1166                    quer ies[0] = V istaCommon QueryFacto ry.createR emoteSigno nEmptyVist aQuery();;
  1167                    quer ies[1] = V istaCommon QueryFacto ry.createR emoteSigno nVistaQuer y(transact ionContext );
  1168                    
  1169                    try
  1170                    {
  1171                             // con nect to th e Vista se rver and a ttempt to  call the s ignon RPC
  1172                             // thi s method m ay retry b oth the co nnection a nd the sig non call
  1173                             // mul tiple time s.
  1174                             String  vistaResu lt = conne ctAndSigno n(queries) ;
  1175                             valida teRemoteCA PRILoginRe sponse(vis taResult);
  1176                             // set  the divis ion for th e user (if  they have  one assig ned)
  1177                             
  1178                             // set ting the d ivision do esn't seem  to work w ith CAPRI  login meth od... not  sure if th at is inte ntional or  true, but  always go t errors a bout conte xt not bei ng set
  1179                             //setU serDivisio n();
  1180                             // can 't run thi s unless h as proper  context                       
  1181                             try 
  1182                             {
  1183                                      //setCon text(MAG_W INDOWS_CON TEXT);
  1184                                      setConte xt(securit yContext);
  1185                                      // JMW 4 /22/09 - d on't need  to get DUZ  here, if  context se t ok don't  need DUZ
  1186                                      //remote Duz = getD UZ(transac tionContex t.getSsn() );
  1187                                      
  1188                                      success  = true;
  1189                             }
  1190                             catch( UnableToCr eateContex tException  utccX) 
  1191                             {
  1192                                      logger.w arn("Unabl eToCreateC ontextExce ption '" +  getVistaC onnection( ).getURL()  + "'.");
  1193                                      try 
  1194                                      {
  1195                                               // user mi ght not ha ve MAG WIN DOWS conte xt assigne d to them
  1196                                               setContext (CAPRI_CON TEXT);
  1197                                               String des iredContex tIEN = get ContextIEN (securityC ontext);
  1198                                              
  1199                                               remoteDuz  = getDUZ(t ransaction Context.ge tSsn());
  1200                                               //getVista Connection ().setUid( remoteDuz) ;
  1201  
  1202                                               assignOpti on(VistaCo mmonQueryF actory.MEN U_SUBSCRIP T, desired ContextIEN , remoteDu z);
  1203  
  1204                                               try
  1205                                               {
  1206                                                       Th read.sleep (2000);
  1207                                               }
  1208                                               catch (Int erruptedEx ception ie )
  1209                                               {
  1210                                                       th row new Me thodExcept ion(ie);
  1211                                               }
  1212  
  1213                                               String cap riIEN = ge tContextIE N(CAPRI_CO NTEXT);
  1214                                               if (!capri IEN.equals (""))
  1215                                               {
  1216                                                       St ring capri MenuOption Number = g etOptionIE N(VistaCom monQueryFa ctory.MENU _SUBSCRIPT , capriIEN , remoteDu z);
  1217                                                       if ( ! "".equ als(capriM enuOptionN umber) )
  1218                                                                remo veOption(V istaCommon QueryFacto ry.MENU_SU BSCRIPT, c apriMenuOp tionNumber , remoteDu z);
  1219                                               }
  1220                                               setContext (securityC ontext);                               
  1221                                               success =  true;
  1222                                      }
  1223                                      catch(Un ableToCrea teContextE xception u tccX2) 
  1224                                      {
  1225                                               logger.war n("Unable  to create  context, "  + utccX.t oString()) ;
  1226                                               throw new  MethodExce ption(utcc X2);
  1227                                      }
  1228                             }
  1229                    }
  1230                    catc h (Excepti on ex)
  1231                    {
  1232                             logger .error(ex) ;
  1233                             throw  new Method Exception( ex);
  1234                    }
  1235                    fina lly 
  1236                    {
  1237                             if( !  success &&  getVistaC onnection( ) != null 
  1238                                      try 
  1239                                      {
  1240                                               logger.inf o("Unable  to connect  remotely,  disconnec ting");
  1241                                               // if the  VistaConne ction is s till conne cted then  the error  occurred a fter the c onnectAndS ignon and  it needs t o be disco nnected
  1242                                               // althoug h maybe no t immediat ely.  If t here was a n error du ring the c onnectAndS ignon then  it is dis connected  immediatel y in there
  1243                                               // and thi s disconne ct should  not be cal led on a V istaConnec tion that  is not con nected
  1244                                               if(getVist aConnectio n().isConn ected())
  1245                                                       ge tVistaConn ection().d isconnect( );
  1246                                      }
  1247                                      catch(Ex ception eX ) {}
  1248                    }
  1249           }
  1250           
  1251           /* *     
  1252            *  If doing  a remote l ogin (CAPR I), the 6t h piece sh ould be a  '1' to ind icate a si lent login  was done  properly.
  1253            *  @param vi staRespons e
  1254            *  @throws I nvalidVist aCredentia lsExceptio n
  1255            * /
  1256           pr ivate void  validateR emoteCAPRI LoginRespo nse(String  vistaResu lt)
  1257           th rows Inval idVistaCre dentialsEx ception
  1258           {
  1259                    if(v istaResult  == null)
  1260                             throw  new Invali dVistaCred entialsExc eption("Re sult of re mote CAPRI  login RPC  was null,  indicates  failed re mote CAPRI  login att empt.");
  1261                    Stri ng [] line s = String Utils.Spli t(vistaRes ult, Strin gUtils.NEW _LINE);
  1262                    if(l ines == nu ll)
  1263                             throw  new Invali dVistaCred entialsExc eption("Re sult of re mote CAPRI  login RPC  was null  array of l ines, indi cates fail ed remote  CAPRI logi n attempt. ");
  1264                    if(l ines.lengt h < 6)
  1265                             throw  new Invali dVistaCred entialsExc eption("Re sult of re mote CAPRI  login RPC  does not  contain at  least 6 l ines of re sponse, in dicates fa iled remot e CAPRI lo gin attemp t.");
  1266                    if(! ("1".equal s(lines[5] .trim())))
  1267                             throw  new Invali dVistaCred entialsExc eption("Re sult of 6t h line of  remote CAP RI login R PC '" + li nes[5].tri m() + "',  not '1', i ndicates f ailed remo te CAPRI l ogin attem pt.");
  1268           }
  1269           
  1270  
  1271           /* *
  1272            *  If doing  a BSE logi n (local o r remote),  the 6th p iece shoul d be a '1'  to indica te a silen t login wa s done pro perly.
  1273            *  @param vi staRespons e
  1274            *  @throws I nvalidVist aCredentia lsExceptio n
  1275            * /
  1276           pr ivate void  validateB SELoginRes ponse(Stri ng vistaRe sult)
  1277           th rows Inval idVistaCre dentialsEx ception
  1278           {
  1279                    if(v istaResult  == null)
  1280                             throw  new Invali dVistaCred entialsExc eption("Re sult of lo cal/remote  BSE login  RPC was n ull, indic ates faile d local/re mote BSE l ogin attem pt.");
  1281                    Stri ng [] line s = String Utils.Spli t(vistaRes ult, Strin gUtils.NEW _LINE);
  1282                    if(l ines == nu ll)
  1283                             throw  new Invali dVistaCred entialsExc eption("Re sult of lo cal/remote  BSE login  RPC was n ull array  of lines,  indicates  failed loc al/remote  BSE login  attempt.") ;
  1284                    if(l ines.lengt h < 6)
  1285                             throw  new Invali dVistaCred entialsExc eption("Re sult of lo cal/remote  BSE login  RPC does  not contai n at least  6 lines o f response , indicate s failed l ocal/remot e BSE logi n attempt. ");
  1286                    if(! ("1".equal s(lines[5] .trim())))
  1287                             throw  new Invali dVistaCred entialsExc eption("Re sult of 6t h line of  local/remo te BSE log in RPC '"  + lines[5] .trim() +  "', not '1 ', indicat es failed  local/remo te BSE log in attempt .");
  1288           }
  1289  
  1290           
  1291           
  1292           pr ivate void  removeOpt ion(String  subscript , String o ptNum, Str ing remote Duz) 
  1293           th rows Excep tion 
  1294           {
  1295                    logg er.info("r emoveOptio n Transact ionContext  (" + Tran sactionCon textFactor y.get().ge tDisplayId entity() +  ").");
  1296                    
  1297                    Vist aQuery msg  = VistaCo mmonQueryF actory.cre ateRemoveO ptionVista Query(subs cript, opt Num, remot eDuz);
  1298                    Stri ng rtn = g etVistaCon nection(). call(msg);
  1299                    if ( !rtn.equal s("[Data]" )) {
  1300                             throw  new Except ion("ERROR : " + rtn) ;
  1301                    }
  1302           }
  1303           
  1304           /*
  1305           pr ivate void  setUserDi vision()
  1306           th rows Metho dException  // not su re if shou ld be conn ection or  method exc eption
  1307           {                 
  1308                    // g et the Sit e that we  are connec ted to
  1309                    Site  site = ge tSite();
  1310                    Stri ng connect edSiteNumb er = site. getSiteNum ber();
  1311                    logg er.info("S etting use r division , local si te number  is '" + co nnectedSit eNumber +  "', Transa ctionConte xt (" + Tr ansactionC ontextFact ory.get(). getDisplay Identity()  + ").");
  1312                    Vist aQuery vm  = VistaCom monQueryFa ctory.crea teGetDivis ionQuery() ;
  1313                    Stri ng rtn = " ";
  1314                    try
  1315                    {
  1316                             rtn =  getVistaCo nnection() .call(vm);
  1317                             String  [] lines  = StringUt ils.Split( rtn, Strin gUtils.NEW _LINE);
  1318                             if((li nes != nul l) && (lin es.length  > 0))
  1319                             {
  1320                                      int divi sionCount  = Integer. parseInt(l ines[0].tr im());
  1321                                      if(divis ionCount >  0)
  1322                                      {
  1323                                               for(int li neNumber =  1; lineNu mber < lin es.length;  lineNumbe r++)
  1324                                               {
  1325                                                       St ring line  = lines[li neNumber];
  1326                                                       
  1327                                                       St ring [] pi eces = Str ingUtils.S plit(line,  StringUti ls.CARET);
  1328                                                       St ring divis ionNumber  = pieces[2 ];
  1329                                                       bo olean defa ultDivisio n = false;
  1330                                                       
  1331                                                       if (pieces.le ngth > 3)
  1332                                                       {
  1333                                                                if(" 1".equals( pieces[3]) )
  1334                                                                         defaul tDivision  = true;
  1335                                                       }
  1336                                                       
  1337                                                       
  1338   //                                                  if (connected SiteNumber .equals(di visionNumb er))
  1339   //                                                  {
  1340   //                                                           setU serDivisio n(line.tri m());
  1341   //                                                           brea k;
  1342   //                                                  }
  1343                                                       
  1344                                                       if (defaultDi vision)
  1345                                                       {
  1346                                                                setU serDivisio n(division Number);
  1347                                                                brea k;
  1348                                                       }
  1349                                               }
  1350                                      }
  1351                                      logger.i nfo("Did n ot find as signed div ision for  site '" +  connectedS iteNumber  + "' for u ser, not e xplicitly  setting di vision.");
  1352                             }
  1353                             else
  1354                             {
  1355                                      // this  should use  the kerne l default  division
  1356                                      logger.i nfo("User  is not ass igned at l east 1 div ision, not  setting d ivision.") ;
  1357                             }
  1358                    }
  1359                    catc h(Exceptio n ex)
  1360                    {
  1361                             logger .error("Er ror settin g user div ision", ex );
  1362                             throw  new Method Exception( "Error set ting user  division",  ex);                     
  1363                    }
  1364           }* /
  1365           
  1366           pr ivate void  setUserDi vision(Str ing divisi on)
  1367           th rows IOExc eption, In validVista Credential sException , VistaMet hodExcepti on, Connec tionExcept ion
  1368           {
  1369                    if(( division ! = null) &&  (division .length()  > 0))
  1370                    {
  1371                             logger .info("Set ting user  division t o '" + div ision + "' .");
  1372                             VistaQ uery vm =  VistaCommo nQueryFact ory.create SetDivisio nQuery(div ision);
  1373                             String  result =  getVistaCo nnection() .call(vm);
  1374                             if((re sult == nu ll) || (!r esult.equa ls("1")))
  1375                             {
  1376                                      throw ne w Connecti onExceptio n("Attempt ed to set  user divis ion to '"  + division  + "', res ult was no t expected  value of  '1' but wa s value '"  + result  + "'.");
  1377                             }
  1378                    }
  1379                    else
  1380                    {
  1381                             logger .debug("Us er divisio n is null  or empty,  not settin g.");
  1382                    }                 
  1383           }
  1384  
  1385           /* *
  1386            *  
  1387            *  @param co ntext
  1388            *  @throws U nableToCre ateContext Exception
  1389            * /
  1390           pr ivate void  setContex t(String c ontext) 
  1391           th rows Unabl eToCreateC ontextExce ption 
  1392           {
  1393                    logg er.info(
  1394                             "setCo ntext(" +  context + 
  1395                             ") Tra nsactionCo ntext (" +  Transacti onContextF actory.get ().getDisp layIdentit y() + ")."
  1396                    );
  1397                    
  1398           Vi staQuery v m = VistaC ommonQuery Factory.cr eateSetCon textVistaQ uery(conte xt);
  1399           St ring rtn =  "";
  1400           tr
  1401           {
  1402                    rtn  = getVista Connection ().call(vm );
  1403           }
  1404           ca tch(Except ion ex) 
  1405           {
  1406                    thro w new Unab leToCreate ContextExc eption(ex) ;
  1407           }
  1408           if ( !rtn.equ als("1") )  
  1409                    thro w new Unab leToCreate ContextExc eption("Un able to se t context  [" + conte xt + "]");
  1410           }
  1411           
  1412           /* *
  1413            *  Create an d call an  RPC to get  the users  DUZ (acco unt ID) fr om VistA.
  1414            *  
  1415            *  @param us erSSN
  1416            *  @return
  1417            *  @throws V istaMethod Exception 
  1418            *  @throws I nvalidVist aCredentia lsExceptio
  1419            *  @throws E xception
  1420            * /
  1421           pr ivate Stri ng getDUZ( String use rSSN) 
  1422           th rows Vista Connection Exception,  IOExcepti on, Invali dVistaCred entialsExc eption, Vi staMethodE xception
  1423           {
  1424                    logg er.info("g etDUZ Tran sactionCon text (" +  Transactio nContextFa ctory.get( ).getDispl ayIdentity () + ").") ;
  1425                    
  1426                    Vist aQuery msg  = VistaCo mmonQueryF actory.cre ateGetDUZV istaQuery( StringUtil .cleanStri ng(userSSN ));
  1427                    Stri ng rtn = c all(msg);
  1428                    if ( !StringUti ls.isNumer ic(rtn))
  1429                             throw  new VistaC onnectionE xception(" Non-numeri c DUZ");
  1430                    
  1431                    retu rn rtn;
  1432           }
  1433  
  1434           /* *
  1435            *  
  1436            *  @param co ntext
  1437            *  @return
  1438            *  @throws V istaMethod Exception 
  1439            *  @throws I nvalidVist aCredentia lsExceptio
  1440            *  @throws E xception
  1441            * /
  1442           pr ivate Stri ng getCont extIEN(Str ing contex t) 
  1443           th rows Vista Connection Exception,  IOExcepti on, Invali dVistaCred entialsExc eption, Vi staMethodE xception
  1444           {
  1445                    logg er.info("g etContextI EN Transac tionContex t (" + Tra nsactionCo ntextFacto ry.get().g etDisplayI dentity()  + ").");
  1446                    
  1447                    Vist aQuery msg  = VistaCo mmonQueryF actory.cre ateGetCont extIENVist aQuery(con text);
  1448                    Stri ng rtn = c all(msg);
  1449                    if(  !StringUti ls.isNumer ic(rtn) )
  1450                             throw  new VistaC onnectionE xception(" Non-numeri c context  IEN for "  + context) ;
  1451                    retu rn rtn;
  1452           }
  1453           
  1454           /* *
  1455            *  @param vm
  1456            *  @return
  1457            *  @throws E xception
  1458            *  @throws M ethodExcep tion
  1459            * /
  1460           pr ivate Stri ng connect AndSignon( VistaQuery  ... signo nQueries) 
  1461           th rows Conne ctionExcep tion, Secu rityCreden tialsExpir edExceptio n, BseFail edExceptio n
  1462           {
  1463                    Stri ng vistaRe sult = nul l;
  1464                    
  1465                    logg er.info("c onnectAndS ignon Tran sactionCon text (" +  Transactio nContextFa ctory.get( ).getDispl ayIdentity () + ").") ;
  1466                    
  1467                    int  retryCount ;
  1468                    Exce ption sign onExceptio n = null;
  1469                    for( retryCount =0; retryC ount<this. failedSign onRetryMax ; ++retryC ount)
  1470                    {
  1471                             try
  1472                             {
  1473                                      long sta rtConnect  = System.c urrentTime Millis();
  1474                                      logger.i nfo("Conne cting to V ista ...") ;
  1475                                      getVista Connection ().connect ();
  1476                                      logger.i nfo("Conne cted to Vi sta in " +  (System.c urrentTime Millis() -  startConn ect) + " m illisecond s, signing  on...");
  1477                                      
  1478                                      long sta rtSignon =  System.cu rrentTimeM illis();
  1479                                      
  1480                                      if(signo nQueries ! = null)
  1481                                      {
  1482                                               int queryC ount = 0;
  1483                                               logger.inf o("Calling  '" + sign onQueries. length + " ' signon q ueries.");
  1484                                               for(VistaQ uery signo nQuery : s ignonQueri es)
  1485                                               {
  1486                                                       vi staResult  = getVista Connection ().call(si gnonQuery) ;
  1487                                                       lo gger.debug ("Result o f VistA si gnon query  [" + quer yCount + " ]: " + vis taResult);
  1488                                                       qu eryCount++ ;
  1489                                               }
  1490                                      }
  1491                                      else
  1492                                      {
  1493                                               logger.inf o("Signon  queries ar e null, sh ould NOT h appen - si gnon proba bly won't  work!");
  1494                                      }
  1495                                      
  1496                                      
  1497                                      
  1498                                      //System .out.print ln("Vista  Result:\n"  + vistaRe sult);
  1499                                      if (vist aResult ==  null)
  1500                                               throw new  VistaConne ctionExcep tion("Null  result re turned fro m Vista in  response  to RPC_SIG NON call." );
  1501                                      logger.i nfo("Signe d on to Vi sta in " +  (System.c urrentTime Millis() -  startSign on) + " mi lliseconds .");
  1502                                      
  1503                                      break;
  1504                             }
  1505                             catch( InvalidVis taCredenti alsExcepti on ivcX)
  1506                             {
  1507                                      // remem ber the fi rst except ion
  1508                                      signonEx ception =  signonExce ption == n ull ? ivcX  : signonE xception;
  1509                                      
  1510                                      // disco nnect and  ignore all  errors
  1511                                      try{getV istaConnec tion().err orDisconne ct();}
  1512                                      catch(Th rowable t) {}
  1513                                      
  1514                                      // Inval idVistaCre dentialsEx ception mi ght occur  if the BSE  token is  bad, if so  then 
  1515                                      // don't  retry (si nce it sti ll won't w ork)
  1516                                      if((ivcX .getMessag e() != nul l) && 
  1517                                               (ivcX.getM essage().s tartsWith( "BSE ERROR  - BSE TOK EN EXPIRED ")))
  1518                                      {
  1519                                               String msg  = "RPC_SI GNON Broke r signon f ailed, BSE  TOKEN EXP IRED";
  1520                                               logger.err or(msg, iv cX);
  1521                                               throw new  SecurityCr edentialsE xpiredExce ption(msg) ;
  1522                                      }
  1523                                      else if( (ivcX.getM essage() ! = null)&& 
  1524                                               (ivcX.getM essage().s tartsWith( "BSE ERROR ")))
  1525                                      {
  1526                                               // if ther e is anoth er type of  error for  BSE, thro w an excep tion
  1527                                               String msg  = "RPC_SI GNON Broke r signon f ailed, " +  ivcX.getM essage();
  1528                                               logger.err or(msg, iv cX);
  1529                                               throw new  BseFailedE xception(m sg);
  1530                                      }
  1531                                      // delay  for a ran dom amount  of time f rom 1 to 2  seconds
  1532                                      long ran domDelay =  (long)(Ma th.random( ) * (FAILE D_SIGNIN_M AX_WAIT_TI ME - FAILE D_SIGNON_M IN_WAIT_TI ME) + FAIL ED_SIGNON_ MIN_WAIT_T IME);
  1533                                      logger.w arn(
  1534                                               "RPC_SIGNO N failed [ " + ivcX.g etClass(). getSimpleN ame() + ":  " + ivcX. getMessage () + 
  1535                                               "] (" + re tryCount +  "), retry ing in " +  randomDel ay + " mil liseconds. "
  1536                                      );
  1537                                      try{Thre ad.sleep(r andomDelay );}
  1538                                      catch(In terruptedE xception i X){}
  1539                             }
  1540                             catch  (Exception  ex)
  1541                             {
  1542                                      // remem ber the fi rst except ion
  1543                                      signonEx ception =  signonExce ption == n ull ? ex :  signonExc eption;
  1544                                      
  1545                                      // disco nnect and  ignore all  errors
  1546                                      try{getV istaConnec tion().err orDisconne ct();}
  1547                                      catch(Th rowable t) {}
  1548                                      
  1549                                      // delay  for a ran dom amount  of time f rom 1 to 2  seconds
  1550                                      long ran domDelay =  (long)(Ma th.random( ) * (FAILE D_SIGNIN_M AX_WAIT_TI ME - FAILE D_SIGNON_M IN_WAIT_TI ME) + FAIL ED_SIGNON_ MIN_WAIT_T IME);
  1551                                      logger.w arn(
  1552                                               "RPC_SIGNO N failed [ " + ex.get Class().ge tSimpleNam e() + ": "  + ex.getM essage() +  
  1553                                               "] (" + re tryCount +  "), retry ing in " +  randomDel ay + " mil liseconds. "
  1554                                      );
  1555                                      try{Thre ad.sleep(r andomDelay );}
  1556                                      catch(In terruptedE xception i X){}
  1557                             }
  1558                    }
  1559                    
  1560                    if(r etryCount  >= FAILED_ SIGNON_MAX _COUNT)
  1561                    {
  1562                             logger .error("RP C_SIGNON f ailed, ret ry count e xceeded.") ;
  1563                             throw  new VistaC onnectionE xception(s ignonExcep tion);
  1564                    }
  1565                    retu rn vistaRe sult;
  1566           }
  1567           
  1568           /* *
  1569            *  Send the  access and  verify co des from t he Transac tionContex t to Vista  and
  1570            *  parse the  results s tring.
  1571            *  
  1572            *  @param tr ansactionC ontext
  1573            *  @throws I nvalidCred entialsExc eption
  1574            *  @throws I OException
  1575            *  @throws V istaMethod Exception 
  1576            *  @throws V istaExcept ion
  1577            * /
  1578           pr ivate void  presentAc cessVerify Credential s(Transact ionContext  transacti onContext)  
  1579           th rows Inval idCredenti alsExcepti on, IOExce ption, Vis taMethodEx ception, M issingCred entialsExc eption
  1580       {
  1581                VistaQue ry avCodeQ uery = Vis taCommonQu eryFactory .createAVC odeVistaQu ery(transa ctionConte xt);
  1582                String v istaResult ;
  1583                
  1584                try
  1585           {
  1586                    vist aResult =  getVistaCo nnection() .call(avCo deQuery);
  1587           } 
  1588                catch (I nvalidVist aCredentia lsExceptio n e)
  1589           {
  1590                    thro w new Inva lidCredent ialsExcept ion(e.getM essage());
  1591           }
  1592                
  1593                // valid ate user c redentials  login inf ormation
  1594                String [ ] authResu lts = Stri ngUtils.Sp lit(vistaR esult, Str ingUtils.N EW_LINE);
  1595                int auth Value = In teger.pars eInt(authR esults[0]. trim());
  1596                if(authV alue <= 0)  
  1597                {
  1598                    logg er.debug(" Authentica tion faile d [" + vis taResult +  "]");
  1599                    if(a uthResults .length >=  4 && auth Results[3]  != null)
  1600                             transa ctionConte xt.addDebu gInformati on("Authen tication f ailed with  message [ " + authRe sults[3].t rim() + "] ");
  1601                    else
  1602                             transa ctionConte xt.addDebu gInformati on("Authen tication f ailed with  failure C ode [" + a uthResults [2].trim()  + "]");
  1603                    // f ailed auth entication , throw an  InvalidCr edentialsE xception
  1604                    // N OTE: conne ction will  be discon nected lat er in the  finally bl ock
  1605                    if(a uthResults [2].trim() .equals("1 "))
  1606                             throw  new Invali dCredentia lsExceptio n("Expired  Verify Co de");
  1607                    else
  1608                    {
  1609                             // JMW  7/25/2012  use the r eal messag e from Vis tA for the  exception
  1610                             // exp lanation f or authent ication fa ilure is i n authResu lts[3]
  1611                             if(aut hResults.l ength >= 4  && authRe sults[3] ! = null)
  1612                             {
  1613                                      throw ne w InvalidC redentials Exception( authResult s[3].trim( ));
  1614                             }
  1615                             else
  1616                             {
  1617                                      throw ne w InvalidC redentials Exception( "Invalid A ccess/Veri fy Codes") ;
  1618                             }
  1619                    }
  1620                }
  1621       }
  1622           
  1623           /* *
  1624            *  
  1625            *  @param su bscript
  1626            *  @param co ntextIEN
  1627            *  @return
  1628            *  @throws E xception
  1629            * /
  1630           pr ivate Stri ng assignO ption(Stri ng subscri pt, String  contextIE N, String  remoteDuz)
  1631       throws  Exception
  1632           {
  1633                    logg er.info("a ssignOptio n Transact ionContext  (" + Tran sactionCon textFactor y.get().ge tDisplayId entity() +  ").");
  1634                    
  1635                    Vist aQuery msg  = VistaCo mmonQueryF actory.cre ateAssignO ptionVista query(subs cript, con textIEN, r emoteDuz);
  1636                    Stri ng rtn = g etVistaCon nection(). call(msg);
  1637                    retu rn VistaCo mmonTransl ator.parse OptionNumb er(rtn);
  1638           }
  1639           
  1640           /* *
  1641            *  
  1642            *  @param su bscript
  1643            *  @param co ntextIen
  1644            *  @return
  1645            *  @throws E xception
  1646            * /
  1647           pr ivate Stri ng getOpti onIEN(Stri ng subscri pt, String  contextIe n, String  remoteDuz)  
  1648           th rows Excep tion 
  1649           {
  1650                    logg er.info("g etOptionIE N Transact ionContext  (" + Tran sactionCon textFactor y.get().ge tDisplayId entity() +  ").");
  1651                    
  1652                    Vist aQuery msg  = VistaCo mmonQueryF actory.cre ateGetOpti onVistaQue ry(subscri pt, contex tIen, remo teDuz);
  1653                    Stri ng rtn = g etVistaCon nection(). call(msg);
  1654                    if ( !StringUti ls.isNumer ic(rtn)) {
  1655                             throw  new Except ion("Non-n umeric opt ion IEN fo r " + subs cript);
  1656                    }
  1657                    retu rn rtn;
  1658           }
  1659  
  1660           /* *
  1661            *  Determine s if an Im aging sess ion has be en created  for this  VistA Conn ection
  1662            *  @return
  1663            * /
  1664           pu blic boole an isSessi onCreated( ) {
  1665                    retu rn session Created;
  1666           }
  1667  
  1668           /* *
  1669            *  Sets the  session cr eated to i ndicate if  an Imagin g session  has been c reated dur ing this V istA conne ction
  1670            *  @param se ssionCreat ed
  1671            * /
  1672           pu blic void  setSession Created(bo olean sess ionCreated ) {
  1673                    this .sessionCr eated = se ssionCreat ed;
  1674           }
  1675  
  1676           /* *
  1677            *  @return t he vistaRa dLoggedIn
  1678            * /
  1679           pu blic boole an isVista RadLoggedI n()
  1680           {
  1681                    retu rn vistaRa dLoggedIn;
  1682           }
  1683  
  1684           /* *
  1685            *  @param vi staRadLogg edIn the v istaRadLog gedIn to s et
  1686            * /
  1687           pu blic void  setVistaRa dLoggedIn( boolean vi staRadLogg edIn) 
  1688           {
  1689                    this .vistaRadL oggedIn =  vistaRadLo ggedIn;
  1690           }        
  1691           
  1692           pu blic stati c ImagingS ecurityCon textType g etImagingS ecurityCon textType()
  1693           {
  1694                    Tran sactionCon text trans actionCont ext = Tran sactionCon textFactor y.get();
  1695                    Stri ng imaging SecurityCo ntextStrin g = transa ctionConte xt.getImag ingSecurit yContextTy pe();
  1696                    if(( imagingSec urityConte xtString = = null) ||  (imagingS ecurityCon textString .length()  == 0))
  1697                    {
  1698                             logger .debug("No  imaging s ecurity co ntext foun d in Trans actionCont ext, using  default ' " + defaul tSecurityC ontextType  + "'");
  1699                             return  defaultSe curityCont extType;
  1700                    }
  1701                    try
  1702                    {
  1703                             return  ImagingSe curityCont extType.va lueOf(imag ingSecurit yContextSt ring);
  1704                    }
  1705                    catc h(IllegalA rgumentExc eption irX )
  1706                    {
  1707                             logger .error("Er ror parsin g security  context f rom Transa ctionConte xt, " + ir X.getMessa ge());
  1708                             return  defaultSe curityCont extType;       
  1709                    }
  1710           }
  1711           
  1712           pr ivate bool ean isBseC redentials InContext( Transactio nContext t ransaction Context)
  1713           {
  1714                    if(t ransaction Context ==  null)
  1715                             return  false;
  1716                    
  1717                    if(t ransaction Context.ge tBrokerSec urityToken () == null )
  1718                             return  false;
  1719                    
  1720                    if(t ransaction Context.ge tBrokerSec urityToken ().length( ) <= 0)
  1721                             return  false;
  1722                    
  1723                    retu rn true;
  1724           }
  1725  
  1726           /* *
  1727            *  @return t he session Index
  1728            * /
  1729           pu blic long  getSession Index()
  1730           {
  1731                    retu rn session Index;
  1732           }
  1733  
  1734           /* *
  1735            *  @param se ssionIndex  the sessi onIndex to  set
  1736            * /
  1737           pu blic void  setSession Index(long  sessionIn dex)
  1738           {
  1739                    this .sessionIn dex = sess ionIndex;
  1740           }
  1741   }