44. EPMO Open Source Coordination Office Redaction File Detail Report

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

44.1 Files compared

# Location File Last Modified
1 C:\working_scrub\Unredacted\eHX Code Base\eHX_Bld2_Source Code_CIF_2017-02-14\NHIN_adapter\AdapterEJB\src\main\java\gov\va\med\nhin\adapter\patientdiscovery AdapterPatientDiscovery.java Fri Feb 10 15:41:44 2017 UTC
2 eHX-CIF.zip\eHX-CIF\eHX Code Base\eHX_Bld2_Source Code_CIF_2017-02-14\NHIN_adapter\AdapterEJB\src\main\java\gov\va\med\nhin\adapter\patientdiscovery AdapterPatientDiscovery.java Tue Apr 4 12:53:58 2017 UTC

44.2 Comparison summary

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