3918. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 6/9/2017 3:50:58 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.

3918.1 Files compared

# Location File Last Modified
1 Fri Jun 9 19:50:58 2017 UTC
2 eHealth_Exch (eHealth Exchange Enhancements) Build 3 docs & code_May_2017.zip\VAP_CIF_CODE0502.zip\VAP_CIF_CODE0502\VAP_CIF_CODE0502\nvap-server\src\main\java\gov\va\nvap\server\service\privacy ConsentManagementServiceImpl.java Fri Apr 21 20:15:58 2017 UTC

3918.2 Comparison summary

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

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

3918.4 Active regular expressions

No regular expressions were active.

3918.5 Comparison detail

        1   package go v.va.nvap. server.ser vice.priva cy;
        2  
        3   import gov .va.nvap.c ommon.date .hl7.HL7Da teUtil;
        4   import gov .va.nvap.c ommon.endp oint.Endpo int;
        5   import gov .va.nvap.c ommon.endp oint.Endpo intExcepti on;
        6   import gov .va.nvap.c ommon.inte rceptor.In terceptor;
        7   import gov .va.nvap.c ommon.inte rceptor.In terceptorE xception;
        8   import gov .va.nvap.c ommon.jaxb .JaxbUtil;
        9   import gov .va.nvap.c ommon.tran sformer.Tr ansformer;
        10   import gov .va.nvap.c ommon.tran sformer.Tr ansformerE xception;
        11   import gov .va.nvap.c ommon.tran sformer.xm l.StringTo XML;
        12   import gov .va.nvap.c ommon.tran sformer.xm l.XMLToStr ing;
        13   import gov .va.nvap.c ommon.util .DocumentB uilderFact oryUtil;
        14   import gov .va.nvap.c ommon.uuid .UUIDUtil;
        15   import gov .va.nvap.c ommon.vali dation.Ass ert;
        16   import gov .va.nvap.c ommon.vali dation.Nul lChecker;
        17   import gov .va.nvap.p rivacy.*;
        18   import gov .va.nvap.p rivacy.dat a.ConsentD irectiveDa ta;
        19   import gov .va.nvap.s erver.endp oint.psim. PersonServ iceInterfa ce;
        20   import gov .va.nvap.s ervice.aud it.AuditSe rvice;
        21   import gov .va.nvap.s ervice.aud it.data.Co nsentAudit ;
        22   import gov .va.nvap.s ervice.pdq .PatientDe mographics ;
        23   import gov .va.nvap.s ervice.pdq .PatientDe mographics Query;
        24   import gov .va.nvap.s ervice.pdq .PatientDe mographics Response;
        25   import gov .va.nvap.s ervice.pdq .PdqExcept ion;
        26   import gov .va.nvap.s ervice.pdq .PdqServic e;
        27   import gov .va.nvap.s ervice.pri vacy.Conse ntManageme ntService;
        28   import gov .va.nvap.s ervice.pri vacy.Conse ntManageme ntServiceE xception;
        29   import gov .va.nvap.s vc.consent mgmt.PIPIn terface;
        30   import gov .va.nvap.s vc.consent mgmt.Polic yConstrain ts;
        31   import gov .va.nvap.s vc.consent mgmt.stub. FacilityRe solver;
        32   import gov .va.nvap.s vc.consent mgmt.stub. adapter.an nounce.dat a.Announce ment;
        33   import gov .va.nvap.s vc.consent mgmt.stub. adapter.an nounce.dat a.Announce mentOrg;
        34   import gov .va.nvap.s vc.consent mgmt.stub. adapter.an nounce.dat a.Announce rInterface ;
        35   import gov .va.nvap.s vc.consent mgmt.stub. adapter.an nounce.dat a.PatientA nnouncer;
        36   import gov .va.nvap.s vc.consent mgmt.stub. adapter.an nounce.dat a.PatientA nnouncerEx ception;
        37   import gov .va.nvap.s vc.consent mgmt.stub. adapter.an nounce.jax b.Announce PatientReq uest;
        38   import gov .va.nvap.s vc.consent mgmt.stub. adapter.an nounce.jax b.Authoriz edOrganiza tionType;
        39   import gov .va.nvap.s vc.consent mgmt.stub. adapter.an nounce.jax b.PatientT ype;
        40   import gov .va.nvap.s vc.consent mgmt.stub. adapter.an nounce.jax b.UserType ;
        41   import gov .va.nvap.s vc.consent mgmt.stub. dao.Delaye dConsentDA O;
        42   import gov .va.nvap.s vc.consent mgmt.stub. data.Conse ntDirectiv e;
        43   import gov .va.nvap.s vc.consent mgmt.stub. data.Delay edConsent;
        44   import gov .va.nvap.s vc.consent mgmt.stub. data.Detai ledConsent Directive;
        45   import gov .va.nvap.s vc.consent mgmt.stub. data.Facil ityOptInCo nsent;
        46   import gov .va.nvap.s vc.consent mgmt.stub. data.Optou tReason;
        47   import gov .va.nvap.s vc.consent mgmt.stub. data.Organ ization;
        48   import gov .va.nvap.s vc.consent mgmt.stub. data.Patie ntDocument ;
        49   import gov .va.nvap.s vc.consent mgmt.stub. data.Patie ntDocument Type;
        50   import gov .va.nvap.s vc.consent mgmt.stub. data.Purpo seOfUse;
        51   import jav a.io.ByteA rrayInputS tream;
        52   import jav a.io.IOExc eption;
        53   import jav a.io.Input Stream;
        54   import jav a.io.Unsup portedEnco dingExcept ion;
        55   import jav a.text.Par seExceptio n;
        56   import jav a.util.*;
        57  
        58   import sta tic java.u til.Calend ar.DAY_OF_ MONTH;
        59  
        60   import jav a.util.log ging.Level ;
        61   import jav a.util.log ging.Logge r;
        62   import jav ax.xml.bin d.JAXBCont ext;
        63   import jav ax.xml.bin d.JAXBExce ption;
        64   import jav ax.xml.bin d.Unmarsha ller;
        65   import jav ax.xml.par sers.Docum entBuilder ;
        66   import jav ax.xml.par sers.Docum entBuilder Factory;
        67   import jav ax.xml.par sers.Parse rConfigura tionExcept ion;
        68   import jav ax.xml.tra nsform.dom .DOMSource ;
        69   import org .apache.co mmons.lang .time.Date Utils;
        70   import org .dozer.Map per;
        71   import org .springfra mework.bea ns.factory .Initializ ingBean;
        72   import org .springfra mework.bea ns.factory .annotatio n.Required ;
        73   import org .springfra mework.oxm .jaxb.Jaxb 2Marshalle r;
        74   import org .w3c.dom.D ocument;
        75   import org .xml.sax.S AXExceptio n;
        76  
        77   /**
        78    * The imp lementatio n of the c onsent man agement se rvice.
        79    *
        80    * @author  Asha Amri traj
        81    * @author  Zack Pete rson
        82    *
        83    */
        84   public cla ss Consent Management ServiceImp l implemen ts Consent Management Service,
        85           In itializing Bean
        86   {
        87  
        88       privat e static f inal Logge r logger
        89                = Logger .getLogger (ConsentMa nagementSe rviceImpl. class.getN ame());
        90  
        91       privat e static f inal boole an SEQUENT IAL_ANNOUN CE = false ;
        92  
        93       privat e Transfor mer<Announ cement, An nouncePati entRequest > announce mentToAnno uncePatien tRequest;
        94  
        95       /**
        96        * The  patient a nnouncer o bject.
        97        */
        98       privat e Announce rInterface  announcer ;
        99       /**
        100        * Mar shall/Unma rshall the  ConsentDi rective ty pes.
        101        */
        102       privat e Jaxb2Mar shaller cm sJaxb2Mars haller;
        103       /**
        104        * Aud it the CDA  R2 XML Pr ivacy Cons ent Direct ive forms.
        105        */
        106       privat e Intercep tor<Object , Object>  consentDir ectiveDocu mentAuditI nterceptor ;
        107       /**
        108        * Con vert the c onsent dir ective CDA  R2 Docume nt to
        109        * Con sentDirect iveAuthori zationResp onse.
        110        */
        111       privat e Transfor mer<Docume nt, Docume nt> consen tDirective DocumentTo Authorizat ionRespons e;
        112       /**
        113        * Con vert to th e intermed iate forma t.
        114        */
        115       privat e Transfor mer<Docume nt, Docume nt> consen tDirective DocumentTo Data;
        116       /**
        117        * Tra nsformer t o transfor m from the  value obj ect to CDA  R2 XML do cument.
        118        */
        119       privat e Transfor mer<Docume nt, Docume nt> dataTo ConsentDir ectiveDocu ment;
        120       /**
        121        * Con vert the c onsent dir ective CDA  R2 Docume nt to
        122        * Con sentDirect iveRevocat ionRespons e.
        123        */
        124       privat e Transfor mer<Docume nt, Docume nt> consen tDirective DocumentTo Revocation Response;
        125       /**
        126        * The  marshalle r to conve rt from Co nsentDirec tiveData X ML to Obje cts.
        127        */
        128       privat e JaxbUtil  dataJaxb2 Marshaller ;
        129       /*
        130        * Fac ility Reso lver
        131        */
        132       privat e Facility Resolver f acilityRes olver;
        133  
        134       /**
        135        * Doz er mapper  to convert  from web  services t ypes to PI P types.
        136        */
        137       privat e Mapper m apper;
        138       /**
        139        * Kee p a copy o f the Opto utReason t ype collec tions. So  we dont ha ve to go
        140        * to  the PIP ev erytime.
        141        */
        142       privat e Collecti on<OptoutR eason> opt OutReasons ;
        143       /**
        144        * Ann ounce pati ents over  the NwHIN.  Called du ring the A uthorizati on.
        145        */
        146       privat e PatientA nnouncer p atientAnno uncer;
        147       // Sto re for per formance
        148       /**
        149        * Kee p a copy o f the Pati entDocumen Type colle ctions. So  we dont h ave to go
        150        * to  the PIP ev erytime.
        151        */
        152       privat e Collecti on<Patient DocumentTy pe> patien tDocumenTy pes;
        153       /**
        154        * Per son Servic e
        155        */
        156       privat e PersonSe rviceInter face perso nService;
        157       /**
        158        * Per son Servic e
        159        */
        160       privat e PdqServi ce pdqServ ice;
        161       /**
        162        * The  policy in formation  point.
        163        */
        164       privat e PIPInter face pip;
        165       /**
        166        * Tra nsforming  from Strin g CDA R2 X ML to Docu ment objec t.
        167        */
        168       privat e StringTo XML string ToXML;
        169       /**
        170        * XML  to String  Transform er.
        171        */
        172       privat e XMLToStr ing xmlToS tring;
        173  
        174       public  void setX mlToString (XMLToStri ng xmlToSt ring)
        175       {
        176           th is.xmlToSt ring = xml ToString;
        177       }
        178  
        179       privat e DelayedC onsentDAO  delayedCon sentDAO;
        180  
        181       /**
        182        * Ref erence to  the audit  service.
        183        */
        184       privat e AuditSer vice audit Service;
        185  
        186       @Overr ide
        187       public  void afte rPropertie sSet() thr ows Except ion
        188       {
        189           //  Update in formation  into the c ache
        190           th is.patient DocumenTyp es = this. pip.getPat ientDocume ntTypes();
        191           th is.optOutR easons = t his.pip.ge tOptoutRea sons();
        192       }
        193  
        194       /*
        195        * @de precated a s of VAP 2 .1. Please  do not us e - AMS
        196        */
        197       privat e Collecti on<Organiz ation> get Authorized Organizati ons(
        198                final Co nsentDirec tive conse ntDirectiv e)
        199       {
        200  
        201           fi nal List<O rganizatio n> optedIn Organizati ons = new  ArrayList< Organizati on>();
        202           //  select on ly to auth orized org anizations
        203  
        204           //  Get Restr iction Con sent Type
        205           fi nal gov.va .nvap.svc. consentmgm t.stub.dat a.ConsentT ype type =  this.pip
        206                    .get ConsentTyp eByName(Co nsentType. NW_HIN_ORG ANIZATION_ RESTRICTIO N_AUTHORIZ ATION.valu e());
        207           //  Get Patie nt IENs
        208           fi nal List<S tring> pat ientIens =  new Array List<Strin g>();
        209           pa tientIens. add(consen tDirective .getPatien tIen());
        210  
        211           fi nal Consen tDirective  restricti on = this. pip
        212                    .get ActiveCons entDirecti ve(patient Iens, type );
        213           //  If no res trictions  or no orgs , return 
        214           if  (NullChec ker.isEmpt y(restrict ion)
        215                    || N ullChecker .isEmpty(r estriction .getExclud edOrganiza tions()))  {
        216                return t his.pip
        217                         .getAllowe dOrganizat ions();
        218           }
        219  
        220           fo r (final O rganizatio n allowedO rganizatio n : this.p ip
        221                    .get AllowedOrg anizations ()) {
        222                boolean  toExclude  = false;
        223                if (Null Checker.is NotEmpty(r estriction
        224                         .getExclud edOrganiza tions()))  {
        225                    for  (final Org anization  excludedOr ganization  : restric tion
        226                             .getEx cludedOrga nizations( )) {
        227                         if (allowe dOrganizat ion.getOrg Number().e quals(
        228                                 ex cludedOrga nization.g etOrgNumbe r())) {
        229                             toExcl ude = true ;
        230                             break;
        231                         }
        232                    }
        233                    if ( !toExclude ) {
        234                         optedInOrg anizations .add(allow edOrganiza tion);
        235                    }
        236                }
        237                else {
        238                    opte dInOrganiz ations.add (allowedOr ganization );
        239                }
        240           }
        241           re turn opted InOrganiza tions;
        242       }
        243  
        244       @Overr ide
        245       public  ConsentDi rectiveDoc umentRetri eveRespons e getConse ntDirectiv eDocuments (
        246                final Co nsentDirec tiveDocume ntRetrieve Request co nsentDirec tiveDocume ntRetrieve Request)
        247                throws C onsentMana gementServ iceExcepti on
        248       {
        249  
        250           if  (NullChec ker.isEmpt y(consentD irectiveDo cumentRetr ieveReques t)) {
        251                throw ne w ConsentM anagementS erviceExce ption("Err or: Consen tDirective DocumentRe trieveRequ est cannot  be null") ;
        252           }
        253           if  (NullChec ker.isEmpt y(consentD irectiveDo cumentRetr ieveReques t.getConse ntDirectiv eReference ())) {
        254                throw ne w ConsentM anagementS erviceExce ption("Err or: Consen tDirective DocumentRe ference ca nnot be nu ll");
        255           }
        256  
        257           //  Get the C onsentDire ctive from  the Conse ntDirectiv eReference
        258           fi nal Consen tDirective ReferenceT ype refere nce = cons entDirecti veDocument RetrieveRe quest.getC onsentDire ctiveRefer ence();
        259           Co nsentDirec tiveDocume ntType typ e = consen tDirective DocumentRe trieveRequ est.getDoc umentType( );
        260  
        261           if  (NullChec ker.isEmpt y(referenc e.getConse ntDirId()) ) {
        262                throw ne w ConsentM anagementS erviceExce ption("Err or: Consen t Dir Id c annot be n ull. Pleas e ensure i t is non-n ull and na mespaced") ;
        263           }
        264           //  Temporary  Solution  - till the  interface s for CMS  are cleane d up, ther e is no se nse creati ng more do zer mappin gs
        265           //  Unnecessa ry element s to query  the conse nt directi ve documen ts will ju st be set  to null
        266           re ference.se tPurposeOf Use(null);
        267           re ference.se tOptinCons entType(nu ll);
        268           re ference.se tOptoutCon sentType(n ull);
        269           re ference.se tOptoutRea son(null);
        270           // done 
        271           fi nal Consen tDirective  consentDi rective =  this.mappe r.map(refe rence, Con sentDirect ive.class) ;
        272           //  Assume AL L if type  is not spe cified
        273           if  (NullChec ker.isEmpt y(type)) {
        274                type = C onsentDire ctiveDocum entType.AL L;
        275           }
        276           //  Lookup th e PatientD ocumentTyp e
        277           fi nal Patien tDocumentT ype curren tType = th is.getPati entDocumen tType(type .value());
        278  
        279           fi nal List<b yte[]> doc uments = n ew ArrayLi st<byte[]> ();
        280           //  Get all t he documen ts if type  is not pr esent
        281           if  (NullChec ker.isEmpt y(currentT ype)) {
        282                final Co llection<P atientDocu ment> pati entDocumen ts = this. pip.getCon sentDirect iveDocumen ts(consent Directive) ;
        283                if (Null Checker.is NotEmpty(p atientDocu ments)) {
        284                    for  (final Pat ientDocume nt patient Document :  patientDo cuments) {
        285                         if (NullCh ecker.isNo tEmpty(pat ientDocume nt)) {
        286                             if (!N ullChecker .isNullOrE mpty(patie ntDocument .getExtern alDocument Id())) {
        287                                 do cuments.ad d(patientD ocument.ge tExternalD ocumentId( ).getBytes ());
        288                             }
        289                             else i f (!NullCh ecker.isNu llOrEmpty( patientDoc ument.getD ocument()) ) {
        290                                 do cuments.ad d(patientD ocument.ge tDocument( ).toString ().getByte s());
        291                             }
        292                         }
        293                    }
        294                }
        295           }
        296           el se {
        297                // Get o nly the ty pe of docu ment speci fied
        298                final Pa tientDocum ent patien tDocument  = this.pip .getConsen tDirective DocumentBy Type(conse ntDirectiv e, current Type);
        299                if (Null Checker.is NotEmpty(p atientDocu ment)) {
        300                    if ( !NullCheck er.isNullO rEmpty(pat ientDocume nt.getExte rnalDocume ntId())) {
        301                         documents. add(patien tDocument. getExterna lDocumentI d().getByt es());
        302                    }
        303                    else  if (!Null Checker.is NullOrEmpt y(patientD ocument.ge tDocument( ))) {
        304                         documents. add(patien tDocument. getDocumen t().toStri ng().getBy tes());
        305                    }
        306                }
        307           }
        308           //  Make the  response a nd return
        309           fi nal Consen tDirective DocumentRe trieveResp onse respo nse = new  ConsentDir ectiveDocu mentRetrie veResponse ();
        310           re sponse.get Documents( ).addAll(d ocuments);
        311           re turn respo nse;
        312       }
        313  
        314       @Overr ide
        315       public  ConsentDi rectiveDet ailedExpir ationRespo nse getAll ExpiringCo nsentDirec tives(
        316                final Co nsentDirec tiveDetail edExpirati onRequest  consentDir ectiveExpi rationRequ est)
        317                throws C onsentMana gementServ iceExcepti on
        318       {
        319  
        320           if  (consentD irectiveEx pirationRe quest.getD ayRange()  < -1) {
        321                throw ne w ConsentM anagementS erviceExce ption("Err or: Day ra nge cannot  be negati ve");
        322           }
        323  
        324           //  Get expir ing active  consent d irectives
        325           fi nal Collec tion<Conse ntDirectiv e> consent Directives  = this.pi p.getExpir ingPatient ConsentDir ectives(nu ll, consen tDirective Expiration Request);
        326  
        327           //  Convert t o the PIP  consent di rective
        328           fi nal Collec tion<Conse ntDirectiv eReference Type> cons entDirecti veReferenc es = new A rrayList<C onsentDire ctiveRefer enceType>( );
        329           fi nal Collec tion<Patie ntDemograp hics> pati entDemogra phicsRefer ences = ne w ArrayLis t<PatientD emographic s>();
        330           fi nal Consen tDirective DetailedEx pirationRe sponse res ponse = ne w ConsentD irectiveDe tailedExpi rationResp onse();
        331           Lo ng totalRo ws = new L ong(0);
        332  
        333           fo r (final C onsentDire ctive cd :  consentDi rectives)  {
        334                if (Null Checker.is NotEmpty(c d)) {
        335                    //Fo r paginati on
        336                    tota lRows = cd .getTotalR ows();
        337  
        338                    fina l ConsentD irectiveRe ferenceTyp e referenc e = this.m apper.map( cd, Consen tDirective ReferenceT ype.class) ;
        339                    cons entDirecti veReferenc es.add(ref erence);
        340  
        341                    fina l String i en = refer ence.getPa tientIen() ;
        342                    // A ssumes tha t there is  only one  icn for ev ery ien
        343                    fina l String i cn = this. personServ ice.getCor relatedIds (ien).get( 0);
        344  
        345                    Pati entDemogra phicsQuery  demograph icsQuery =  new Patie ntDemograp hicsQuery( );
        346                    demo graphicsQu ery.setPat ientId(icn );
        347  
        348                    Pati entDemogra phicsRespo nse demogr aphicsResp onse = new  PatientDe mographics Response() ;
        349                    try  {
        350                         demographi csResponse  = this.pd qService.g etPatientD emographic s(demograp hicsQuery) ;
        351                         patientDem ographicsR eferences. add(demogr aphicsResp onse.getPa tientDemog raphics()) ;
        352                    }
        353                    catc h (PdqExce ption e) {
        354                         // TODO: H andle Exce ption
        355                    }
        356                    catc h (Runtime Exception  e) { //Cat ches if ic n does not  exist
        357                         patientDem ographicsR eferences. add(new Pa tientDemog raphics()) ;
        358                    }
        359                }
        360           }
        361  
        362           if  (NullChec ker.isNotE mpty(conse ntDirectiv eReference s)) {
        363                response .getConsen tDirective Reference( ).addAll(c onsentDire ctiveRefer ences);
        364           }
        365           if  (NullChec ker.isNotE mpty(patie ntDemograp hicsRefere nces)) {
        366                response .getPatien tDemograph icsReferen ce().addAl l(patientD emographic sReference s);
        367           }
        368  
        369           re sponse.set TotalRows( totalRows) ;
        370  
        371           re turn respo nse;
        372       }
        373  
        374       @Overr ide
        375       public  ConsentDi rectiveDet ailedExpir ationRespo nse getAll ExpiringDe tailedCons entDirecti ves(
        376                final Co nsentDirec tiveDetail edExpirati onRequest  consentDir ectiveExpi rationRequ est)
        377                throws C onsentMana gementServ iceExcepti on
        378       {
        379  
        380           //  Get expir ing active  consent d irectives
        381           fi nal Collec tion<Detai ledConsent Directive>  consentDi rectives =  this.pip. getExpirin gPatientDe tailedCons entDirecti ves(consen tDirective Expiration Request);
        382  
        383           //  Convert t o the PIP  consent di rective
        384           fi nal Collec tion<Detai ledConsent DirectiveR eferenceTy pe> consen tDirective References  = new Arr ayList<Det ailedConse ntDirectiv eReference Type>();
        385           fi nal Consen tDirective DetailedEx pirationRe sponse res ponse = ne w ConsentD irectiveDe tailedExpi rationResp onse();
        386           Lo ng totalRo ws = (long ) 0;
        387  
        388           fo r (final D etailedCon sentDirect ive cd : c onsentDire ctives) {
        389                if (Null Checker.is NotEmpty(c d)) {
        390                    //Fo r paginati on
        391                    tota lRows = cd .getTotalR ows();
        392  
        393                    fina l Detailed ConsentDir ectiveRefe renceType  reference  = this.map per.map(cd , Detailed ConsentDir ectiveRefe renceType. class);
        394                    cons entDirecti veReferenc es.add(ref erence);
        395                }
        396           }
        397  
        398           if  (NullChec ker.isNotE mpty(conse ntDirectiv eReference s)) {
        399                response .getDetail edConsentD irectiveRe ference(). addAll(con sentDirect iveReferen ces);
        400           }
        401  
        402           re sponse.set TotalRows( totalRows) ;
        403  
        404           re turn respo nse;
        405       }
        406  
        407       @Overr ide
        408       public  ConsentDi rectiveDet ailedExpir ationRespo nse getAut horizedCon sentForSum mary(
        409                final Co nsentDirec tiveDetail edExpirati onRequest  consentDir ectiveExpi rationRequ est)
        410                throws C onsentMana gementServ iceExcepti on
        411       {
        412  
        413           //  Get expir ing active  consent d irectives
        414           fi nal Collec tion<Facil ityOptInCo nsent> con sentDirect ives = thi s.pip.getA uthorizedC onsentForS ummary();
        415  
        416           //  Convert t o the PIP  consent di rective
        417           fi nal Collec tion<Facil ityOptInCo nsentType>  consentDi rectiveRef erences =  new ArrayL ist<Facili tyOptInCon sentType>( );
        418           fi nal Consen tDirective DetailedEx pirationRe sponse res ponse = ne w ConsentD irectiveDe tailedExpi rationResp onse();
        419  
        420           fo r (final F acilityOpt InConsent  cd : conse ntDirectiv es) {
        421                if (Null Checker.is NotEmpty(c d)) {
        422                    fina l Facility OptInConse ntType ref erence = t his.mapper .map(cd, F acilityOpt InConsentT ype.class) ;
        423                    cons entDirecti veReferenc es.add(ref erence);
        424                }
        425           }
        426  
        427           if  (NullChec ker.isNotE mpty(conse ntDirectiv eReference s)) {
        428                response .getFacili tyOptInCon sentRefere nce().addA ll(consent DirectiveR eferences) ;
        429           }
        430  
        431           re turn respo nse;
        432       }
        433  
        434       @Overr ide
        435       public  ConsentDi rectiveQue ryResponse  getConsen tDirective s(
        436                final Co nsentDirec tiveQueryR equest con sentDirect iveQueryRe quest)
        437                throws C onsentMana gementServ iceExcepti on
        438       {
        439           if  (NullChec ker.isEmpt y(consentD irectiveQu eryRequest )) {
        440                throw ne w ConsentM anagementS erviceExce ption("Err or: Consen tDirective QueryReque st cannot  be null");
        441           }
        442           if  (NullChec ker.isEmpt y(consentD irectiveQu eryRequest .getPatien tId())) {
        443                throw ne w ConsentM anagementS erviceExce ption("Err or: Patien t ID canno t be null" );
        444           }
        445  
        446           St ring conse ntType = " ";
        447           if  (NullChec ker.isNotE mpty(conse ntDirectiv eQueryRequ est.getSer viceConsum erContext( ))
        448                    && N ullChecker .isNotEmpt y(consentD irectiveQu eryRequest .getServic eConsumerC ontext().g etConsentT ype())) {
        449                consentT ype = cons entDirecti veQueryReq uest.getSe rviceConsu merContext ().getCons entType(). value();
        450           }
        451  
        452           //  Get the a ctive cons ent direct ive
        453           fi nal String  patientId  = consent DirectiveQ ueryReques t.getPatie ntId();
        454  
        455           //  Skip corr elation if  SSA
        456           Li st<String>  patientIe ns = new A rrayList<S tring>();
        457           if  (consentT ype.equals (ConsentTy pe.SSA_AUT HORIZATION .value()))  {
        458                patientI ens.add(pa tientId);
        459           }
        460           el se {
        461                patientI ens = this .personSer vice.getCo rrelatedId s(patientI d);
        462           }
        463  
        464           fi nal Collec tion<Conse ntDirectiv e> consent Directives  = new Arr ayList<Con sentDirect ive>();
        465           if  (NullChec ker.isNotE mpty(conse ntDirectiv eQueryRequ est.getQue ryParam())
        466                    && c onsentDire ctiveQuery Request.ge tQueryPara m().equals (ConsentDi rectiveQue ryParamTyp e.ACTIVE))  {
        467                // TODO:  Optimize
        468                if (Null Checker.is Empty(cons entType))  {
        469                    for  (final Con sentType t ype : Cons entType.va lues()) {
        470                         final Cons entDirecti ve consent Directive  = this.pip .getActive ConsentDir ective(pat ientIens,  this.pip.g etConsentT ypeByName( type.value ()));
        471                         if (NullCh ecker.isNo tEmpty(con sentDirect ive)) {
        472                             consen tDirective s.add(cons entDirecti ve);
        473                         }
        474                    }
        475                }
        476                else {
        477                    fina l ConsentD irective c onsentDire ctive = th is.pip.get ActiveCons entDirecti ve(patient Iens, this .pip.getCo nsentTypeB yName(cons entType));
        478                    if ( NullChecke r.isNotEmp ty(consent Directive) ) {
        479                         consentDir ectives.ad d(consentD irective);
        480                    }
        481                }
        482                if (Null Checker.is Empty(cons entDirecti ves)) {
        483                    retu rn new Con sentDirect iveQueryRe sponse();
        484                }
        485           }  // Get all  consent d irectives
        486           el se {
        487                Collecti on<Consent Directive>  allConsen tDirective s = new Ar rayList<Co nsentDirec tive>();
        488                allConse ntDirectiv es = this. pip.getCon sentHistor y(patientI ens);
        489                // Filte r only the  consent d irectives  requested  by consent  type
        490                if (Null Checker.is NotEmpty(c onsentType )) {
        491                    for  (final Con sentDirect ive direct ive : allC onsentDire ctives) {
        492                         if (NullCh ecker.isNo tEmpty(dir ective)) {
        493                             if (di rective.ge tOptinCons entType(). getName(). equals(con sentType))  {
        494                                 co nsentDirec tives.add( directive) ;
        495                             }
        496                         }
        497                    }
        498                }
        499                else {
        500                    cons entDirecti ves.addAll (allConsen tDirective s);
        501                }
        502           }
        503  
        504           //  Convert t o the PIP  consent di rective
        505           fi nal Collec tion<Conse ntDirectiv eReference Type> cons entDirecti veReferenc es = new A rrayList<C onsentDire ctiveRefer enceType>( );
        506           fo r (final C onsentDire ctive cd :  consentDi rectives)  {
        507                if (Null Checker.is NotEmpty(c d)) {
        508                    fina l ConsentD irectiveRe ferenceTyp e referenc e = this.m apper.map( cd, Consen tDirective ReferenceT ype.class) ;
        509                    cons entDirecti veReferenc es.add(ref erence);
        510                }
        511           }
        512           //  Make the  response
        513           fi nal Consen tDirective QueryRespo nse respon se = new C onsentDire ctiveQuery Response() ;
        514           if  (NullChec ker.isNotE mpty(conse ntDirectiv eReference s)) {
        515                response .getConsen tDirective Reference( ).addAll(c onsentDire ctiveRefer ences);
        516           }
        517           re turn respo nse;
        518       }
        519  
        520       /**
        521        * Con venience m ethod to g et the PIP  Organizat ion from a n oid.
        522        */
        523       privat e Organiza tion getOr ganization ByOid(fina l String o id)
        524       {
        525           fo r (final O rganizatio n org : th is.pip.get AllowedOrg anizations ()) {
        526                if (org. getOrgOid( ).equals(o id)) {
        527                    retu rn org;
        528                }
        529           }
        530           re turn null;
        531       }
        532  
        533       @Overr ide
        534       public  Organizat ionsQueryR esponse ge tOrganizat ions(
        535                final Or ganization sQueryRequ est organi zationsQue ryRequest)
        536                throws C onsentMana gementServ iceExcepti on
        537       {
        538           //  Get the l ist of org anizations  from the  pip.
        539           fi nal Collec tion<Organ ization> o rganizatio ns = this. pip.getAll owedOrgani zations();
        540           if  (NullChec ker.isEmpt y(organiza tions)) {
        541                throw ne w ConsentM anagementS erviceExce ption("Err or: Consen tDirective Organizati ons cannot  be null") ;
        542           }
        543           //  sort orga nizations  collection
        544           Co llections. sort((List ) organiza tions, new  Comparato r<Organiza tion>()
        545           {
        546                @Overrid e
        547                public i nt compare (final Org anization  o1, final  Organizati on o2)
        548                {
        549                    retu rn o1.getO rgName().c ompareToIg noreCase(o 2.getOrgNa me());
        550                }
        551           }) ;
        552           //  Construct  response
        553           fi nal Organi zationsQue ryResponse  response  = new Orga nizationsQ ueryRespon se();
        554           //  Convert r esponses u sing Dozer  to Webser vice types  and add t o the
        555           //  response
        556           fo r (final O rganizatio n organiza tion : org anizations ) {
        557                final Or ganization Type org =  this.mapp er.map(org anization,  Organizat ionType.cl ass);
        558                response .getOrgani zation().a dd(org);
        559           }
        560           //  Return re sponse
        561           re turn respo nse;
        562       }
        563       
        564       @Overr ide
        565       public  Organizat ionTrusted SourceResp onse getIs Organizati onTrustedS ource(fina l Organiza tionTruste dSourceReq uest organ izationTru stedSource Request) t hrows Cons entManagem entService Exception  {
        566           Or ganization TrustedSou rceRespons e resp = n ew Organiz ationTrust edSourceRe sponse();
        567           
        568           St ring orgId  = organiz ationTrust edSourceRe quest.getO rganizatio nId();
        569           
        570           //  Exchange  will be pa ssing OIDs  that star t with com munity id  prefix "ur n:oid:", w hich we mu st strip.
        571           if  (orgId.to LowerCase( ).startsWi th("urn:oi d:")) {
        572                orgId =  orgId.subs tring(8);
        573           }
        574           
        575           Bo olean isTr usted = th is.pip.get IsOrganiza tionTruste dSource(or gId);
        576           
        577           re sp.setIsTr usted(isTr usted);
        578           
        579           re turn resp;
        580       }
        581       
        582       /**
        583        * Con venience m ethod to g et the Pat ientDocume ntType fro m a string .
        584        */
        585       privat e PatientD ocumentTyp e getPatie ntDocument Type(final  String ty pe)
        586       {
        587           fo r (final P atientDocu mentType p Type : thi s.patientD ocumenType s) {
        588                if (pTyp e.getDocum entName(). equals(typ e)) {
        589                    retu rn pType;
        590                }
        591           }
        592           re turn null;
        593       }
        594  
        595       privat e ConsentD irectiveDa ta unmarsh alConsentD irectiveDa ta(String  consentDir ectiveStri ng)
        596       {
        597           Co nsentDirec tiveData c onsentDire ctiveData  = null;
        598  
        599           tr y {
        600                JAXBCont ext jaxbCo ntext = JA XBContext. newInstanc e(ConsentD irectiveDa ta.class);
        601                Unmarsha ller jaxbU nmarshalle r = jaxbCo ntext.crea teUnmarsha ller();
        602                InputStr eam consen tDirective Stream = n ew ByteArr ayInputStr eam(consen tDirective String.get Bytes("UTF -8"));
        603                Document BuilderFac tory dbf =  DocumentB uilderFact oryUtil.ge tDocumentB uilderFact ory(null,  true, fals e, false);
        604                Document Builder db  = dbf.new DocumentBu ilder();
        605                Document  d = db.pa rse(consen tDirective Stream);
        606                consentD irectiveDa ta = (Cons entDirecti veData) ja xbUnmarsha ller.unmar shal(d);
        607           }
        608           ca tch (JAXBE xception e x) {
        609                Logger.g etLogger(C onsentMana gementServ iceImpl.cl ass.getNam e()).log(L evel.SEVER E, null, e x);
        610           }
        611           ca tch (Unsup portedEnco dingExcept ion ex) {
        612                Logger.g etLogger(C onsentMana gementServ iceImpl.cl ass.getNam e()).log(L evel.SEVER E, null, e x);
        613           }
        614           ca tch (Parse rConfigura tionExcept ion ex) {
        615                Logger.g etLogger(C onsentMana gementServ iceImpl.cl ass.getNam e()).log(L evel.SEVER E, null, e x);
        616           }
        617           ca tch (SAXEx ception ex ) {
        618                Logger.g etLogger(C onsentMana gementServ iceImpl.cl ass.getNam e()).log(L evel.SEVER E, null, e x);
        619           }
        620           ca tch (IOExc eption ex)  {
        621                Logger.g etLogger(C onsentMana gementServ iceImpl.cl ass.getNam e()).log(L evel.SEVER E, null, e x);
        622           }
        623  
        624           re turn conse ntDirectiv eData;
        625       }
        626  
        627       /**
        628        * Con vert from  the Consen tDirective Data to th e CDA R2 X ML Privacy  consent
        629        * dir ective doc ument and  then conve rt that to  string.
        630        */
        631       privat e String m akeConsent DirectiveD ocumentStr ing(
        632                final Co nsentDirec tiveData d ata)
        633       {
        634           tr y {
        635                // Conve rt the Con sentDirect iveData to  XML docum ent
        636                final Do cument con sentDirect iveDataDoc  = this.da taJaxb2Mar shaller.ma rshal(data );
        637                // Conve rt Consent DirectiveD ata XML to  CDA R2 XM L
        638                final Do cument con sentDirect iveDocumen t = this.d ataToConse ntDirectiv eDocument. transform( consentDir ectiveData Doc);
        639                // Conve rt CDA R2  XML to str ing
        640                final St ring conse ntDirectiv eDocumentS tring = th is.xmlToSt ring.trans form(conse ntDirectiv eDocument) ;
        641                return c onsentDire ctiveDocum entString;
        642           }
        643           ca tch (final  Transform erExceptio n ex) {
        644                throw ne w RuntimeE xception(e x);
        645           }
        646           ca tch (final  JAXBExcep tion ex) {
        647                throw ne w RuntimeE xception(e x);
        648           }
        649       }
        650  
        651       @Overr ide
        652       public  ConsentDi rectiveAut horization Response p rocessCons entDirecti veAuthoriz ation(
        653                final Co nsentDirec tiveAuthor izationReq uest conse ntDirectiv eAuthoriza tionReques t)
        654                throws C onsentMana gementServ iceExcepti on
        655       {
        656           if  (NullChec ker.isEmpt y(consentD irectiveAu thorizatio nRequest))  {
        657                throw ne w ConsentM anagementS erviceExce ption("Err or: Consen tDirective Authorizat ionRequest  cannot be  null");
        658           }
        659           if  (NullChec ker.isEmpt y(consentD irectiveAu thorizatio nRequest.g etDocument ())) {
        660                throw ne w ConsentM anagementS erviceExce ption("Err or: Consen tDirective Document c annot be n ull");
        661           }
        662  
        663           //  Get the C DA R2 XML  document
        664           St ring conse ntDirectiv eString =  new String (consentDi rectiveAut horization Request.ge tDocument( ));
        665           co nsentDirec tiveString  = consent DirectiveS tring.trim ();
        666  
        667           tr y {
        668                ServiceC onsumerCon textType s cct = cons entDirecti veAuthoriz ationReque st.getServ iceConsume rContext() ;
        669                ConsentD irectiveDa ta consent DirectiveD ata;
        670  
        671                // Conve rt to XML
        672                Document  consentDi rectiveDoc  = this.st ringToXML. transform( consentDir ectiveStri ng);
        673  
        674                if (scct .getServic eConsumerT ype().valu e().equals IgnoreCase ("Exchange ")
        675                         && scct.ge tConsentTy pe().value ().equalsI gnoreCase( "SSA Autho rization") ) {
        676                    cons entDirecti veData = u nmarshalCo nsentDirec tiveData(c onsentDire ctiveStrin g);
        677                    cons entDirecti veString =  this.make ConsentDir ectiveDocu mentString (consentDi rectiveDat a);
        678                    cons entDirecti veAuthoriz ationReque st.setDocu ment(conse ntDirectiv eString.ge tBytes());
        679                    cons entDirecti veDoc = th is.stringT oXML.trans form(conse ntDirectiv eString);
        680                }
        681                else {
        682                    // N eed to get  the User  informatio n from the  CDA R2
        683                    fina l Document  consentDi rectiveDat aDoc = thi s.consentD irectiveDo cumentToDa ta.transfo rm(consent DirectiveD oc);
        684                    cons entDirecti veData = ( ConsentDir ectiveData ) this.dat aJaxb2Mars haller.unm arshal(con sentDirect iveDataDoc );
        685                }
        686  
        687                if (Null Checker.is Empty(cons entDirecti veData)) {
        688                    thro w new Cons entManagem entService Exception( "Error: Co nsentDirec tiveData c annot be n ull");
        689                }
        690                if (Null Checker.is Empty(cons entDirecti veData.get Icn())) {
        691                    thro w new Cons entManagem entService Exception( "Error: Co nsentDirec tiveData I CN cannot  be null");
        692                }
        693  
        694                // TODO:  Temporary  Fix for e Benefits n ot to popu late
        695                // Servi ceContextC onsumerTyp e
        696                // The a bove appro ach involv es changin g CDAR2, w hich we sh ould not
        697                // be do ing if sub mitted by  "eBenefits ". Remove  comment
        698                scct = t his.valida teAndFixSe rviceConsu merContext (scct, con sentDirect iveData.ge tIcn());
        699                consentD irectiveAu thorizatio nRequest.s etServiceC onsumerCon text(scct) ;
        700                if (Null Checker.is Empty(scct )) {
        701                    thro w new Cons entManagem entService Exception( "Error: Se rviceConsu merContext Type is re quired");
        702                }
        703                if (Null Checker.is Empty(scct .getConsen tType()))  {
        704                    thro w new Cons entManagem entService Exception( "Error: Se rviceConsu merContext Type Conse ntType is  required") ;
        705                }
        706                ConsentD irective c onsentDire ctive;
        707  
        708                // Make  the respon se
        709                final Do cument con sentDirect iveAuthori zationResp onseDoc =  this.conse ntDirectiv eDocumentT oAuthoriza tionRespon se.transfo rm(consent DirectiveD oc);
        710                // Unmar shal the r esponse fr om XML to  objects
        711                final Co nsentDirec tiveAuthor izationRes ponse resp onse = (Co nsentDirec tiveAuthor izationRes ponse) thi s.cmsJaxb2 Marshaller .unmarshal (new DOMSo urce(conse ntDirectiv eAuthoriza tionRespon seDoc));
        712                // Conve rt referen ce from th e request  to the PIP  consent d irective
        713                // Mostl y the opt- in date, c reated dat e, expirat ion date,  patient id
        714                // are t he only fi elds popul ated
        715                consentD irective =  this.mapp er.map(res ponse.getC onsentDire ctiveRefer ence(), Co nsentDirec tive.class );
        716  
        717                // Add t he exclude d organiza tions
        718                final Co llection<O rganizatio n> exclude dOrganizat ions = con sentDirect ive.getExc ludedOrgan izations() ;
        719                // Add e xclusions
        720                if (Null Checker.is NotEmpty(e xcludedOrg anizations )) {
        721                    fina l Collecti on<Organiz ation> res etExcluded Org = new  ArrayList< Organizati on>();
        722                    for  (final Org anization  org : excl udedOrgani zations) {
        723                         final Orga nization s toredOrg =  this.getO rganizatio nByOid(org .getOrgOid ());
        724                         if (NullCh ecker.isNo tEmpty(sto redOrg)) {
        725                             resetE xcludedOrg .add(store dOrg);
        726                         }
        727                    }
        728                    cons entDirecti ve.setExcl udedOrgani zations(re setExclude dOrg);
        729                }
        730                // Conse nt Type is  required!
        731                final go v.va.nvap. svc.consen tmgmt.stub .data.Cons entType ty pe = this. pip.getCon sentTypeBy Name(scct. getConsent Type().val ue());
        732                final Pu rposeOfUse  pou = thi s.pip.getP urposeOfUs eByValue(c onsentDire ctiveData. getCompone ntPurposeO fUseDispla yName());
        733  
        734                if (Null Checker.is Empty(type )) {
        735                    thro w new Cons entManagem entService Exception( "Error: No t a valid  consent ty pe " + scc t.getConse ntType().v alue());
        736                }
        737                if (Null Checker.is Empty(cons entDirecti ve.getOpti nDate()))  {
        738                    thro w new Cons entManagem entService Exception( "Error: Op tinDate ca nnot be nu ll");
        739                }
        740                if (Null Checker.is Empty(cons entDirecti ve.getOpti nTS())) {
        741                    thro w new Cons entManagem entService Exception( "Error: Op tinTS cann ot be null ");
        742                }
        743                consentD irective.s etOptinCon sentType(t ype);
        744                consentD irective.s etPurposeO fUse(pou);
        745  
        746                final Li st<String>  patientIe ns = new A rrayList<S tring>();
        747                patientI ens.add(co nsentDirec tive.getPa tientIen() );
        748  
        749                // Check  if there' s a delaye d consent  of the sam e type (eh x vs ssa)  in PENDING  status, w e need to  first canc el that co nsent by 
        750                // setti ng status  to CANCELE D and reso lution dat e to now.
        751                DelayedC onsent dc  = this.del ayedConsen tDAO.findB yTypeAndSt atus(scct. getConsent Type().get Value(), " PENDING",  consentDir ective.get PatientIen ());
        752  
        753                if (!Nul lChecker.i sNullOrEmp ty(dc)) {
        754                    // T here is a  delayed co nsent in p ending sta tus, so we  need to s et it to C ANCELLED a nd the res olution da te to now.
        755                    try  {
        756                         dc.setStat us("CANCEL ED");
        757                         dc.setReso lutionDate (new Date( ));
        758                         this.delay edConsentD AO.update( dc);
        759                    } ca tch (Excep tion ex) {
        760                         throw new  ConsentMan agementSer viceExcept ion("There  was an er ror cancel ling the d elayed con sent.");
        761                    }
        762                }
        763  
        764                final Co nsentDirec tiveRefere nceType co nsentDirec tiveRefere nce = this .mapper.ma p(consentD irective,  ConsentDir ectiveRefe renceType. class);
        765                final Co nsentDirec tive exist ingDirecti ve = this. pip.getAct iveConsent Directive( patientIen s, type);
        766                ConsentT ype authCo nsentType  = scct.get ConsentTyp e();
        767  
        768                Date doc StartDate  = consentD irective.g etOptinDat e();
        769                if (exis tingDirect ive != nul l && exist ingDirecti ve.getOpti nDate() !=  null && d ocStartDat e.before(e xistingDir ective.get OptinDate( )))  {
        770                    thro w new Cons entManagem entService Exception(
        771                             "Error : An activ e consent  directive  " + existi ngDirectiv e.getConse ntDirId()
        772                             + " cr eated on "  + existin gDirective .getOptinD ate()
        773                             + " al ready exis ts for the  patient f or " + exi stingDirec tive.getOp tinConsent Type().get Name());
        774                } else i f(existing Directive  != null &&  docStartD ate.after( existingDi rective.ge tOptinDate ())) {     // Revoke  old and co mmit new
        775                    // T ry Revoke
        776                    try  {
        777                         revokeOldC onsent(scc t, consent DirectiveR eference,  existingDi rective);
        778                    } ca tch (Excep tion ex) {
        779                         ex.printSt ackTrace() ;
        780                         throw new  ConsentMan agementSer viceExcept ion("There  was an er ror while  revoking t he old con sent. ", e x);
        781                    }
        782                }
        783                scct.set ConsentTyp e(authCons entType);
        784                consentD irective.s etOptinTS( consentDir ective.get OptinDate( ));
        785  
        786                Calendar  c = Calen dar.getIns tance();
        787                c.setTim e(consentD irective.g etOptinDat e());
        788                c.add(Ca lendar.YEA R, 10);                              // add  10 years  to optin t o get the  expiration  date
        789                consentD irective.s etExpirati onDate(c.g etTime());
        790  
        791                this.pip .storeCons entDirecti ve(consent Directive) ;
        792  
        793                // Get t he consent  directive  Id
        794                final Pa tientDocum ent patien tDocument  = new Pati entDocumen t();
        795                patientD ocument.se tConsentDi rective(co nsentDirec tive);
        796                patientD ocument.se tDocument( consentDir ectiveStri ng);
        797                patientD ocument.se tPatientDo cumentType (this.getP atientDocu mentType(" Authorize" ));
        798                patientD ocument.se tExternalD ocumentId( consentDir ectiveAuth orizationR equest.get DasDocumen tId());
        799                // Save  Document
        800                this.pip .storePati entDocumen t(patientD ocument);
        801                // Send  Response
        802                final Co nsentDirec tiveAuthor izationRes ponse resp onseType =  new Conse ntDirectiv eAuthoriza tionRespon se();
        803                // Conve rt from PI P consent  directive  to webserv ice types  using
        804                // dozer
        805                // TODO:  ConsentDi rective Id  is not pa ssed back  in the res ponse
        806   //             final  ConsentDir ectiveRefe renceType  consentDir ectiveRefe rence = th is.mapper. map(consen tDirective , ConsentD irectiveRe ferenceTyp e.class);
        807                response Type.setCo nsentDirec tiveRefere nce(consen tDirective Reference) ;
        808                if(conse ntDirectiv e.getConse ntDirId()  != null)
        809                    {
        810                    resp onseType.g etConsentD irectiveRe ference(). setConsent DirId(cons entDirecti ve.getCons entDirId() .toString( ));
        811                    }
        812                // Annou nce only f or NwHIN C onsentType
        813                if (Cons entType.NW _HIN_AUTHO RIZATION.e quals(scct .getConsen tType()))  {
        814                    // C heck if an nouncement  is in exc lusion tim eframe
        815                    int  announceEx clusionTim eframeHour s = this.a nnouncer.g etAnnounce ExclusionT imeframeHo urs();
        816                    anno unceExclus ionTimefra meHours =  0 - announ ceExclusio nTimeframe Hours; //M ake negati ve
        817                    Cale ndar cal =  Calendar. getInstanc e();
        818                    cal. add(Calend ar.HOUR, a nnounceExc lusionTime frameHours );
        819                    Date  timeframe BeginDate  = cal.getT ime();
        820                    List <Announcem ent> timef rameAnnoun cements
        821                             = this .announcer .getNonBat chAnnounce mentsByCre atedTs(tim eframeBegi nDate, con sentDirect ive.getPat ientIen()) ;
        822                    if ( timeframeA nnouncemen ts == null  || timefr ameAnnounc ements.isE mpty()) {
        823                         // Get the  opted-in  organizati ons
        824                         final Coll ection<Org anization>  optedInOr ganization s = this.p ip.getAllo wedNonCons umerOnlyOr ganization s();
        825                         //.getAuth orizedOrga nizations( consentDir ective);
        826  
        827                         if (NullCh ecker.isNo tEmpty(opt edInOrgani zations))  {
        828                             try {
        829                                 //  For each  authorized  organizat ions
        830                                 fi nal Announ cement ann ouncement  = new Anno uncement() ;
        831                                 fi nal List<A uthorizedO rganizatio nType> aut horizedOrg s = new Ar rayList<Au thorizedOr ganization Type>();
        832                                 if  (!SEQUENT IAL_ANNOUN CE) {
        833                                      // Store  announcem ent
        834                                      announce ment.setCr eatedTs(ne w Date());
        835                                      announce ment.setPa tientConse ntDir(cons entDirecti ve);
        836                                      announce ment.setSc heduledTs( new Date() );
        837                                      announce ment.setTa rgetOrgani zation(nul l);
        838                                      announce ment.setUs erId(conse ntDirectiv eData
        839                                               .getAuthor PersonOid( ));
        840                                      this.ann ouncer.sto reAnnounce ment(annou ncement);
        841                                 }
        842                                 fo r (final O rganizatio n organiza tion : opt edInOrgani zations) {
        843                                      if (SEQU ENTIAL_ANN OUNCE) {
        844                                          // S tore annou ncement
        845                                          anno uncement.s etCreatedT s(new Date ());
        846                                          anno uncement.s etPatientC onsentDir( consentDir ective);
        847                                          anno uncement.s etSchedule dTs(new Da te());
        848                                          anno uncement.s etTargetOr ganization (organizat ion);
        849                                          anno uncement.s etUserId(c onsentDire ctiveData
        850                                                   .getAu thorPerson Oid());
        851                                          this .announcer .storeAnno uncement(a nnouncemen t);
        852                                      }
        853                                      else {
        854                                          Anno uncementOr g announce Org = new  Announceme ntOrg();
        855                                          anno unceOrg.se tAnnouncem ent(announ cement);
        856                                          anno unceOrg.se tTargetOrg anization( organizati on);
        857                                          try  {
        858                                               this.annou ncer.creat eAnnouncem entOrg(ann ounceOrg);
        859                                          }
        860                                          catc h (Excepti on ex) {
        861                                               // Announc eOrg stora ge fail
        862                                          }
        863                                      }
        864  
        865                                      // Conve rt orgs fo r request  insertion
        866                                      final Au thorizedOr ganization Type autho rizedOrgan ization =  new Author izedOrgani zationType ();
        867                                      authoriz edOrganiza tion.setOr gNumber(or ganization
        868                                               .getOrgNum ber());
        869                                      authoriz edOrganiza tion.setOr gName(orga nization
        870                                               .getOrgNam e());
        871                                      authoriz edOrganiza tion.setOr gOid(organ ization
        872                                               .getOrgOid ());
        873                                      authoriz edOrgs.add (authorize dOrganizat ion);
        874                                 }
        875                                 //  Convert i nto Announ cePatientR equest
        876                                 fi nal Announ cePatientR equest ann ouncePatie ntRequest  = this.ann ouncementT oAnnounceP atientRequ est
        877                                          .tra nsform(ann ouncement) ;
        878                                 //  Strip the  last anno uncement t arget orga nization s o it is no t counted  twice
        879                                 an nouncePati entRequest .getAuthor izedOrgani zations(). clear();
        880                                 //  Add all o rganizatio ns
        881                                 an nouncePati entRequest .getAuthor izedOrgani zations(). addAll(aut horizedOrg s);
        882                                 //  Get the u ser inform ation from  the conse nt
        883                                 //  directive
        884                                 //  data obje ct
        885                                 fi nal UserTy pe userTyp e = new Us erType();
        886                                 //  Anand - 0 8/27/2011
        887                                 //  If Servic e Consumer  is "Veter ans_Portal " aka
        888                                 //  eBenefits , and tran saction in voked is
        889                                 //  opt-in/op t-out,
        890                                 //  the
        891                                 //  business  requiremen t is to
        892                                 //  1) Set Us er Id to " eBenefits"
        893                                 //  2) Set Fa cility to  an ESR(Pat ient
        894                                 //  Preferred )/MVI(Last
        895                                 //  Visited),  in that o rder
        896                                 //
        897                                 //  Todo: Sin ce Announc e is impli cit, how d o we
        898                                 //  handle it
        899                                 //  ?
        900                                 //  For the m oment, onl y overridi ng userid
        901                                 fi nal Servic eConsumer  sc = scct. getService ConsumerTy pe();
        902  
        903                                 if  (NullChec ker.isNotE mpty(sc))  {
        904                                      userType .setUserId (scct.getU ser());
        905                                      userType .setFacili tyNumber(s cct.getFac ility());
        906                                 }
        907                                 el se {
        908                                      userType .setUserId (consentDi rectiveDat a.getAutho rPersonOid ());
        909                                      userType .setFacili tyNumber(c onsentDire ctiveData. getAuthorP ersonFacil ityNumber( ));
        910                                 }
        911                                 us erType.set FullName(c onsentDire ctiveData. getAuthorP ersonFamil yName());
        912                                 fi nal Patien tType pati entType =  new Patien tType();
        913                                 pa tientType. setGivenNa me(consent DirectiveD ata.getPat ientRoleGi venName()) ;
        914                                 pa tientType. setLastNam e(consentD irectiveDa ta.getPati entRoleFam ilyName()) ;
        915                                 pa tientType. setMiddleN ame(consen tDirective Data.getPa tientRoleM iddleName( ));
        916                                 pa tientType. setSsn(con sentDirect iveData.ge tPatientRo leSsn());
        917                                 an nouncePati entRequest .setUser(u serType);
        918                                 //  Announce  patients s ynchronous ly over th e NwHIN
        919                                 //  Create th e request  for async  announce
        920                                 //  Call the  announce b ean
        921                                 th is.patient Announcer. announceAs ync(announ cePatientR equest);
        922                             }
        923                             catch  (final Pat ientAnnoun cerExcepti on ex) {
        924                                 th row new Co nsentManag ementServi ceExceptio n(ex);
        925                             }
        926                         }
        927                    }
        928                }
        929  
        930                try {
        931                    this .consentDi rectiveDoc umentAudit Intercepto r.intercep t(consentD irectiveAu thorizatio nRequest);
        932                }
        933                catch (f inal Inter ceptorExce ption ex)  {
        934                    thro w new Cons entManagem entService Exception( ex);
        935                }
        936  
        937                // Retur n response
        938                return r esponseTyp e;
        939           }
        940           ca tch (final  JAXBExcep tion ex) {
        941                throw ne w ConsentM anagementS erviceExce ption(ex);
        942           }
        943           ca tch (final  Transform erExceptio n ex) {
        944                throw ne w ConsentM anagementS erviceExce ption("Err or: Consen tDirective Document i s not a va lid XML do cument");
        945           }
        946       }
        947       privat e Endpoint <Object, S tring> vis taPatientP rimaryView Endpoint;
        948       privat e Transfor mer<String , Map<Stri ng, Object >> patient PrimaryVie wRpcRespon seToProper tyMap;
        949  
        950       privat e void rev okeOldCons ent(Servic eConsumerC ontextType  scct, Con sentDirect iveReferen ceType ref erence, Ob ject oldCo nsent)
        951                throws C onsentMana gementServ iceExcepti on, JAXBEx ception, T ransformer Exception  {
        952           fi nal String  ien = ref erence.get PatientIen ();
        953           //  Assumes t hat there  is only on e icn for  every ien
        954           fi nal String  icn = thi s.personSe rvice.getC orrelatedI ds(ien).ge t(0);
        955           Pa tientDemog raphics de mographics  = null;
        956           Pa tientDemog raphicsQue ry demogra phicsQuery  = new Pat ientDemogr aphicsQuer y();
        957           de mographics Query.setP atientId(i cn);
        958  
        959           Pa tientDemog raphicsRes ponse demo graphicsRe sponse = n ew Patient Demographi csResponse ();
        960           fi nal Collec tion<Patie ntDemograp hics> pati entDemogra phicsRefer ences = ne w ArrayLis t<PatientD emographic s>();
        961           tr y {
        962                demograp hicsRespon se = this. pdqService .getPatien tDemograph ics(demogr aphicsQuer y);
        963                demograp hics = dem ographicsR esponse.ge tPatientDe mographics ();
        964           }
        965           ca tch (PdqEx ception e)  {
        966                // TODO:  Handle Ex ception
        967           }
        968           ca tch (Runti meExceptio n e) { //C atches if  icn does n ot exist
        969                patientD emographic sReference s.add(new  PatientDem ographics( ));
        970           }
        971  
        972           Co nsentDirec tiveData d ata = new  ConsentDir ectiveData ();
        973           da ta.setIcn( icn);
        974  
        975           if  (NullChec ker.isNotE mpty(demog raphics))
        976                {
        977                data.set PatientRol eCity(demo graphics.g etResidenc eCity());
        978                data.set PatientRol eState(dem ographics. getResiden ceState()) ;
        979                data.set PatientRol eGivenName (demograph ics.getFir stName());
        980                data.set PatientRol eFamilyNam e(demograp hics.getLa stName());
        981                data.set PatientRol eFamilyNam eAlias(dem ographics. getAlias1( ));
        982                data.set PatientRol eMiddleNam e(demograp hics.getMi ddleName() );
        983                data.set PatientRol eMiddleNam eAlias(dem ographics. getAlias2( ));
        984                data.set PatientRol eEthnicGro upCodeDisp layText(de mographics
        985                         .getEthnic ityDescrip tion());
        986                data.set PatientRol eSsn(demog raphics.ge tSsn());
        987                data.set PatientRol eGenderCod e(demograp hics.getGe nder());
        988                data.set PatientRol eGenderDis playText(d emographic s
        989                         .getGender Descriptio n());
        990                data.set PatientRol eMaritalSt atusCode(d emographic s
        991                         .getMarita lStatus()) ;
        992                data.set PatientRol eMaritalSt atusDispla yText(demo graphics
        993                         .getMarita lStatusDes cription() );
        994                data.set PatientRol ePostalCod e(demograp hics.getRe sidenceZip 4());
        995                data.set PatientRol ePrefix(de mographics .getPrefix ());
        996                data.set PatientRol eStreetAdd ressLine(d emographic s
        997                         .getStreet AddressLin e1());
        998                data.set PatientRol eSuffix(de mographics .getSuffix ());
        999                data.set PatientRol eTelecom(d emographic s.getResid encePhoneN umber());
        1000                data.set PatientRol eProviderO rganizatio nName(demo graphics
        1001                         .getFacili tyName());
        1002                data.set PatientRol eProviderO rganizatio nNumber(de mographics
        1003                         .getFacili tyNumber() );
        1004                if (Null Checker.is NotEmpty(d emographic s.getDob() )) {
        1005                    try  {
        1006                         // Need to  use the H L7 date, b ecause the  CDA R2 ne eds it
        1007                         data.setPa tientRoleD ob(HL7Date Util
        1008                                 .y yyyMMddhhm mssZ(demog raphics.ge tDob()));
        1009                    } ca tch (final  ParseExce ption ex)  {
        1010                         throw new  RuntimeExc eption(ex) ;
        1011                    }
        1012                }
        1013           }
        1014           //  Set a uni que id per  document
        1015           da ta.setDocI d(UUIDUtil .generateU UID());
        1016  
        1017           //  Set the s tatus code  to aborte d
        1018           da ta.setComp onentStatu sCode("abo rted");
        1019  
        1020           //  Set docum ent dates  and times  to now
        1021           tr y {
        1022                final St ring signa tureDateSt ring = HL7 DateUtil
        1023                         .yyyyMMddh hmmssZ(new  Date());
        1024                // Set t he effecti ve date
        1025                data.set EffectiveD ateTime(HL 7DateUtil. yyyyMMddhh mmssZ(new  Date()));
        1026                // Creat e the begi n and end  date
        1027                data.set Documentat ionBeginTi me(signatu reDateStri ng);
        1028                // Start  and end t ime are re quired
        1029                data.set Documentat ionEndTime (signature DateString );
        1030           }  catch (fin al ParseEx ception ex ) {
        1031                throw ne w RuntimeE xception(e x);
        1032           }
        1033  
        1034           //  Set the c onsent dir ective
        1035           Co nsentDirec tive cd =  ((ConsentD irective)  oldConsent );
        1036           da ta.setPrev iousConsen tDirective Id(cd.getC onsentDirI d().toStri ng());
        1037           da ta.setOpto utReason(" New Author ization");
        1038           //  For now s ets user t o an autom atic servi ce
        1039           da ta.setAuth orPersonOi d("Automat ic Service ");
        1040           da ta.setAuth orPersonOr gOid("Auto matic Serv ice");
        1041  
        1042           //  Make the  request to  revoke
        1043           fi nal Servic eConsumerC ontextType  sc = new  ServiceCon sumerConte xtType();
        1044           sc .setUser(" Automatic  Service");
        1045  
        1046           Co nsentAudit  ca = audi tService.g etLatestAu dit(cd.get PatientIen (), cd.get OptinConse ntType().g etName());
        1047           if (ca != nul l){
        1048                sc.setFa cility(ca. getFacilit y());
        1049           }
        1050           sc .setServic eConsumerT ype(Servic eConsumer. ADMINISTRA TOR_PORTAL );
        1051  
        1052           if  (cd.getPu rposeOfUse () != null ) {
        1053                data.set ComponentP urposeOfUs eDisplayNa me(cd.getP urposeOfUs e().getPou Value());
        1054           }
        1055           ;
        1056           St ring auth  = gov.va.n vap.privac y.ConsentT ype.fromVa lue(cd.get OptinConse ntType().g etName()). name();
        1057           St ring deAut hName = au th.substri ng(0, auth .lastIndex Of("_")) +  "_REVOCAT ION";
        1058           sc .setConsen tType(Cons entType.va lueOf(deAu thName));
        1059  
        1060           //  Convert t he PDF int o byte str ing
        1061           //  Convert t he Consent DirectiveD ata to XML  document
        1062           fi nal Docume nt consent DirectiveD ataDoc = t his.dataJa xb2Marshal ler.marsha l(data);
        1063                // Conve rt Consent DirectiveD ata XML to  CDA R2 XM L
        1064           fi nal Docume nt consent DirectiveD ocument =  this.dataT oConsentDi rectiveDoc ument.tran sform(cons entDirecti veDataDoc) ;
        1065           //  Convert C DA R2 XML  to string
        1066           fi nal String  consentDi rectiveDoc umentStrin g = this.x mlToString .transform (consentDi rectiveDoc ument);
        1067           fi nal byte[]  consentDi rectiveDoc umentBytes  = consent DirectiveD ocumentStr ing.getByt es();
        1068  
        1069           fi nal Consen tDirective Revocation Request re quest = ne w ConsentD irectiveRe vocationRe quest();
        1070           re quest.setS erviceCons umerContex t(sc);
        1071           re quest.setO ptoutReaso n(ConsentD irectiveOp tOutReason Type.fromV alue("New  Authorizat ion"));
        1072           re quest.setD ocument(co nsentDirec tiveDocume ntBytes);
        1073  
        1074           pr ocessConse ntDirectiv eRevocatio n(request) ;
        1075           }
        1076  
        1077       /**
        1078        * Pro cesses the  revocatio n of a con sent for a  particula r consent  directive.
        1079        * Thi s method a lso insert s a patien t document  into the  database i f the
        1080        * rev ocation is  not becau se of a de ceased pat ient.
        1081        *
        1082        * @pa ram consen tDirective Revocation Request Re quest obje ct for con sent
        1083        * rev ocation
        1084        *
        1085        * @re turn the r esponse ob ject for t he revocat ion
        1086        *
        1087        * @th rows gov.v a.nvap.ser vice.priva cy.Consent Management ServiceExc eption
        1088        */
        1089       @Overr ide
        1090       public  ConsentDi rectiveRev ocationRes ponse proc essConsent DirectiveR evocation(
        1091           fi nal Consen tDirective Revocation Request co nsentDirec tiveRevoca tionReques t) throws  ConsentMan agementSer viceExcept ion {
        1092           re turn proce ssOldConse ntDirectiv eRevocatio n(consentD irectiveRe vocationRe quest, nul l);
        1093       }
        1094       
        1095       @Overr ide
        1096       public   ConsentD irectiveRe vocationRe sponse pro cessOldCon sentDirect iveRevocat ion(
        1097           fi nal Consen tDirective Revocation Request co nsentDirec tiveRevoca tionReques t, Object  oldConsent )
        1098           th rows Conse ntManageme ntServiceE xception {
        1099  
        1100           if  (NullChec ker.isEmpt y(consentD irectiveRe vocationRe quest)) {
        1101                throw ne w ConsentM anagementS erviceExce ption("Err or: Consen tDirective Revocation Request el ement cann ot be null ");
        1102           }
        1103           if  (NullChec ker.isEmpt y(consentD irectiveRe vocationRe quest.getD ocument()) ) {
        1104                throw ne w ConsentM anagementS erviceExce ption("Err or: docume nt element  is null o r invalid" );
        1105           }
        1106           if  (NullChec ker.isEmpt y(consentD irectiveRe vocationRe quest.getO ptoutReaso n())) {
        1107                throw ne w ConsentM anagementS erviceExce ption("Err or: optout Reason ele ment is nu ll or inva lid");
        1108           }
        1109  
        1110           Se rviceConsu merContext Type scct  = consentD irectiveRe vocationRe quest.getS erviceCons umerContex t();
        1111  
        1112           //  Get the C DA R2 XML  String
        1113           St ring conse ntDirectiv eString =  new String (consentDi rectiveRev ocationReq uest.getDo cument());
        1114           co nsentDirec tiveString  = consent DirectiveS tring.trim ();
        1115  
        1116           if  (scct.get ServiceCon sumerType( ) == null)  {
        1117                throw ne w ConsentM anagementS erviceExce ption("Err or: servic eConsumerC ontext.ser viceConsum erType ele ment is nu ll or inva lid");
        1118           }
        1119  
        1120           if  (scct.get ServiceCon sumerType( ).value(). equalsIgno reCase("Ex change")
        1121                    && s cct.getCon sentType() .value().e qualsIgnor eCase("SSA  Revocatio n")) {
        1122                ConsentD irectiveDa ta consent DirectiveD ata = unma rshalConse ntDirectiv eData(cons entDirecti veString);
        1123                consentD irectiveSt ring = thi s.makeCons entDirecti veDocument String(con sentDirect iveData);
        1124                consentD irectiveRe vocationRe quest.setD ocument(co nsentDirec tiveString .getBytes( ));
        1125           }
        1126  
        1127           //  Temp fix:  To includ e opt-out  reason in  the conten t.
        1128           tr y {
        1129                // Conve rt to XML  consent di rective do cument
        1130                final Do cument doc  = this.st ringToXML. transform( consentDir ectiveStri ng);
        1131                // Make  the respon se by tran sforming f rom the CD A R2 Docum ent
        1132                final Do cument con sentDirect iveRevocat ionRespons eDoc = thi s.consentD irectiveDo cumentToRe vocationRe sponse.tra nsform(doc );
        1133                // Conve rt the XML  response  to JAXB ob jects
        1134                final Co nsentDirec tiveRevoca tionRespon se respons e = (Conse ntDirectiv eRevocatio nResponse)  this.cmsJ axb2Marsha ller.unmar shal(new D OMSource(c onsentDire ctiveRevoc ationRespo nseDoc));
        1135                // Get t he Consent DirectiveR eference
        1136                final Co nsentDirec tiveRefere nceType re ference =  response.g etConsentD irectiveRe ference();
        1137  
        1138                // TODO:  Temporary  Fix for e Benefits n ot to popu late
        1139                // Servi ceContextC onsumerTyp e
        1140                // The a bove appro ach involv es changin g CDAR2, w hich we sh ould not
        1141                // be do ing if sub mitted by  "eBenefits ". Remove  comment
        1142                scct = t his.valida teAndFixSe rviceConsu merContext (scct, ref erence.get PatientIen ());
        1143                consentD irectiveRe vocationRe quest.setS erviceCons umerContex t(scct);
        1144                if (scct  == null)  {
        1145                    thro w new Cons entManagem entService Exception( "Error: se rviceConsu merContext  element i s null or  invalid");
        1146                }
        1147                if (scct .getConsen tType() ==  null) {
        1148                    thro w new Cons entManagem entService Exception( "Error: se rviceConsu merContext .consentTy pe element  is null o r invalid" );
        1149                }
        1150  
        1151                // Call  pip to get  the activ e consent  directive,  and use t hat to
        1152                // store  the optOu t informat ion
        1153                // Has t o be atlea st one act ive consen t directiv e or throw  error
        1154                ConsentT ype active ConsentTyp e = null;
        1155                if (Cons entType.NW _HIN_REVOC ATION.valu e().equals (scct.getC onsentType ().value() )) {
        1156                    acti veConsentT ype = Cons entType.NW _HIN_AUTHO RIZATION;
        1157                }
        1158                else if  (ConsentTy pe.SSA_REV OCATION.va lue().equa ls(scct.ge tConsentTy pe().value ())) {
        1159                    acti veConsentT ype = Cons entType.SS A_AUTHORIZ ATION;
        1160                }
        1161                else if  (ConsentTy pe.NW_HIN_ ORGANIZATI ON_RESTRIC TION_REVOC ATION.valu e().equals (scct.getC onsentType ().value() )) {
        1162                    acti veConsentT ype = Cons entType.NW _HIN_ORGAN IZATION_RE STRICTION_ AUTHORIZAT ION;
        1163                }
        1164  
        1165                if (acti veConsentT ype == nul l) {
        1166                    thro w new Cons entManagem entService Exception( "Error: se rviceConsu merContext .consentTy pe element  is invali d");
        1167                }
        1168  
        1169                final go v.va.nvap. svc.consen tmgmt.stub .data.Cons entType db ConsentTyp e = this.p ip.getCons entTypeByN ame(scct.g etConsentT ype().valu e());
        1170                final go v.va.nvap. svc.consen tmgmt.stub .data.Cons entType ac tiveDbCons entType =  this.pip.g etConsentT ypeByName( activeCons entType.va lue());
        1171  
        1172                //Skip c orrelation  for SSA o r if passe d old cons ent for ex pired pati ents
        1173                ConsentD irective a ctiveConse ntDirectiv e;
        1174                if (oldC onsent !=  null && ol dConsent i nstanceof  ConsentDir ective) {
        1175                    acti veConsentD irective =  (ConsentD irective)o ldConsent;
        1176                }
        1177                else if  (scct.getC onsentType ().value() .equalsIgn oreCase("S SA Revocat ion")) {
        1178                    List  ienList =  new Array List();
        1179                    ienL ist.add(re ference.ge tPatientIe n());
        1180                    acti veConsentD irective =  this.pip. getActiveC onsentDire ctive(ienL ist, activ eDbConsent Type);
        1181                }
        1182                else {
        1183                    acti veConsentD irective =  this.pip. getActiveC onsentDire ctive(this .personSer vice.getCo rrelatedId s(referenc e.getPatie ntIen()),  activeDbCo nsentType) ;
        1184                }
        1185  
        1186                if (Null Checker.is Empty(acti veConsentD irective))  {
        1187                    thro w new Cons entManagem entService Exception( "Error: Th e Patient  does not h ave an act ive consen t directiv e");
        1188                }
        1189                // Set t he optout  date
        1190  
        1191                activeCo nsentDirec tive.setOp toutTS(ref erence.get OptoutTS() );
        1192                activeCo nsentDirec tive.setOp toutDate(r eference.g etOptoutDa te());
        1193                activeCo nsentDirec tive.setOp toutConsen tType(dbCo nsentType) ;
        1194  
        1195                if (scct .getServic eConsumerT ype().valu e().equals IgnoreCase ("Exchange ")
        1196                         && scct.ge tConsentTy pe().value ().equalsI gnoreCase( "SSA Revoc ation")) {
        1197                    acti veConsentD irective.s etOptoutTS (new Date( ));
        1198                    acti veConsentD irective.s etOptoutDa te(new Dat e());
        1199                    scct .setUser(" SSA_USER") ;
        1200                }
        1201  
        1202                // Set t he optout  reason
        1203                for (fin al OptoutR eason optO utReason :  this.optO utReasons)  {
        1204                    fina l String r eason = co nsentDirec tiveRevoca tionReques t.getOptou tReason(). value();
        1205                    if ( optOutReas on.getText ().equals( reason)) {
        1206                         activeCons entDirecti ve.setOpto utReason(o ptOutReaso n);
        1207                         break;
        1208                    }
        1209                }
        1210                // Save  Directive
        1211                this.pip .storeCons entDirecti ve(activeC onsentDire ctive);
        1212                // Store  the CDA R 2 XML as t he patient  document  if patient  is not de ceased
        1213                if (!act iveConsent Directive. getOptoutR eason().ge tText().eq uals("Pati ent Deceas ed")) {
        1214                    fina l PatientD ocument pa tientDocum ent = new  PatientDoc ument();
        1215                    pati entDocumen t.setConse ntDirectiv e(activeCo nsentDirec tive);
        1216                    pati entDocumen t.setDocum ent(consen tDirective String);
        1217                    pati entDocumen t.setPatie ntDocument Type(this. getPatient DocumentTy pe("Revoke "));
        1218                    // S ave Docume nt
        1219                    this .pip.store PatientDoc ument(pati entDocumen t);
        1220                }
        1221                // Send  Response
        1222                final Co nsentDirec tiveRevoca tionRespon se respons eType = ne w ConsentD irectiveRe vocationRe sponse();
        1223                // Conve rt from PI P consent  directive  to webseri ve types u sing dozer
        1224                final Co nsentDirec tiveRefere nceType co nsentDirec tiveRefere nce = this .mapper.ma p(activeCo nsentDirec tive, Cons entDirecti veReferenc eType.clas s);
        1225                response Type.setCo nsentDirec tiveRefere nce(consen tDirective Reference) ;
        1226                // Retur n response
        1227  
        1228                // Inter cept & Aud it
        1229                try {
        1230                    this .consentDi rectiveDoc umentAudit Intercepto r.intercep t(consentD irectiveRe vocationRe quest);
        1231                }
        1232                catch (f inal Inter ceptorExce ption ex)  {
        1233                    thro w new Cons entManagem entService Exception( ex);
        1234                }
        1235  
        1236                return r esponseTyp e;
        1237           }
        1238           ca tch (final  Transform erExceptio n ex) {
        1239                throw ne w ConsentM anagementS erviceExce ption("Err or: docume nt element  is not a  valid XML  document") ;
        1240           }
        1241       }
        1242  
        1243       @Overr ide
        1244       public  ConsentDi rectiveUpd ateRespons e processC onsentDire ctiveUpdat e(
        1245                final Co nsentDirec tiveUpdate Request co nsentDirec tiveUpdate Request)
        1246                throws C onsentMana gementServ iceExcepti on
        1247       {
        1248  
        1249           if  (NullChec ker.isEmpt y(consentD irectiveUp dateReques t)) {
        1250                throw ne w ConsentM anagementS erviceExce ption("Err or: Consen tDirective UpdateRequ est cannot  be null") ;
        1251           }
        1252           if  (NullChec ker.isEmpt y(consentD irectiveUp dateReques t.getDocum ent())) {
        1253                throw ne w ConsentM anagementS erviceExce ption("Err or: Consen t Directiv e Document  cannot be  null");
        1254           }
        1255  
        1256           //  Get the C DA R2 XML  document
        1257           St ring conse ntDirectiv eString =  new String (consentDi rectiveUpd ateRequest .getDocume nt());
        1258           co nsentDirec tiveString  = consent DirectiveS tring.trim ();
        1259           tr y {
        1260                // Conve rt to XML
        1261                final Do cument con sentDirect iveDoc = t his.string ToXML.tran sform(cons entDirecti veString);
        1262                // Need  to get the  informati on from th e CDA R2
        1263                final Do cument con sentDirect iveDataDoc  = this.co nsentDirec tiveDocume ntToData.t ransform(c onsentDire ctiveDoc);
        1264                // Conve rt to help er VO
        1265                final Co nsentDirec tiveData c onsentDire ctiveData  = (Consent DirectiveD ata) this. dataJaxb2M arshaller. unmarshal( consentDir ectiveData Doc);
        1266  
        1267                final St ring icn =  consentDi rectiveDat a.getIcn() ;
        1268                final St ring id =  consentDir ectiveData .getDocId( );
        1269                final St ring statu s = consen tDirective Data.getCo mponentSta tusCode();
        1270                // Verif y the requ ired field s
        1271                if (Null Checker.is Empty(icn) ) {
        1272                    thro w new Cons entManagem entService Exception( "Error: IC N cannot b e null");
        1273                }
        1274                if (Null Checker.is Empty(id))  {
        1275                    thro w new Cons entManagem entService Exception( "Error: Do cument Id  cannot be  null");
        1276                }
        1277                if (Null Checker.is Empty(stat us)) {
        1278                    thro w new Cons entManagem entService Exception( "Error: St atus code  cannot be  null");
        1279                }
        1280  
        1281                // TODO:  Temporary  Fix for e Benefits n ot to popu late
        1282                // Servi ceContextC onsumerTyp e
        1283                // The a bove appro ach involv es changin g CDAR2, w hich we sh ould not
        1284                // be do ing if sub mitted by  "eBenefits ". Remove  comment
        1285                ServiceC onsumerCon textType s cct = cons entDirecti veUpdateRe quest.getS erviceCons umerContex t();
        1286                scct = t his.valida teAndFixSe rviceConsu merContext (scct, icn );
        1287                consentD irectiveUp dateReques t.setServi ceConsumer Context(sc ct);
        1288                if (Null Checker.is Empty(scct )) {
        1289                    thro w new Cons entManagem entService Exception( "Error: Se rviceConsu merContext Tye is req uired");
        1290                }
        1291                if (Null Checker.is Empty(scct .getConsen tType()))  {
        1292                    thro w new Cons entManagem entService Exception( "Error: Se rviceConsu merType Co nsentType  is require d");
        1293                }
        1294  
        1295                // Get t he type fo r query
        1296                PatientD ocumentTyp e type = n ull;
        1297                if ("abo rted".equa ls(status) ) {
        1298                    type  = this.ge tPatientDo cumentType ("OPT-OUT" );
        1299                }
        1300                else if  ("active". equals(sta tus)) {
        1301                    type  = this.ge tPatientDo cumentType ("OPT-IN") ;
        1302                }
        1303                else {
        1304                    thro w new Cons entManagem entService Exception( "Error: Co nsent dire ctive stat us code is  not suppo rted");
        1305                }
        1306                final Li st<String>  ids = new  ArrayList <String>() ;
        1307                ids.add( icn);
        1308                final Co llection<C onsentDire ctive> con sentDirect ives = thi s.pip.getC onsentHist ory(ids);
        1309                PatientD ocument pa tientDocum ent = null ;
        1310                // Get t he documen t to updat e
        1311                for (fin al Consent Directive  consentDir  : consent Directives ) {
        1312                    pati entDocumen t = this.p ip.getCons entDirecti veDocument ByType(con sentDir, t ype);
        1313                    if ( NullChecke r.isNotEmp ty(patient Document))  {
        1314                         final Stri ng documen t = (Strin g) patient Document.g etDocument ();
        1315                         if (docume nt.contain s(consentD irectiveDa ta.getDocI d())) {
        1316                             break;
        1317                         }
        1318                    }
        1319  
        1320                }
        1321                // Set t he new con tent
        1322                if (pati entDocumen t != null)  {
        1323                    pati entDocumen t.setDocum ent(consen tDirective String);
        1324                }
        1325  
        1326                // Updat e
        1327                this.pip .updatePat ientDocume nt(patient Document);
        1328                // Retur n the cons ent direct ive associ ated with  the update
        1329                final Co nsentDirec tiveUpdate Response r esponse =  new Consen tDirective UpdateResp onse();
        1330  
        1331                if (pati entDocumen t != null)  {
        1332                    fina l ConsentD irectiveRe ferenceTyp e consentD irectiveRe ference =  this.mappe r.map(pati entDocumen t.getConse ntDirectiv e(), Conse ntDirectiv eReference Type.class );
        1333                    resp onse.setCo nsentDirec tiveRefere nce(consen tDirective Reference) ;
        1334                }
        1335  
        1336                // Inter cept and a udit the C DA R2 XML  Request
        1337                try {
        1338                    this .consentDi rectiveDoc umentAudit Intercepto r.intercep t(consentD irectiveUp dateReques t);
        1339                }
        1340                catch (f inal Inter ceptorExce ption ex)  {
        1341                    thro w new Cons entManagem entService Exception( ex);
        1342                }
        1343  
        1344                return r esponse;
        1345           }
        1346           ca tch (final  Transform erExceptio n ex) {
        1347                throw ne w ConsentM anagementS erviceExce ption(ex);
        1348           }
        1349           ca tch (final  JAXBExcep tion ex) {
        1350                throw ne w ConsentM anagementS erviceExce ption(ex);
        1351           }
        1352       }
        1353  
        1354       @Overr ide
        1355       public  Restricti onsQueryRe sponse get Restrictio ns(final R estriction sQueryRequ est rqr)
        1356                throws C onsentMana gementServ iceExcepti on
        1357       {
        1358  
        1359           Po licyConstr aints pc =  null;
        1360           tr y {
        1361                ArrayLis t<String>  patients =  new Array List<Strin g>();
        1362                patients .add(rqr.g etPatientI d());
        1363                //get th e constarn ts for the  patient
        1364                pc = thi s.pip.getP olicyConst raints(pat ients, thi s.pip.getC onsentType ByName(Con sentType.N W_HIN_ORGA NIZATION_R ESTRICTION _AUTHORIZA TION.value ()));
        1365           }
        1366           ca tch (final  Exception  e) {
        1367                if (Cons entManagem entService Impl.logge r.isLoggab le(Level.F INE)) {
        1368                    e.pr intStackTr ace();
        1369                }
        1370                ConsentM anagementS erviceImpl .logger.lo gp(Level.W ARNING, th is.getClas s().getNam e(), "getR estriction s", e.getM essage());
        1371           }
        1372           Re strictions QueryRespo nse respon se = new R estriction sQueryResp onse();
        1373           if  (pc != nu ll) {
        1374                Collecti on<Organiz ation> org anizations  = pc.getP atientExcl udedOrgani zations();
        1375                for (fin al Organiz ation orga nization :  organizat ions) {
        1376                    fina l Organiza tionType o rg = this. mapper.map (organizat ion, Organ izationTyp e.class);
        1377                    resp onse.getOr ganization ().add(org );
        1378                }
        1379           }
        1380  
        1381           re turn respo nse;
        1382       }
        1383  
        1384       @Overr ide
        1385       public  StatusQue ryResponse  getStatus (final Sta tusQueryRe quest sqr)
        1386                throws C onsentMana gementServ iceExcepti on
        1387       {
        1388  
        1389           Ar rayList<St ring> expi ringTypes  = new Arra yList<Stri ng>();//co nsents tha t do expir e
        1390           Ar rayList<St ring> none xpiringTyp es = new A rrayList<S tring>();/ /things th at don't e xpire
        1391           ex piringType s.add(Cons entType.NW _HIN_AUTHO RIZATION.v alue());
        1392           ex piringType s.add(Cons entType.SS A_AUTHORIZ ATION.valu e());
        1393           no nexpiringT ypes.add(C onsentType .NW_HIN_OR GANIZATION _RESTRICTI ON_AUTHORI ZATION.val ue());
        1394           Co llection<C onsentDire ctive> all ConsentDir ectives =  null;
        1395           
        1396           // get the la st millise cond from  yesterday  because we  want to g et all the  active co nsents inc luding tod ay at midn ight (12:0 0 AM)
        1397           Da te startOf Today = Da teUtils.tr uncate(new  Date(), C alendar.DA Y_OF_MONTH );
        1398           Da te lastMil lisecondOf Yesterday  = DateUtil s.addMilli seconds(st artOfToday , -1);
        1399           
        1400           tr y {
        1401                ArrayLis t<String>  patients =  new Array List<Strin g>();
        1402                patients .add(sqr.g etPatientI d());
        1403                allConse ntDirectiv es = this. pip.getCon sentHistor y(patients );
        1404           }
        1405           ca tch (final  Exception  e) {
        1406                if (Cons entManagem entService Impl.logge r.isLoggab le(Level.F INE)) {
        1407                    e.pr intStackTr ace();
        1408                }
        1409                ConsentM anagementS erviceImpl .logger.lo gp(Level.W ARNING, th is.getClas s().getNam e(), "getS tatus", e. getMessage ());
        1410           }
        1411           St atusQueryR esponse re sponse = n ew StatusQ ueryRespon se();
        1412           if  (allConse ntDirectiv es != null ) {
        1413                for (fin al Consent Directive  directive  : allConse ntDirectiv es) {
        1414                    if ( NullChecke r.isNotEmp ty(directi ve) && Nul lChecker.i sEmpty(dir ective.get OptoutTS() ) && NullC hecker.isE mpty(direc tive.getOp toutDate() )) {
        1415                         if (nonexp iringTypes .contains( directive. getOptinCo nsentType( ).getName( ))) {
        1416                             respon se.getAuth orization( ).add(dire ctive.getO ptinConsen tType().ge tName());
        1417                         }
        1418                         else if (e xpiringTyp es.contain s(directiv e.getOptin ConsentTyp e().getNam e())
        1419                                 &&  directive .getExpira tionDate() .after(las tMilliseco ndOfYester day)) {
        1420                             respon se.getAuth orization( ).add(dire ctive.getO ptinConsen tType().ge tName());
        1421                         }
        1422                    }
        1423                }
        1424           }
        1425           fo r (int c =  0; c < re sponse.get Authorizat ion().size (); c++) {
        1426                response .getAuthor ization(). set(c, res ponse.getA uthorizati on().get(c ).replace( "NwHIN", " eHealth")) ;
        1427           }
        1428           re turn respo nse;
        1429       }
        1430  
        1431       @Requi red
        1432       public  void setD ataToConse ntDirectiv eDocument( Transforme r<Document , Document > dataToCo nsentDirec tiveDocume nt)
        1433       {
        1434           th is.dataToC onsentDire ctiveDocum ent = data ToConsentD irectiveDo cument;
        1435       }
        1436  
        1437       @Requi red
        1438       public  void setA nnouncemen tToAnnounc ePatientRe quest(
        1439                final Tr ansformer< Announceme nt, Announ cePatientR equest> an nouncement ToAnnounce PatientReq uest)
        1440       {
        1441           th is.announc ementToAnn ouncePatie ntRequest  = announce mentToAnno uncePatien tRequest;
        1442       }
        1443  
        1444       @Requi red
        1445       public  void setA nnouncer(f inal Annou ncerInterf ace announ cer)
        1446       {
        1447           th is.announc er = annou ncer;
        1448       }
        1449  
        1450       @Requi red
        1451       public  void setC msJaxb2Mar shaller(fi nal Jaxb2M arshaller  jaxb2Marsh aller)
        1452       {
        1453           th is.cmsJaxb 2Marshalle r = jaxb2M arshaller;
        1454       }
        1455  
        1456       @Requi red
        1457       public  void setC onsentDire ctiveDocum entAuditIn terceptor(
        1458                final In terceptor< Object, Ob ject> cons entDirecti veDocument AuditInter ceptor)
        1459       {
        1460           th is.consent DirectiveD ocumentAud itIntercep tor = cons entDirecti veDocument AuditInter ceptor;
        1461       }
        1462  
        1463       @Requi red
        1464       public  void setC onsentDire ctiveDocum entToAutho rizationRe sponse(
        1465                final Tr ansformer< Document,  Document>  consentDir ectiveDocu mentToAuth orizationR esponse)
        1466       {
        1467           th is.consent DirectiveD ocumentToA uthorizati onResponse  = consent DirectiveD ocumentToA uthorizati onResponse ;
        1468       }
        1469  
        1470       @Requi red
        1471       public  void setC onsentDire ctiveDocum entToData(
        1472                final Tr ansformer< Document,  Document>  consentDir ectiveDocu mentToData )
        1473       {
        1474           th is.consent DirectiveD ocumentToD ata = cons entDirecti veDocument ToData;
        1475       }
        1476  
        1477       @Requi red
        1478       public  void setC onsentDire ctiveDocum entToRevoc ationRespo nse(
        1479                final Tr ansformer< Document,  Document>  consentDir ectiveDocu mentToRevo cationResp onse)
        1480       {
        1481           th is.consent DirectiveD ocumentToR evocationR esponse =  consentDir ectiveDocu mentToRevo cationResp onse;
        1482       }
        1483  
        1484       @Requi red
        1485       public  void setD ataJaxb2Ma rshaller(f inal JaxbU til dataJa xb2Marshal ler)
        1486       {
        1487           th is.dataJax b2Marshall er = dataJ axb2Marsha ller;
        1488       }
        1489  
        1490       @Requi red
        1491       public  void setF acilityRes olver(fina l Facility Resolver f acilityRes olver)
        1492       {
        1493           th is.facilit yResolver  = facility Resolver;
        1494       }
        1495  
        1496       @Requi red
        1497       public  void setM apper(fina l Mapper m apper)
        1498       {
        1499           th is.mapper  = mapper;
        1500       }
        1501  
        1502       @Requi red
        1503       public  void setP atientAnno uncer(fina l PatientA nnouncer p atientAnno uncer)
        1504       {
        1505           th is.patient Announcer  = patientA nnouncer;
        1506       }
        1507  
        1508       @Requi red
        1509       public  void setP ersonServi ce(final P ersonServi ceInterfac e personSe rvice)
        1510       {
        1511           th is.personS ervice = p ersonServi ce;
        1512       }
        1513  
        1514       @Requi red
        1515       public  void setP dqService( final PdqS ervice pdq Service)
        1516       {
        1517           th is.pdqServ ice = pdqS ervice;
        1518       }
        1519  
        1520       @Requi red
        1521       public  void setP ip(final P IPInterfac e pip)
        1522       {
        1523           th is.pip = p ip;
        1524       }
        1525  
        1526       @Requi red
        1527       public  void setS tringToXML (final Str ingToXML s tringToXML )
        1528       {
        1529           th is.stringT oXML = str ingToXML;
        1530       }
        1531       
        1532       @Requi red
        1533       public  void setD elayedCons entDAO(fin al Delayed ConsentDAO  delayedCo nsentDAO)  {
        1534           th is.delayed ConsentDAO  = delayed ConsentDAO ;
        1535       }
        1536  
        1537       @Requi red
        1538       public  void setA uditServic e(final Au ditService  auditServ ice) {
        1539           th is.auditSe rvice = au ditService ;
        1540       }
        1541  
        1542       // TOD O: Fix - e Benefits c an send ot her consen t types
        1543       privat e ServiceC onsumerCon textType v alidateAnd FixService ConsumerCo ntext(
        1544                ServiceC onsumerCon textType s cct, final  String ic n)
        1545       {
        1546           //  if (NullC hecker.isE mpty(scct) ) {
        1547           //  scct = ne w ServiceC onsumerCon textType() ;
        1548           //  scct.setC onsentType (ConsentTy pe.NW_HIN_ AUTHORIZAT ION);
        1549           //  scct.setS erviceCons umerType(S erviceCons umer.VETER ANS_PORTAL );
        1550           //  }
        1551           //  If Facili ty is Empt y it must  be from eB enefits
        1552           if  (NullChec ker.isEmpt y(scct.get ServiceCon sumerType( ))) {
        1553                scct.set ServiceCon sumerType( ServiceCon sumer.VETE RANS_PORTA L);
        1554           }
        1555           if  (scct.get ServiceCon sumerType( ).value(). equals(Ser viceConsum er.VETERAN S_PORTAL.v alue())) {
        1556                scct.set User("eBen efits");
        1557                // Get P atientPref erred Faci lity
        1558                String p pf = "";
        1559                try {
        1560                    ppf  = this.fac ilityResol ver.getPat ientPrefer redFacilit y(icn);
        1561                }
        1562                catch (f inal Excep tion e) {
        1563                    e.pr intStackTr ace();
        1564                }
        1565                scct.set Facility(p pf);
        1566           }
        1567           el se if (scc t.getServi ceConsumer Type().val ue().equal s(ServiceC onsumer.KI OSK.value( ))) {
        1568                scct.set User(Servi ceConsumer .KIOSK.val ue());
        1569                // Get P atientPref erred Faci lity
        1570                String p pf = "";
        1571                try {
        1572                    ppf  = this.fac ilityResol ver.getPat ientPrefer redFacilit y(icn);
        1573                }
        1574                catch (f inal Excep tion e) {
        1575                    e.pr intStackTr ace();
        1576                }
        1577                scct.set Facility(p pf);
        1578           }
        1579           //  if (NullC hecker.isE mpty(scct. getConsent Type())) {
        1580           //  scct.setC onsentType (ConsentTy pe.NW_HIN_ AUTHORIZAT ION);
        1581           //  }
        1582           re turn scct;
        1583       }
        1584   }