44. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 3/1/2018 12:13:15 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.

44.1 Files compared

# Location File Last Modified
1 ehealth_xchange_cif.zip\NHIN_adapter\AdapterEJB\src\main\java\gov\va\med\nhin\adapter\patientdiscovery AdapterPatientDiscovery.java Thu Feb 22 14:26:26 2018 UTC
2 ehealth_xchange_cif.zip\NHIN_adapter\AdapterEJB\src\main\java\gov\va\med\nhin\adapter\patientdiscovery AdapterPatientDiscovery.java Tue Feb 27 14:24:32 2018 UTC

44.2 Comparison summary

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

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

44.4 Active regular expressions

No regular expressions were active.

44.5 Comparison detail

  1   package go v.va.med.n hin.adapte r.patientd iscovery;
  2  
  3   import jav a.io.IOExc eption;
  4   import jav a.io.Input Stream;
  5   import jav a.io.Input StreamRead er;
  6   import jav a.io.Strin gWriter;
  7   import jav a.math.Big Integer;
  8   import jav a.text.Par seExceptio n;
  9   import jav a.text.Sim pleDateFor mat;
  10   import jav a.util.Dat e;
  11   import jav a.util.Lis t;
  12   import jav a.util.Map ;
  13   import jav a.util.UUI D;
  14  
  15   import jav ax.activat ion.DataHa ndler;
  16   import jav ax.ejb.EJB ;
  17   import jav ax.ejb.*;
  18   import jav ax.jws.Web Service;
  19   import jav ax.xml.bin d.JAXBCont ext;
  20   import jav ax.xml.bin d.JAXBElem ent;
  21   import jav ax.xml.bin d.JAXBExce ption;
  22   import jav ax.xml.bin d.Marshall er;
  23   import jav ax.xml.bin d.util.JAX BSource;
  24   import jav ax.xml.ws. BindingTyp e;
  25  
  26   import org .apache.co mmons.io.I OUtils;
  27   import org .hl7.v3.Ad dPatientCo rrelationR equestType ;
  28   import org .hl7.v3.CE ;
  29   import org .hl7.v3.CO CTMT090300 UV01Assign edDevice;
  30   import org .hl7.v3.Co mmunicatio nFunctionT ype;
  31   import org .hl7.v3.En tityClassD evice;
  32   import org .hl7.v3.II ;
  33   import org .hl7.v3.MC CIMT000300 UV01Agent;
  34   import org .hl7.v3.MC CIMT000300 UV01Device ;
  35   import org .hl7.v3.MC CIMT000300 UV01Organi zation;
  36   import org .hl7.v3.MC CIMT000300 UV01Receiv er;
  37   import org .hl7.v3.MC CIMT000300 UV01Sender ;
  38   import org .hl7.v3.MF MIMT700711 UV01Author OrPerforme r;
  39   import org .hl7.v3.MF MIMT700711 UV01Custod ian;
  40   import org .hl7.v3.PR PAIN201301 UV02;
  41   import org .hl7.v3.PR PAIN201305 UV02;
  42   import org .hl7.v3.PR PAIN201306 UV02;
  43   import org .hl7.v3.PR PAIN201306 UV02MFMIMT 700711UV01 ControlAct Process;
  44   import org .hl7.v3.PR PAIN201306 UV02MFMIMT 700711UV01 Registrati onEvent;
  45   import org .hl7.v3.PR PAIN201306 UV02MFMIMT 700711UV01 Subject1;
  46   import org .hl7.v3.PR PAIN201306 UV02MFMIMT 700711UV01 Subject2;
  47   import org .hl7.v3.PR PAMT201306 UV02Living SubjectId;
  48   import org .hl7.v3.PR PAMT201310 UV02Patien t;
  49   import org .hl7.v3.PR PAMT201310 UV02Person ;
  50   import org .hl7.v3.PR PAMT201310 UV02QueryM atchObserv ation;
  51   import org .hl7.v3.PR PAMT201310 UV02Subjec t;
  52   import org .hl7.v3.Pa rticipatio nTargetSub ject;
  53   import org .hl7.v3.Re spondingGa tewayPRPAI N201305UV0 2RequestTy pe;
  54   import org .hl7.v3.XP articipati onAuthorPe rformer;
  55   import org .slf4j.Log ger;
  56   import org .slf4j.Log gerFactory ;
  57  
  58   import gov .hhs.fha.n hinc.adapt erpatientd iscovery.A dapterPati entDiscove ryPortType ;
  59   import gov .hhs.fha.n hinc.adapt erpolicyen gine.Adapt erPolicyEn ginePortTy pe;
  60   import gov .hhs.fha.n hinc.commo n.eventcom mon.PatDis cReqEventT ype;
  61   import gov .hhs.fha.n hinc.commo n.nhinccom mon.Assert ionType;
  62   import gov .hhs.fha.n hinc.commo n.nhinccom mon.CeType ;
  63   import gov .hhs.fha.n hinc.commo n.nhinccom mon.HomeCo mmunityTyp e;
  64   import gov .hhs.fha.n hinc.commo n.nhinccom mon.NhinTa rgetCommun itiesType;
  65   import gov .hhs.fha.n hinc.commo n.nhinccom mon.NhinTa rgetCommun ityType;
  66   import gov .hhs.fha.n hinc.commo n.nhinccom mon.Person NameType;
  67   import gov .hhs.fha.n hinc.commo n.nhinccom mon.SamlAu thzDecisio nStatement Type;
  68   import gov .hhs.fha.n hinc.commo n.nhinccom mon.SamlIs suerType;
  69   import gov .hhs.fha.n hinc.commo n.nhinccom mon.UserTy pe;
  70   import gov .hhs.fha.n hinc.commo n.nhinccom monadapter .CheckPoli cyRequestT ype;
  71   import gov .hhs.fha.n hinc.commo n.nhinccom monadapter .CheckPoli cyResponse Type;
  72   import gov .hhs.fha.n hinc.commo n.nhinccom monentity. Responding GatewayCro ssGatewayQ ueryReques tType;
  73   import gov .hhs.fha.n hinc.entit ydocquery. EntityDocQ ueryPortTy pe;
  74   import gov .hhs.fha.n hinc.entit ydocretrie ve.EntityD ocRetrieve PortType;
  75   import gov .hhs.fha.n hinc.nhinc lib.NhincC onstants;
  76   import gov .hhs.fha.n hinc.patie ntdb.model .Patient;
  77   import gov .hhs.fha.n hinc.trans form.polic y.PolicyEn gineTransf ormer;
  78   import gov .hhs.fha.n hinc.trans form.subdi sc.HL7Cons tants;
  79   import gov .va.med.nh in.adapter .adapterga teway.docq uery.Entit yDocQueryP ortTypeLoc al;
  80   import gov .va.med.nh in.adapter .adapterga teway.docr etrieve.En tityDocRet rievePortT ypeLocal;
  81   import gov .va.med.nh in.adapter .audit.Aud it;
  82   import gov .va.med.nh in.adapter .audit.Aud itManager;
  83   import gov .va.med.nh in.adapter .audit.Aud itManagerL ocal;
  84   import gov .va.med.nh in.adapter .documentr epository. Document;
  85   import gov .va.med.nh in.adapter .documentr epository. DocumentRe pository;
  86   import gov .va.med.nh in.adapter .documentr epository. DocumentRe positoryLo cal;
  87   import gov .va.med.nh in.adapter .facilitym anager.Fac ility;
  88   import gov .va.med.nh in.adapter .facilitym anager.Fac ilityManag er;
  89   import gov .va.med.nh in.adapter .facilitym anager.Fac ilityManag erLocal;
  90   import gov .va.med.nh in.adapter .facilitym anager.Ope rationOnOf f;
  91   import gov .va.med.nh in.adapter .logging.A dapterPDEr ror;
  92   import gov .va.med.nh in.adapter .logging.E rrorMessag e;
  93   import gov .va.med.nh in.adapter .logging.E ventAuditi ngFactory;
  94   import gov .va.med.nh in.adapter .logging.E ventAuditi ngFactoryI mpl;
  95   import gov .va.med.nh in.adapter .logging.L ogConstant s;
  96   import gov .va.med.nh in.adapter .logging.L ogConstant s.Auditing Event;
  97   import gov .va.med.nh in.adapter .logging.M essagingHe lper;
  98   import gov .va.med.nh in.adapter .logging.M essagingHe lper.Query Type;
  99   import gov .va.med.nh in.adapter .mpi.hl7pa rsers.HL7D bParser201 306;
  100   import gov .va.med.nh in.adapter .mvi.Adapt erMviPortT ypeLocal;
  101   import gov .va.med.nh in.adapter .mvi.hl7pa rsers.HL7P arser20130 5;
  102   import gov .va.med.nh in.adapter .mvi.hl7pa rsers.HL7P arser20130 6;
  103   import gov .va.med.nh in.adapter .mvi.hl7tr ansforms.A dapterHL7P RPA201301T ransforms;
  104   import gov .va.med.nh in.adapter .patientco rrelation. PatientCor relationPo rtTypeLoca l;
  105   import gov .va.med.nh in.adapter .policyeng ine.Adapte rPolicyEng inePortTyp eLocal;
  106   import gov .va.med.nh in.adapter .propertyl ookup.Prop ertyLookup ;
  107   import gov .va.med.nh in.adapter .propertyl ookup.Prop ertyLookup Local;
  108   import gov .va.med.nh in.adapter .utils.Aud itUtil;
  109   import gov .va.med.nh in.adapter .utils.Nul lChecker;
  110   import gov .va.med.nh in.adapter .utils.das .DasDAO;
  111   import gov .va.med.nh in.adapter .utils.das .DasDAOHtt pImpl;
  112   import gov .va.med.nh in.adapter .utils.das .DasExcept ion;
  113   import gov .va.med.nh in.adapter .utils.das .DasOperat ionSendACP DocumentRe quest;
  114   import gov .va.med.nh in.adapter .utils.das .DasOperat ionSendACP DocumentRe sponse;
  115   import gov .va.nvap.p rivacy.Con sentDirect iveAuthori zationRequ estType;
  116   import gov .va.nvap.p rivacy.Con sentDirect iveAuthori zationResp onseType;
  117   import gov .va.nvap.p rivacy.Con sentDirect iveOptOutR easonType;
  118   import gov .va.nvap.p rivacy.Con sentDirect iveQueryPa ramType;
  119   import gov .va.nvap.p rivacy.Con sentDirect iveQueryRe questType;
  120   import gov .va.nvap.p rivacy.Con sentDirect iveQueryRe sponseType ;
  121   import gov .va.nvap.p rivacy.Con sentDirect iveReferen ceType;
  122   import gov .va.nvap.p rivacy.Con sentDirect iveRevocat ionRequest Type;
  123   import gov .va.nvap.p rivacy.Con sentDirect iveRevocat ionRespons eType;
  124   import gov .va.nvap.p rivacy.Con sentType;
  125   import gov .va.nvap.p rivacy.Ser viceConsum er;
  126   import gov .va.nvap.p rivacy.Ser viceConsum erContextT ype;
  127   import gov .va.nvap.p rivacy.dat a.ConsentD irectiveDa ta;
  128   import ihe .iti.xds_b ._2007.Ret rieveDocum entSetRequ estType;
  129   import ihe .iti.xds_b ._2007.Ret rieveDocum entSetRequ estType.Do cumentRequ est;
  130   import ihe .iti.xds_b ._2007.Ret rieveDocum entSetResp onseType;
  131   import ihe .iti.xds_b ._2007.Ret rieveDocum entSetResp onseType.D ocumentRes ponse;
  132   import jav ax.jws.Han dlerChain;
  133   import oas is.names.t c.ebxml_re grep.xsd.q uery._3.Ad hocQueryRe quest;
  134   import oas is.names.t c.ebxml_re grep.xsd.q uery._3.Ad hocQueryRe sponse;
  135   import oas is.names.t c.ebxml_re grep.xsd.q uery._3.Re sponseOpti onType;
  136   import oas is.names.t c.ebxml_re grep.xsd.r im._3.Adho cQueryType ;
  137   import oas is.names.t c.ebxml_re grep.xsd.r im._3.Exte rnalIdenti fierType;
  138   import oas is.names.t c.ebxml_re grep.xsd.r im._3.Extr insicObjec tType;
  139   import oas is.names.t c.ebxml_re grep.xsd.r im._3.Iden tifiableTy pe;
  140   import oas is.names.t c.ebxml_re grep.xsd.r im._3.Regi stryObject ListType;
  141   import oas is.names.t c.ebxml_re grep.xsd.r im._3.Slot Type1;
  142   import oas is.names.t c.ebxml_re grep.xsd.r im._3.Valu eListType;
  143   import oas is.names.t c.xacml._2 _0.context .schema.os .DecisionT ype;
  144   import org .hl7.fhir. dstu3.mode l.AuditEve nt;
  145   import pri vacy.servi ce.nvap. DNS     .ConsentMa nagementPo rtType;
  146   import pri vacy.servi ce.nvap. DNS     .ConsentMa nagementSe rviceFault Message;
  147  
  148   /**
  149    *
  150    * @author   DN S      VAZQUD
  151    * @author  Zack Pete rson
  152    */
  153   @WebServic e(serviceN ame = "Ada pterPatien tDiscovery ",
  154       //wsdl Location =  "META-INF /wsdl/Adap terPatient Discovery. wsdl",
  155       portNa me = "Adap terPatient DiscoveryP ortSoap",
  156       endpoi ntInterfac e = "gov.h hs.fha.nhi nc.adapter patientdis covery.Ada pterPatien tDiscovery PortType",
  157       target Namespace  = "urn:gov :hhs:fha:n hinc:adapt erpatientd iscovery")
  158   @BindingTy pe(value =  javax.xml .ws.soap.S OAPBinding .SOAP12HTT P_BINDING)
  159   @HandlerCh ain(file =  "SOAPHand lerChain.x ml")
  160   @Transacti onAttribut e(value =  Transactio nAttribute Type.SUPPO RTS)
  161   @Stateless (name = "A dapterPati entDiscove ry")
  162   public cla ss Adapter PatientDis covery imp lements Ad apterPatie ntDiscover yPortType
  163   {
  164       privat e static f inal Logge r logger =  LoggerFac tory.getLo gger(Adapt erPatientD iscovery.c lass.getNa me());
  165  
  166       privat e static f inal long  MILLIS_IN_ YEAR = 100 0L * 60 *  60 * 24 *  365;
  167  
  168       privat e AdapterM viPortType Local adap terMvi;
  169       privat e PatientC orrelation PortTypeLo cal adapte rPatientCo rrelation;
  170       privat e AdapterP olicyEngin ePortType  adapterPol icyEngine;
  171       privat e ConsentM anagementP ortType va pConsentMa nagement;
  172       privat e Facility Manager fa cilityMana ger;
  173       privat e Property Lookup pro pertyLooku p;
  174  
  175       privat e EntityDo cQueryPort Type entit yDocQuery;
  176       privat e EntityDo cRetrieveP ortType en tityDocRet rieve;
  177  
  178       // aud it logging
  179       privat e AuditMan ager audit Manager;
  180       privat e Document Repository  documentR epository;
  181       privat e DasDAO d asDAO;
  182  
  183       privat e static J AXBContext  context;
  184  
  185       static  {
  186           tr y {
  187                context  = JAXBCont ext.newIns tance(PRPA IN201306UV 02.class);
  188           }
  189           ca tch (JAXBE xception e ) {
  190                logger.d ebug("JAXB Exception  occurred a t initiali zation: ",  e);
  191           }
  192       }
  193  
  194       @EJB(b eanInterfa ce = Adapt erMviPortT ypeLocal.c lass, bean Name = "Ad apterMVI")
  195       public  void setA dapterMvi( AdapterMvi PortTypeLo cal adapte rMvi)
  196       {
  197           th is.adapter Mvi = adap terMvi;
  198       }
  199  
  200       @EJB(b eanInterfa ce = Patie ntCorrelat ionPortTyp eLocal.cla ss, beanNa me = "Adap terPatient Correlatio n")
  201       public  void setA dapterPati entCorrela tion(Patie ntCorrelat ionPortTyp eLocal ada pterPatien tCorrelati on)
  202       {
  203           th is.adapter PatientCor relation =  adapterPa tientCorre lation;
  204       }
  205  
  206       @EJB(b eanInterfa ce = Adapt erPolicyEn ginePortTy peLocal.cl ass, beanN ame = "Ada pterPolicy Engine")
  207       public  void setA dapterPoli cyEngine(A dapterPoli cyEnginePo rtType ada pterPolicy Engine)
  208       {
  209           th is.adapter PolicyEngi ne = adapt erPolicyEn gine;
  210       }
  211  
  212       @EJB(b eanInterfa ce = VapCo nsentManag ementPortT ypeLocal.c lass, bean Name = "Va pConsentMa nagement")
  213       public  void setV apConsentM anagement( ConsentMan agementPor tType vapC onsentMana gement)
  214       {
  215           th is.vapCons entManagem ent = vapC onsentMana gement;
  216       }
  217  
  218       @EJB(b eanInterfa ce = Facil ityManager Local.clas s, beanNam e = "Facil ityManager ")
  219       public  void setF acilityMan ager(Facil ityManager  facilityM anager)
  220       {
  221           th is.facilit yManager =  facilityM anager;
  222       }
  223  
  224       @EJB(b eanInterfa ce = Prope rtyLookupL ocal.class , beanName  = "Proper tyFileLook up")
  225       public  void setP ropertyLoo kup(Proper tyLookup p ropertyLoo kup)
  226       {
  227           th is.propert yLookup =  propertyLo okup;
  228       }
  229  
  230       @EJB(b eanInterfa ce = Entit yDocQueryP ortTypeLoc al.class,  beanName =  "EntityDo cQueryOrch ")
  231       public  void setE ntityDocQu ery(Entity DocQueryPo rtType ent ityDocQuer y)
  232       {
  233           th is.entityD ocQuery =  entityDocQ uery;
  234       }
  235  
  236       @EJB(b eanInterfa ce = Entit yDocRetrie vePortType Local.clas s, beanNam e = "Adapt erGatewayD ocRetrieve ")
  237       public  void setE ntityDocRe trieve(Ent ityDocRetr ievePortTy pe entityD ocRetrieve )
  238       {
  239           th is.entityD ocRetrieve  = entityD ocRetrieve ;
  240       }
  241  
  242       @EJB(b eanInterfa ce = Audit ManagerLoc al.class,  beanName =  "AuditMan ager")
  243       public  void setA uditManage r(AuditMan ager audit Manager)
  244       {
  245           th is.auditMa nager = au ditManager ;
  246       }
  247  
  248       @EJB(b eanInterfa ce = Docum entReposit oryLocal.c lass, bean Name = "Do cumentRepo sitory")
  249       public  void setD ocumentRep ository(Do cumentRepo sitory doc umentRepos itory)
  250       {
  251           th is.documen tRepositor y = docume ntReposito ry;
  252       }
  253  
  254       public  void setD asDAO(DasD AO dasDAO)
  255       {
  256           th is.dasDAO  = dasDAO;
  257       }
  258  
  259       @Overr ide
  260       public  PRPAIN201 306UV02 re spondingGa tewayPRPAI N201305UV0 2(Respondi ngGatewayP RPAIN20130 5UV02Reque stType req uest)
  261       {
  262           Ev entAuditin gFactory<A uditEvent>  afac
  263                = EventA uditingFac toryImpl.g etFactory( AuditEvent .class);
  264           af ac.info(af ac.newEven t(request. getAsserti on(),
  265                                      LogConst ants.Audit ingEvent.P DIN_BEGIN,  getClass( )));
  266  
  267           St ring partn erCommunit yId = requ est.getAss ertion().g etHomeComm unity().ge tHomeCommu nityId();
  268           lo gger.debug ("Starting   Patient  Discovery  and Home C ommunity I D is {} ",  partnerCo mmunityId) ;
  269           Ma p<Object,  Object> se archResult sMap = nul l;
  270           PR PAIN201306 UV02 ret =  null;
  271  
  272           bo olean alre adyLoggedE nd = false ;
  273           tr y {
  274                /*
  275                                       * NOTE:  the MVI R PC code (p re MVI web  service m igration -  SR345)
  276                                       * would  flip the  sender/rec eiver it g ot in the  request wh en setting
  277                                       * the 1 306 respon se. Also n oted I bel ieve the r equest ->  receiver
  278                                       * OID s ent by par tner to ad apter is a lways the  VA's OID ( i.e.
  279                                       * getHo meCommunit yId()) but  decided t o keep as  close to o riginal
  280                                       * code.
  281                 */
  282                String s endingHCID  = getSend erOID(requ est.getPRP AIN201305U V02());
  283                String s endingFaci lityNumber  = getFaci lityNumber (sendingHC ID);
  284                String v aHCID = ge tHomeCommu nityId();
  285                String r oid = send ingHCID;
  286                String s oid = getR eceiverOID (request.g etPRPAIN20 1305UV02() );
  287  
  288                AuditEve nt eventPa rtnerAuth  = afac.new Event(requ est.getAss ertion(),
  289                                                                Audi tingEvent. PDIN_PARTN ERAUTH, ge tClass());
  290  
  291                if (faci lityManage r.isPartne rAllowed(p artnerComm unityId, O perationOn Off.ONBOAR D)) {
  292                    if ( facilityMa nager.isPa rtnerAllow ed(partner CommunityI d, Operati onOnOff.IN _PD)) {
  293                         ErrorMessa ge errorMe ssage = nu ll;
  294                         AuditEvent  event = n ull;
  295  
  296                         eventPartn erAuth.set Outcome(Au ditEvent.A uditEventO utcome._0) ;
  297                         afac.info( eventPartn erAuth);
  298  
  299                         AuditEvent  eventPati entMatch =  afac.newE vent(reque st.getAsse rtion(),
  300                                                                          Audit ingEvent.P DIN_PATIEN TMATCH, ge tClass());
  301  
  302                         if (checkP olicyNHINI n(request) ) {
  303                             search ResultsMap  = findCan didates(re quest, eve ntPatientM atch);
  304                             if (nu ll != sear chResultsM ap) {
  305                                 PR PAIN201306 UV02 mviRe sults
  306                                                    = PRP AIN201306U V02.class. cast(searc hResultsMa p.get("PRP AIN201306U V02"));
  307                                 if  (null !=  mviResults  && isMatc h(request,  mviResult s)) {
  308                                      if (chec kPolicyPat ientDiscov eryIn(roid , soid, re quest, mvi Results))  {
  309                                          even tPatientMa tch.setOut come(Audit Event.Audi tEventOutc ome._0);
  310                                          afac .info(even tPatientMa tch);
  311  
  312                                          Audi tEvent eve ntPatientC orrelation s
  313                                                      = a fac.newEve nt(Auditin gEvent.PDI N_CORRELAT ESTORED, g etClass()) ;
  314  
  315                                          // T ake MVI 13 06 respons e and use  to copy/up date for t he
  316                                          // A dapter's 1 306 respon se.
  317                                          II r emotePatie ntIdReques t
  318                                             =  extractPa tientIdFro m201305(re quest.getP RPAIN20130 5UV02());
  319  
  320                                          if ( remotePati entIdReque st == null ) {
  321  
  322                                               eventPatie ntCorrelat ions.setOu tcome(Audi tEvent.Aud itEventOut come._4);
  323                                               eventPatie ntCorrelat ions.setOu tcomeDesc( "No Remote  Patient I D was sent  in PD req uest so no t calling  addPatient Correlatio n");
  324                                               afac.error (eventPati entCorrela tions);
  325  
  326                                               logger.war n("No Remo te Patient  ID was se nt in PD r equest so  not callin g addPatie ntCorrelat ion.");
  327                                          }
  328                                          else  {
  329                                               boolean co rrelationA lreadyExis ts
  330                                                       =  HL7Parser2 01306.extr actMatchin gId(mviRes ults,
  331                                                                                               remote PatientIdR equest.get Extension( ), "NI", s endingFaci lityNumber ,
  332                                                                                               remote PatientIdR equest.get Root()) !=  null;
  333  
  334                                               if (correl ationAlrea dyExists)  {
  335                                                   logger .debug("Re mote Patie nt ID: ''{ }'' " + "i s already  correlated  in MVI fo r HCID: '' {}''.", re motePatien tIdRequest , sendingH CID);
  336                                               }
  337                                               // even if  the remot e Patient  ID is alre ady
  338                                               // correla ted we wil l call add PatientCor relation t o
  339                                               // enter A udit log e ntry.
  340                                               Patient se archResult Patient =  (Patient)s earchResul tsMap.get( "SEARCH_RE SULT_PATIE NT");
  341  
  342                                               // Indicat ing the co rrelation  already ex ists will
  343                                               // skip ad ding the c orrelation  for SSA
  344                                               if (facili tyManager. getFacilit yByFacilit yNumber("2 00NSS") ==  null
  345                                                   || req uest.getAs sertion(). getHomeCom munity().g etHomeComm unityId(). contains(f acilityMan ager.getFa cilityByFa cilityNumb er("200NSS ").getHome CommunityI d())) {
  346                                                   correl ationAlrea dyExists =  false;
  347                                               }
  348  
  349                                               addPatient Correlatio n(request,  mviResult s,
  350                                                                       searchRe sultPatien t, correla tionAlread yExists,
  351                                                                       eventPat ientCorrel ations);
  352  
  353                                               if (AuditE vent.Audit EventOutco me._0 == e ventPatien tCorrelati ons.getOut come()) {
  354                                                   afac.i nfo(eventP atientCorr elations);
  355                                               }
  356                                               else {
  357                                                   afac.e rror(event PatientCor relations) ;
  358                                               }
  359                                          }
  360  
  361                                          ret  = processM VIResults( mviResults , vaHCID,  sendingHCI D);
  362                                      }
  363                                      else {
  364                                          // c heck patie ntdiscover yin failed
  365                                          Adap terPDError .queryErro r(request,  ErrorMess age.IN_PD_ FAILED_POL ICY_CHECK) ;
  366                                      }
  367                                 }
  368                                 el se {
  369                                      // null  mvi result s or no ma tch
  370                                      errorMes sage = (nu ll == mviR esults
  371                                                       ?  ErrorMessa ge.IN_PD_N O_RESPONSE
  372                                                       :  ErrorMessa ge.IN_PD_N O_MATCH);
  373                                      event =  eventPatie ntMatch;
  374                                 }
  375                             }
  376                             else {
  377                                 //  null sear chResultsM ap
  378                                 er rorMessage  = ErrorMe ssage.IN_P D_NO_MATCH ;
  379                                 ev ent = even tPatientMa tch;
  380                             }
  381                         }
  382                         else {
  383                             // che ckNHIN pol icy failed
  384                             errorM essage = E rrorMessag e.IN_PD_FA ILED_POLIC Y_CHECK;
  385                             event  = eventPar tnerAuth;
  386                         }
  387  
  388                         if (null ! = errorMes sage) {
  389                             event. setOutcome (AuditEven t.AuditEve ntOutcome. _4);
  390                             event. setOutcome Desc(error Message.ge tMessage() );
  391                             afac.e rror(event );
  392  
  393                             Adapte rPDError.q ueryError( request, e rrorMessag e);
  394  
  395                             ret =  createPati entNotFoun dResponse( request, v aHCID, get AssigningA uthorityId ());
  396                         }
  397                    }
  398                    else  {
  399                         // isPartn erAllowed
  400                         eventPartn erAuth.set Outcome(Au ditEvent.A uditEventO utcome._4) ;
  401                         eventPartn erAuth.set OutcomeDes c(ErrorMes sage.IN_PD _DISABLED. getMessage ());
  402                         afac.error (eventPart nerAuth);
  403  
  404                         AdapterPDE rror.query Error(requ est, Error Message.IN _PD_DISABL ED);
  405                         ret = crea teErrorRes ponse(requ est, vaHCI D, getAssi gningAutho rityId());
  406                    }
  407                }
  408                else {
  409                    // i sPartnerAl lowed
  410                    even tPartnerAu th.setOutc ome(AuditE vent.Audit EventOutco me._4);
  411                    even tPartnerAu th.setOutc omeDesc(Er rorMessage .IN_PD_NOT _A_PARTNER .getMessag e());
  412                    afac .error(eve ntPartnerA uth);
  413  
  414                    Adap terPDError .queryErro r(request,  ErrorMess age.IN_PD_ NOT_A_PART NER);
  415                    ret  = createEr rorRespons e(request,  vaHCID, g etAssignin gAuthority Id());
  416                }
  417  
  418   //                                                  if  ( checkPo licyNHINIn ( request  )
  419   //                                                                    && ( s earchResul tsMap = fi ndCandidat es( reques t, eventPa tientMatch  ) ) != nu ll
  420   //                                                                    && ( m viResults  = (PRPAIN2 01306UV02)  searchRes ultsMap.ge t( "PRPAIN 201306UV02 " ) ) != n ull
  421   //                                                                    && isM atch( requ est, mviRe sults, eve ntPatientM atch )
  422   //                                                                    && che ckPolicyPa tientDisco veryIn( ro id, soid,  request, m viResults  ) ) {
  423   //
  424   //                                                  }
  425   //                                                  el se {
  426   ////                                                         if (  !checkPol icyNHINIn(  request )  ) {
  427   ////                                                                  eventP olicyCheck .setOutcom e( AuditEv ent.AuditE ventOutcom e._4 );
  428   ////                                                                  eventP olicyCheck .setOutcom eDesc( "PD  Failed ch eckPolicy"  );
  429   ////                                                                  afac.e rror( even tPolicyChe ck );
  430   ////
  431   ////                                                                  Adapte rPDError.q ueryError(  request,  ErrorMessa ge.IN_PD_F AILED_POLI CY_CHECK ) ;
  432   ////                                                         }
  433   ////                                                         else  if ( find Candidates ( request,  eventPati entMatch )  == null )  {
  434   ////                                                                  eventP atientMatc h.setOutco me( AuditE vent.Audit EventOutco me._4 );
  435   ////                                                                  eventP atientMatc h.setOutco meDesc( "P D Failed t o find can didates" ) ;
  436   ////                                                                  afac.e rror( even tPatientMa tch );
  437   ////
  438   ////                                                                  Adapte rPDError.q ueryError(  request,  ErrorMessa ge.IN_PD_N O_MATCH );
  439   ////                                                         }
  440   ////                                                         else  if ( sear chResultsM ap != null  && search ResultsMap .get( "PRP AIN201306U V02" ) ==  null ) {
  441   ////                                                                  eventP olicyCheck .setOutcom e( AuditEv ent.AuditE ventOutcom e._4 );
  442   ////                                                                  eventP olicyCheck .setOutcom eDesc( "PD  Failed to  find 1306  response"  );
  443   ////                                                                  afac.e rror( even tPolicyChe ck );
  444   ////
  445   ////                                                                  Adapte rPDError.q ueryError(  request,  ErrorMessa ge.IN_PD_N O_RESPONSE  );
  446   ////                                                         }
  447   ////                                                         else  if ( !isM atch( requ est, mviRe sults, nul l ) ) {
  448   ////                                                                  Adapte rPDError.q ueryError(  request,  ErrorMessa ge.IN_PD_N O_MATCH );
  449   ////                                                         }
  450   ////                                                         else  if ( !che ckPolicyPa tientDisco veryIn( ro id, soid,  request, m viResults  ) ) {
  451   ////                                                                  Adapte rPDError.q ueryError(  request,  ErrorMessa ge.IN_PD_F AILED_POLI CY_CHECK ) ;
  452   ////                                                         }
  453   //                                                           ret  = createPa tientNotFo undRespons e( request , vaHCID,  getAssigni ngAuthorit yId() );
  454   //                                                  }
  455   //                                          }
  456   //                                          else {
  457   //                                                  ev entPolicyC heck.setOu tcome( Aud itEvent.Au ditEventOu tcome._4 ) ;
  458   //                                                  ev entPolicyC heck.setOu tcomeDesc(  ErrorMess age.IN_PD_ DISABLED.g etMessage( ) );
  459   //                                                  af ac.error(  eventPolic yCheck );
  460   //
  461   //                                                  Ad apterPDErr or.queryEr ror( reque st, ErrorM essage.IN_ PD_DISABLE D );
  462   //                                                  re t = create ErrorRespo nse( reque st, vaHCID , getAssig ningAuthor ityId() );
  463   //                                          }
  464   //                                 }
  465   //                                 else {
  466   //                                          eventPolic yCheck.set Outcome( A uditEvent. AuditEvent Outcome._4  );
  467   //                                          eventPolic yCheck.set OutcomeDes c( ErrorMe ssage.IN_P D_NOT_A_PA RTNER.getM essage() ) ;
  468   //                                          afac.error (eventPoli cyCheck );
  469   //
  470   //                                          AdapterPDE rror.query Error( req uest, Erro rMessage.I N_PD_NOT_A _PARTNER ) ;
  471   //                                          ret = crea teErrorRes ponse( req uest, vaHC ID, getAss igningAuth orityId()  );
  472   //                                 }
  473           }
  474           ca tch (Throw able t) {
  475                String h cid;
  476                String h cidName;
  477                if (requ est.getAss ertion() ! = null &&  request.ge tAssertion ().getHome Community( ) != null)  {
  478                    hcid  = request .getAssert ion().getH omeCommuni ty().getHo meCommunit yId();
  479                    hcid Name = req uest.getAs sertion(). getHomeCom munity().g etName();
  480                }
  481                else {
  482                    hcid  = "N/A";
  483                    hcid Name = "No t Availabl e";
  484                }
  485  
  486                logger.e rror("Erro r processi ng Patient Discovery  from {} {}  - {}", hc id, hcidNa me, t.getM essage());
  487  
  488                ret = cr eateErrorR esponse(re quest, get HomeCommun ityId(), g etAssignin gAuthority Id());
  489  
  490                AdapterP DError.que ryError(re quest, Err orMessage. IN_PD_UNKN OWN);
  491  
  492                AuditEve nt ae = af ac.newEven t(Auditing Event.PDIN _END, getC lass());
  493                ae.setOu tcome(Audi tEvent.Aud itEventOut come._8);
  494                ae.setOu tcomeDesc( "Error pro cessing Pa tientDisco very");
  495                afac.err or(ae);
  496                alreadyL oggedEnd =  true;
  497           }
  498  
  499           lo gger.debug ("respondi ngGatewayP RPAIN20130 5UV02() ex ited");
  500  
  501           if  (!already LoggedEnd)  {
  502                afac.inf o(Auditing Event.PDIN _END, getC lass());
  503           }
  504  
  505           re turn ret;
  506       }
  507  
  508       /**
  509        * Tak es the MVI  1305 resp onse/resul ts and mak e copy and  update as  needed
  510        * for  use as th e Adapter' s PD respo nse to Par tner.
  511        *
  512        * @pa ram mviRes ult
  513        * @re turn
  514        */
  515       privat e PRPAIN20 1306UV02 p rocessMVIR esults(PRP AIN201306U V02 mvi130 6Result, S tring vaHo meFacility ID, String  sendingFa cilityOID)
  516       {
  517           PR PAIN201306 UV02 adapt er1306Resp onse = nul l;
  518           tr y {
  519                adapter1 306Respons e = (PRPAI N201306UV0 2)context. createUnma rshaller() .unmarshal (new JAXBS ource(cont ext, mvi13 06Result)) ;
  520           }
  521           ca tch (JAXBE xception e ) {
  522                logger.e rror("JAXB Exception  occurred w hile makin g copy of  MVI PRPAIN 201306UV02  response  message.",  e);
  523                throw ne w RuntimeE xception(e .getMessag e());
  524           }
  525  
  526           se tSenderId( adapter130 6Response,  vaHomeFac ilityID);
  527           se tReceiver( adapter130 6Response,  sendingFa cilityOID) ;
  528           se tSubjectPa tientId(ad apter1306R esponse, v aHomeFacil ityID);
  529  
  530           se tRequiredE lements(ad apter1306R esponse, v aHomeFacil ityID);
  531           re turn adapt er1306Resp onse;
  532       }
  533  
  534       /**
  535        * Tak es the MVI  1305 resp onse/resul ts and add s missing  required e lements in
  536        * the  response
  537        *
  538        * @pa ram mviRes ult
  539        * @re turn
  540        */
  541       privat e void set RequiredEl ements(PRP AIN201306U V02 mvi130 6Result, S tring vaHo meFacility ID)
  542       {
  543           PR PAIN201306 UV02MFMIMT 700711UV01 ControlAct Process co ntrolAckPr ocess = mv i1306Resul t.getContr olActProce ss();
  544  
  545           if  (controlA ckProcess  == null) {
  546                return;
  547           }
  548           //  create au thor or pe rformer
  549           if  (controlA ckProcess. getAuthorO rPerformer () == null  || contro lAckProces s.getAutho rOrPerform er().size( ) < 1) {
  550                controlA ckProcess. getAuthorO rPerformer ().add(cre ateAuthorO rPerformer (vaHomeFac ilityID));
  551           }
  552  
  553           Li st<PRPAIN2 01306UV02M FMIMT70071 1UV01Subje ct1> subje ctList = c ontrolAckP rocess.get Subject();
  554           fo r (PRPAIN2 01306UV02M FMIMT70071 1UV01Subje ct1 subjec t : subjec tList) {
  555                PRPAIN20 1306UV02MF MIMT700711 UV01Regist rationEven t regEvent  = subject .getRegist rationEven t();
  556                if (regE vent != nu ll) {
  557                    PRPA IN201306UV 02MFMIMT70 0711UV01Su bject2 sub ject1 = re gEvent.get Subject1() ;
  558                    PRPA MT201310UV 02Patient  patient =  subject1.g etPatient( );
  559                    if ( patient !=  null) {
  560                         JAXBElemen t<PRPAMT20 1310UV02Pe rson> patP erson = pa tient.getP atientPers on();
  561                         // add det erminer co de to pati ent person
  562                         if (patPer son != nul l && patPe rson.getVa lue() != n ull) {
  563                             patPer son.getVal ue().setDe terminerCo de("INSTAN CE");
  564  
  565                             if (pa tPerson.ge tValue().g etClassCod e().size()  > 0) {
  566                                 pa tPerson.ge tValue().g etClassCod e().clear( );
  567                             }
  568  
  569                             patPer son.getVal ue().getCl assCode(). add("PSN") ;
  570                         }
  571  
  572                         List<PRPAM T201310UV0 2Subject>  subjectOf1 List = pat ient.getSu bjectOf1() ;
  573                         for (PRPAM T201310UV0 2Subject s ubjectOf1  : subjectO f1List) {
  574                             // set  type code  on subjec t of 1
  575                             subjec tOf1.setTy peCode(Par ticipation TargetSubj ect.SBJ);
  576  
  577                             // set  class cod e on query  match obs ervation
  578                             PRPAMT 201310UV02 QueryMatch Observatio n queryMat chObservat ion = subj ectOf1.get QueryMatch Observatio n();
  579  
  580                             if (qu eryMatchOb servation  != null) {
  581                                 if  (queryMat chObservat ion.getCla ssCode().s ize() > 0)  {
  582                                      queryMat chObservat ion.getCla ssCode().c lear();
  583                                 }
  584                                 qu eryMatchOb servation. getClassCo de().add(" OBS");
  585                             }
  586                         }
  587                    }
  588                    // s et Code on  assigned  Entity
  589                    MFMI MT700711UV 01Custodia n custodia n = regEve nt.getCust odian();
  590                    if ( custodian  != null &&  custodian .getAssign edEntity()  != null)  {
  591                         CE ce = ne w CE();
  592                         ce.setCode ("NotHealt hDataLocat or");
  593                         ce.setCode System("1. 3.6.1.4.1. 19376.1.2. 27.2");
  594                         custodian. getAssigne dEntity(). setCode(ce );
  595                    }
  596                }
  597           }
  598       }
  599  
  600       /**
  601        * Tak es the ass igning aut hority and  created a uthor or p erformer o bject on
  602        * the  xml
  603        *
  604        * @pa ram assign ingAuthori ty
  605        * @re turn
  606        */
  607       privat e MFMIMT70 0711UV01Au thorOrPerf ormer crea teAuthorOr Performer( String ass igningAuth ority)
  608       {
  609           MF MIMT700711 UV01Author OrPerforme r authorOr Performer  = new MFMI MT700711UV 01AuthorOr Performer( );
  610           au thorOrPerf ormer.setT ypeCode(XP articipati onAuthorPe rformer.AU T);
  611  
  612           CO CTMT090300 UV01Assign edDevice a ssignedDev ice = new  COCTMT0903 00UV01Assi gnedDevice ();
  613           II  id = new  II();
  614           id .setRoot(a ssigningAu thority);
  615           as signedDevi ce.setClas sCode(HL7C onstants.A SSIGNED_DE VICE_CLASS _CODE);
  616           as signedDevi ce.getId() .add(id);
  617  
  618           ja vax.xml.na mespace.QN ame xmlqna me = new j avax.xml.n amespace.Q Name("urn: hl7-org:v3 ", "assign edDevice") ;
  619           JA XBElement< COCTMT0903 00UV01Assi gnedDevice > assigned DeviceJAXB Element =  new JAXBEl ement<>(xm lqname, CO CTMT090300 UV01Assign edDevice.c lass, assi gnedDevice );
  620  
  621           au thorOrPerf ormer.setA ssignedDev ice(assign edDeviceJA XBElement) ;
  622  
  623           re turn autho rOrPerform er;
  624       }
  625  
  626       /**
  627        * Gra b the ICN  and then c lear out a ll the oth er correla ted IDs si nce the
  628        * ext ernal part ner only c ares about  the ICN.  Strip the  ICN down t o just the
  629        * val ue (e.g. r emove ID t ype of "NI ", etc.).
  630        *
  631        * @pa ram adapte r1306Respo nse
  632        * @pa ram vaHome Facility
  633        */
  634       privat e void set SubjectPat ientId(PRP AIN201306U V02 adapte r1306Respo nse, Strin g vaHomeFa cilityID)
  635       {
  636  
  637           PR PAMT201310 UV02Patien t patient  = HL7Parse r201306.ex tractSubje ctPatient( adapter130 6Response) ;
  638           if  (patient  != null &&  patient.g etId() !=  null && pa tient.getI d().size()  > 0) {
  639                II newIC N = new II ();
  640                II icn =  HL7Parser 201306.ext ractICNId( patient.ge tId());
  641                newICN.s etExtensio n(HL7Parse r201306.ex tractICNVa lue(icn.ge tExtension ()));
  642                newICN.s etRoot(vaH omeFacilit yID);
  643  
  644                patient. getId().cl ear();
  645                patient. getId().ad d(newICN);
  646           }
  647       }
  648  
  649       privat e void set Receiver(P RPAIN20130 6UV02 adap ter1306Res ponse, Str ing sendin gFacilityO ID)
  650       {
  651           if  (adapter1 306Respons e.getRecei ver() != n ull && ada pter1306Re sponse.get Receiver() .size() >  0) {
  652                adapter1 306Respons e.getRecei ver().clea r();
  653           }
  654  
  655           //  Set the r eceiver
  656           MC CIMT000300 UV01Receiv er receive r = new MC CIMT000300 UV01Receiv er();
  657           re ceiver.set TypeCode(C ommunicati onFunction Type.RCV);
  658  
  659           MC CIMT000300 UV01Device  receiverD evice = ne w MCCIMT00 0300UV01De vice();
  660           re ceiverDevi ce.setDete rminerCode ("INSTANCE "); // HL7 Constants. RECEIVER_D ETERMINER_ CODE
  661           re ceiverDevi ce.setClas sCode(Enti tyClassDev ice.DEV);
  662  
  663           II  receiverI d = new II ();
  664           re ceiverId.s etRoot(sen dingFacili tyOID);
  665  
  666           re ceiverDevi ce.getId() .add(recei verId);
  667           re ceiver.set Device(rec eiverDevic e);
  668           ad apter1306R esponse.ge tReceiver( ).add(rece iver);
  669  
  670           //  adapter13 06Response .getReceiv er().get(0 ).getDevic e().getAsA gent().get Value().
  671           //  Setup Rec eiver -> D evice -> A gent
  672           MC CIMT000300 UV01Agent  receiverDe viceAgent  = new MCCI MT000300UV 01Agent();
  673           re ceiverDevi ceAgent.ge tClassCode ().add("AG NT");
  674           MC CIMT000300 UV01Organi zation rep resentedOr g = new MC CIMT000300 UV01Organi zation();
  675           re presentedO rg.setClas sCode("ORG ");
  676           re presentedO rg.setDete rminerCode ("INSTANCE ");
  677  
  678           II  represent edOrgId =  new II();
  679           re presentedO rgId.setRo ot(sending FacilityOI D);
  680           //  represent edOrgId.se tExtension (facilityN umber);
  681           re presentedO rg.getId() .add(repre sentedOrgI d);
  682  
  683           or g.hl7.v3.O bjectFacto ry objFact ory = new  org.hl7.v3 .ObjectFac tory();
  684           JA XBElement< MCCIMT0003 00UV01Agen t> jaxbEle mentAgent  = objFacto ry.createM CCIMT00030 0UV01Devic eAsAgent(r eceiverDev iceAgent);
  685           JA XBElement< MCCIMT0003 00UV01Orga nization>  jaxbElemen tRepresent edOrg = ob jFactory.c reateMCCIM T000300UV0 1AgentRepr esentedOrg anization( represente dOrg);
  686  
  687           re ceiverDevi ceAgent.se tRepresent edOrganiza tion(jaxbE lementRepr esentedOrg );
  688           re ceiverDevi ce.setAsAg ent(jaxbEl ementAgent );
  689       }
  690  
  691       privat e void set SenderId(P RPAIN20130 6UV02 adap ter1306Res ponse, Str ing vaHome FacilityID )
  692       {
  693           if  (adapter1 306Respons e != null  && adapter 1306Respon se.getSend er() != nu ll && adap ter1306Res ponse.getS ender().ge tDevice()  != null &&  adapter13 06Response .getSender ().getDevi ce().getId () != null  && adapte r1306Respo nse.getSen der().getD evice().ge tId().size () > 0 &&  adapter130 6Response. getSender( ).getDevic e().getId( ).get(0) ! = null) {
  694                MCCIMT00 0300UV01Se nder sende r = adapte r1306Respo nse.getSen der();
  695                MCCIMT00 0300UV01De vice sende rDevice =  sender.get Device();
  696                II sende rDeviceId  = senderDe vice.getId ().get(0);
  697                senderDe viceId.set Root(vaHom eFacilityI D);
  698  
  699                // Setup  Sender ->  Device ->  Agent
  700                MCCIMT00 0300UV01Ag ent sender DeviceAgen t = new MC CIMT000300 UV01Agent( );
  701                senderDe viceAgent. getClassCo de().add(" AGNT");
  702                MCCIMT00 0300UV01Or ganization  represent edOrg = ne w MCCIMT00 0300UV01Or ganization ();
  703                represen tedOrg.set ClassCode( "ORG");
  704                represen tedOrg.set Determiner Code("INST ANCE");
  705  
  706                II repre sentedOrgI d = new II ();
  707                represen tedOrgId.s etRoot(vaH omeFacilit yID);
  708                // repre sentedOrgI d.setExten sion(facil ityNumber) ;
  709                represen tedOrg.get Id().add(r epresented OrgId);
  710  
  711                org.hl7. v3.ObjectF actory obj Factory =  new org.hl 7.v3.Objec tFactory() ;
  712                JAXBElem ent jaxbEl ementAgent  = objFact ory.create MCCIMT0003 00UV01Devi ceAsAgent( senderDevi ceAgent);
  713                JAXBElem ent<MCCIMT 000300UV01 Organizati on> jaxbEl ementRepre sentedOrg  = objFacto ry.createM CCIMT00030 0UV01Agent Represente dOrganizat ion(repres entedOrg);
  714  
  715                senderDe viceAgent. setReprese ntedOrgani zation(jax bElementRe presentedO rg);
  716                senderDe vice.setAs Agent(jaxb ElementAge nt);
  717                sender.s etDevice(s enderDevic e);
  718           }
  719       }
  720  
  721       /**
  722        * TOD O
  723        * <ol >
  724        * <li >The sende r OID exis ts.</li>
  725        * <li >The sende r OID is n ot the sam e as the H omeCommuni tyId.</li>
  726        * <li >The sende r OID is k nown to th e facility  manager.< /li>
  727        * </o l>
  728        *
  729        * @pa ram reques t The web  service re quest.
  730        * @re turn true  if TODO
  731        */
  732       privat e boolean  checkPolic yNHINIn(Re spondingGa tewayPRPAI N201305UV0 2RequestTy pe request )
  733       {
  734           St ring sende rOID = get SenderOID( request.ge tPRPAIN201 305UV02()) ;
  735  
  736           // @formatter :off
  737           re turn !Null Checker.is NullOrEmpt y(senderOI D)
  738                && !send erOID.equa ls(propert yLookup.ge tProperty( "HomeCommu nityId"))
  739                && facil ityManager .getFacili tyByHomeCo mmunityId( senderOID)  != null;
  740           // @formatter :on
  741       }
  742  
  743       /**
  744        * TOD O: What ar e candidat es?
  745        *
  746        * @pa ram reques t The web  service re quest.
  747        * @pa ram eventP atientMatc h the logg ing
  748        * @re turn a map  containin g candidat es. TODO:  What are k eys and va lues?
  749        */
  750       @Suppr essWarning s("uncheck ed")
  751       privat e Map<Obje ct, Object > findCand idates(Res pondingGat ewayPRPAIN 201305UV02 RequestTyp e request,
  752                                                      Aud itEvent ev entPatient Match)
  753       {
  754           re turn adapt erMvi.find Candidates Map(reques t, eventPa tientMatch );
  755       }
  756  
  757       /**
  758        * The re is a ma tch if the  response  contains a  value for  the
  759        * Con trolActPro cess's sub ject. TODO : what is  a ControlA ctProcess?
  760        *
  761        * @pa ram reques t The web  service re quest.
  762        * @pa ram respon se TODO: t his is ext racted fro m the find Candidates  method.
  763        * @re turn true  if there i s match, f alse other wise.
  764        */
  765       privat e boolean  isMatch(Re spondingGa tewayPRPAI N201305UV0 2RequestTy pe request ,
  766                                 PR PAIN201306 UV02 respo nse)
  767       {
  768           bo olean ok =  (response  != null
  769                           && respo nse.getCon trolActPro cess() !=  null
  770                           && !Null Checker.is NullOrEmpt y(response .getContro lActProces s().getSub ject()));
  771  
  772           re turn ok;
  773       }
  774  
  775       /**
  776        *
  777        * @pa ram roid
  778        * @pa ram soid
  779        * @pa ram reques t
  780        * @pa ram respon se
  781        * @re turn
  782        */
  783       privat e boolean  checkPolic yPatientDi scoveryIn( String roi d, String  soid, Resp ondingGate wayPRPAIN2 01305UV02R equestType  request,  PRPAIN2013 06UV02 res ponse)
  784       {
  785           Ev entAuditin gFactory<A uditEvent>  afac
  786                                                = EventAu ditingFact oryImpl.ge tFactory(A uditEvent. class);
  787  
  788           Pa tDiscReqEv entType po licyCheckR eq = new P atDiscReqE ventType() ;
  789           po licyCheckR eq.setDire ction(Nhin cConstants .POLICYENG INE_INBOUN D_DIRECTIO N);
  790  
  791           po licyCheckR eq.setPRPA IN201306UV 02(respons e);
  792           po licyCheckR eq.setAsse rtion(requ est.getAss ertion());
  793           Ho meCommunit yType send erHC = new  HomeCommu nityType() ;
  794           se nderHC.set HomeCommun ityId(roid );
  795           po licyCheckR eq.setSend ingHomeCom munity(sen derHC);
  796           Ho meCommunit yType rece iverHC = n ew HomeCom munityType ();
  797           re ceiverHC.s etHomeComm unityId(so id);
  798           po licyCheckR eq.setRece ivingHomeC ommunity(r eceiverHC) ;
  799  
  800           Po licyEngine Transforme r policyEn gineTransf ormer = ne w PolicyEn gineTransf ormer();
  801           Ch eckPolicyR equestType  checkPoli cyRequest  = policyEn gineTransf ormer.tran sformPatDi scReqToChe ckPolicy(p olicyCheck Req);
  802  
  803           lo gger.info( "About to  enter chec kACPDocume nt...");
  804           //  Do ACP do cument que ry/retriev e
  805           Au ditEvent e vent = afa c.newEvent (request.g etAssertio n(),
  806                                                AuditingE vent.PDIN_ PATIENTSHA RE, getCla ss());
  807           bo olean isPe rmitted =  checkACPDo cument(req uest, resp onse, send erHC, even t);
  808  
  809           //  If valid  eAuth cann ot be obta ined, call  VAP for c heck polic y
  810           if  (!isPermi tted) {
  811                afac.err or(event.s etOutcome( AuditEvent .AuditEven tOutcome._ 4));
  812                event =  afac.newEv ent(reques t.getAsser tion(),
  813                                        Auditi ngEvent.PD IN_PATIENT SHARE, get Class());
  814                Messagin gHelper<Au ditEvent>  msg = afac .messaging ();
  815                msg.addQ uery(event , checkPol icyRequest , CheckPol icyRequest Type.class ,
  816                              Query Type.REQUE ST, null);
  817  
  818                CheckPol icyRespons eType chec kPolicyRes ponse = ad apterPolic yEngine.ch eckPolicy( checkPolic yRequest);
  819                msg.addQ uery(event , checkPol icyRespons e, CheckPo licyRespon seType.cla ss,
  820                              Query Type.RESPO NSE, null) ;
  821  
  822                isPermit ted = (che ckPolicyRe sponse.get Response() .getResult ().get(0). getDecisio n() == Dec isionType. PERMIT);
  823           }
  824  
  825           if  (isPermit ted) {
  826                afac.inf o(event);
  827           }
  828           el se {
  829                event.se tOutcome(A uditEvent. AuditEvent Outcome._4 );
  830                event.se tOutcomeDe sc(ErrorMe ssage.IN_P D_FAILED_P OLICY_CHEC K.getMessa ge());
  831                afac.err or(event);
  832           }
  833  
  834           re turn isPer mitted;
  835       }
  836  
  837       /**
  838        *
  839        * @pa ram reques t
  840        * @pa ram respon se
  841        * @pa ram sender HC
  842        * @re turn
  843        */
  844       privat e boolean  checkACPDo cument(Res pondingGat ewayPRPAIN 201305UV02 RequestTyp e request,
  845                                           PRP AIN201306U V02 respon se, HomeCo mmunityTyp e senderHC , AuditEve nt event)
  846       {
  847           Ev entAuditin gFactory<A uditEvent>  afac
  848                                                = EventAu ditingFact oryImpl.ge tFactory(A uditEvent. class);
  849  
  850           As sertionTyp e assertio n = reques t.getAsser tion();
  851  
  852           lo gger.info( "Checking  if UserTyp e Exists.. .");
  853           Us erType use rType = as sertion.ge tUserInfo( );
  854           if  (NullChec ker.isNull OrEmpty(us erType)) {
  855                logger.d ebug("User  Info is n ull, retur ning FALSE ");
  856                return f alse;
  857           }
  858  
  859           St ring ssaOI D = assert ion.getHom eCommunity ().getHome CommunityI d();
  860           if  (NullChec ker.isNull OrEmpty(ss aOID)) {
  861                logger.d ebug("asse rtion User  Organizat ion is nul l, returni ng FALSE") ;
  862                return f alse;
  863           }
  864  
  865           if  (facility Manager.ge tFacilityB yFacilityN umber("200 NSS") != n ull) {
  866                if (!ssa OID.contai ns(facilit yManager.g etFacility ByFacility Number("20 0NSS").get FullHomeCo mmunityId( ))) {
  867   //                 lo gger.info( "SSA ID in  DB is: {0 }", facili tyManager. getFacilit yByFacilit yNumber("2 00NSS").ge tHomeCommu nityId());
  868                    // n ot SSA, do n't do ACP  Check
  869                    retu rn false;
  870                }
  871           }
  872           el se {
  873                logger.i nfo("SSA f acility no t found in  the datab ase.");
  874                // SSA n ot in DB,  don't do A CP Check
  875                return f alse;
  876           }
  877  
  878           St ring exclu deSections String = p ropertyLoo kup.getPro perty("exc ludePatien tDiscovery Sections") ;
  879           if  (NullChec ker.isNull OrEmpty(ex cludeSecti onsString) ) {
  880                excludeS ectionsStr ing = "";
  881           }
  882  
  883           Da te accessC onsentDocu mentServic eStartDate ;
  884           Da te accessC onsentDocu mentServic eStopDate;
  885  
  886           Re trieveDocu mentSetRes ponseType  accessCons entRetriev eResponse  = null;
  887           by te[] acpDo cument = n ull;
  888           if  (!exclude SectionsSt ring.conta ins("1"))  {
  889                /*
  890                              * Che ck request  Assertion  section a nd send Ac cess Conse nt Policy
  891                              * (AC P) Query D ocument (Q D)/Retriev e Document  (RD) to t he
  892                              * Ori ginator of  PD reques t.
  893                 */
  894                SamlAuth zDecisionS tatementTy pe authZDe cisionStat ement = as sertion.ge tSamlAuthz DecisionSt atement();
  895                logger.i nfo("Got a uthZDecisi onStatemen t from ass ertion.");
  896  
  897                if (Null Checker.is NullOrEmpt y(authZDec isionState ment)) {
  898                    // S AML sectio n is empty , don't do  Access Co nsent doc  query
  899                    retu rn false;
  900                }
  901  
  902                // eAuth  requests  will have  ACP while  wet sig wi ll not
  903                if (Null Checker.is NullOrEmpt y(authZDec isionState ment.getEv idence().g etAssertio n().getAcc essConsent Policy()))  {
  904                    // w et signatu re, don't  do Access  Consent do c query
  905                    retu rn false;
  906                }
  907  
  908                // get v alues requ ired for A CP doc que ry
  909                if (Null Checker.is NullOrEmpt y(authZDec isionState ment.getEv idence().g etAssertio n().getIns tanceAcces sConsentPo licy())) {
  910                    retu rn false;
  911                }
  912  
  913                String s amlInstanc eAccessPol icy = auth ZDecisionS tatement.g etEvidence ().getAsse rtion().ge tInstanceA ccessConse ntPolicy() .get(0);
  914  
  915                if (Null Checker.is NullOrEmpt y(assertio n.getUniqu ePatientId ())) {
  916                    retu rn false;
  917                }
  918  
  919                String s amlPatient Id = asser tion.getUn iquePatien tId().get( 0);
  920                logger.d ebug("Star ting ACP D Q for Saml  Patient I D {}= ", s amlPatient Id);
  921  
  922                // do En tityDocQue ry to get  Access Con sent doc I d from ori ginator
  923                gov.hhs. fha.nhinc. common.nhi nccommonen tity.Respo ndingGatew ayCrossGat ewayQueryR equestType  accessCon sentQueryR equest;
  924                AdhocQue ryResponse  accessCon sentQueryR esponse;
  925  
  926                try {
  927                    gov. hhs.fha.nh inc.common .nhinccomm onentity.O bjectFacto ry objFact ory = new  gov.hhs.fh a.nhinc.co mmon.nhinc commonenti ty.ObjectF actory();
  928                    acce ssConsentQ ueryReques t = objFac tory.creat eRespondin gGatewayCr ossGateway QueryReque stType();
  929  
  930                    // b uild Acces s Consent  Doc Query  request
  931                    Adho cQueryRequ est aqr =  new AdhocQ ueryReques t();
  932                    aqr. setFederat ed(false);
  933                    aqr. setStartIn dex(BigInt eger.value Of(0));
  934                    aqr. setMaxResu lts(BigInt eger.value Of(-1));
  935  
  936                    // A dhocQuery
  937                    Adho cQueryType  aqt = new  AdhocQuer yType();
  938                    aqt. setHome("u rn:oid:" +  propertyL ookup.getP roperty("H omeCommuni tyId"));
  939                    aqt. setId("urn :uuid:14d4 debf-8f97- 4251-9a74- a90016b0af 0d");
  940  
  941                    // a dd slots
  942                    Slot Type1 slot ;
  943                    Valu eListType  valueList;
  944  
  945                    // $ XDSDocumen tEntryPati entId
  946                    slot  = new Slo tType1();
  947                    slot .setName(" $XDSDocume ntEntryPat ientId");
  948                    valu eList = ne w ValueLis tType();
  949                    valu eList.getV alue().add (samlPatie ntId);
  950                    slot .setValueL ist(valueL ist);
  951                    aqt. getSlot(). add(slot);
  952  
  953                    // $ XDSDocumen tEntryStat us
  954                    slot  = new Slo tType1();
  955                    slot .setName(" $XDSDocume ntEntrySta tus");
  956                    valu eList = ne w ValueLis tType();
  957                    valu eList.getV alue().add ("urn:oasi s:names:tc :ebxmlregr ep:StatusT ype:Approv ed");
  958                    slot .setValueL ist(valueL ist);
  959                    aqt. getSlot(). add(slot);
  960  
  961                    // $ XDSDocumen tEntryClas sCode
  962                    slot  = new Slo tType1();
  963                    slot .setName(" $XDSDocume ntEntryCla ssCode");
  964                    valu eList = ne w ValueLis tType();
  965                    valu eList.getV alue().add ("57016-8" );
  966                    slot .setValueL ist(valueL ist);
  967                    aqt. getSlot(). add(slot);
  968  
  969                    // $ XDSDocumen tEntryEven tCodeList
  970                    slot  = new Slo tType1();
  971                    slot .setName(" $XDSDocume ntEntryEve ntCodeList ");
  972                    valu eList = ne w ValueLis tType();
  973                    valu eList.getV alue().add (samlInsta nceAccessP olicy);
  974                    slot .setValueL ist(valueL ist);
  975                    aqt. getSlot(). add(slot);
  976  
  977                    aqr. setAdhocQu ery(aqt);
  978  
  979                    // R esponse Op tions
  980                    Resp onseOption Type rot =  new Respo nseOptionT ype();
  981                    rot. setReturnC omposedObj ects(true) ;
  982                    rot. setReturnT ype("LeafC lass");
  983  
  984                    aqr. setRespons eOption(ro t);
  985  
  986                    acce ssConsentQ ueryReques t.setAdhoc QueryReque st(aqr);
  987  
  988                    // a ssertion
  989                    Asse rtionType  asrt = cre ateAsserti on(asserti on, samlPa tientId);
  990  
  991                    acce ssConsentQ ueryReques t.setAsser tion(asrt) ;
  992  
  993                    // t arget comm unities
  994                    Nhin TargetComm unitiesTyp e targetCo mmunities  = new Nhin TargetComm unitiesTyp e();
  995                    Nhin TargetComm unityType  targetComm unity = ne w NhinTarg etCommunit yType();
  996                    targ etCommunit y.setHomeC ommunity(s enderHC);
  997                    targ etCommunit ies.getNhi nTargetCom munity().a dd(targetC ommunity);
  998                    acce ssConsentQ ueryReques t.setNhinT argetCommu nities(tar getCommuni ties);
  999  
  1000                    afac .messaging ().addQuer y(event, a ccessConse ntQueryReq uest,
  1001                                                 Respondi ngGatewayC rossGatewa yQueryRequ estType.cl ass,
  1002                                                 QueryTyp e.REQUEST,  "dq");
  1003  
  1004                    // c all Entity DocQuery
  1005                    acce ssConsentQ ueryRespon se = entit yDocQuery. responding GatewayCro ssGatewayQ uery(acces sConsentQu eryRequest );
  1006  
  1007                    afac .messaging ().addQuer y(event, a ccessConse ntQueryRes ponse,
  1008                                                 AdhocQue ryResponse .class, Qu eryType.RE SPONSE, nu ll);
  1009  
  1010                }
  1011                catch (E xception e ) {
  1012                    logg er.error(" Error invo king DocQu ery", e);
  1013                    retu rn false;
  1014                }
  1015  
  1016                if (!acc essConsent QueryRespo nse.getSta tus().equa lsIgnoreCa se("urn:oa sis:names: tc:ebxml-r egrep:Resp onseStatus Type:Succe ss")) {
  1017                    logg er.warn("S AML Patien t Id = {},  ACP docum ent query  status = { } ", samlP atientId,  accessCons entQueryRe sponse.get Status());
  1018                    retu rn false;
  1019                }
  1020  
  1021                // parse  doc query  response  and get Do cument Uni que Id and  Repo
  1022                // Uniqu e Id
  1023                String a ccessConse ntDocument UniqueId =  null;
  1024                String a ccessConse ntReposito ryUniqueId  = null;
  1025                String a ccessConse ntDocument CreationTi me = null;
  1026                String a ccessConse ntDocument ServiceSta rtTime = n ull;
  1027                String a ccessConse ntDocument ServiceSto pTime = nu ll;
  1028  
  1029                Extrinsi cObjectTyp e extrinsi cObject;
  1030                List<Slo tType1> ex trinsicObj ectSlotLis t;
  1031                List<Ext ernalIdent ifierType>  extrinsic ObjectExte rnalIdenti fierList;
  1032  
  1033                Registry ObjectList Type regis tryObjectL ist = acce ssConsentQ ueryRespon se.getRegi stryObject List();
  1034  
  1035                List<JAX BElement<?  extends I dentifiabl eType>> id entifiable List;
  1036                if (regi stryObject List != nu ll) {
  1037                    iden tifiableLi st = regis tryObjectL ist.getIde ntifiable( );
  1038                }
  1039                else {
  1040                    logg er.debug(" DQ respons e registry ObjectList  is null.  Returning  to regular  PD...");
  1041                    retu rn false;
  1042                }
  1043  
  1044                if (iden tifiableLi st == null ) {
  1045                    logg er.debug(" DQ respons e identifi ableList i s null. Re turning to  regular P D...");
  1046                    retu rn false;
  1047                }
  1048  
  1049                for (JAX BElement<?  extends I dentifiabl eType> ide ntifiable  : identifi ableList)  {
  1050                    if ( identifiab le.getValu e() instan ceof Extri nsicObject Type) {
  1051                         extrinsicO bject = (E xtrinsicOb jectType)i dentifiabl e.getValue ();
  1052  
  1053                         // get Slo ts
  1054                         extrinsicO bjectSlotL ist = extr insicObjec t.getSlot( );
  1055                         for (SlotT ype1 extri nsicObject Slot : ext rinsicObje ctSlotList ) {
  1056                             // sea rch for sl ot.name =  'repositor yUniqueId'
  1057                             if (ex trinsicObj ectSlot.ge tName().eq ualsIgnore Case("repo sitoryUniq ueId")) {
  1058                                 ac cessConsen tRepositor yUniqueId  = extrinsi cObjectSlo t.getValue List().get Value().ge t(0);
  1059                             }
  1060                             // sea rch for sl ot.name =  'creationT ime'
  1061                             if (ex trinsicObj ectSlot.ge tName().eq ualsIgnore Case("crea tionTime") ) {
  1062                                 ac cessConsen tDocumentC reationTim e = extrin sicObjectS lot.getVal ueList().g etValue(). get(0);
  1063                             }
  1064  
  1065                             if (ex trinsicObj ectSlot.ge tName().eq ualsIgnore Case("serv iceStartTi me")) {
  1066                                 ac cessConsen tDocumentS erviceStar tTime = ex trinsicObj ectSlot.ge tValueList ().getValu e().get(0) ;
  1067                             }
  1068  
  1069                             if (ex trinsicObj ectSlot.ge tName().eq ualsIgnore Case("serv iceStopTim e")) {
  1070                                 ac cessConsen tDocumentS erviceStop Time = ext rinsicObje ctSlot.get ValueList( ).getValue ().get(0);
  1071                             }
  1072                         }
  1073  
  1074                         // get Ext ernalIdent ifiers
  1075                         extrinsicO bjectExter nalIdentif ierList =  extrinsicO bject.getE xternalIde ntifier();
  1076                         for (Exter nalIdentif ierType ex trinsicObj ectExterna lIdentifie r : extrin sicObjectE xternalIde ntifierLis t) {
  1077                             if (ex trinsicObj ectExterna lIdentifie r.getName( ).getLocal izedString ().get(0). getValue() .equalsIgn oreCase("X DSDocument Entry.uniq ueId")) {
  1078                                 ac cessConsen tDocumentU niqueId =  extrinsicO bjectExter nalIdentif ier.getVal ue();
  1079                             }
  1080                         }
  1081                    }
  1082                }
  1083  
  1084                logger.d ebug("acce ssConsentD ocumentUni queId = {}  ", access ConsentDoc umentUniqu eId);
  1085                logger.d ebug("acce ssConsentR epositoryU niqueId =  {} ", acce ssConsentR epositoryU niqueId);
  1086                logger.d ebug("acce ssConsentD ocumentCre ationTime  = {} ", ac cessConsen tDocumentC reationTim e);
  1087  
  1088                if (Null Checker.is NullOrEmpt y(accessCo nsentDocum entUniqueI d)) {
  1089                    logg er.warn("S AML Patien t Id ={} A CP Documen t Unique I d is not p rovided",  samlPatien tId);
  1090                    retu rn false;
  1091                }
  1092  
  1093                if (Null Checker.is NullOrEmpt y(accessCo nsentRepos itoryUniqu eId)) {
  1094                    logg er.warn("S AML Patien t Id={} AC P Reposito ry Unique  Id is not  provided",  samlPatie ntId);
  1095                    retu rn false;
  1096                }
  1097  
  1098                if (Null Checker.is NullOrEmpt y(accessCo nsentDocum entCreatio nTime) ||  accessCons entDocumen tCreationT ime.length () < 8) {
  1099                    logg er.warn("S AML Patien t Id ={} f or whcih A CP Creatio n Time is  not provid ed", samlP atientId);
  1100                    retu rn false;
  1101                }
  1102  
  1103                if (Null Checker.is NullOrEmpt y(accessCo nsentDocum entService StartTime)  || access ConsentDoc umentServi ceStartTim e.length()  < 8) {
  1104                    logg er.warn("S AML Patien t Id ={} f or whcih A CP Service  Start Tim e is not p rovided",  samlPatien tId);
  1105                    retu rn false;
  1106                }
  1107  
  1108                if (Null Checker.is NullOrEmpt y(accessCo nsentDocum entService StopTime)  || accessC onsentDocu mentServic eStopTime. length() <  8) {
  1109                    logg er.warn("S AML Patien t Id ={} f or whcih A CP Service  Stop Time  is not pr ovided", s amlPatient Id);
  1110                    retu rn false;
  1111                }
  1112  
  1113                logger.d ebug("Star ting ACP D R for Saml  Patient I D {}= ", s amlPatient Id);
  1114  
  1115                // do En tityDocRet rieve to g et Access  Consent do c from ori ginator
  1116                gov.hhs. fha.nhinc. common.nhi nccommonen tity.Respo ndingGatew ayCrossGat ewayRetrie veRequestT ype access ConsentRet rieveReque st;
  1117  
  1118                try {
  1119                    gov. hhs.fha.nh inc.common .nhinccomm onentity.O bjectFacto ry objFact ory = new  gov.hhs.fh a.nhinc.co mmon.nhinc commonenti ty.ObjectF actory();
  1120                    acce ssConsentR etrieveReq uest = obj Factory.cr eateRespon dingGatewa yCrossGate wayRetriev eRequestTy pe();
  1121  
  1122                    // b uild Acces s Consent  Doc Retriv e request
  1123                    Retr ieveDocume ntSetReque stType rds rt = new R etrieveDoc umentSetRe questType( );
  1124  
  1125                    // D ocument Re quest
  1126                    Docu mentReques t dr = new  RetrieveD ocumentSet RequestTyp e.Document Request();
  1127  
  1128                    dr.s etHomeComm unityId(ss aOID);
  1129                    dr.s etReposito ryUniqueId (accessCon sentReposi toryUnique Id);
  1130                    dr.s etDocument UniqueId(a ccessConse ntDocument UniqueId);
  1131                    rdsr t.getDocum entRequest ().add(dr) ;
  1132                    acce ssConsentR etrieveReq uest.setRe trieveDocu mentSetReq uest(rdsrt );
  1133  
  1134                    // A ssertion
  1135                    Asse rtionType  asrt = cre ateAsserti on(asserti on, samlPa tientId);
  1136                    acce ssConsentR etrieveReq uest.setAs sertion(as rt);
  1137  
  1138                    // t arget comm unities
  1139                    Nhin TargetComm unitiesTyp e targetCo mmunities  = new Nhin TargetComm unitiesTyp e();
  1140                    Nhin TargetComm unityType  targetComm unity = ne w NhinTarg etCommunit yType();
  1141                    Home CommunityT ype ssaHC  = senderHC ;
  1142                    ssaH C.setHomeC ommunityId (ssaOID);
  1143                    targ etCommunit y.setHomeC ommunity(s saHC);
  1144                    targ etCommunit ies.getNhi nTargetCom munity().a dd(targetC ommunity);
  1145                    acce ssConsentR etrieveReq uest.setNh inTargetCo mmunities( targetComm unities);
  1146  
  1147                    // c all Entity DocRetieve
  1148                    acce ssConsentR etrieveRes ponse = en tityDocRet rieve.resp ondingGate wayCrossGa tewayRetri eve(access ConsentRet rieveReque st);
  1149                }
  1150                catch (T hrowable t ) {
  1151                    logg er.error(" Error invo king DocRe trieve", t );
  1152                    retu rn false;
  1153                }
  1154  
  1155                // check  if patien t authoriz ed
  1156                if (acce ssConsentR etrieveRes ponse.getR egistryRes ponse() ==  null) {
  1157                    logg er.error(" Doc Retrie ve respons e is not v alid.");
  1158                    retu rn false;
  1159                }
  1160                else if  (accessCon sentRetrie veResponse .getRegist ryResponse ().getStat us() == nu ll) {
  1161                    if ( accessCons entRetriev eResponse. getRegistr yResponse( ).getRegis tryErrorLi st() != nu ll) {
  1162                         if (access ConsentRet rieveRespo nse.getReg istryRespo nse().getR egistryErr orList().g etRegistry Error() !=  null) {
  1163                             if (!a ccessConse ntRetrieve Response.g etRegistry Response() .getRegist ryErrorLis t().getReg istryError ().isEmpty ()) {
  1164                                 lo gger.error ("Doc Retr ieve respo nse contai ns errors. ");
  1165                                 re turn false ;
  1166                             }
  1167                         }
  1168                    }
  1169                }
  1170                else if  (!accessCo nsentRetri eveRespons e.getRegis tryRespons e().getSta tus().equa lsIgnoreCa se("urn:oa sis:names: tc:ebxml-r egrep:Resp onseStatus Type:Succe ss")) {
  1171                    logg er.error(" Doc Retrie ve respons e status i s not Succ ess.");
  1172                    retu rn false;
  1173                }
  1174  
  1175                // See i f the docu ment is va lid, that  is creatio nTime > to day - 1
  1176                // year
  1177                // creat ionTime fo rmat is YY YYMMDD
  1178                Date acc essConsent DocumentCr eationDate ;
  1179                try {
  1180                    acce ssConsentD ocumentCre ationDate  = new Simp leDateForm at("yyyyMM dd").parse (accessCon sentDocume ntCreation Time.subst ring(0, 8) );
  1181                }
  1182                catch (P arseExcept ion ex) {
  1183                    logg er.error(" Document c reation da te is not  valid.", e x);
  1184                    retu rn false;
  1185                }
  1186                try {
  1187                    acce ssConsentD ocumentSer viceStartD ate = new  SimpleDate Format("yy yyMMdd").p arse(acces sConsentDo cumentServ iceStartTi me.substri ng(0, 8));
  1188                }
  1189                catch (P arseExcept ion ex) {
  1190                    logg er.error(" Document S erviceStar tTime is n ot valid." , ex);
  1191                    retu rn false;
  1192                }
  1193                try {
  1194                    acce ssConsentD ocumentSer viceStopDa te = new S impleDateF ormat("yyy yMMdd").pa rse(access ConsentDoc umentServi ceStopTime .substring (0, 8));
  1195                }
  1196                catch (P arseExcept ion ex) {
  1197                    logg er.error(" Document S erviceStop Time is no t valid.",  ex);
  1198                    retu rn false;
  1199                }
  1200  
  1201                // Rejec t if eAuth  is expire d.
  1202                /*  was
  1203                Date yea rAgo = new  Date(Syst em.current TimeMillis () - MILLI S_IN_YEAR) ;
  1204                if (acce ssConsentD ocumentCre ationDate. before(yea rAgo)) {
  1205                    retu rn false;
  1206                }
  1207                 */
  1208                if (acce ssConsentD ocumentSer viceStopDa te.before( new Date() )) {
  1209                    logg er.error(" eAuth is e xpired.");
  1210                    retu rn false;
  1211                }
  1212  
  1213                // call  VLER-DAS t o save the  ACP doc
  1214                if (Null Checker.is NullOrEmpt y(accessCo nsentRetri eveRespons e.getDocum entRespons e())) {
  1215                    logg er.error(" Doc Retrie ve respons e has no D ocument in  it.");
  1216                    retu rn false;
  1217                }
  1218  
  1219                acpDocum ent = getD ocumentAsB ytes(acces sConsentRe trieveResp onse.getDo cumentResp onse().get (0).getDoc ument());
  1220  
  1221                if (Null Checker.is NullOrEmpt y(acpDocum ent)) {
  1222                    logg er.error(" Failed to  convert do cument to  byte array .");
  1223                    retu rn false;
  1224                }
  1225           }
  1226           el se {
  1227                // SSA D Q/DR secti on skipped  for testi ng
  1228                accessCo nsentRetri eveRespons e = new Re trieveDocu mentSetRes ponseType( );
  1229                Document Response d ocResponse  = new Doc umentRespo nse();
  1230                String t estDocStri ng = "Test  eAuth";
  1231                acpDocum ent = test DocString. getBytes() ;
  1232                DataHand ler dataHa ndler = ne w DataHand ler(acpDoc ument, "ap plication/ octet-stre am");
  1233                docRespo nse.setDoc ument(data Handler);
  1234                accessCo nsentRetri eveRespons e.getDocum entRespons e().add(do cResponse) ;
  1235                accessCo nsentDocum entService StartDate  = new Date ();
  1236                accessCo nsentDocum entService StopDate =  new Date( System.cur rentTimeMi llis() + M ILLIS_IN_Y EAR);
  1237           }
  1238  
  1239           Da sOperation SendACPDoc umentRespo nse res =  null;
  1240           if  (!exclude SectionsSt ring.conta ins("2"))  {
  1241                // get u rl from th e property  table
  1242                String e ndPoint =  propertyLo okup.getPr operty("vl er.das.eau thsubmit.u rl");
  1243                if (Null Checker.is NullOrEmpt y(endPoint )) {
  1244                    logg er.error(" VLER DAS A CP URL vle r.das.eaut hsubmit.ur l is not c onfigured  in the VA  Adapter Pr operties t able");
  1245                    retu rn false;
  1246                }
  1247  
  1248                // insta ntiate Das  Http clie nt
  1249                DasDAO m yDasDAO =  (null == t his.dasDAO
  1250                                     ? new Das DAOHttpImp l(endPoint )
  1251                                     : this.da sDAO);
  1252  
  1253                DasOpera tionSendAC PDocumentR equest req ;
  1254  
  1255                // call  VLER DAS A CP push
  1256                try {
  1257                    req  = new DasO perationSe ndACPDocum entRequest ();
  1258                    req. setMessage (acpDocume nt);
  1259  
  1260                    res  = myDasDAO .doOperati onSendACPD ocument(re q);
  1261  
  1262                    audi tACPDocume nt(asserti on, access ConsentRet rieveRespo nse, res);
  1263                }
  1264                catch (D asExceptio n e) {
  1265                    logg er.error(" Failed to  write eAut h document  to DAS.",  e);
  1266                    retu rn false;
  1267                }
  1268           }
  1269           el se {
  1270                // DAS s torage sec tion skipp ed for tes ting
  1271                res = ne w DasOpera tionSendAC PDocumentR esponse();
  1272                res.setD ocId("0000 000000");
  1273           }
  1274  
  1275           if  (!exclude SectionsSt ring.conta ins("3"))  {
  1276                try {
  1277                    if ( !updateVap Consent(re quest, res ponse,
  1278                                            ac cessConsen tDocumentS erviceStar tDate, acc essConsent DocumentSe rviceStopD ate,
  1279                                            re s.getDocId ())) {
  1280                         logger.err or("Failed  to update  consent i n VAP.");
  1281                         return fal se;
  1282                    }
  1283                }
  1284                catch (E xception e ) {
  1285                    logg er.error(" Failed to  invoke upd ate consen t to VAP." , e);
  1286                    retu rn false;
  1287                }
  1288           }
  1289  
  1290           re turn true;
  1291       }
  1292  
  1293       privat e ConsentD irectiveAu thorizatio nResponseT ype author izeVapCons ent(Respon dingGatewa yPRPAIN201 305UV02Req uestType r equest,
  1294                                                                                    PRPAIN 201306UV02  response,
  1295                                                                                    Servic eConsumerC ontextType  scct,
  1296                                                                                    Date d ocStartDat e, Date do cStopDate,
  1297                                                                                    String  dasDocId)
  1298       {
  1299           lo gger.info( "Entering  authorizeV apConsent. ..");
  1300           PR PAMT201310 UV02Patien t patient  = HL7Parse r201306.ex tractSubje ctPatient( response);
  1301  
  1302           Co nsentDirec tiveData d ata = new  ConsentDir ectiveData ();
  1303  
  1304           Pa tient pati entInfo =  HL7Parser2 01305.extr actMpiPati entFromMes sage(reque st.getPRPA IN201305UV 02());
  1305           da ta.setPati entRoleSsn (patientIn fo.getSsn( ));
  1306           da ta.setPati entRoleGiv enName(pat ientInfo.g etPersonna mes().get( 0).getFirs tName());
  1307           da ta.setPati entRoleFam ilyName(pa tientInfo. getPersonn ames().get (0).getLas tName());
  1308           da ta.setPati entRoleMid dleName(pa tientInfo. getPersonn ames().get (0).getMid dleName()) ;
  1309  
  1310           if  (patient  != null &&  patient.g etId() !=  null && pa tient.getI d().size()  > 0) {
  1311                II icn =  HL7Parser 201306.ext ractICNId( patient.ge tId());
  1312                data.set Icn(HL7Par ser201306. extractICN Value(icn. getExtensi on()));
  1313           }
  1314  
  1315           if  (patient  == null) {
  1316                logger.d ebug("pati ent is nul l");
  1317           }
  1318           el se if (pat ient.getId () == null ) {
  1319                logger.d ebug("pati ent.getId( ) is null" );
  1320           }
  1321           el se {
  1322                logger.d ebug("pati ent.getId( ) length:  {}", patie nt.getId() .size());
  1323           }
  1324  
  1325           //  For VA us er informa tion
  1326           As sertionTyp e assertio nType = cr eateAssert ion(reques t.getAsser tion(), da ta.getIcn( ));
  1327           //  Set autho r
  1328           da ta.setAuth orPersonOi d(assertio nType.getU serInfo(). getRoleCod ed().getCo de());
  1329           da ta.setAuth orPersonOr gOid(asser tionType.g etUserInfo ().getOrg( ).getHomeC ommunityId ());
  1330  
  1331           //  Set the s tatus to a ctive
  1332           da ta.setComp onentStatu sCode("act ive");
  1333           da ta.setComp onentPurpo seOfUseDis playName(" COVERAGE") ;
  1334  
  1335           tr y {
  1336                final St ring begin DateString  = HL7Date Util.yyyyM MddhhmmssZ (docStartD ate);
  1337                final St ring endDa teString =  HL7DateUt il.yyyyMMd dhhmmssZ(d ocStopDate );
  1338  
  1339                // Set t he effecti ve date
  1340                data.set EffectiveD ateTime(be ginDateStr ing);
  1341                // Creat e the begi n and end  date
  1342                data.set Documentat ionBeginTi me(beginDa teString);
  1343                data.set Documentat ionEndTime (endDateSt ring);
  1344           }
  1345           ca tch (final  ParseExce ption ex)  {
  1346                logger.e rror("Date  parsing e xception w hile creat ing VAP co nsent auth orization  request.") ;
  1347                throw ne w RuntimeE xception(e x);
  1348           }
  1349  
  1350           tr y {
  1351                final by te[] conse ntDirectiv eDocumentB ytes = thi s.makeCons entDirecti veDocument String(dat a);
  1352                // Creat e the requ est and se nd to the  consent ma nagement s ervice
  1353                final Co nsentDirec tiveAuthor izationReq uestType c onsentAuth Request =  new Consen tDirective Authorizat ionRequest Type();
  1354                consentA uthRequest .setDocume nt(consent DirectiveD ocumentByt es);
  1355  
  1356                consentA uthRequest .setServic eConsumerC ontext(scc t);
  1357                consentA uthRequest .setDasDoc umentId(da sDocId);
  1358  
  1359                logger.d ebug("Atte mpting to  authorize  new consen t to VAP.. .");
  1360                return v apConsentM anagement. processCon sentDirect iveAuthori zation(con sentAuthRe quest);
  1361           }
  1362           ca tch (Conse ntManageme ntServiceF aultMessag e ex) {
  1363                logger.e rror("Exce ption atte mpting to  authorize  VAP consen t");
  1364           }
  1365  
  1366           re turn null;
  1367       }
  1368  
  1369       privat e boolean  updateVapC onsent(Res pondingGat ewayPRPAIN 201305UV02 RequestTyp e request,  PRPAIN201 306UV02 re sponse,
  1370                                           Dat e docStart Date, Date  docStopDa te, String  dasDocId)
  1371       {
  1372           lo gger.debug ("Entering  updateVap Consent... ");
  1373           //  First try  to retrie ve existin g VAP cons ent direct ory for SS A auth
  1374           Co nsentDirec tiveQueryR equestType  consentDi rectiveQue ry = new C onsentDire ctiveQuery RequestTyp e();
  1375           PR PAMT201310 UV02Patien t patient  = HL7Parse r201306.ex tractSubje ctPatient( response);
  1376           if  (patient  != null &&  patient.g etId() !=  null && pa tient.getI d().size()  > 0) {
  1377                II icn =  HL7Parser 201306.ext ractICNId( patient.ge tId());
  1378                logger.d ebug("icn:  {}", icn. toString() );
  1379                consentD irectiveQu ery.setPat ientId(HL7 Parser2013 06.extract ICNValue(i cn.getExte nsion()));
  1380                logger.d ebug("icn. getExtensi on(): {}",  icn.getEx tension()) ;
  1381           }
  1382  
  1383           if  (patient  == null) {
  1384                logger.d ebug("pati ent is nul l");
  1385           }
  1386           el se if (pat ient.getId () == null ) {
  1387                logger.d ebug("pati ent.getId( ) is null" );
  1388           }
  1389           el se {
  1390                logger.d ebug("pati ent.getId( ) length:  {}", patie nt.getId() .size());
  1391           }
  1392  
  1393           Co nsentType  ssaAuthTyp e = Consen tType.SSA_ AUTHORIZAT ION;
  1394           Se rviceConsu merContext Type scct  = new Serv iceConsume rContextTy pe();
  1395           sc ct.setCons entType(ss aAuthType) ;
  1396           sc ct.setUser (request.g etAssertio n().getUse rInfo().ge tUserName( ));
  1397  
  1398           if  (facility Manager.ge tFacilityB yFacilityN umber("200 NSS") != n ull) {
  1399                scct.set Facility(f acilityMan ager.getFa cilityByFa cilityNumb er("200NSS ").getFaci lityName() );
  1400           }
  1401           el se {
  1402                scct.set Facility(" SSA");
  1403           }
  1404  
  1405           sc ct.setServ iceConsume rType(Serv iceConsume r.EXCHANGE );
  1406           co nsentDirec tiveQuery. setService ConsumerCo ntext(scct );
  1407  
  1408           co nsentDirec tiveQuery. setQueryPa ram(Consen tDirective QueryParam Type.ACTIV E);
  1409  
  1410           Co nsentDirec tiveQueryR esponseTyp e consentD irectiveRe sponse;
  1411  
  1412           lo gger.info( "Attemptin g to get c urrent VAP  consent d irective f or SSA aut horization ...");
  1413           tr y {
  1414                consentD irectiveRe sponse = v apConsentM anagement. getConsent Directives (consentDi rectiveQue ry);
  1415           }
  1416           ca tch (Conse ntManageme ntServiceF aultMessag e ex) {
  1417                logger.e rror("Coul dn't get V AP consent  directive .");
  1418  
  1419                return f alse;
  1420           }
  1421           lo gger.info( "Received  VAP consen t directiv e response ");
  1422  
  1423           if  (consentD irectiveRe sponse !=  null && co nsentDirec tiveRespon se.getCons entDirecti veReferenc e() != nul l && !cons entDirecti veResponse .getConsen tDirective Reference( ).isEmpty( )) {
  1424                logger.i nfo("Curre nt VAP con sent direc tive extra cted");
  1425  
  1426                // Check  if eAuth  is newer t han curren t consent  directive
  1427                logger.i nfo("Check ing if eAu th is newe r than the  current S SA authori zation..." );
  1428                ConsentD irectiveRe ferenceTyp e currentC onsentRefe rence = co nsentDirec tiveRespon se.getCons entDirecti veReferenc e().get(0) ;
  1429                Date cur rentConsen tDate = cu rrentConse ntReferenc e.getOptin Date();
  1430                if (docS tartDate.a fter(curre ntConsentD ate)) {
  1431                    logg er.info("e Auth is ne wer than c urrent SSA  authoriza tion");
  1432                    // D elete exis ting conse nt directi ve first
  1433                    Cons entDirecti veRevocati onRequestT ype revoca tionReques t = new Co nsentDirec tiveRevoca tionReques tType();
  1434                    revo cationRequ est.setOpt outReason( ConsentDir ectiveOptO utReasonTy pe.NEW_AUT HORIZATION );
  1435                    scct .setConsen tType(Cons entType.SS A_REVOCATI ON);
  1436                    revo cationRequ est.setSer viceConsum erContext( scct);
  1437  
  1438                    // C reate Cons entDirecti veData for  revocatio n request  from
  1439                    // r esponse
  1440                    Cons entDirecti veData cur rentConsen tData = ne w ConsentD irectiveDa ta();
  1441                    curr entConsent Data.setDo cId(curren tConsentRe ference.ge tConsentDi rId());
  1442                    curr entConsent Data.setIc n(currentC onsentRefe rence.getP atientIen( ));
  1443  
  1444                    // E xtract Pat ient info
  1445                    Pati ent patien tInfo = HL 7Parser201 305.extrac tMpiPatien tFromMessa ge(request .getPRPAIN 201305UV02 ());
  1446                    curr entConsent Data.setPa tientRoleS sn(patient Info.getSs n());
  1447                    curr entConsent Data.setPa tientRoleG ivenName(p atientInfo .getPerson names().ge t(0).getFi rstName()) ;
  1448                    curr entConsent Data.setPa tientRoleF amilyName( patientInf o.getPerso nnames().g et(0).getL astName()) ;
  1449                    curr entConsent Data.setPa tientRoleM iddleName( patientInf o.getPerso nnames().g et(0).getM iddleName( ));
  1450                    try  {
  1451                         currentCon sentData.s etDocument ationBegin Time(HL7Da teUtil.yyy yMMddhhmms sZ(current ConsentRef erence.get OptinDate( )));
  1452                         currentCon sentData.s etDocument ationEndTi me(HL7Date Util.yyyyM MddhhmmssZ (currentCo nsentRefer ence.getEx pirationDa te()));
  1453                    }
  1454                    catc h (ParseEx ception ex ) {
  1455                         logger.err or("Could  not parse  current co nsent Opt- in or expi ration dat e");
  1456                         return fal se;
  1457                    }
  1458                    curr entConsent Data.setCo mponentSta tusCode("a borted");
  1459                    curr entConsent Data.setCo mponentPur poseOfUseD isplayName ("COVERAGE ");
  1460                    fina l byte[] c onsentDire ctiveDocum entBytes =  this.make ConsentDir ectiveDocu mentString (currentCo nsentData) ;
  1461                    revo cationRequ est.setDoc ument(cons entDirecti veDocument Bytes);
  1462                    logg er.info("C onsent rev ocation re quest crea ted for VA P");
  1463  
  1464                    try  {
  1465                         logger.deb ug("Attemp ting to re voke old V AP consent ...");
  1466                         ConsentDir ectiveRevo cationResp onseType r evocationR esponse =  vapConsent Management .processCo nsentDirec tiveRevoca tion(revoc ationReque st);
  1467  
  1468                         if (revoca tionRespon se == null  || revoca tionRespon se.getCons entDirecti veReferenc e() == nul l) {
  1469                             // Con sent revoc ation fail ed
  1470                             logger .info("Fai led to rev oke old co nsent. Ret urning to  regulare P D flow..." );
  1471                             return  false;
  1472                         }
  1473                    }
  1474                    catc h (Consent Management ServiceFau ltMessage  ex) {
  1475                         logger.err or("Error  attempting  to revoke  old VAP c onsent");
  1476                         return fal se;
  1477                    }
  1478                    logg er.info("O ld VAP con sent succe ssfully re voked");
  1479  
  1480                    scct .setConsen tType(ssaA uthType);
  1481                    Cons entDirecti veAuthoriz ationRespo nseType co nsentManag ementRespo nse = auth orizeVapCo nsent(requ est, respo nse, scct,  docStartD ate, docSt opDate, da sDocId);
  1482  
  1483                    if ( consentMan agementRes ponse == n ull || con sentManage mentRespon se.getCons entDirecti veReferenc e() == nul l) {
  1484                         // Consent  authoriza tion faile d
  1485                         logger.err or("VAP co nsent auth orization  failed.");
  1486                         return fal se;
  1487                    }
  1488                }
  1489           }
  1490           el se {
  1491                logger.d ebug("No c urrent SSA  authoriza tion conse nt directi ve. Attemp ting to au thorize... ");
  1492                ConsentD irectiveAu thorizatio nResponseT ype consen tManagemen tResponse  = authoriz eVapConsen t(request,  response,  scct, doc StartDate,  docStopDa te, dasDoc Id);
  1493  
  1494                if (cons entManagem entRespons e == null  || consent Management Response.g etConsentD irectiveRe ference()  == null) {
  1495                    // C onsent aut horization  failed
  1496                    logg er.error(" VAP consen t authoriz ation fail ed.");
  1497                    retu rn false;
  1498                }
  1499           }
  1500  
  1501           re turn true;
  1502       }
  1503  
  1504       /**
  1505        * Con vert from  the Consen tDirective Data to th e CDA R2 X ML Privacy  consent
  1506        * dir ective doc ument and  then conve rt that to  string.
  1507        */
  1508       privat e byte[] m akeConsent DirectiveD ocumentStr ing(final  ConsentDir ectiveData  data)
  1509       {
  1510           tr y {
  1511                // Conve rt the Con sentDirect iveData to  XML docum ent
  1512                JAXBCont ext consen tDirective JaxbContex t = JAXBCo ntext.newI nstance(Co nsentDirec tiveData.c lass);
  1513  
  1514                StringWr iter strin gWriter =  new String Writer();
  1515                Marshall er consent DirectiveM arshaller  = consentD irectiveJa xbContext. createMars haller();
  1516                consentD irectiveMa rshaller.s etProperty (Marshalle r.JAXB_FOR MATTED_OUT PUT, true) ;
  1517                consentD irectiveMa rshaller.m arshal(dat a, stringW riter);
  1518                String c onsentDire ctiveDocum entString  = stringWr iter.toStr ing();
  1519  
  1520                return c onsentDire ctiveDocum entString. getBytes() ;
  1521           }
  1522           ca tch (final  JAXBExcep tion ex) {
  1523                throw ne w RuntimeE xception(e x);
  1524           }
  1525       }
  1526  
  1527       public  II extrac tPatientId From201305 (PRPAIN201 305UV02 re quest)
  1528       {
  1529           II  patId = n ull;
  1530           St ring aaId;
  1531  
  1532           if  (request  != null &&  request.g etControlA ctProcess( ) != null)  {
  1533                aaId = g etAAOID(re quest);
  1534  
  1535                if (!Nul lChecker.i sNullOrEmp ty(aaId))  {
  1536                    if ( request.ge tControlAc tProcess() .getQueryB yParameter () != null  && reques t.getContr olActProce ss().getQu eryByParam eter().get Value() !=  null && r equest.get ControlAct Process(). getQueryBy Parameter( ).getValue ().getPara meterList( ) != null  && !NullCh ecker.isNu llOrEmpty( request.ge tControlAc tProcess() .getQueryB yParameter ().getValu e().getPar ameterList ().getLivi ngSubjectI d())) {
  1537                         for (PRPAM T201306UV0 2LivingSub jectId liv ingSubId :  request.g etControlA ctProcess( ).getQuery ByParamete r().getVal ue().getPa rameterLis t().getLiv ingSubject Id()) {
  1538                             for (I I id : liv ingSubId.g etValue())  {
  1539                                 if  (id != nu ll && !Nul lChecker.i sNullOrEmp ty(id.getR oot()) &&  !NullCheck er.isNullO rEmpty(id. getExtensi on()) && a aId.conten tEquals(id .getRoot() )) {
  1540                                      patId =  new II();
  1541                                      patId.se tRoot(id.g etRoot());
  1542                                      patId.se tExtension (id.getExt ension());
  1543  
  1544                                      // break  out of in ner loop
  1545                                      break;
  1546                                 }
  1547                             }
  1548  
  1549                             // If  the patien t id was f ound then  break out  of outer
  1550                             // loo p
  1551                             if (pa tId != nul l) {
  1552                                 br eak;
  1553                             }
  1554                         }
  1555                    }
  1556                }
  1557           }
  1558  
  1559           re turn patId ;
  1560       }
  1561  
  1562       privat e void add PatientCor relation(R espondingG atewayPRPA IN201305UV 02RequestT ype reques t, PRPAIN2 01306UV02  response,
  1563                                             P atient sea rchResultP atient, bo olean corr elationAlr eadyExists , AuditEve nt logging Event)
  1564       {
  1565           PR PAIN201301 UV02 prpai n201301UV0 2 = Adapte rHL7PRPA20 1301Transf orms.creat ePRPA20130 1(request. getPRPAIN2 01305UV02( ), getHome CommunityI d());
  1566           /*
  1567                     * 0 4/30/2014  - SR345 -  With the o ld RPC cal ls the res ults were  mapped
  1568                     * t o a PRPAIN 201306UV02  response  and the IC N was inse rted as th e first
  1569                     * e lement in  the Subjec t1->Patien t->Id list . Now that  we are us ing the
  1570                     * M VI web ser vice and u sing the P RPAIN20130 6UV02 resp onse they
  1571                     * r eturned/po pulated th ere's no g uarantee I CN will be  first in  the
  1572                     * l ist. There fore need  to search  for it.
  1573            * /
  1574           //  II localP atientId =
  1575           //  response. getControl ActProcess ().getSubj ect().get( 0).getRegi strationEv ent().getS ubject1(). getPatient ().getId() .get(0);
  1576           II  localPati entId = HL 7Parser201 306.extrac tICNId(res ponse);
  1577           pr pain201301 UV02.getCo ntrolActPr ocess().ge tSubject() .get(0).ge tRegistrat ionEvent() .getSubjec t1().getPa tient().ge tId().add( localPatie ntId);
  1578           Ad dPatientCo rrelationR equestType  r = new A ddPatientC orrelation RequestTyp e();
  1579           r. setPRPAIN2 01301UV02( prpain2013 01UV02);
  1580           r. setAsserti on(request .getAssert ion());
  1581           ad apterPatie ntCorrelat ion.addPat ientCorrel ation(r, s earchResul tPatient,  correlatio nAlreadyEx ists, logg ingEvent);
  1582       }
  1583  
  1584       privat e PRPAIN20 1306UV02 c reatePatie ntNotFound Response(R espondingG atewayPRPA IN201305UV 02RequestT ype reques t, String  homeCommun ityId, Str ing assign ingAuthori tyId)
  1585       {
  1586           re turn HL7Db Parser2013 06.BuildMe ssageFromM piPatients (null, req uest.getPR PAIN201305 UV02(), ho meCommunit yId, assig ningAuthor ityId);
  1587       }
  1588  
  1589       /* 
  1590          SSA  receives  an Incorre ct  respon se "Patien t Not Foun d" when ac tually the re is HTTP 500 server  error.
  1591          ehx -181: fix  to a produ ction issu e reported  by SSA. 
  1592        */
  1593       privat e PRPAIN20 1306UV02 c reateError Response(R espondingG atewayPRPA IN201305UV 02RequestT ype reques t, String  homeCommun ityId, Str ing assign ingAuthori tyId)
  1594       {
  1595  
  1596           // ehx-181: b elow comme nt block e xists befo re fix. 3/ 8/2017
  1597           /* *
  1598            *  ********* ******
  1599            *  PRPAIN201 306UV02 re t =
  1600            *  HL7DbPars er201306.B uildMessag eFromMpiPa tients(nul l,
  1601            *  request.g etPRPAIN20 1305UV02() , homeComm unityId,
  1602            *  assigning AuthorityI d);
  1603            *
  1604            *  // set Ap plicaton E rror code  CS appErro r = new CS ();
  1605            *  appError. setCode("A E");
  1606            *  ret.getAc knowledgem ent().get( 0).setType Code(appEr ror);
  1607            *
  1608            *  // set Qu ery Error  Code
  1609            *  ret.getCo ntrolActPr ocess().ge tQueryAck( ).getQuery ResponseCo de().setCo de("QE");
  1610            *
  1611            *  return re t;
  1612           ** ********** *******
  1613            * /
  1614           /* */
  1615           lo gger.debug ("throwing  an explic it runtime  exception . the runt ime except ion is aut omatically  handled i n the resp onse to bu ild the so ap fault." );
  1616           // the runtim e exceptio n is captu red in the  response  to build t he soap fa ult
  1617           th row new Ru ntimeExcep tion("Inte rnal Error r");
  1618           /* */
  1619       }
  1620  
  1621       privat e String g etSenderOI D(PRPAIN20 1305UV02 r equest)
  1622       {
  1623           St ring ret =  null;
  1624  
  1625           if  (request. getSender( ) != null  && request .getSender ().getDevi ce() != nu ll && requ est.getSen der().getD evice().ge tAsAgent()  != null & & request. getSender( ).getDevic e().getAsA gent().get Value() !=  null && r equest.get Sender().g etDevice() .getAsAgen t().getVal ue().getRe presentedO rganizatio n() != nul l && reque st.getSend er().getDe vice().get AsAgent(). getValue() .getRepres entedOrgan ization(). getValue()  != null & & request. getSender( ).getDevic e().getAsA gent().get Value().ge tRepresent edOrganiza tion().get Value().ge tId() != n ull && !Nu llChecker. isNullOrEm pty(reques t.getSende r().getDev ice().getA sAgent().g etValue(). getReprese ntedOrgani zation().g etValue(). getId()))  {
  1626                ret = re quest.getS ender().ge tDevice(). getAsAgent ().getValu e().getRep resentedOr ganization ().getValu e().getId( ).get(0).g etRoot();
  1627           }
  1628  
  1629           re turn ret;
  1630       }
  1631  
  1632       privat e String g etAAOID(PR PAIN201305 UV02 reque st)
  1633       {
  1634           re turn HL7Pa rser201305 .extractRe moteAssign ingAuthori tyID(reque st);
  1635       }
  1636  
  1637       privat e String g etReceiver OID(PRPAIN 201305UV02  request)
  1638       {
  1639           St ring ret =  null;
  1640  
  1641           if  (request  != null &&  !NullChec ker.isNull OrEmpty(re quest.getR eceiver())  && reques t.getRecei ver().get( 0) != null  && reques t.getRecei ver().get( 0).getDevi ce() != nu ll && requ est.getRec eiver().ge t(0).getDe vice().get AsAgent()  != null &&  request.g etReceiver ().get(0). getDevice( ).getAsAge nt().getVa lue() != n ull && req uest.getRe ceiver().g et(0).getD evice().ge tAsAgent() .getValue( ).getRepre sentedOrga nization()  != null & & request. getReceive r().get(0) .getDevice ().getAsAg ent().getV alue().get Represente dOrganizat ion().getV alue() !=  null && !N ullChecker .isNullOrE mpty(reque st.getRece iver().get (0).getDev ice().getA sAgent().g etValue(). getReprese ntedOrgani zation().g etValue(). getId()) & & request. getReceive r().get(0) .getDevice ().getAsAg ent().getV alue().get Represente dOrganizat ion().getV alue().get Id().get(0 ) != null  && !NullCh ecker.isNu llOrEmpty( request.ge tReceiver( ).get(0).g etDevice() .getAsAgen t().getVal ue().getRe presentedO rganizatio n().getVal ue().getId ().get(0). getRoot()) ) {
  1642                ret = re quest.getR eceiver(). get(0).get Device().g etAsAgent( ).getValue ().getRepr esentedOrg anization( ).getValue ().getId() .get(0).ge tRoot();
  1643           }
  1644  
  1645           re turn ret;
  1646       }
  1647  
  1648       privat e Assertio nType crea teAssertio n(Assertio nType from Assertion,  String pa tientId)
  1649       {
  1650           As sertionTyp e asrt = n ew Asserti onType();
  1651           Fa cility hom eFacility  = getHomeF acility();
  1652  
  1653           as rt.setAuth orized(tru e);
  1654  
  1655           Ho meCommunit yType home Community  = new Home CommunityT ype();
  1656           ho meCommunit y.setHomeC ommunityId (homeFacil ity.getFul lHomeCommu nityId());
  1657           ho meCommunit y.setName( homeFacili ty.getFaci lityName() );
  1658           as rt.setHome Community( homeCommun ity);
  1659  
  1660           Us erType use r = new Us erType();
  1661           Ce Type roleC oded = new  CeType();
  1662           ro leCoded.se tCode("224 608005");
  1663           us er.setUser Name("VA_U SER");
  1664           Pe rsonNameTy pe personN ame = new  PersonName Type();
  1665           pe rsonName.s etGivenNam e("VA");
  1666           pe rsonName.s etFamilyNa me("User") ;
  1667           us er.setPers onName(per sonName);
  1668  
  1669           if  (user.get PersonName () != null  && (NullC hecker.isN otNullOrEm pty(user.g etPersonNa me().getFa milyName() ) || NullC hecker.isN otNullOrEm pty(user.g etPersonNa me().getSe condNameOr Initials() ) || NullC hecker.isN otNullOrEm pty(user.g etPersonNa me().getGi venName()) )) {
  1670  
  1671                user.set UserName(u ser.getUse rName() +  ", CN=" +  createFull Name(user. getPersonN ame()) + " , O=" + ho meFacility .getFacili tyName());
  1672           }
  1673           el se {
  1674                user.set UserName(u ser.getUse rName() +  ", CN=" +  user.getUs erName() +  ", O=" +  homeFacili ty.getFaci lityName() );
  1675           }
  1676  
  1677           ro leCoded.se tCodeSyste m("2.16.84 0.1.113883 .6.96");
  1678           ro leCoded.se tCodeSyste mName("SNO MED_CT");
  1679  
  1680           us er.setRole Coded(role Coded);
  1681           us er.setOrg( homeCommun ity);
  1682           as rt.setUser Info(user) ;
  1683  
  1684           as rt.getUniq uePatientI d().add(pa tientId);
  1685  
  1686           Ce Type p = n ew CeType( );
  1687           p. setCodeSys tem("2.16. 840.1.1138 83.3.18.7. 1");
  1688           p. setCodeSys temName("n hin-purpos e");
  1689           p. setDisplay Name("COVE RAGE");
  1690           if  (fromAsse rtion.getP urposeOfDi sclosureCo ded() != n ull) {
  1691                p.setCod e(fromAsse rtion.getP urposeOfDi sclosureCo ded().getC ode());
  1692           }
  1693           el se {
  1694                p.setCod e("COVERAG E");
  1695           }
  1696           as rt.setPurp oseOfDiscl osureCoded (p);
  1697  
  1698           Sa mlIssuerTy pe sit = n ew SamlIss uerType();
  1699           si t.setIssue r(property Lookup.get Property(" AssertionI ssuer"));
  1700           si t.setIssue rFormat(pr opertyLook up.getProp erty("Asse rtionIssue rFormat")) ;
  1701           as rt.setSaml Issuer(sit );
  1702  
  1703           as rt.setMess ageId("urn :uuid:" +  UUID.rando mUUID().to String());
  1704  
  1705           re turn asrt;
  1706       }
  1707  
  1708       privat e Facility  getHomeFa cility()
  1709       {
  1710           re turn facil ityManager .getFacili tyByFacili tyNumber(" VA");
  1711       }
  1712  
  1713       privat e Facility  getHomeFa cility(Str ing homeCo mmunityId)
  1714       {
  1715           Fa cility fac ility;
  1716  
  1717           fa cility = f acilityMan ager.getFa cilityByFu llHomeComm unityId(ho meCommunit yId);
  1718  
  1719           if  (NullChec ker.isNotN ullOrEmpty (facility) ) {
  1720                return f acility;
  1721           }
  1722  
  1723           fa cility = f acilityMan ager.getFa cilityByHo meCommunit yId(homeCo mmunityId) ;
  1724  
  1725           re turn facil ity;
  1726       }
  1727  
  1728       privat e String g etHomeComm unityId()
  1729       {
  1730           St ring ret =  null;
  1731           Fa cility fac ility = fa cilityMana ger.getFac ilityByFac ilityNumbe r("VA");
  1732  
  1733           if  (facility  != null)  {
  1734                ret = fa cility.get HomeCommun ityId();
  1735           }
  1736  
  1737           re turn ret;
  1738       }
  1739  
  1740       privat e String g etHomeComm unityId(As sertionTyp e assertio n)
  1741       {
  1742           if  (NullChec ker.isNull OrEmpty(as sertion))  {
  1743                logger.e rror("Asse rtion sect ion is emp ty");
  1744                return n ull;
  1745           }
  1746  
  1747           if  (NullChec ker.isNull OrEmpty(as sertion.ge tHomeCommu nity())) {
  1748                logger.e rror("Home Community  section is  empty");
  1749                return n ull;
  1750           }
  1751  
  1752           re turn asser tion.getHo meCommunit y().getHom eCommunity Id();
  1753       }
  1754  
  1755       privat e String g etFacility Number(Str ing hcid)
  1756       {
  1757           St ring ret =  null;
  1758           Fa cility fac ility = fa cilityMana ger.getFac ilityByHom eCommunity Id(hcid);
  1759  
  1760           if  (facility  != null)  {
  1761                ret = fa cility.get FacilityNu mber();
  1762           }
  1763  
  1764           re turn ret;
  1765       }
  1766  
  1767       privat e String g etAssignin gAuthority Id()
  1768       {
  1769           re turn prope rtyLookup. getPropert y("Assigni ngAuthorit y");
  1770       }
  1771  
  1772       privat e String c reateFullN ame(Person NameType p ersonName)
  1773       {
  1774           St ringBuilde r ret = ne w StringBu ilder();
  1775  
  1776           if  (NullChec ker.isNotN ullOrEmpty (personNam e.getGiven Name())) {
  1777                ret.appe nd(personN ame.getGiv enName());
  1778           }
  1779  
  1780           if  (NullChec ker.isNotN ullOrEmpty (personNam e.getSecon dNameOrIni tials()))  {
  1781                if (ret. length() >  0) {
  1782                    ret. append(' ' );
  1783                }
  1784                ret.appe nd(personN ame.getSec ondNameOrI nitials()) ;
  1785           }
  1786  
  1787           if  (NullChec ker.isNotN ullOrEmpty (personNam e.getFamil yName()))  {
  1788                if (ret. length() >  0) {
  1789                    ret. append(' ' );
  1790                }
  1791                ret.appe nd(personN ame.getFam ilyName()) ;
  1792           }
  1793  
  1794           re turn ret.t oString();
  1795       }
  1796  
  1797       privat e void aud itACPDocum ent(Assert ionType as sertion, R etrieveDoc umentSetRe sponseType  body, Das OperationS endACPDocu mentRespon se respons e)
  1798       {
  1799           lo gger.info( "In auditA CPDocument ...");
  1800  
  1801           //  create re cord in th e DOCUMENT  table
  1802           Do cument doc ument = ne w Document ();
  1803  
  1804           by te[] acpBy tes = getD ocumentAsB ytes(body. getDocumen tResponse( ).get(0).g etDocument ());
  1805           do cument.set DocumentUn iqueId(res ponse.getD ocId());
  1806           do cument.set RawData(ac pBytes);
  1807           do cument.set Size(acpBy tes.length );
  1808           do cument.set Availabili tyStatus(" urn:oasis: names:tc:e bxmlregrep :StatusTyp e:Approved ");
  1809           do cument.set LastAccess edTime(new  Date());
  1810           do cument.set CreationTi me(new Dat e());
  1811           do cument.set ClassCode( "57016-8") ;
  1812           do cument.set ClassCodeD isplayName ("Privacy  Policy Ack nowledgeme nt");
  1813           do cument.set ClassCodeS cheme("1.3 .6.1.4.1.1 9376.1.2.3 ");
  1814           do cument.set MimeType(" text/xml") ;
  1815           do cument.set PatientId( assertion. getUniqueP atientId() .get(0));
  1816           do cument.set FormatCode DisplayNam e("Privacy  Policy Ac knowledgem ent");
  1817           do cument.set SourcePati entId(asse rtion.getU niquePatie ntId().get (0));
  1818           do cument.set PatientSSN (assertion .getSSN()) ;
  1819  
  1820           if  (NullChec ker.isNotN ullOrEmpty (assertion .getUserIn fo())) {
  1821  
  1822                if (Null Checker.is NotNullOrE mpty(asser tion.getUs erInfo().g etOrg()))  {
  1823                    // d ocument.se tPatientPr eferredFac ilityNumbe r(assertio n.getUserI nfo().getO rg().getHo meCommunit yId());
  1824                    docu ment.setPa tientPrefe rredFacili tyName(ass ertion.get UserInfo() .getOrg(). getName()) ;
  1825                }
  1826  
  1827                if (Null Checker.is NotNullOrE mpty(asser tion.getUs erInfo().g etPersonNa me())) {
  1828                    Pers onNameType  userName  = assertio n.getUserI nfo().getP ersonName( );
  1829                    docu ment.setPa tientGiven Name(userN ame.getGiv enName());
  1830                    docu ment.setPa tientLastN ame(userNa me.getFami lyName());
  1831                }
  1832           }
  1833           lo gger.info( "Document  object suc cessfully  created");
  1834           do cumentRepo sitory.sto reDocument (document) ;
  1835           lo gger.info( "Document  stored to  DAS");
  1836  
  1837           lo gger.info( "Building  audit obje ct for doc ument subm ission..." );
  1838           //  create re cord in th e AUDIT ta ble
  1839           Au dit audit  = new Audi t();
  1840  
  1841           au dit.setAct ion("Docum entSubmiss ionIn");
  1842           au dit.setAud itTime(new  Date());
  1843           au dit.setDoc umentId(do cument.get DocumentUn iqueId());
  1844           au dit.setRem oteDocumen tId(docume nt.getDocu mentUnique Id());
  1845           //  audit.set RemoteDocu mentReposi toryId(d.g etReposito ryUniqueId ());
  1846           au dit.setRem oteOrganiz ationId(ge tHomeCommu nityId(ass ertion));
  1847  
  1848           if  (NullChec ker.isNotN ullOrEmpty (assertion .getUserIn fo())) {
  1849                audit.se tUserId(as sertion.ge tUserInfo( ).getUserN ame());
  1850  
  1851                if (Null Checker.is NotNullOrE mpty(asser tion.getUs erInfo().g etRoleCode d())) {
  1852                    audi t.setUserR ole(assert ion.getUse rInfo().ge tRoleCoded ().getCode ());
  1853                }
  1854  
  1855                if (Null Checker.is NotNullOrE mpty(asser tion.getUs erInfo().g etOrg()))  {
  1856                    audi t.setUserF acilityNum ber(assert ion.getUse rInfo().ge tOrg().get HomeCommun ityId());
  1857                    audi t.setUserF acilityNam e(assertio n.getUserI nfo().getO rg().getNa me());
  1858                }
  1859  
  1860                if (Null Checker.is NotNullOrE mpty(asser tion.getUs erInfo().g etPersonNa me())) {
  1861                    Pers onNameType  userName  = assertio n.getUserI nfo().getP ersonName( );
  1862                    if ( !NullCheck er.isNullO rEmpty(use rName.getF ullName()) ) {
  1863                         audit.setU serName(us erName.get FullName() );
  1864                    }
  1865                    else  {
  1866                         audit.setU serName(us erName.get GivenName( ) + " " +  userName.g etFamilyNa me());
  1867                    }
  1868                }
  1869           }
  1870  
  1871           if  (NullChec ker.isNotN ullOrEmpty (assertion .getPurpos eOfDisclos ureCoded() )) {
  1872                audit.se tPurposeFo rUse(asser tion.getPu rposeOfDis closureCod ed().getCo de());
  1873           }
  1874  
  1875           au dit.setSys temId(Audi tUtil.chec kSystemId( assertion) );
  1876  
  1877           au dit.setOrg anizationI d(getHomeC ommunityId (assertion ));
  1878           au dit.setPat ientId(ass ertion.get UniquePati entId().ge t(0));
  1879           au dit.setPat ientSSN(do cument.get PatientSSN ());
  1880           if  (NullChec ker.isNotN ullOrEmpty (assertion .getPerson Name())) {
  1881                audit.se tPatientGi venName(as sertion.ge tPersonNam e().getGiv enName());
  1882                audit.se tPatientLa stName(ass ertion.get PersonName ().getFami lyName());
  1883           }
  1884           au dit.setPat ientFacili tyNumber(g etHomeFaci lity(getHo meCommunit yId(assert ion)).getF acilityNum ber());
  1885           au dit.setPat ientFacili tyName(get HomeFacili ty(getHome CommunityI d(assertio n)).getFac ilityName( ));
  1886  
  1887           au dit.setDet ails("VLER  DAS Doc I d: " + res ponse.getD ocId());
  1888           lo gger.info( "Audit obj ect create d");
  1889  
  1890           au ditManager .storeAudi t(audit);
  1891           lo gger.info( "Audit sto red");
  1892       }
  1893  
  1894       privat e byte[] g etDocument AsBytes(Da taHandler  doc)
  1895       {
  1896           if  (NullChec ker.isNull OrEmpty(do c)) {
  1897                logger.e rror("Docu ment secti on is empt y");
  1898                return n ull;
  1899           }
  1900  
  1901           by te[] docBy tes = null ;
  1902           In putStream  is = null;
  1903           tr y {
  1904                is = doc .getInputS tream();
  1905                InputStr eamReader  isr = new  InputStrea mReader(is );
  1906                // Strin g encoding  = isr.get Encoding() ;
  1907                docBytes  = IOUtils .toByteArr ay(isr);
  1908           }
  1909           ca tch (IOExc eption e)  {
  1910                logger.e rror("Erro r getting  Document f rom Provid eAndRegist erDocument Set");
  1911                return n ull;
  1912           }
  1913           //  fix for f ortify iss ue - Unrel eased Reso urce: Stre ams RTC ti cket #
  1914           //  163005
  1915           fi nally {
  1916                if (is ! = null) {
  1917                    try  {
  1918                         is.close() ;
  1919                    }
  1920                    catc h (IOExcep tion e) {
  1921                         logger.err or("Error  getting Do cument fro m ProvideA ndRegister DocumentSe t");
  1922                    }
  1923                }
  1924           }
  1925  
  1926           if  (NullChec ker.isNull OrEmpty(do cBytes)) {
  1927                logger.e rror("Docu ment conte nt is empt y");
  1928                return n ull;
  1929           }
  1930  
  1931           re turn docBy tes;
  1932       }
  1933   }