224. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 6/9/2017 3:45:44 PM Eastern 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.

224.1 Files compared

# Location File Last Modified
1 eHealth_Exch (eHealth Exchange Enhancements) Build 3 docs & code_May_2017.zip\eHXE_Build3_2017-05-04.zip\NHIN_adapter\AdapterEJB\src\main\java\gov\va\med\nhin\adapter\patientdiscovery AdapterPatientDiscovery.java Wed May 3 15:58:46 2017 UTC
2 eHealth_Exch (eHealth Exchange Enhancements) Build 3 docs & code_May_2017.zip\eHXE_Build3_2017-05-04.zip\NHIN_adapter\AdapterEJB\src\main\java\gov\va\med\nhin\adapter\patientdiscovery AdapterPatientDiscovery.java Thu Jun 1 21:38:38 2017 UTC

224.2 Comparison summary

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

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

224.4 Active regular expressions

No regular expressions were active.

224.5 Comparison detail

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