155. EPMO Open Source Coordination Office Redaction File Detail Report

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

155.1 Files compared

# Location File Last Modified
1 C:\AraxisMergeCompare\Pri_un\IV-ehmp_cif\VistaDataSourceCommon\main\src\java\gov\va\med\imaging\vistadatasource\session VistaSession.java Thu Jun 29 17:23:07 2017 UTC
2 C:\AraxisMergeCompare\Pri_re\IV-ehmp_cif\VistaDataSourceCommon\main\src\java\gov\va\med\imaging\vistadatasource\session VistaSession.java Fri Jul 7 18:49:57 2017 UTC

155.2 Comparison summary

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

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

155.4 Active regular expressions

No regular expressions were active.

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