389. EPMO Open Source Coordination Office Redaction File Detail Report

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

389.1 Files compared

# Location File Last Modified
1 IV-eHMP_CIF.zip\IMAG_Source\VISA\Java\VistaDataSourceCommon\main\src\java\gov\va\med\imaging\vistadatasource\session VistaSession.java Mon Dec 4 21:34:58 2017 UTC
2 IV-eHMP_CIF.zip\IMAG_Source\VISA\Java\VistaDataSourceCommon\main\src\java\gov\va\med\imaging\vistadatasource\session VistaSession.java Tue Dec 5 15:34:58 2017 UTC

389.2 Comparison summary

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

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

389.4 Active regular expressions

No regular expressions were active.

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