21. EPMO Open Source Coordination Office Redaction File Detail Report

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

21.1 Files compared

# Location File Last Modified
1 ehealth_xchange_cif.zip\NHIN_adapter\AdapterEJB\src\archive\java\gov\va\med\nhin\adapter\adaptergateway\docquery AdapterGatewayDocQueryOrchBean.java Thu Feb 22 14:25:44 2018 UTC
2 ehealth_xchange_cif.zip\NHIN_adapter\AdapterEJB\src\archive\java\gov\va\med\nhin\adapter\adaptergateway\docquery AdapterGatewayDocQueryOrchBean.java Tue Feb 27 14:23:55 2018 UTC

21.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 2 1232
Changed 1 2
Inserted 0 0
Removed 0 0

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

21.4 Active regular expressions

No regular expressions were active.

21.5 Comparison detail

  1   package go v.va.med.n hin.adapte r.adapterg ateway.doc query;
  2  
  3   import jav a.util.Arr ayList;
  4   import jav a.util.Dat e;
  5   import jav a.util.Has hMap;
  6   import jav a.util.Lis t;
  7   import jav a.util.Map ;
  8   import jav a.util.con current.Ca llable;
  9   import jav a.util.con current.Ex ecutionExc eption;
  10   import jav a.util.con current.Ex ecutorComp letionServ ice;
  11   import jav a.util.con current.Ex ecutorServ ice;
  12   import jav a.util.reg ex.Matcher ;
  13   import jav a.util.reg ex.Pattern ;
  14  
  15   import jav ax.ejb.EJB ;
  16   import jav ax.ejb.*;
  17  
  18   import gov .va.med.nh in.adapter .utils.Log Util;
  19   import org .apache.co mmons.lang 3.StringUt ils;
  20   import org .hl7.v3.II ;
  21   import org .hl7.v3.PR PAIN201310 UV02;
  22   import org .hl7.v3.PR PAMT201304 UV02Patien t;
  23   import org .hl7.v3.Re trievePati entCorrela tionsReque stType;
  24   import org .hl7.v3.Re trievePati entCorrela tionsRespo nseType;
  25   import org .slf4j.Log ger;
  26   import org .slf4j.Log gerFactory ;
  27  
  28   import gov .hhs.fha.n hinc.adapt erpolicyen gine.Adapt erPolicyEn ginePortTy pe;
  29   import gov .hhs.fha.n hinc.commo n.eventcom mon.AdhocQ ueryReques tEventType ;
  30   import gov .hhs.fha.n hinc.commo n.eventcom mon.AdhocQ ueryReques tMessageTy pe;
  31   import gov .hhs.fha.n hinc.commo n.nhinccom mon.Assert ionType;
  32   import gov .hhs.fha.n hinc.commo n.nhinccom mon.HomeCo mmunityTyp e;
  33   import gov .hhs.fha.n hinc.commo n.nhinccom mon.NhinTa rgetCommun ityType;
  34   import gov .hhs.fha.n hinc.commo n.nhinccom monadapter .CheckPoli cyRequestT ype;
  35   import gov .hhs.fha.n hinc.commo n.nhinccom monadapter .CheckPoli cyResponse Type;
  36   import gov .hhs.fha.n hinc.nhinc componentp atientcorr elation.Pa tientCorre lationPort Type;
  37   import gov .hhs.fha.n hinc.nhinc lib.NhincC onstants;
  38   import gov .hhs.fha.n hinc.trans form.polic y.PolicyEn gineTransf ormer;
  39   import gov .hhs.fha.n hinc.trans form.subdi sc.HL7PRPA 201309Tran sforms;
  40   import gov .va.med.nh in.adapter .audit.req uests.Requ estActions ;
  41   import gov .va.med.nh in.adapter .audit.req uests.Requ estAudit;
  42   import gov .va.med.nh in.adapter .audit.req uests.Requ estAuditEn tity;
  43   import gov .va.med.nh in.adapter .facilitym anager.Fac ility;
  44   import gov .va.med.nh in.adapter .facilitym anager.Fac ilityManag er;
  45   import gov .va.med.nh in.adapter .facilitym anager.Fac ilityManag erLocal;
  46   import gov .va.med.nh in.adapter .facilitym anager.Ope rationOnOf f;
  47   import gov .va.med.nh in.adapter .logging.C heckPolicy ;
  48   import gov .va.med.nh in.adapter .logging.E rrorMessag e;
  49   import gov .va.med.nh in.adapter .logging.M aintLog;
  50   import gov .va.med.nh in.adapter .patientco rrelation. PatientCor relationPo rtTypeLoca l;
  51   import gov .va.med.nh in.adapter .policyeng ine.Adapte rPolicyEng inePortTyp eLocal;
  52   import gov .va.med.nh in.adapter .utils.Nul lChecker;
  53   import oas is.names.t c.ebxml_re grep.xsd.q uery._3.Ad hocQueryRe quest;
  54   import oas is.names.t c.ebxml_re grep.xsd.q uery._3.Ad hocQueryRe sponse;
  55   import oas is.names.t c.ebxml_re grep.xsd.r im._3.Adho cQueryType ;
  56   import oas is.names.t c.ebxml_re grep.xsd.r im._3.Slot Type1;
  57   import oas is.names.t c.ebxml_re grep.xsd.r im._3.Valu eListType;
  58   import oas is.names.t c.ebxml_re grep.xsd.r s._3.Regis tryError;
  59   import oas is.names.t c.ebxml_re grep.xsd.r s._3.Regis tryErrorLi st;
  60  
  61   /**
  62    *
  63    * @author   DN S      VAZQUD
  64    */
  65   @Transacti onAttribut e(value =  Transactio nAttribute Type.SUPPO RTS)
  66   @Stateless (name = "A dapterGate wayDocQuer yOrch")
  67   public cla ss Adapter GatewayDoc QueryOrchB ean implem ents Adapt erGatewayD ocQueryPor tTypeLocal
  68   {
  69           pr ivate clas s SendRequ estRespons e
  70           {
  71                    publ ic AdhocQu eryRespons e adhocQue ryResponse ;
  72                    publ ic II remo tePatientI d;
  73                    publ ic String  remoteHome CommunityI d;
  74                    publ ic SendReq uestExcept ion sre =  null;
  75  
  76                    publ ic boolean  hasError( )
  77                    {
  78                             if(sre  == null)
  79                             {
  80                                      return f alse;
  81                             }
  82  
  83                             return  true;
  84                    }
  85           }
  86  
  87           pr ivate clas s SendRequ estExcepti on extends  Exception
  88           {
  89                    publ ic II remo tePatientI d;
  90                    publ ic String  remoteHome CommunityI d;
  91           }
  92  
  93           pr ivate clas s SendRequ estCallabl e implemen ts Callabl e<SendRequ estRespons e>
  94           {
  95                    priv ate final  AdhocQuery Request ad hocQueryRe quest;
  96                    priv ate final  AssertionT ype assert ion;
  97                    priv ate II rem otePatient Id;
  98                    priv ate String  remoteHom eCommunity Id;
  99                    priv ate String  auditUUID ;
  100  
  101                    publ ic SendReq uestCallab le(AdhocQu eryRequest  adhocQuer yRequest,  AssertionT ype assert ion, II re motePatien tId, Strin g remoteHo meCommunit yId, Strin g auditUUI D)
  102                    {
  103                             this.a dhocQueryR equest = a dhocQueryR equest;
  104                             this.a ssertion =  assertion ;
  105                             this.r emotePatie ntId = rem otePatient Id;
  106                             this.r emoteHomeC ommunityId  = remoteH omeCommuni tyId;
  107                             this.a uditUUID =  auditUUID ;
  108                    }
  109  
  110                    publ ic SendReq uestRespon se call()  throws Exc eption
  111                    {
  112                             return  sendReque st(adhocQu eryRequest , assertio n, remoteP atientId,  remoteHome CommunityI d, auditUU ID);
  113                    }
  114           }
  115  
  116           pr ivate stat ic final L ogger logg er = Logge rFactory.g etLogger(A dapterGate wayDocQuer yOrchBean. class.getN ame());
  117  
  118           st atic priva te final S tring EBXM L_DOCENTRY _PATIENT_I D = "$XDSD ocumentEnt ryPatientI d";
  119  
  120           pr ivate Faci lityManage r facility Manager;
  121           pr ivate Pati entCorrela tionPortTy pe adapter PatientCor relation;
  122           pr ivate Adap terPolicyE nginePortT ype adapte rPolicyEng ine;
  123           pr ivate NHIN DocQueryRe questSende r nhinDocQ ueryReques tSender;
  124           pr ivate Exec utorServic e executor Service;
  125           pr ivate Requ estAudit r equestAudi t;
  126  
  127           @E JB(beanInt erface = F acilityMan agerLocal. class, bea nName = "F acilityMan ager")
  128           pu blic void  setFacilit yManager(F acilityMan ager facil ityManager )
  129           {
  130                    this .facilityM anager = f acilityMan ager;
  131           }
  132  
  133           @E JB(beanInt erface = A dapterPoli cyEnginePo rtTypeLoca l.class, b eanName =  "AdapterPo licyEngine ")
  134           pu blic void  setAdapter PolicyEngi ne(Adapter PolicyEngi nePortType  adapterPo licyEngine )
  135           {
  136                    this .adapterPo licyEngine  = adapter PolicyEngi ne;
  137           }
  138  
  139           @E JB(beanInt erface = P atientCorr elationPor tTypeLocal .class, be anName = " AdapterPat ientCorrel ation")
  140           pu blic void  setAdapter PatientCor relation(P atientCorr elationPor tType adap terPatient Correlatio n)
  141           {
  142                    this .adapterPa tientCorre lation = a dapterPati entCorrela tion;
  143           }
  144  
  145           @E JB(beanInt erface = N HINDocQuer yRequestSe nder.class , beanName  = "NhincP roxyNHINDo cQueryRequ estSender" )
  146           pu blic void  setNhinDoc QueryReque stSender(N HINDocQuer yRequestSe nder nhinD ocQueryReq uestSender )
  147           {
  148                    this .nhinDocQu eryRequest Sender = n hinDocQuer yRequestSe nder;
  149           }
  150  
  151           @E JB(beanInt erface = W orkManager ExecutorSe rviceLocal .class, be anName = " WorkManage rExecutorS ervice")
  152           pu blic void  setExecuto rService(E xecutorSer vice execu torService )
  153           {
  154                    this .executorS ervice = e xecutorSer vice;
  155           }
  156  
  157           @E JB(beanInt erface = R equestAudi t.class, b eanName =  "RequestAu dit")
  158           pu blic void  setRequest Audit(Requ estAudit r equestAudi t)
  159           {
  160                    this .requestAu dit = requ estAudit;
  161           }
  162  
  163           pu blic Respo ndingGatew ayCrossGat ewayQueryR esponseTyp e respondi ngGatewayC rossGatewa yQuery(Res pondingGat ewayCrossG atewayQuer yRequestTy pe respond ingGateway CrossGatew ayQueryReq uest)
  164           {
  165                    Resp ondingGate wayCrossGa tewayQuery ResponseTy pe ret = c reateRespo ndingGatew ayCrossGat ewayQueryR esponse();
  166  
  167                    Exec utorComple tionServic e<SendRequ estRespons e> complet ionService  = new Exe cutorCompl etionServi ce<SendReq uestRespon se>(execut orService) ;
  168                    II p atientId =  getPatien tId(respon dingGatewa yCrossGate wayQueryRe quest.getA dhocQueryR equest());
  169  
  170                    logg er.debug(" Patient Id  {} :", pa tientId);
  171  
  172                    if(p atientId ! = null)
  173                    {
  174                             // Set up incomin g request  audit valu es.
  175                             Reques tAuditEnti ty request AuditEntit y = new Re questAudit Entity();
  176                             reques tAuditEnti ty.setPid( patientId. getExtensi on());
  177                             reques tAuditEnti ty.generat eUUID();
  178                             reques tAuditEnti ty.setStar tTime(new  Date());
  179                             reques tAuditEnti ty.setActi on(Request Actions.PA RENT_REQUE ST.getValu e());
  180  
  181                             // CCR  177986
  182                             logger .debug("Re questAudit Entity req uestAuditE ntity {} " , requestA uditEntity );
  183  
  184                             if(res pondingGat ewayCrossG atewayQuer yRequest ! = null &&  responding GatewayCro ssGatewayQ ueryReques t.getAsser tion() !=  null && re spondingGa tewayCross GatewayQue ryRequest. getAsserti on().getHo meCommunit y() != nul l && Strin gUtils.isN otBlank(re spondingGa tewayCross GatewayQue ryRequest. getAsserti on().getHo meCommunit y().getHom eCommunity Id()))
  185                             {
  186                                      logger.d ebug("Home  community  Id {} fro m the requ est ", res pondingGat ewayCrossG atewayQuer yRequest.g etAssertio n().getHom eCommunity ().getHome CommunityI d()); // C CR
  187                                                                                                                                                                                                                                                                                                                                                                                             // 177 986
  188  
  189                                      requestA uditEntity .setHcid(r espondingG atewayCros sGatewayQu eryRequest .getAssert ion().getH omeCommuni ty().getHo meCommunit yId());
  190                             }
  191                             else
  192                             {
  193                                      requestA uditEntity .setHcid(" UNKNOWN");
  194                             }
  195  
  196                             Retrie vePatientC orrelation sResponseT ype patien tCorrelati ons = getP atientCorr elations(p atientId,  responding GatewayCro ssGatewayQ ueryReques t.getAsser tion());
  197                             if(pat ientCorrel ations !=  null && pa tientCorre lations.ge tPRPAIN201 310UV02()  != null)
  198                             {
  199                                      int numS ubmitted =  0;
  200                                      PRPAMT20 1304UV02Pa tient pati ent = extr actPatient (patientCo rrelations .getPRPAIN 201310UV02 ());
  201  
  202                                      for(II c orrelatedP atientId :  patient.g etId())
  203                                      {
  204                                               List<Strin g> remoteH omeCommuni tyIds = ge tRemoteHom eCommunity Ids(correl atedPatien tId);
  205                                               for(String  remoteHom eCommunity Id : remot eHomeCommu nityIds)
  206                                               {
  207                                                       if (facilityM anager.isP artnerAllo wed(remote HomeCommun ityId, Ope rationOnOf f.ONBOARD) )
  208                                                       {
  209                                                                if(f acilityMan ager.isPar tnerAllowe d(remoteHo meCommunit yId, Opera tionOnOff. OUT_DQ))
  210                                                                {
  211                                                                         AdhocQ ueryReques t adhocQue ryRequest  = createAd hocQueryRe quest(resp ondingGate wayCrossGa tewayQuery Request.ge tAdhocQuer yRequest() , remoteHo meCommunit yId, corre latedPatie ntId);
  212                                                                         if(che ckPolicy(a dhocQueryR equest, re spondingGa tewayCross GatewayQue ryRequest. getAsserti on(), remo teHomeComm unityId))
  213                                                                         {
  214                                                                                  SendRequ estCallabl e callable  = new Sen dRequestCa llable(adh ocQueryReq uest, resp ondingGate wayCrossGa tewayQuery Request.ge tAssertion (), correl atedPatien tId, remot eHomeCommu nityId, re questAudit Entity.get Uuid());
  215                                                                                  completi onService. submit(cal lable);
  216                                                                                  ++numSub mitted;
  217                                                                         }
  218                                                                }
  219                                                                else
  220                                                                {
  221                                                                         addErr orToRespon se(ret, re spondingGa tewayCross GatewayQue ryRequest. getAdhocQu eryRequest (), ErrorM essage.OUT _DQ_DISABL ED.getMess age(), rem oteHomeCom munityId,  correlated PatientId. getExtensi on());
  222  
  223                                                                         // CCR  177986 -  parameteri zed loggin g
  224                                                                         logger .error(Err orMessage. OUT_DQ_DIS ABLED + "  {} ", "Rem ote Commun ity ID");
  225                                                                }
  226                                                       }
  227                                                       el se
  228                                                       {
  229                                                                addE rrorToResp onse(ret,  responding GatewayCro ssGatewayQ ueryReques t.getAdhoc QueryReque st(), Erro rMessage.O UT_DQ_NOT_ A_PARTNER. getMessage (), remote HomeCommun ityId, cor relatedPat ientId.get Extension( ));
  230  
  231                                                                // C CR 177986  - paramete rized logg ing
  232                                                                logg er.error(E rrorMessag e.OUT_DQ_N OT_A_PARTN ER + " {}  ", "Remote  Community  ID");
  233                                                       }
  234                                               }
  235                                      }
  236  
  237                                      if(patie nt.getId() .size() <  1)
  238                                      {
  239                                               // CCR 177 986- added  logger as  a paramet er
  240                                               MaintLog.q ueryError( responding GatewayCro ssGatewayQ ueryReques t, ErrorMe ssage.OUT_ DQ_NO_CORR ELATIONS,  logger);
  241                                      }
  242  
  243                                      for(int  i = 0; i <  numSubmit ted; ++i)
  244                                      {
  245                                               try
  246                                               {
  247                                                       Se ndRequestR esponse re sponse = c ompletionS ervice.tak e().get();
  248                                                       if (!response .hasError( ))
  249                                                       {
  250                                                                addR esultToRes ponse(ret,  response) ;
  251                                                       }
  252                                                       el se
  253                                                       {
  254                                                                Send RequestExc eption sre  = respons e.sre;
  255                                                                addE rrorToResp onse(ret,  responding GatewayCro ssGatewayQ ueryReques t.getAdhoc QueryReque st(), Stri ngUtils.EM PTY, sre.r emoteHomeC ommunityId , sre.remo tePatientI d.getExten sion());
  256  
  257                                                                // C CR 177986-  logging u pdates
  258                                                                logg er.error(" Error send ing DocQue ry for com munity Id:  {} with e xception:  {}", new O bject[] {  sre.remote HomeCommun ityId, sre .getCause( ).getMessa ge() });
  259                                                       }
  260                                               }
  261                                               catch(Exec utionExcep tion ee)
  262                                               {
  263                                                       lo gger.error ("An Unkno wn error o ccured pro cessing an  outbound  doc query  request",  ee);
  264                                                       Ma intLog.que ryError(re spondingGa tewayCross GatewayQue ryRequest,  ErrorMess age.OUT_DQ _UNKNOWN,  "An Unknow n error oc cured proc essing an  outbound d oc query r equest.",  logger);
  265                                               }
  266                                               catch(Inte rruptedExc eption ie)
  267                                               {
  268                                                       lo gger.error ("Outbound  Doc Query  Threads i nterrupted .  Return  will not b e complete  ", ie);
  269                                               }
  270                                               catch(Exce ption e)
  271                                               {
  272                                                       lo gger.error ("Error in  Outbound  Doc Query" , e);
  273                                               }
  274                                      }
  275                             }
  276                             else
  277                             {
  278                                      MaintLog .queryErro r(respondi ngGatewayC rossGatewa yQueryRequ est, Error Message.OU T_DQ_NO_CO RRELATIONS , logger);
  279                             }
  280  
  281                             reques tAudit.sto reAudit(re questAudit Entity);
  282                    }
  283                    else
  284                    {
  285                             MaintL og.queryEr ror(respon dingGatewa yCrossGate wayQueryRe quest, Err orMessage. OUT_DQ_NO_ PATIENT_ID , logger);
  286                    }
  287  
  288                    retu rn ret;
  289           }
  290  
  291           pr ivate Resp ondingGate wayCrossGa tewayQuery ResponseTy pe createR espondingG atewayCros sGatewayQu eryRespons e()
  292           {
  293                    Comm unityAdhoc QueryRespo nsesType c ommunityRe sponses =  new Commun ityAdhocQu eryRespons esType();
  294  
  295                    Resp ondingGate wayCrossGa tewayQuery ResponseTy pe ret = n ew Respond ingGateway CrossGatew ayQueryRes ponseType( );
  296                    ret. setCommuni tyResponse s(communit yResponses );
  297  
  298                    retu rn ret;
  299           }
  300  
  301           pr ivate II g etPatientI d(AdhocQue ryRequest  adhocQuery Request)
  302           {
  303                    II r et = new I I();
  304                    Map< String, Li st<String> > slotMap  = getMapFr omSlots(ad hocQueryRe quest.getA dhocQuery( ).getSlot( ));
  305                    Stri ng patient Id = slotM ap.get(EBX ML_DOCENTR Y_PATIENT_ ID).get(0) ;
  306                    Patt ern p = Pa ttern.comp ile("\\d{1 0}V\\d{6}" );
  307                    Matc her m = p. matcher(pa tientId);
  308                    if(m .find())
  309                    {
  310                             ret =  new II();
  311                             ret.se tExtension (m.group() );
  312                             ret.se tRoot(getH omeCommuni tyId());
  313                    }
  314                    retu rn ret;
  315           }
  316  
  317           pr ivate Map< String, Li st<String> > getMapFr omSlots(Li st<SlotTyp e1> slots)
  318           {
  319                    Hash Map<String , List<Str ing>> ret  = new Hash Map<String , List<Str ing>>();
  320  
  321                    for( SlotType1  slot : slo ts)
  322                    {
  323                             if(!Nu llChecker. isNullOrEm pty(slot.g etName())  && !NullCh ecker.isNu llOrEmpty( slot.getVa lueList())  && !NullC hecker.isN ullOrEmpty (slot.getV alueList() .getValue( )))
  324                             {
  325                                      List<Str ing> value s = ret.ge t(slot.get Name());
  326                                      if(value s == null)
  327                                      {
  328                                               values = n ew ArrayLi st<String> ();
  329                                               ret.put(sl ot.getName (), values );
  330                                      }
  331                                      values.a ddAll(pars eParamForm attedStrin gs(slot.ge tValueList ().getValu e()));
  332                             }
  333                    }
  334  
  335                    retu rn ret;
  336           }
  337  
  338           pu blic List< String> pa rseParamFo rmattedStr ings(List< String> pa ramFormatt edStrings)
  339           {
  340                    List <String> r et = new A rrayList<S tring>();
  341  
  342                    for( String par amFormatte dString :  paramForma ttedString s)
  343                    {
  344                             parseP aramFormat tedString( paramForma ttedString , ret);
  345                    }
  346  
  347                    retu rn ret;
  348           }
  349  
  350           pu blic void  parseParam FormattedS tring(Stri ng paramFo rmattedStr ing, List< String> re sultCollec tion)
  351           {
  352                    if(( paramForma ttedString  != null)  && (result Collection  != null))
  353                    {
  354                             String  working =  paramForm attedStrin g;
  355                             if(par amFormatte dString.st artsWith(" ("))
  356                             {
  357                                      working  = paramFor mattedStri ng.substri ng(1);
  358                                      int endI ndex = wor king.index Of(")");
  359                                      if(endIn dex != -1)
  360                                      {
  361                                               working =  working.su bstring(0,  endIndex) ;
  362                                      }
  363                             }
  364                             String [] multiVa lueString  = working. split(",") ;
  365                             if(mul tiValueStr ing != nul l)
  366                             {
  367                                      for(int  i = 0; i <  multiValu eString.le ngth; i++)
  368                                      {
  369                                               String sin gleValue =  multiValu eString[i] ;
  370                                               if(singleV alue != nu ll)
  371                                               {
  372                                                       si ngleValue  = singleVa lue.trim() ;
  373                                               }
  374                                               if(singleV alue.start sWith("'") )
  375                                               {
  376                                                       si ngleValue  = singleVa lue.substr ing(1);
  377                                                       in t endTickI ndex = sin gleValue.i ndexOf("'" );
  378                                                       if (endTickIn dex != -1)
  379                                                       {
  380                                                                sing leValue =  singleValu e.substrin g(0, endTi ckIndex);
  381                                                       }
  382                                               }
  383                                               resultColl ection.add (singleVal ue);
  384                                      }
  385                             }
  386                    }
  387           }
  388  
  389           pr ivate Retr ievePatien tCorrelati onsRespons eType getP atientCorr elations(I I patientI d, Asserti onType ass ertion)
  390           {
  391                    Retr ievePatien tCorrelati onsRequest Type reque st = creat eRetrieveP atientCorr elationsRe quest(pati entId);
  392                    requ est.setAss ertion(ass ertion);
  393                    retu rn adapter PatientCor relation.r etrievePat ientCorrel ations(req uest);
  394           }
  395  
  396           pr ivate Retr ievePatien tCorrelati onsRequest Type creat eRetrieveP atientCorr elationsRe quest(II p atientId)
  397           {
  398                    Retr ievePatien tCorrelati onsRequest Type ret =  new Retri evePatient Correlatio nsRequestT ype();
  399                    ret. setPRPAIN2 01309UV02( HL7PRPA201 309Transfo rms.create PRPA201309 (patientId .getRoot() , patientI d.getExten sion()));
  400                    retu rn ret;
  401           }
  402  
  403           pr ivate Stri ng getHome CommunityI d()
  404           {
  405                    Stri ng ret = n ull;
  406                    Faci lity facil ity = faci lityManage r.getFacil ityByFacil ityNumber( "VA");
  407                    if(f acility !=  null)
  408                    {
  409                             ret =  facility.g etHomeComm unityId();
  410                    }
  411                    retu rn ret;
  412           }
  413  
  414           pr ivate PRPA MT201304UV 02Patient  extractPat ient(PRPAI N201310UV0 2 prpain20 1310UV02)
  415           {
  416                    PRPA MT201304UV 02Patient  ret = null ;
  417  
  418                    if(p rpain20131 0UV02.getC ontrolActP rocess() ! = null &&  !NullCheck er.isNullO rEmpty(prp ain201310U V02.getCon trolActPro cess().get Subject())  && prpain 201310UV02 .getContro lActProces s().getSub ject().get (0).getReg istrationE vent() !=  null && pr pain201310 UV02.getCo ntrolActPr ocess().ge tSubject() .get(0).ge tRegistrat ionEvent() .getSubjec t1() != nu ll && prpa in201310UV 02.getCont rolActProc ess().getS ubject().g et(0).getR egistratio nEvent().g etSubject1 ().getPati ent() != n ull)
  419                    {
  420                             ret =  prpain2013 10UV02.get ControlAct Process(). getSubject ().get(0). getRegistr ationEvent ().getSubj ect1().get Patient();
  421                    }
  422  
  423                    retu rn ret;
  424           }
  425  
  426           pr ivate List <String> g etRemoteHo meCommunit yIds(II re motePatien tId)
  427           {
  428                    List <String> r et = new A rrayList<S tring>();
  429                    List <Facility>  remoteFac ilities =  facilityMa nager.getF acilitiesC ontainingA ssigningAu thority(re motePatien tId.getRoo t());
  430  
  431                    if(N ullChecker .isNotNull OrEmpty(re moteFacili ties))
  432                    {
  433                             for(Fa cility rem oteFacilit y : remote Facilities )
  434                             {
  435                                      ret.add( remoteFaci lity.getHo meCommunit yId());
  436                             }
  437                    }
  438  
  439                    retu rn ret;
  440           }
  441  
  442           pr ivate bool ean checkP olicy(Adho cQueryRequ est adhocQ ueryReques t, Asserti onType ass ertion, St ring homeC ommunityId )
  443           {
  444                    Adho cQueryRequ estMessage Type adhoc QueryReque stMessage  = new Adho cQueryRequ estMessage Type();
  445                    adho cQueryRequ estMessage .setAdhocQ ueryReques t(adhocQue ryRequest) ;
  446                    adho cQueryRequ estMessage .setAssert ion(assert ion);
  447  
  448                    Home CommunityT ype receiv ingHomeCom munity = n ew HomeCom munityType ();
  449                    rece ivingHomeC ommunity.s etHomeComm unityId(ho meCommunit yId);
  450  
  451                    Home CommunityT ype sendin gHomeCommu nity = new  HomeCommu nityType() ;
  452                    send ingHomeCom munity.set HomeCommun ityId(getH omeCommuni tyId());
  453  
  454                    Adho cQueryRequ estEventTy pe adhocQu eryRequest Event = ne w AdhocQue ryRequestE ventType() ;
  455                    adho cQueryRequ estEvent.s etMessage( adhocQuery RequestMes sage);
  456                    adho cQueryRequ estEvent.s etDirectio n(NhincCon stants.POL ICYENGINE_ OUTBOUND_D IRECTION);
  457                    adho cQueryRequ estEvent.s etReceivin gHomeCommu nity(recei vingHomeCo mmunity);
  458                    adho cQueryRequ estEvent.s etSendingH omeCommuni ty(sending HomeCommun ity);
  459                    adho cQueryRequ estEvent.s etInterfac e(NhincCon stants.AUD IT_LOG_ENT ITY_INTERF ACE);
  460  
  461                    Poli cyEngineTr ansformer  policyEngi neTransfor mer = new  PolicyEngi neTransfor mer();
  462                    Chec kPolicyReq uestType c heckPolicy Request =  policyEngi neTransfor mer.transf ormAdhocQu eryToCheck Policy(adh ocQueryReq uestEvent) ;
  463  
  464                    Chec kPolicyRes ponseType  checkPolic yResponse  = adapterP olicyEngin e.checkPol icy(checkP olicyReque st);
  465  
  466                    retu rn CheckPo licy.check Policy(che ckPolicyRe quest, che ckPolicyRe sponse);
  467           }
  468  
  469           pr ivate Send RequestRes ponse send Request(Ad hocQueryRe quest adho cQueryRequ est, Asser tionType a ssertion,  II remoteP atientId,  String rem oteHomeCom munityId,  final Stri ng auditUU ID) throws  SendReque stExceptio n
  470           {
  471                    Send RequestRes ponse ret  = new Send RequestRes ponse();
  472                    Requ estAuditEn tity audit Entity = n ew Request AuditEntit y();
  473                    audi tEntity.se tStartTime (new Date( ));
  474                    audi tEntity.se tUuid(audi tUUID);
  475                    audi tEntity.se tHcid(remo teHomeComm unityId);
  476                    audi tEntity.se tPid(remot ePatientId .getExtens ion());
  477                    audi tEntity.se tAction(Re questActio ns.QUERY_R EQUEST.get Value());
  478  
  479                    try
  480                    {
  481                             final  String ver sion = "2. 0";
  482                             ret.ad hocQueryRe sponse = n hinDocQuer yRequestSe nder.sendR equest(adh ocQueryReq uest, asse rtion, rem oteHomeCom munityId,  version);
  483                             auditE ntity.setS topTime(ne w Date());
  484                             auditE ntity.setS tatus(ret. adhocQuery Response.g etStatus() );
  485                             reques tAudit.sto reAudit(au ditEntity) ;
  486                             ret.re moteHomeCo mmunityId  = remoteHo meCommunit yId;
  487                             ret.re motePatien tId = remo tePatientI d;
  488                    }
  489                    catc h(Throwabl e e)
  490                    {
  491                             SendRe questExcep tion sre =  new SendR equestExce ption();
  492                             sre.re moteHomeCo mmunityId  = remoteHo meCommunit yId;
  493                             sre.re motePatien tId = remo tePatientI d;
  494                             sre.in itCause(e) ;
  495                             auditE ntity.setS topTime(ne w Date());
  496                             auditE ntity.setS tatus("Fai led:" + e. getMessage ());
  497                             reques tAudit.sto reAudit(au ditEntity) ;
  498                             ret.sr e = sre;
  499                    }
  500                    retu rn ret;
  501           }
  502  
  503           pr ivate Adho cQueryRequ est create AdhocQuery Request(Ad hocQueryRe quest from AdhocQuery Request, S tring home CommunityI d, II remo tePatientI d)
  504           {
  505                    Adho cQueryRequ est ret =  new AdhocQ ueryReques t();
  506                    ret. setFederat ion(fromAd hocQueryRe quest.getF ederation( ));
  507                    ret. setMaxResu lts(fromAd hocQueryRe quest.getM axResults( ));
  508                    ret. setStartIn dex(fromAd hocQueryRe quest.getS tartIndex( ));
  509                    ret. setId(from AdhocQuery Request.ge tId());
  510                    ret. setComment (fromAdhoc QueryReque st.getComm ent());
  511                    ret. setRequest SlotList(f romAdhocQu eryRequest .getReques tSlotList( ));
  512                    ret. setAdhocQu ery(create AdhocQuery (fromAdhoc QueryReque st.getAdho cQuery(),  homeCommun ityId, rem otePatient Id));
  513                    ret. setRespons eOption(fr omAdhocQue ryRequest. getRespons eOption()) ;
  514                    retu rn ret;
  515           }
  516  
  517           pr ivate Adho cQueryType  createAdh ocQuery(Ad hocQueryTy pe fromAdh ocQuery, S tring home CommunityI d, II remo tePatientI d)
  518           {
  519                    Adho cQueryType  ret = new  AdhocQuer yType();
  520                    ret. setDescrip tion(fromA dhocQuery. getDescrip tion());
  521                    ret. setHome("u rn:oid:" +  homeCommu nityId);
  522                    ret. setId(from AdhocQuery .getId());
  523                    ret. setLid(fro mAdhocQuer y.getLid() );
  524                    ret. setName(fr omAdhocQue ry.getName ());
  525                    ret. setObjectT ype(fromAd hocQuery.g etObjectTy pe());
  526                    ret. setQueryEx pression(f romAdhocQu ery.getQue ryExpressi on());
  527                    ret. setStatus( fromAdhocQ uery.getSt atus());
  528                    ret. setVersion Info(fromA dhocQuery. getVersion Info());
  529                    ret. getExterna lIdentifie r().addAll (fromAdhoc Query.getE xternalIde ntifier()) ;
  530                    ret. getSlot(). addAll(cre ateSlots(f romAdhocQu ery.getSlo t(), remot ePatientId ));
  531                    ret. getClassif ication(). addAll(fro mAdhocQuer y.getClass ification( ));
  532                    retu rn ret;
  533           }
  534  
  535           pr ivate List <SlotType1 > createSl ots(List<S lotType1>  slots, II  remotePati entId)
  536           {
  537                    Arra yList<Slot Type1> ret  = new Arr ayList<Slo tType1>();
  538  
  539                    for( SlotType1  slot : slo ts)
  540                    {
  541                             SlotTy pe1 newSlo t;
  542                             if(slo t.getName( ).equals(E BXML_DOCEN TRY_PATIEN T_ID))
  543                             {
  544                                      newSlot  = new Slot Type1();
  545                                      newSlot. setName(EB XML_DOCENT RY_PATIENT _ID);
  546                                      newSlot. setValueLi st(createV alueList(" '" + remot ePatientId .getExtens ion() + "^ ^^&" + rem otePatient Id.getRoot () + "&ISO '"));
  547                             }
  548                             else
  549                             {
  550                                      newSlot  = slot;
  551                             }
  552                             ret.ad d(newSlot) ;
  553                    }
  554  
  555                    retu rn ret;
  556           }
  557  
  558           pr ivate Valu eListType  createValu eList(Stri ng value)
  559           {
  560                    Valu eListType  ret = new  ValueListT ype();
  561                    ret. getValue() .add(value );
  562                    retu rn ret;
  563           }
  564  
  565           pr ivate void  addResult ToResponse (Respondin gGatewayCr ossGateway QueryRespo nseType re spondingGa tewayCross GatewayQue ryResponse , SendRequ estRespons e response )
  566           {
  567                    Home CommunityT ype homeCo mmunity =  new HomeCo mmunityTyp e();
  568                    home Community. setHomeCom munityId(r esponse.re moteHomeCo mmunityId) ;
  569                    Faci lity facil ity = faci lityManage r.getFacil ityByHomeC ommunityId (response. remoteHome CommunityI d);
  570                    home Community. setName(fa cility.get FacilityNa me());
  571  
  572                    Nhin TargetComm unityType  nhinTarget Community  = new Nhin TargetComm unityType( );
  573                    nhin TargetComm unity.setH omeCommuni ty(homeCom munity);
  574  
  575                    Comm unityAdhoc QueryRespo nseType co mmunityRes ponse = ne w Communit yAdhocQuer yResponseT ype();
  576                    comm unityRespo nse.setAdh ocQueryRes ponse(resp onse.adhoc QueryRespo nse);
  577                    comm unityRespo nse.setNhi nTargetCom munity(nhi nTargetCom munity);
  578  
  579                    resp ondingGate wayCrossGa tewayQuery Response.g etCommunit yResponses ().getComm unityRespo nse().add( communityR esponse);
  580           }
  581  
  582           pr ivate void  addErrorT oResponse( Responding GatewayCro ssGatewayQ ueryRespon seType res pondingGat ewayCrossG atewayQuer yResponse,  AdhocQuer yRequest a dhocQueryR equest, fi nal String  errorMess age, final  String hc id, final  String pat ientId)
  583           {
  584                    Adho cQueryResp onse adhoc QueryRespo nse = crea teAdhocQue ryResponse Error(adho cQueryRequ est);
  585                    adho cQueryResp onse.setRe gistryErro rList(new  RegistryEr rorList()) ;
  586                    adho cQueryResp onse.getRe gistryErro rList().se tHighestSe verity("ur n:oasis:na mes:tc:ebx ml-regrep: ErrorSever ityType:Er ror");
  587  
  588                    Regi stryError  registryEr ror = new  RegistryEr ror();
  589                    regi stryError. setErrorCo de("XDSReg istryError ");
  590                    regi stryError. setCodeCon text("Inte rnal Regis try/Reposi tory Error  - HCID =  " + hcid +  " - " + " , patientI d = " + pa tientId +  " " + erro rMessage);
  591                    regi stryError. setSeverit y("urn:oas is:names:t c:ebxml-re grep:Error SeverityTy pe:Error") ;
  592                    adho cQueryResp onse.getRe gistryErro rList().ge tRegistryE rror().add (registryE rror);
  593  
  594                    Home CommunityT ype homeCo mmunity =  new HomeCo mmunityTyp e();
  595                    home Community. setHomeCom munityId(h cid);
  596                    Faci lity facil ity = faci lityManage r.getFacil ityByHomeC ommunityId (hcid);
  597                    home Community. setName(fa cility.get FacilityNa me());
  598  
  599                    Nhin TargetComm unityType  nhinTarget Community  = new Nhin TargetComm unityType( );
  600                    nhin TargetComm unity.setH omeCommuni ty(homeCom munity);
  601  
  602                    Comm unityAdhoc QueryRespo nseType co mmunityRes ponse = ne w Communit yAdhocQuer yResponseT ype();
  603                    comm unityRespo nse.setAdh ocQueryRes ponse(adho cQueryResp onse);
  604                    comm unityRespo nse.setNhi nTargetCom munity(nhi nTargetCom munity);
  605  
  606                    resp ondingGate wayCrossGa tewayQuery Response.g etCommunit yResponses ().getComm unityRespo nse().add( communityR esponse);
  607           }
  608  
  609           pr ivate Adho cQueryResp onse creat eAdhocQuer yResponseE rror(Adhoc QueryReque st adhocQu eryRequest )
  610           {
  611                    Adho cQueryResp onse ret =  new Adhoc QueryRespo nse();
  612                    ret. setRequest Id(adhocQu eryRequest .getId());
  613                    ret. setStartIn dex(adhocQ ueryReques t.getStart Index());
  614                    ret. setStatus( "urn:oasis :names:tc: ebxml-regr ep:Respons eStatusTyp e:Failure" );
  615                    retu rn ret;
  616           }
  617   }