4298. EPMO Open Source Coordination Office Redaction File Detail Report

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

4298.1 Files compared

# Location File Last Modified
1 Fri Jun 9 19:51:26 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-web\src\main\java\gov\va\nvap\web\patient PatientDetails.java Fri Apr 21 20:15:58 2017 UTC

4298.2 Comparison summary

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

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

4298.4 Active regular expressions

No regular expressions were active.

4298.5 Comparison detail

        1   package go v.va.nvap. web.patien t;
        2  
        3   import gov .va.nvap.c ommon.tran sformer.Tr ansformerE xception;
        4   import gov .va.nvap.c ommon.vali dation.Ass ert;
        5   import gov .va.nvap.c ommon.vali dation.Nul lChecker;
        6   import gov .va.nvap.c ommon.xpat h.XPathExc eption;
        7   import gov .va.nvap.p rivacy.Con sentDirect iveOptOutR easonType;
        8   import gov .va.nvap.p rivacy.Con sentDirect iveReferen ceType;
        9   import gov .va.nvap.p rivacy.Con sentType;
        10   import gov .va.nvap.p rivacy.Org anizationT ype;
        11   import gov .va.nvap.s ervice.ada pter.doc.A dapterExce ption;
        12   import gov .va.nvap.s ervice.pdq .Facility;
        13   import gov .va.nvap.s ervice.pdq .PatientCo rrelations Query;
        14   import gov .va.nvap.s ervice.pdq .PatientCo rrelations Response;
        15   import gov .va.nvap.s ervice.pdq .PatientDe mographics ;
        16   import gov .va.nvap.s ervice.pdq .PatientDe mographics Query;
        17   import gov .va.nvap.s ervice.pdq .PatientDe mographics Response;
        18   import gov .va.nvap.s ervice.pdq .PdqExcept ion;
        19   import gov .va.nvap.s ervice.pdq .PdqServic e;
        20   import gov .va.nvap.s ervice.pdq .RemovePat ientCorrel ationReque st;
        21   import gov .va.nvap.s vc.consent mgmt.jpa.C onsentDire ctiveJpaCo ntroller;
        22   import gov .va.nvap.s vc.consent mgmt.stub. adapter.an nounce.dat a.Announce ment;
        23   import gov .va.nvap.s vc.consent mgmt.stub. adapter.an nounce.dat a.PatientA nnouncer;
        24   import gov .va.nvap.s vc.consent mgmt.stub. dao.DelayR easonDAO;
        25   import gov .va.nvap.s vc.consent mgmt.stub. dao.Delaye dConsentDA O;
        26   import gov .va.nvap.s vc.consent mgmt.stub. dao.Letter TypeDAO;
        27   import gov .va.nvap.s vc.consent mgmt.stub. dao.MailLo gDAO;
        28   import gov .va.nvap.s vc.consent mgmt.stub. dao.MailNo tification DAO;
        29   import gov .va.nvap.s vc.consent mgmt.stub. dao.MailTe mplateDAO;
        30   import gov .va.nvap.s vc.consent mgmt.stub. data.Conse ntDirectiv e;
        31   import gov .va.nvap.s vc.consent mgmt.stub. data.Delay Reason;
        32   import gov .va.nvap.s vc.consent mgmt.stub. data.Delay edConsent;
        33   import gov .va.nvap.s vc.consent mgmt.stub. data.MailL og;
        34   import gov .va.nvap.s vc.consent mgmt.stub. data.MailN otificatio n;
        35   import gov .va.nvap.w eb.consent .audit.Aud itedConsen tEx;
        36   import gov .va.nvap.w eb.consent .audit.dao .AuditedCo nsentDAO;
        37   import gov .va.nvap.w eb.consent .comment.C onsentComm ent;
        38   import gov .va.nvap.w eb.consent .comment.C onsentComm entDAO;
        39   import gov .va.nvap.w eb.helper. document.D ocumentHel per;
        40   import gov .va.nvap.w eb.helper. document.M ediaType;
        41   import gov .va.nvap.w eb.helper. document.R epresentat ionType;
        42   import gov .va.nvap.w eb.helper. facility.F acilityHel per;
        43   import gov .va.nvap.w eb.helper. privacy.Co nsentManag ementHelpe r;
        44   import gov .va.nvap.w eb.user.Us erHelper;
        45   import gov .va.nvap.w eb.util.Co nstants;
        46   import gov .va.nvap.w eb.util.DA SUtil;
        47   import gov .va.nvap.w eb.util.da te.DateUti l;
        48   import gov .va.nvap.w eb.util.fi le.FileUpl oadUtil;
        49   import gov .va.nvap.w eb.util.fi le.PdfGene rator;
        50   import jav a.io.ByteA rrayInputS tream;
        51   import jav a.io.ByteA rrayOutput Stream;
        52   import jav a.io.IOExc eption;
        53   import jav a.io.Input Stream;
        54   import jav a.io.Input StreamRead er;
        55   import jav a.io.Reade r;
        56   import jav a.io.Unsup portedEnco dingExcept ion;
        57   import jav a.net.URL;
        58   import jav a.text.Par seExceptio n;
        59   import jav a.text.Sim pleDateFor mat;
        60   import jav a.util.Arr ayList;
        61   import jav a.util.Arr ays;
        62   import jav a.util.Col lection;
        63   import jav a.util.Col lections;
        64   import jav a.util.Com parator;
        65   import jav a.util.Dat e;
        66   import jav a.util.Has hMap;
        67   import jav a.util.Lis t;
        68   import jav a.util.Map ;
        69   import jav a.util.Sca nner;
        70   import jav a.util.log ging.Level ;
        71   import jav a.util.log ging.Logge r;
        72   import jav ax.ejb.EJB ;
        73   import jav ax.servlet .ServletEx ception;
        74   import jav ax.servlet .ServletOu tputStream ;
        75   import jav ax.servlet .http.Http ServletReq uest;
        76   import jav ax.servlet .http.Http ServletRes ponse;
        77   import jav ax.servlet .http.Http Session;
        78   import org .apache.co mmons.file upload.Fil eItem;
        79   import org .apache.co mmons.io.I OUtils;
        80   import sta tic org.ap ache.commo ns.lang.St ringEscape Utils.esca peXml;
        81   import org .apache.co mmons.logg ing.Log;
        82   import org .apache.co mmons.logg ing.LogFac tory;
        83   import org .json.JSON Exception;
        84   import org .json.JSON Object;
        85   import web logic.net. http.Https URLConnect ion;
        86  
        87   /**
        88    * Get the  detailed  view of th e patient.
        89    *
        90    * @author  Asha Amri traj
        91    * @author  Irakli Ka kushadze
        92    * @author  Zack Pete rson
        93    */
        94   public cla ss Patient Details ex tends
        95                    gov. va.nvap.we b.app.Resp onseDispat cherHttpSe rvlet {
        96           st atic priva te final L og LOG = L ogFactory. getLog(Pat ientDetail s.class);
        97  
        98           /* *
        99            *  Serial UI D.
        100            * /
        101           pr ivate stat ic final l ong serial VersionUID  = 9603553 8957225940 3L;
        102  
        103       privat e static f inal int b ufferSize  = 8192;
        104  
        105           /* *
        106            *  Announce  patients t o the NwHI N.
        107            * /
        108           @E JB(beanInt erface = P atientAnno uncer.clas s, mappedN ame = "Pat ientAnnoun cer")
        109           pr ivate Pati entAnnounc er patient Announcer;
        110           /* *
        111            *  Patient D emographic s Service  to get the  demograph ics and co rrelations
        112            *  from the  MPI.
        113            * /
        114           @E JB(beanInt erface = P dqService. class, map pedName =  "PdqServic e")
        115           Pd qService p dqService;
        116  
        117           /* *
        118            *  Announce  is called  when the u ser clicke d on Annou nce on the  Patient
        119            *  Details p age.
        120        *
        121        * @pa ram reques t http ser vlet reque st
        122        * @pa ram respon se http se rvlet resp onse
        123        *
        124        * @th rows javax .servlet.S ervletExce ption
        125        * @th rows java. io.IOExcep tion
        126            * /
        127           pu blic void  announce(f inal HttpS ervletRequ est reques t,
        128                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        129                             IOExce ption {
        130                    // G et the ICN
        131                    fina l String i cn = reque st.getPara meter("icn ");
        132                    Asse rt.assertN otEmpty(ic n, "ICN ca nnot be nu ll!");
        133                    if ( this.valid ate(reques t, respons e, "announ ce")) {
        134                PatientA nnounceThr ead announ ceThread =
        135                         new Patien tAnnounceT hread("ann ouncerThre ad");
        136                announce Thread.set CmsHelper( this.getCm sHelper()) ;
        137                announce Thread.set FacilityHe lper(this. getFacilit yHelper()) ;
        138                announce Thread.set PatientAnn ouncer(thi s.patientA nnouncer);
        139                announce Thread.set PatientIcn (icn);
        140                announce Thread.set PdqService (this.pdqS ervice);
        141                announce Thread.set RemoteUser Id(UserHel per.getUse rName(requ est));
        142                announce Thread.sta rt();
        143  
        144                final Ht tpSession  session =  request.ge tSession(f alse);
        145                session. setAttribu te("messag e", "Patie nt announc ement star ted. You m ay move on  to anothe r announce ment or ac tivity.");
        146  
        147                this.for ward(reque st, respon se, "searc h");
        148                    } el se {
        149                             // Val idation
        150                             this.f orward(req uest, resp onse, "val idate");
        151                    }
        152           }
        153  
        154       public  void dela yAuthoriza tion(final  List<File Item> file Items,
        155                             final  HttpServle tRequest r equest, fi nal HttpSe rvletRespo nse respon se)
        156                             throws  ServletEx ception, I OException  {
        157  
        158           fi nal HttpSe ssion sess ion = requ est.getSes sion(false );
        159  
        160                    // G et the fie lds
        161                    fina l Map<Stri ng, String > formFiel ds = FileU ploadUtil
        162                                      .getForm Fields(fil eItems);
        163  
        164           Lo ng consent Id = null;
        165  
        166           // Get all th e delay re asons
        167           Co llection<D elayReason > delayRea sonCollect ion = this .getDelayR easonDAO() .findAll() ;
        168  
        169           // Get the de lay reason (s) select ed
        170           fi nal ArrayL ist<String > delayRea sons = new  ArrayList <String>(A rrays.asLi st(formFie lds.get("c ollectedRe asons").sp lit(","))) ;
        171  
        172           Ar rayList<De layReason>  theseReas ons = new  ArrayList< DelayReaso n>();
        173  
        174           // Convert th e list of  delay reas on id stri ngs into D elayReason  objects
        175           fo r (DelayRe ason reaso n : delayR easonColle ction) {
        176                if (dela yReasons.c ontains(re ason.getDe layReasonI d().toStri ng())) {
        177                    thes eReasons.a dd(reason) ;
        178                }
        179           }
        180  
        181                    // G et other f ields from  the form.
        182                    fina l String c onsentType  = formFie lds.get("c onsentType ");
        183           fi nal String  comments  = formFiel ds.get("co mments");
        184                    Stri ng userFac ilityStati onId = for mFields.ge t("userFac ility");
        185  
        186           if  (this.val idate(form Fields, re quest, res ponse, "de layAuthori zation"))  {
        187  
        188                             final  String use rId = User Helper.get UserName(r equest);
        189  
        190                             if (Nu llChecker. isEmpty(us erFacility StationId) ) {
        191                                      userFaci lityStatio nId = this .getFacili tyHelper()
        192                                                       .g etFaciltyS tationIdBy UserId(use rId);
        193                             }
        194  
        195                PatientD emographic s patientD emographic s = (Patie ntDemograp hics)sessi on.getAttr ibute("pat ientDemogr aphics");
        196  
        197                gov.va.n vap.svc.co nsentmgmt. stub.data. ConsentTyp e consentT ypeObject  = this.get ConsentDir ectiveJpaC ontroller( )
        198                    .fin dConsentTy peByName(c onsentType );
        199                Date tod ay = new D ate();
        200                DelayedC onsent da  = new Dela yedConsent ();
        201                da.setDa teAdded(to day);
        202                da.setDe layReasonC ollection( theseReaso ns);
        203                da.setPa tientFirst Name(patie ntDemograp hics.getFi rstName()) ;
        204                da.setPa tientLastN ame(patien tDemograph ics.getLas tName());
        205                da.setPa tientMiddl eName(pati entDemogra phics.getM iddleName( ));
        206                da.setPa tientSsn(p atientDemo graphics.g etSsn());
        207                da.setPa tientIen(( String)ses sion.getAt tribute("p atientIen" ));
        208                da.setCo nsentTypeI d(consentT ypeObject) ;
        209                da.setSt ationNumbe r(userFaci lityStatio nId);
        210                da.setUs erId(userI d);
        211  
        212                try {
        213                    cons entId = th is.getDela yedConsent DAO().crea te(da);
        214                } catch  (Exception  ex) {
        215                    Logg er.getLogg er(Patient Details.cl ass.getNam e()).log(L evel.SEVER E, null, e x);
        216                }
        217  
        218                //Handle  comments
        219                if(!Null Checker.is Empty(comm ents)) {
        220                    Cons entComment  comment =  new Conse ntComment( );
        221                    comm ent.setCom ments(comm ents);
        222                    comm ent.setCon sentType(c onsentType );
        223                    comm ent.setUse rId(userId );
        224                    comm ent.setDat eAdded(new  Date());
        225                    comm ent.setDel ayedConsen tId(consen tId);
        226  
        227                    this .getConsen tCommentDA O().create (comment);
        228                }
        229                // Succe ss
        230                this.for ward(reque st, respon se, "succe ss");
        231                    } el se {
        232                             // Val idate
        233                             this.f orward(req uest, resp onse, "val idate");
        234                    }
        235  
        236       }
        237  
        238       public  ConsentDi rectiveJpa Controller  getConsen tDirective JpaControl ler() {
        239           fi nal Consen tDirective JpaControl ler consen tDirective JpaControl ler = this .getBean(" consentDir ectiveJpaC ontroller" ,
        240                ConsentD irectiveJp aControlle r.class);
        241           re turn conse ntDirectiv eJpaContro ller;
        242       }
        243  
        244           /* *
        245            *  Get the c onsent man agement he lper from  Spring.
        246            * /
        247           pu blic Conse ntManageme ntHelper g etCmsHelpe r() {
        248                    fina l ConsentM anagementH elper cmsH elper = th is.getBean ("cmsHelpe r",
        249                                      ConsentM anagementH elper.clas s);
        250                    retu rn cmsHelp er;
        251           }
        252  
        253       public  DelayedCo nsentDAO g etDelayedC onsentDAO( ) {
        254           fi nal Delaye dConsentDA O delayedC onsentDAO  = this.get Bean("Dela yedConsent DAO", Dela yedConsent DAO.class) ;
        255           re turn delay edConsentD AO;
        256       }
        257  
        258       public  DelayReas onDAO getD elayReason DAO() {
        259           fi nal DelayR easonDAO d elayReason DAO = this .getBean(" DelayReaso nDAO", Del ayReasonDA O.class);
        260           re turn delay ReasonDAO;
        261       }
        262  
        263           /* *
        264            *  Get the d ocument he lper from  Spring.
        265            * /
        266           pu blic Docum entHelper  getDocumen tHelper()  {
        267                    retu rn this.ge tBean("ada pterDocume ntHelper",  DocumentH elper.clas s);
        268           }
        269  
        270           /* *
        271            *  Get the f acility he lper from  Spring.
        272            * /
        273           pu blic Facil ityHelper  getFacilit yHelper()  {
        274                    fina l Facility Helper fac ilityHelpe r = this.g etBean("fa cilityHelp er",
        275                                      Facility Helper.cla ss);
        276                    retu rn facilit yHelper;
        277           }
        278  
        279       public  ConsentCo mmentDAO g etConsentC ommentDAO( ) {
        280           fi nal Consen tCommentDA O consentC ommentDAO  = this.get Bean("cons entComment DAO", Cons entComment DAO.class) ;
        281  
        282           re turn conse ntCommentD AO;
        283       }
        284  
        285       public  PatientCo mmentDAO g etPatientC ommentDAO( ) {
        286           fi nal Patien tCommentDA O patientC ommentDAO  = this.get Bean("pati entComment DAO", Pati entComment DAO.class) ;
        287  
        288           re turn patie ntCommentD AO;
        289       }
        290  
        291       public  AuditedCo nsentDAO g etAuditedC onsentDAO( ) {
        292           fi nal Audite dConsentDA O auditedC onsentDAO  = this.get Bean("audi tedConsent DAO", Audi tedConsent DAO.class) ;
        293  
        294           re turn audit edConsentD AO;
        295       }
        296  
        297       public  LetterTyp eDAO getLe tterTypeDA O() {
        298           fi nal Letter TypeDAO le tterTypeDA O = this.g etBean("le tterTypeDA O", Letter TypeDAO.cl ass);
        299  
        300           re turn lette rTypeDAO;
        301       }
        302  
        303       public  MailNotif icationDAO  getMailNo tification DAO() {
        304           fi nal MailNo tification DAO mailNo tification DAO = this .getBean(" MailNotifi cationDAO" , MailNoti ficationDA O.class);
        305  
        306           re turn mailN otificatio nDAO;
        307       }
        308  
        309       public  MailLogDA O getMailL ogDAO() {
        310           fi nal MailLo gDAO mailL ogDAO = th is.getBean ("MailLogD AO", MailL ogDAO.clas s);
        311  
        312           re turn mailL ogDAO;
        313       }
        314  
        315       public  MailTempl ateDAO get MailTempla teDAO() {
        316           fi nal MailTe mplateDAO  mailTempla teDAO = th is.getBean ("MailTemp lateDAO",  MailTempla teDAO.clas s);
        317  
        318           re turn mailT emplateDAO ;
        319       }
        320  
        321           /* *
        322            *  Show the  consent ma nagement h istory.
        323        *
        324        * @pa ram reques t http ser vlet reque st
        325        * @pa ram respon se http se rvlet resp onse
        326        *
        327        * @th rows javax .servlet.S ervletExce ption
        328        * @th rows java. io.IOExcep tion
        329            * /
        330           pu blic void  history(fi nal HttpSe rvletReque st request ,
        331                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        332                             IOExce ption {
        333                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        334                    // D ocument ty pe = OPT-I N/OPT-OUT
        335                    fina l String d ocumentTyp e = reques t.getParam eter("docu mentType") ;
        336                    fina l String c onsentDirI d = reques t.getParam eter("cons entDirId") ;
        337  
        338                    Asse rt.assertN otEmpty(do cumentType , "Documen t Type can not be nul l!");
        339                    fina l String d ocument =  this.getCm sHelper(). retrieveDo cument(
        340                                      consentD irId, docu mentType);
        341                    // S et the doc ument for  further qu eries
        342                    sess ion.setAtt ribute("do cument", d ocument);
        343                    sess ion.setAtt ribute("do cumentType ", documen tType);
        344                    sess ion.setAtt ribute("co nsentDirId ", consent DirId);
        345                    // R eturn the  PDF
        346                    try  {
        347                             if ( D ASUtil.isD ASDocument (document) ){
        348                    // G et from DA S and show
        349                    // C ommented o ut code th at should  only be in voked
        350                    // i n dev/test  environme nt anyway  to get aro und
        351                    // f ixing code  that will  not be us ed in prod uction.
        352                                      /*if ( C onstants.i sDasUseMoc kRetrieve( ) ){
        353                                               //mockGetD ocumentFro mDAS(respo nse.getOut putStream( ));
        354                                      }else{*/
        355                                               getDocumen tFromDAS(r esponse.ge tOutputStr eam(), doc ument);
        356                                      //}
        357                             }else{
        358                                      final St ring attac hment = th is.getDocu mentHelper ()
        359                                                       .g etPrivacyC onsentDire ctiveAttac hment(docu ment);
        360                                      if (Null Checker.is NotEmpty(a ttachment) ) {
        361                                               this.getDo cumentHelp er()
        362                                                                .wri teAttachme ntToStream (
        363                                                                                  response ,
        364                                                                                  attachme nt,
        365                                                                                  MediaTyp e.fromValu e(this.get DocumentHe lper()
        366                                                                                                   .g etPrivacyC onsentDire ctiveMedia Type(
        367                                                                                                                     docume nt)),
        368                                                                                  Represen tationType .B64);
        369                                      } else {
        370                                               session.se tAttribute ("informat ionMessage ",
        371                                                                "The re are no  attachment s associat ed with th is consent  directive .");
        372                                               this.forwa rd(request , response , "noattac hment");
        373                                      }
        374                             }
        375                    } ca tch (final  Transform erExceptio n ex) {
        376                             throw  new Servle tException (ex);
        377                    } ca tch (final  XPathExce ption ex)  {
        378                             throw  new Servle tException (ex);
        379                    }
        380  
        381           }
        382  
        383           /* *
        384            *  User sele cted opt-i n in the P atient det ails page.
        385        *
        386        * @pa ram fileIt ems list o f uploaded  file item s
        387        * @pa ram reques t http ser vlet reque st
        388        * @pa ram respon se http se rvlet resp onse
        389        *
        390        * @th rows javax .servlet.S ervletExce ption
        391        * @th rows java. io.IOExcep tion
        392            * /
        393           pu blic void  optIn(fina l List<Fil eItem> fil eItems,
        394                             final  HttpServle tRequest r equest, fi nal HttpSe rvletRespo nse respon se)
        395                             throws  ServletEx ception, I OException  {
        396                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        397  
        398                    // G et the fie lds
        399                    fina l Map<Stri ng, String > formFiel ds = FileU ploadUtil
        400                                      .getForm Fields(fil eItems);
        401  
        402                    // G et the upl oaded file s
        403                    fina l List<Fil eItem> fil esUploaded  = FileUpl oadUtil
        404                                      .getFile sUploaded( fileItems) ;
        405  
        406           St ring conse ntId = "";
        407  
        408                    // G et the icn
        409                    fina l String i cn = formF ields.get( "icn");
        410                    fina l String c onsentType  = formFie lds.get("c onsentType ");
        411                    fina l String p urposeOfUs e = formFi elds.get(" purposeOfU se");
        412                    fina l String e xpirationY ears = for mFields.ge t("expirat ionYears") ;
        413                    fina l String c omments =  formFields .get("comm ents");
        414                    // G et the org anizations  selected  by the use r
        415                    fina l String n ewRight =  formFields .get("newR ight");
        416                    // G et the dat e signed
        417                    fina l String s ignatureDa teStr = fo rmFields.g et("signat ureDate");
        418                    Stri ng userFac ilityStati onId = for mFields.ge t("userFac ility");
        419  
        420                    Stri ng[] organ izationNum bers = nul l;
        421                    if ( NullChecke r.isNotEmp ty(newRigh t)) {
        422                             organi zationNumb ers = newR ight.split (",");
        423  
        424                    }
        425  
        426                    if ( this.valid ate(formFi elds, requ est, respo nse, "optI n")) {
        427                             // Get  the date  after vali dation
        428                             final  Date signa tureDate =  DateUtil
        429                                               .parseDate MMddyyyy(s ignatureDa teStr);
        430                             // May be go to M PI
        431                             final  PatientDem ographics  patientDem ographics  = (Patient Demographi cs) sessio n
        432                                               .getAttrib ute("patie ntDemograp hics");
        433                             // Get  the files  uploaded
        434                             final  String use rId = User Helper.get UserName(r equest);
        435                             // Do  it as part  of the GU I if possi ble
        436  
        437                             if (Nu llChecker. isEmpty(us erFacility StationId) ) {
        438                                      userFaci lityStatio nId = this .getFacili tyHelper()
        439                                                       .g etFaciltyS tationIdBy UserId(use rId);
        440                             }
        441                             if ("N wHIN Organ ization Re striction  Modificati on"
        442                                               .equals(co nsentType) ) {
        443                                      this.get CmsHelper( ).optOut(
        444                                                       ic n,
        445                                                       pa tientDemog raphics,
        446                                                       fi lesUploade d,
        447                                                       "R evoked",
        448                                                       us erId,
        449                                                       us erFacility StationId,
        450                                                       si gnatureDat e,
        451                                                       Co nsentType. NW_HIN_ORG ANIZATION_ RESTRICTIO N_REVOCATI ON
        452                                                                         .value (), purpos eOfUse);
        453                                      consentI d = this.g etCmsHelpe r()
        454                                                       .o ptIn(icn,
        455                                                                         organi zationNumb ers,
        456                                                                         patien tDemograph ics,
        457                                                                         filesU ploaded,
        458                                                                         userId ,
        459                                                                         userFa cilityStat ionId,
        460                                                                         signat ureDate,
        461                                                                         Consen tType.NW_H IN_ORGANIZ ATION_REST RICTION_AU THORIZATIO N
        462                                                                                           .value(),  purposeOfU se, expira tionYears) ;
        463  
        464                             } else  {
        465                                      // Call  opt-in wit h files up loaded
        466                                      consentI d = this.g etCmsHelpe r().optIn( icn, organ izationNum bers,
        467                                                       pa tientDemog raphics, f ilesUpload ed, userId ,
        468                                                       us erFacility StationId,  signature Date, cons entType,
        469                                                       pu rposeOfUse , expirati onYears);
        470                             }
        471  
        472                // Updat e correspo nding dela yed author ization (i f one exis ts) after  opt-in
        473                boolean  delayedCon sentUpdate d = false;
        474                if (cons entType.eq uals(Conse ntType.NW_ HIN_AUTHOR IZATION.va lue()) ||  consentTyp e.equals(C onsentType .SSA_AUTHO RIZATION.v alue())) {
        475                    List <DelayedCo nsent> del ayedConsen ts = this. getDelayed ConsentDAO ().findByP atientIen( icn);
        476                    if ( delayedCon sents.size () > 0) {
        477                         gov.va.nva p.svc.cons entmgmt.st ub.data.Co nsentType  consentTyp eObject =  this.getCo nsentDirec tiveJpaCon troller(). findConsen tTypeByNam e(consentT ype);
        478                         if (consen tTypeObjec t != null)  {
        479                            for (De layedConse nt dc : de layedConse nts) {
        480                                 lo ng delayed Id = dc.ge tConsentTy peId().get ConsentTyp eId();
        481                                 if  ((consent TypeObject .getConsen tTypeId()  == delayed Id) && dc. getStatus( ).equals(" PENDING"))  {
        482                                      delayedC onsentUpda ted = true ;
        483                                      try {
        484                                          dc.s etStatus(" APPROVED") ;
        485                                          dc.s etResoluti onDate(new  Date());
        486                                          this .getDelaye dConsentDA O().update (dc);
        487  
        488                                          //St ore any co mments wit h the dela yed author zation
        489                                          if(! NullChecke r.isEmpty( comments))  {
        490                                               ConsentCom ment comme nt = new C onsentComm ent();
        491                                               comment.se tComments( comments);
        492                                               comment.se tConsentTy pe(consent Type);
        493                                               comment.se tUserId(us erId);
        494                                               comment.se tDateAdded (new Date( ));
        495                                               comment.se tDelayedCo nsentId(dc .getDelaye dConsentId ());
        496  
        497                                               this.getCo nsentComme ntDAO().cr eate(comme nt);
        498                                          }
        499                                      } catch  (Exception  ex) {
        500                                          Logg er.getLogg er(Patient Details.cl ass.getNam e()).log(L evel.SEVER E, null, e x);
        501                                      }
        502                                 }
        503                             }
        504                         }
        505                    }
        506                }
        507                if (!del ayedConsen tUpdated)  {
        508                    //Ha ndle comme nts normal ly if not  approving  a delayed  authorizat ion
        509                    if(! NullChecke r.isEmpty( comments))  {
        510                         ConsentCom ment comme nt = new C onsentComm ent();
        511                         comment.se tComments( comments);
        512                         comment.se tConsentTy pe(consent Type);
        513                         //There is  no Restri ction Modi fication c onsent typ e so we ne ed to chan ge it to A uthorizati on in orde r to be
        514                         //populate d correctl y in the j sp.
        515                         if (consen tType.equa ls("NwHIN  Organizati on Restric tion Modif ication"))  {
        516                             commen t.setConse ntType(Con sentType.N W_HIN_ORGA NIZATION_R ESTRICTION _AUTHORIZA TION.value ());
        517                         }
        518                         comment.se tUserId(us erId);
        519                         comment.se tDateAdded (new Date( ));
        520                         comment.se tConsentId (Long.valu eOf(consen tId));
        521  
        522                         this.getCo nsentComme ntDAO().cr eate(comme nt);
        523                    }
        524                }
        525                             // Suc cess
        526                             this.f orward(req uest, resp onse, "suc cess");
        527                             // ann ounce(requ est, respo nse);
        528                    } el se {
        529                             // Val idate
        530                             this.f orward(req uest, resp onse, "val idate");
        531                    }
        532           }
        533  
        534           /* *
        535            *  The user  selected o pt-out fro m the Pati ent detail s page.
        536        *
        537        * @pa ram reques t http ser vlet reque st
        538        * @pa ram respon se http se rvlet resp onse
        539        *
        540        * @th rows javax .servlet.S ervletExce ption
        541        * @th rows java. io.IOExcep tion
        542            * /
        543           pu blic void  optOut(fin al List<Fi leItem> fi leItems,
        544                             final  HttpServle tRequest r equest, fi nal HttpSe rvletRespo nse respon se)
        545                             throws  ServletEx ception, I OException  {
        546                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        547  
        548                    // G et the fie lds
        549                    fina l Map<Stri ng, String > formFiel ds = FileU ploadUtil
        550                                      .getForm Fields(fil eItems);
        551                    // G et the upl oaded file s
        552                    fina l List<Fil eItem> fil esUploaded  = FileUpl oadUtil
        553                                      .getFile sUploaded( fileItems) ;
        554                    fina l String c onsentType  = formFie lds.get("c onsentType ");
        555  
        556                    Stri ng consent Id = "";
        557  
        558                    // G et the icn
        559                    fina l String i cn = formF ields.get( "icn");
        560                    // G et the opt  out reaso n
        561                    fina l String r eason = fo rmFields.g et("reason ");
        562                    Stri ng signatu reDateStr  = formFiel ds.get("si gnatureDat e");
        563                    Stri ng comment s = formFi elds.get(" comments") ;
        564                    Stri ng decease dDateStr =  formField s.get("dec easedDate" );
        565                    Stri ng userFac ilityStati onId = for mFields.ge t("userFac ility");
        566                    fina l String p urposeOfUs e = formFi elds.get(" purposeOfU se");
        567                    fina l String e xpiryYears  = formFie lds.get("e xpirationY ears");
        568                    if ( ConsentDir ectiveOptO utReasonTy pe.PATIENT _DECEASED. value().eq uals(
        569                                      reason))  {
        570                             signat ureDateStr  = decease dDateStr;
        571                    }
        572  
        573                    if ( this.valid ate(formFi elds, requ est, respo nse, "optO ut")) {
        574                             final  Date signa tureDate =  DateUtil
        575                                               .parseDate MMddyyyy(s ignatureDa teStr);
        576                             // May be go to M PI
        577                             final  PatientDem ographics  patientDem ographics  = (Patient Demographi cs) sessio n
        578                                               .getAttrib ute("patie ntDemograp hics");
        579                             // Get  the files  uploaded
        580                             final  String use rId = User Helper.get UserName(r equest);
        581                             if (Nu llChecker. isEmpty(us erFacility StationId) ) {
        582                                      userFaci lityStatio nId = this .getFacili tyHelper()
        583                                                       .g etFaciltyS tationIdBy UserId(use rId);
        584                             }
        585  
        586                             // Opt -out witho ut files
        587                             consen tId = this .getCmsHel per().optO ut(icn, pa tientDemog raphics, f ilesUpload ed,
        588                                               reason, us erId, user FacilitySt ationId, s ignatureDa te,
        589                                               consentTyp e, purpose OfUse);
        590                             if (Co nsentDirec tiveOptOut ReasonType .NEW_AUTHO RIZATION.v alue()
        591                                               .equals(re ason)) {
        592                                      if (Cons entType.NW _HIN_REVOC ATION.valu e().equals (consentTy pe)) {
        593                                               consentId  = this.get CmsHelper( ).optIn(ic n, null, p atientDemo graphics,
        594                                                                null , userId,  userFacili tyStationI d, signatu reDate,
        595                                                                Cons entType.NW _HIN_AUTHO RIZATION.v alue(),
        596                                                                purp oseOfUse,  expiryYear s);
        597                                      } else i f (Consent Type.SSA_R EVOCATION. value().eq uals(
        598                                                       co nsentType) ) {
        599                                               consentId  = this.get CmsHelper( ).optIn(ic n, null, p atientDemo graphics,
        600                                                                null , userId,  userFacili tyStationI d, signatu reDate,
        601                                                                Cons entType.SS A_AUTHORIZ ATION.valu e(),
        602                                                                purp oseOfUse,  expiryYear s);
        603                                      }
        604                             }
        605  
        606                             //hand le comment s
        607                             if(!Nu llChecker. isEmpty(co mments)) {
        608                                 Co nsentComme nt comment  = new Con sentCommen t();
        609                                 co mment.setC omments(co mments);
        610                                 co mment.setC onsentType (consentTy pe);
        611                                 co mment.setU serId(user Id);
        612                                 co mment.setD ateAdded(n ew Date()) ;
        613                                 co mment.setC onsentId(L ong.valueO f(consentI d));
        614  
        615                                 th is.getCons entComment DAO().crea te(comment );
        616                             }
        617  
        618                             // Rem ove attrib utes befor e exiting
        619                             // Suc cess
        620                             this.f orward(req uest, resp onse, "suc cess");
        621                    } el se {
        622                             // Val idate
        623                             this.f orward(req uest, resp onse, "val idate");
        624                    }
        625           }
        626  
        627           /* *
        628            *  If a syst em adminis trator nee ds to remo ve all cor relations  from the M PI.
        629        *
        630        * @pa ram reques t http ser vlet reque st
        631        * @pa ram respon se http se rvlet resp onse
        632        *
        633        * @th rows javax .servlet.S ervletExce ption
        634        * @th rows java. io.IOExcep tion
        635            * /
        636           pu blic void  revoke(fin al HttpSer vletReques t request,
        637                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        638                             IOExce ption {
        639                    // G et the icn
        640                    fina l String i cn = reque st.getPara meter("icn ");
        641                    fina l String c omments =  request.ge tParameter ("comments ");
        642                    fina l String c onsentType  = request .getParame ter("conse ntType");
        643                    if ( this.valid ate(reques t, respons e, "revoke ")) {
        644                             // Mak e the corr elations q uery
        645                             final  PatientCor relationsQ uery corre lationsQue ry = new P atientCorr elationsQu ery();
        646                             correl ationsQuer y.setPatie ntId(icn);
        647                             try {
        648                                      // Get t he correla tions resp onse
        649                                      final Pa tientCorre lationsRes ponse corr elationsRe sponse = t his.pdqSer vice
        650                                                       .g etCorrelat edFaciliti es(correla tionsQuery );
        651                                      // Get t he demogra phics
        652                                      final Pa tientDemog raphicsQue ry demogra phicsQuery  = new Pat ientDemogr aphicsQuer y();
        653                                      demograp hicsQuery. setPatient Id(icn);
        654                                      final Pa tientDemog raphicsRes ponse demo graphicsRe sponse = t his.pdqSer vice
        655                                                       .g etPatientD emographic s(demograp hicsQuery) ;
        656                                      final Pa tientDemog raphics de mographics  = demogra phicsRespo nse
        657                                                       .g etPatientD emographic s();
        658                                      // Get a ll the fac ilities
        659                                      final Li st<Facilit y> facilit ies = corr elationsRe sponse
        660                                                       .g etFaciliti es();
        661                                      // For e ach NwHIN  facilities  other tha n DoD, cre ate a requ est to
        662                                      // remov e the corr elations o n the MPI.
        663                                      if (Null Checker.is NotEmpty(f acilities) ) {
        664                                               for (final  Facility  facility :  facilitie s) {
        665                                                       //  Get the o rganizatio n
        666                                                       fi nal Organi zationType  stdOrgani zation = t his
        667                                                                         .getCm sHelper(). getOrganiz ationByNum ber(
        668                                                                                           facility.g etFacility Id());
        669                                                       //  You reall y cant rem ove the Do D correlat ions
        670                                                       if  (NullChec ker.isEmpt y(stdOrgan ization)
        671                                                                         || (Nu llChecker. isNotEmpty (stdOrgani zation) &&  stdOrgani zation
        672                                                                                           .getOrgNum ber().equa ls("200DOD "))) {
        673                                                       }  else {
        674                                                                // G et the fac ility to b e removed  from the M PI
        675                                                                // c orrelation
        676                                                                Stri ng correla tedAssigni ngAuthorit yName = fa cility
        677                                                                                  .getAssi gningAutho rityName() ;
        678                                                                fina l String c orrelatedA ssigningAu thorityOid  = stdOrga nization
        679                                                                                  .getOrgO id();
        680                                                                fina l String f irstName =  demograph ics
        681                                                                                  .getFirs tName();
        682                                                                fina l String m iddleName  = demograp hics
        683                                                                                  .getMidd leName();
        684                                                                fina l String l astName =  demographi cs.getLast Name();
        685                                                                fina l RemovePa tientCorre lationRequ est remove PatientCor relationRe quest = ne w RemovePa tientCorre lationRequ est();
        686                                                                if ( NullChecke r
        687                                                                                  .isEmpty (correlate dAssigning AuthorityN ame)) {
        688                                                                         correl atedAssign ingAuthori tyName = s tdOrganiza tion
        689                                                                                           .getOrgNum ber();
        690                                                                }
        691                                                                // S et values
        692                                                                remo vePatientC orrelation Request
        693                                                                                  .setCorr elatedAssi gningAutho rityName(c orrelatedA ssigningAu thorityNam e);
        694                                                                remo vePatientC orrelation Request
        695                                                                                  .setCorr elatedAssi gningAutho rityOid(co rrelatedAs signingAut horityOid) ;
        696                                                                remo vePatientC orrelation Request
        697                                                                                  .setCorr elatedPati entId(faci lity
        698                                                                                                   .g etCorrelat edPatientI d());
        699                                                                remo vePatientC orrelation Request.se tPatientId (icn);
        700                                                                remo vePatientC orrelation Request
        701                                                                                  .setPati entFirstNa me(firstNa me);
        702                                                                remo vePatientC orrelation Request
        703                                                                                  .setPati entMiddleN ame(middle Name);
        704                                                                remo vePatientC orrelation Request
        705                                                                                  .setPati entLastNam e(lastName );
        706                                                                remo vePatientC orrelation Request.se tUserId(Us erHelper.g etUserName (request)) ;
        707                                                                // C all the se rvice to r emove corr elations.
        708                                                                Remo vePatientC orrelation Request r  = this.pdq Service
        709                                                                                  .removeP atientCorr elation(re movePatien tCorrelati onRequest) ;
        710  
        711                                                                //ha ndle comme nts
        712                                                                if(! NullChecke r.isEmpty( comments))  {
        713                                                                     ConsentCom ment comme nt = new C onsentComm ent();
        714                                                                     comment.se tComments( comments);
        715                                                                     comment.se tConsentTy pe(consent Type);
        716                                                                     comment.se tUserId(Us erHelper.g etUserName (request)) ;
        717                                                                     comment.se tDateAdded (new Date( ));
        718                                                                     //TODO: co mment.setC onsentId(L ong.valueO f(consentI d));
        719  
        720                                                                     this.getCo nsentComme ntDAO().cr eate(comme nt);
        721                                                                }
        722                                                       }
        723                                               }
        724                                      }
        725                             } catc h (final P dqExceptio n ex) {
        726                                      throw ne w ServletE xception(e x);
        727                             }
        728                             this.f orward(req uest, resp onse, "suc cess");
        729                    } el se {
        730                             this.f orward(req uest, resp onse, "val idate");
        731                    }
        732           }
        733       /*
        734       Method  that upda tes delaye d authoriz ation upon  cancelati on.
        735       */
        736       public  void canc elDelay(fi nal HttpSe rvletReque st request ,
        737                final Ht tpServletR esponse re sponse) th rows Servl etExceptio n,
        738                IOExcept ion {
        739  
        740           fi nal HttpSe ssion sess ion = requ est.getSes sion(false );
        741  
        742           // Find the d elayed aut horization  by the id  sent in f rom the js p
        743           De layedConse nt dc = th is.getDela yedConsent DAO().find ByDelayedC onsentId(( Long)sessi on.getAttr ibute("del ayedConsen tId"));
        744           St ring comme nts = requ est.getPar ameter("ca ncelCommen ts");
        745  
        746           // Create com ment if ap plicable
        747           if  (!NullChe cker.isNul lOrEmpty(c omments))  {
        748                ConsentC omment com ment = new  ConsentCo mment();
        749                comment. setComment s(comments );
        750                comment. setDateAdd ed(new Dat e());
        751                comment. setUserId( UserHelper .getUserNa me(request ));
        752                comment. setDelayed ConsentId( dc.getDela yedConsent Id());
        753                comment. setConsent Type(dc.ge tConsentTy peId().get Name());
        754                this.get ConsentCom mentDAO(). create(com ment);
        755           }
        756  
        757           dc .setStatus ("CANCELED ");
        758           dc .setResolu tionDate(n ew Date()) ;
        759  
        760           tr y {
        761                this.get DelayedCon sentDAO(). update(dc) ;
        762           }  catch (Exc eption e)  {
        763                throw ne w ServletE xception(" There was  an issue u pdating th e delayed  authorizat ion with i d" + dc.ge tDelayedCo nsentId()) ;
        764           }
        765  
        766           th is.forward (request,  response,  "success") ;
        767       }
        768       /*
        769       Method  that pass es attribu tes to can celDelay m ethod and  calls the  cancel jsp
        770       */
        771       public  void canc elDelayedA uthorizati on(final H ttpServlet Request re quest,
        772                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        773                             IOExce ption {
        774  
        775           fi nal HttpSe ssion sess ion = requ est.getSes sion(false );
        776  
        777                    fina l String i cn = (Stri ng) sessio n.getAttri bute("icn" );
        778           fi nal long d elayedCons entId = (L ong.parseL ong(reques t.getParam eter("dela yedConsent Id")));
        779           se ssion.setA ttribute(" delayedCon sentId", d elayedCons entId);
        780           th is.forward (request,r esponse, " cancelDela y");
        781       }
        782  
        783       public  void prin tLetter(fi nal HttpSe rvletReque st request ,
        784                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        785                             IOExce ption {
        786  
        787           fi nal HttpSe ssion sess ion = requ est.getSes sion(false );
        788  
        789           se ssion.remo veAttribut e("delayed Consent");
        790           se ssion.remo veAttribut e("consent ");
        791  
        792                    fina l String i cn = (Stri ng) sessio n.getAttri bute("icn" );
        793           if  (request. getParamet er("delaye dConsentId ") != null ) {
        794                if (requ est.getPar ameter("ss aDelay") ! = null) {
        795                    sess ion.setAtt ribute("ss aDelay", t rue);
        796                }
        797                else if  (request.g etParamete r("eheDela y") != nul l) {
        798                    sess ion.setAtt ribute("eh eDelay", t rue);
        799                }
        800                DelayedC onsent dc  = this.get DelayedCon sentDAO(). findByDela yedConsent Id(Long.pa rseLong(re quest.getP arameter(" delayedCon sentId"))) ;
        801                session. setAttribu te("delaye dConsent",  dc);
        802           }
        803           el se if (req uest.getPa rameter("c onsentId")  != null)  {
        804                ConsentD irective c onsent = t his.getCon sentDirect iveJpaCont roller().f indConsent Directive( Long.parse Long(reque st.getPara meter("con sentId"))) ;
        805                session. setAttribu te("consen t", consen t);
        806           }
        807  
        808                    this .forward(r equest, re sponse, "p rintLetter ");
        809  
        810       }
        811  
        812       public  class Con sentWrappe r {
        813  
        814           pr ivate Cons entDirecti veReferenc eType norm alConsent;
        815           pr ivate Dela yedConsent  delayedCo nsent;
        816           pr ivate Bool ean isRevo ked;
        817           pr ivate Stri ng user;
        818           pr ivate List <ConsentCo mment> com ments = ne w ArrayLis t<ConsentC omment>();
        819           pr ivate Bool ean hasOpt InDocument Attachment ;
        820           pr ivate Bool ean hasOpt OutDocumen tAttachmen t;
        821           pr ivate List <MailNotif ication> m ailNotific ations = n ew ArrayLi st<MailNot ification> ();
        822  
        823           pu blic Conse ntWrapper( ConsentDir ectiveRefe renceType  normalCons ent, boole an isRevok ed) {
        824                this.nor malConsent  = normalC onsent;
        825                this.isR evoked = i sRevoked;
        826           }
        827  
        828           pu blic Conse ntWrapper( DelayedCon sent delay edConsent)  {
        829                this.del ayedConsen t = delaye dConsent;
        830                this.use r = delaye dConsent.g etUserId() ;
        831           }
        832  
        833           pu blic Date  entryDate( ) {
        834                if (norm alConsent  == null) {
        835                    retu rn delayed Consent.ge tDateAdded ();
        836                } else i f (isRevok ed) {
        837                    retu rn normalC onsent.get OptoutTS() ;
        838                } else {
        839                    retu rn normalC onsent.get OptinTS();
        840                }
        841           }
        842  
        843           pu blic List< ConsentCom ment> getC omments()  {
        844                return t his.commen ts;
        845           }
        846  
        847           pu blic List< MailNotifi cation> ge tMailNotif ications()  {
        848                return t his.mailNo tification s;
        849           }
        850  
        851           pu blic Delay edConsent  getDelayed Consent()  {
        852                return t his.delaye dConsent;
        853           }
        854  
        855           pu blic Conse ntDirectiv eReference Type getNo rmalConsen t() {
        856                return t his.normal Consent;
        857           }
        858  
        859  
        860           pu blic void  setOptInDo cumentAtta chment(boo lean hasAt tachment)  {
        861                this.has OptInDocum entAttachm ent = hasA ttachment;
        862           }
        863  
        864           pu blic boole an getOptI nDocumentA ttachment( ) {
        865                return t his.hasOpt InDocument Attachment ;
        866           }
        867  
        868           pu blic void  hasOptOutD ocumentAtt achment(bo olean hasA ttachment)  {
        869                this.has OptOutDocu mentAttach ment = has Attachment ;
        870           }
        871  
        872           pu blic boole an getOptO utDocument Attachment () {
        873                return t his.hasOpt OutDocumen tAttachmen t;
        874           }
        875  
        876           pu blic void  setUser(St ring user)  {
        877                this.use r = user;
        878           }
        879  
        880           pu blic Strin g getUser( ) {
        881                return t his.user;
        882           }
        883  
        884           pu blic boole an getIsRe voked(){
        885                return t his.isRevo ked;
        886           }
        887  
        888           pu blic Strin g getConse ntDisplayN ame() {
        889                String d isplayName ;
        890                if (norm alConsent  == null) {
        891                    disp layName =  delayedCon sent.getCo nsentTypeI d().getNam e();
        892                } else i f (isRevok ed) {
        893                    disp layName =  normalCons ent.getOpt outConsent Type().val ue();
        894                } else {
        895                    disp layName =  normalCons ent.getOpt inConsentT ype().valu e();
        896                }
        897                return d isplayName .replace(" NwHIN", Co nstants.ge tOrganizat ionName()) ;
        898           }
        899  
        900       }
        901  
        902       /**
        903        * Bas e method t hat handle s requests  that don' t specify  another me thod
        904        *
        905        * @pa ram reques t http ser vlet reque st
        906        * @pa ram respon se http se rvlet resp onse
        907        *
        908        * @th rows javax .servlet.S ervletExce ption
        909        * @th rows java. io.IOExcep tion
        910        */
        911           @O verride
        912           pr otected vo id unspeci fied(final  HttpServl etRequest  request,
        913                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        914                             IOExce ption {
        915                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        916  
        917                    fina l String i cn = (Stri ng) sessio n.getAttri bute("icn" );
        918  
        919                    if ( !NullCheck er.isNullO rEmpty(icn )) {
        920                             // Sto re the req uest id in  the sessi on
        921                             this.s etRequestI d(request,  response) ;
        922                             try {
        923                    List <ConsentWr apper> con sents = ne w ArrayLis t<ConsentW rapper>();
        924                    List <Long> con sentIds =  new ArrayL ist<Long>( );
        925  
        926                    // G et consent  directive s for curr ent patien t
        927                    List <ConsentDi rectiveRef erenceType > consentD irectiveRe ferences =  this.getC msHelper() .getConsen tDirective History(ic n);
        928  
        929                    // g et CONSENT _AUDIT inf o for this  patient
        930                    List <Object> a uditedCons entsUnorde red = this .getAudite dConsentDA O().getRes ultsByPati entId(icn) ;
        931  
        932                    // m ake a copy  of audite dConsentsU nordered s o that the  copy will  match the  consentDi rectiveRef erences
        933                    // a ccording t o the User Ids in aud itedConsen tsUnordere d
        934                    // b ut first m ake sure t here is on e auditedC onsent for  each cons entDirecti veReferenc es
        935                    Arra yList<Audi tedConsent Ex> audite dConsents  = new Arra yList<Audi tedConsent Ex>();
        936                    for  (ConsentDi rectiveRef erenceType  cdr : con sentDirect iveReferen ces) {
        937                         // find th e userId i n auditedC onsentsUno rdered for  this cons entDirecti veReferenc e
        938                         ConsentWra pper wrapp erOut = nu ll, wrappe rIn = null ;
        939                         //check wh ether alre ady found  optin/opto ut for thi s
        940                         Boolean fo undOptIn =  false;
        941                         Boolean fo undOptOut  = false;
        942                         //check to  see if co nsent is o pted out
        943                         if (cdr.ge tOptoutTS( ) != null)  {
        944                             wrappe rOut = new  ConsentWr apper(cdr,  true);
        945                         }else{
        946                             foundO ptOut = tr ue;
        947                         }
        948                         wrapperIn  = new Cons entWrapper (cdr, fals e);
        949                         //go throu gh audits
        950                         for (int i  = 0; i <  auditedCon sentsUnord ered.size( ); i++) {
        951                             Audite dConsentEx  ac = (Aud itedConsen tEx)audite dConsentsU nordered.g et(i);
        952                             String  consentTy pe = ac.ge tConsentTy pe();
        953                             String  cdrOptInC onsentType  =
        954                                 (c dr.getOpti nConsentTy pe() != nu ll) ? cdr. getOptinCo nsentType( ).value()  : "null";
        955                             String  cdrOptOut ConsentTyp e =
        956                                 (c dr.getOpto utConsentT ype() != n ull) ? cdr .getOptout ConsentTyp e().value( ) : "null" ;
        957                             if (co nsentType. equals(cdr OptInConse ntType) &&  !foundOpt In){
        958                                  w rapperIn.s etUser(ac. getUserId( ));
        959                                  f oundOptIn=  true;
        960                                  a uditedCons entsUnorde red.remove (i);
        961                                  i --;
        962                             }
        963                             else i f (consent Type.equal s(cdrOptOu tConsentTy pe) && !fo undOptOut  && wrapper Out != nul l) {
        964                                 fo undOptOut  = true;
        965                                 wr apperOut.s etUser(ac. getUserId( ));
        966                                 au ditedConse ntsUnorder ed.remove( i);
        967                                  i --;
        968                             }
        969                             if(fou ndOptIn &&  foundOptO ut){
        970                                 br eak;
        971                             }
        972                         }
        973                         if(wrapper Out != nul l){
        974                             consen ts.add(wra pperOut);
        975                         }
        976                         consents.a dd(wrapper In);
        977                         consentIds .add(Long. parseLong( cdr.getCon sentDirId( )));
        978                    }
        979  
        980                    //no w that we  have the c onsent Ids  for this  patient, l et's get t he comment s for them
        981                    if ( !consentId s.isEmpty( )) {
        982                         List<Conse ntComment>  comments  = this.get ConsentCom mentDAO(). getComment sByConsent Ids(consen tIds);
        983                         for (Conse ntComment  comment :  comments)  {
        984                             //Ther e is no Re striction  Modificati on consent  type so w e need to  change it  to Authori zation in  order to b e
        985                             //popu lated corr ectly in t he jsp.
        986                             if (co mment.getC onsentType ().equals( "NwHIN Org anization  Restrictio n Modifica tion")) {
        987                                 co mment.setC onsentType (ConsentTy pe.NW_HIN_ ORGANIZATI ON_RESTRIC TION_AUTHO RIZATION.v alue());
        988                             }
        989                             for (C onsentWrap per consen tWrapper :  consents)  {
        990                                 if  (comment. getConsent Id().toStr ing().equa ls(consent Wrapper.no rmalConsen t.getConse ntDirId()) ) {
        991                                      consentW rapper.com ments.add( comment);
        992                                 }
        993                             }
        994                         }
        995                    }
        996  
        997                    //ge t mail_not ification  data and a dd it to t he Consent Wrapper fo r "normal"  eHealth E xchange Re vocations
        998                    if ( !consentId s.isEmpty( )) {
        999                         List<MailN otificatio n> mails =  this.getM ailNotific ationDAO() .findByCon sentDirIds (consentId s);
        1000                         for (MailN otificatio n mail : m ails) {
        1001                             for (C onsentWrap per consen tWrapper :  consents)  {
        1002                                 if (mail.getC onsentDirI d().getCon sentDirId( ).toString ().equals( consentWra pper.norma lConsent.g etConsentD irId())) {
        1003                                      consentW rapper.mai lNotificat ions.add(m ail);
        1004                                 }
        1005                             }
        1006                         }
        1007                    }
        1008  
        1009                    //Ge t any dela yed consen t authoriz ations for  current p atient
        1010                    List <DelayedCo nsent> del ayedConsen tReference s = this.g etDelayedC onsentDAO( ).findByPa tientIen(i cn);
        1011  
        1012                    Dela yedConsent  NwHINacti veDelay =  null;
        1013                    Dela yedConsent  SSAactive Delay = nu ll;
        1014                    List <Long> del ayedConsen tIds = new  ArrayList <Long>();
        1015  
        1016                    for  (DelayedCo nsent dc :  delayedCo nsentRefer ences) {
        1017                         consents.a dd(new Con sentWrappe r(dc));
        1018                         delayedCon sentIds.ad d(dc.getDe layedConse ntId());
        1019  
        1020                         //Populate  any activ e delays
        1021                         if (dc.get Status().e quals("PEN DING")) {
        1022                             if (dc .getConsen tTypeId(). getName(). contains(" NwHIN")) {
        1023                                 Nw HINactiveD elay = dc;
        1024                             }
        1025                             else i f (dc.getC onsentType Id().getNa me().conta ins("SSA") ) {
        1026                                 SS AactiveDel ay = dc;
        1027                             }
        1028                         }
        1029                    }
        1030                    if ( delayedCon sentIds.si ze() > 0)  {
        1031                         List<Conse ntComment>  delayedCo mments = t his.getCon sentCommen tDAO().get CommentsBy DelayedCon sentIds(de layedConse ntIds);
        1032                         for (Conse ntComment  comment :  delayedCom ments) {
        1033                             for (C onsentWrap per consen tWrapper :  consents)  {
        1034                                 if  (consentW rapper.del ayedConsen t != null)  {
        1035                                      if (comm ent.getDel ayedConsen tId().equa ls(consent Wrapper.de layedConse nt.getDela yedConsent Id())) {
        1036                                          cons entWrapper .comments. add(commen t);
        1037                                      }
        1038                                 }
        1039                             }
        1040                         }
        1041                    }
        1042  
        1043                    //ge t mail_not ification  data and a dd it to t he Consent Wrapper fo r Delayed  Consents
        1044                    try  {
        1045                         List<MailN otificatio n> mails =  this.getM ailNotific ationDAO() .findByDel ayedConsen tIds(delay edConsentI ds);
        1046                         for (MailN otificatio n mail : m ails) {
        1047                             for (C onsentWrap per consen tWrapper :  consents)  {
        1048                                 if (consentWr apper.dela yedConsent  != null)  {
        1049                                      if(mail. getDelayed ConsentId( ).getDelay edConsentI d().equals (consentWr apper.dela yedConsent .getDelaye dConsentId ()))
        1050                                      consentW rapper.mai lNotificat ions.add(m ail);
        1051                                 }
        1052                             }
        1053                         }
        1054                    } ca tch (Excep tion e) {
        1055                         throw new  ServletExc eption(e);
        1056                    }
        1057  
        1058                    sess ion.setAtt ribute("Nw HINactiveD elay", NwH INactiveDe lay);
        1059                    sess ion.setAtt ribute("SS AactiveDel ay", SSAac tiveDelay) ;
        1060  
        1061                    // I rakli Kaku shadze 11/ 25/2014 JA ZZ 442142  -
        1062                    // G et the lis t of annou ncements f or this pa tient by c onsent dir ective
        1063                    // I D list so  that we ca n change c aption of  "Announce"  button to  "Re-Annou nce"
        1064                    // i f the pati ent has al ready been  announced .
        1065                    Stri ng lastAnn ounceMessa ge = "";
        1066                    if ( consentIds .isEmpty() ) {
        1067                         session.se tAttribute ("hasBeenA nnounced",  false);
        1068                    } el se {
        1069                         List<Annou ncement> a nnouncemen ts = this. patientAnn ouncer.get Announceme ntsByConse ntDirectiv eId(consen tIds);
        1070                         session.se tAttribute ("hasBeenA nnounced",  !announce ments.isEm pty());
        1071  
        1072                         if (!annou ncements.i sEmpty())  {
        1073                             // Che ck to see  if this pa tient was  announced  successful ly.
        1074                             for (i nt i = ann ouncements .size() -  1; i >= 0;  i--) {
        1075                                 if  (announce ments.get( i).getAnno uncementRe sult() !=  null) {
        1076                                      if (Inte ger.parseI nt(announc ements.get (i).getAnn ouncementR esult()) >  0) {
        1077                                          if ( announceme nts.get(i) .getComple tedTs() !=  null) {
        1078                                               lastAnnoun ceMessage  = "Last su ccessful a nnouncemen t: " +
        1079                                                   new Si mpleDateFo rmat("yyyy -MM-dd HH: mm:ss").fo rmat(annou ncements.g et(i).getC ompletedTs ());
        1080                                               break;
        1081                                          }
        1082                                      }
        1083                                 }
        1084                             }
        1085                             if (la stAnnounce Message.le ngth() ==  0) {
        1086                                 //  There are  no succes sful annou ncements,  let's show  the last  failed ann ouncement,  if any.
        1087                                 fo r (int i =  announcem ents.size( ) - 1; i > = 0; i--)  {
        1088                                      if (anno uncements. get(i).get Announceme ntResult()  != null)  {
        1089                                          if ( announceme nts.get(i) .getComple tedTs() !=  null) {
        1090                                               lastAnnoun ceMessage  = "No succ essful ann ouncements . Last fai led announ cement: "  +
        1091                                                   new Si mpleDateFo rmat("yyyy -MM-dd HH: mm:ss").fo rmat(annou ncements.g et(i).getC ompletedTs ());
        1092                                               break;
        1093                                          }
        1094                                      }
        1095                                 }
        1096                             }
        1097                             if (la stAnnounce Message.le ngth() ==  0) {
        1098                                 //  There are  no comple ted announ cements, l et's show  the last s cheduled a nnouncemen t, if any.
        1099                                 fo r (int i =  announcem ents.size( ) - 1; i > = 0; i--)  {
        1100                                      if (anno uncements. get(i).get CreatedTs( )!= null)  {
        1101                                          last AnnounceMe ssage = "N o complete d announce ments. Las t schedule d announce ment: " +
        1102                                               new Simple DateFormat ("yyyy-MM- dd HH:mm:s s").format (announcem ents.get(i ).getCreat edTs());
        1103                                          brea k;
        1104                                      }
        1105                                 }
        1106                             }
        1107                         }
        1108                    }
        1109                    sess ion.setAtt ribute("la stAnnounce ment", las tAnnounceM essage);
        1110  
        1111                                      // Get t he demogra phic detai ls section
        1112                                      final Pa tientDemog raphicsQue ry patient Demographi csQuery =  new Patien tDemograph icsQuery() ;
        1113                                      patientD emographic sQuery.set PatientId( icn);
        1114                                      final Pa tientDemog raphicsRes ponse pati entDemogra phicsRespo nse = this .pdqServic e
        1115                                                       .g etPatientD emographic s(patientD emographic sQuery);
        1116                                      final Pa tientDemog raphics de mographics  = patient Demographi csResponse
        1117                                                       .g etPatientD emographic s();
        1118                                      session. setAttribu te("patien tDemograph ics", demo graphics);
        1119                                      session. setAttribu te("isOrga nizationEx clusionsAl lowed", th is
        1120                                                       .g etCmsHelpe r().isOrga nizationEx clusionsAl lowed());
        1121                                      session. setAttribu te("isForm UploadAllo wed", this .getCmsHel per()
        1122                                                       .i sFormUploa dEnabled() );
        1123  
        1124                                      session. setAttribu te("maxFil eUploadSiz e", this
        1125                                                       .g etDocument Helper().g etMaxUploa dFileSize( ));
        1126                                      // Get t he allowed  organizat ions to li st them on  the patie nt
        1127                                      // detai ls page
        1128                    fina l ArrayLis t<Organiza tionType>  allowedOrg anizations  = new Arr ayList<Org anizationT ype>(this. getCmsHelp er().getAl lowedNonCo nsumerOnly Organizati ons());
        1129                                      //final  Collection <Organizat ionType> a llowedOrga nizations  = this.get CmsHelper( ).getAllow edNonConsu merOnlyOrg anizations ();
        1130                                      session. setAttribu te("allowe dOrganizat ions",allo wedOrganiz ations);
        1131  
        1132                    fina l ArrayLis t<gov.va.n vap.svc.fa cility.dat a.Facility > allowedF acilities  = new Arra yList<gov. va.nvap.sv c.facility .data.Faci lity>(this .getFacili tyHelper() .getAllowe dVistAFaci lities());
        1133                                      //final  Collection <gov.va.nv ap.svc.fac ility.data .Facility>  allowedFa cilities =  this.getF acilityHel per().getA llowedVist AFacilitie s();
        1134                                      session. setAttribu te("allowe dFacilitie s", allowe dFacilitie s);
        1135                                      // Get t he Default  Facility  by user id
        1136                                      /*
        1137                                      final go v.va.nvap. svc.facili ty.data.Fa cility def aultUserFa cility = t his
        1138                                                       .g etFacility Helper().g etFacility StationByV HAUserId(
        1139                                                                         UserHe lper.getUs erName(req uest));
        1140                                      if (Null Checker.is NotEmpty(d efaultUser Facility))  {
        1141                                               session.se tAttribute ("defaultU serFacilit y",
        1142                                                                defa ultUserFac ility);
        1143                                      }
        1144                                      */
        1145                                      final go v.va.nvap. svc.facili ty.data.Fa cility def aultUserFa cility =
        1146                                               (gov.va.nv ap.svc.fac ility.data .Facility)  session.g etAttribut e("default UserFacili ty");
        1147  
        1148                                      // Get a ll the con sent direc tives - ne eded to po pulate the
        1149                                      // conse nt managem ent histor y
        1150   //                                 final Li st<Consent DirectiveR eferenceTy pe> consen tDirective References  = this
        1151   //                                                  .g etCmsHelpe r().getCon sentDirect iveHistory (icn);
        1152                                      // Get t he active  consent di rective to  display b efore hist ory
        1153                                      ConsentD irectiveRe ferenceTyp e activeCo nsentDirec tiveRefere nceType =  null;
        1154                                      ConsentD irectiveRe ferenceTyp e ssaActiv eConsentDi rectiveRef erenceType  = null;
        1155                                      ConsentD irectiveRe ferenceTyp e nwhinOrg Restrictio nsActiveCo nsentDirec tiveRefere nceType =  null;
        1156                                      if (Null Checker.is NotEmpty(c onsentDire ctiveRefer ences)) {
        1157                                               for (final  ConsentDi rectiveRef erenceType  type : co nsentDirec tiveRefere nces) {
        1158                                                       if  (NullChec ker.isEmpt y(type.get OptoutTS() )
        1159                                                                         && Con sentType.N W_HIN_AUTH ORIZATION. value()
        1160                                                                                           .equals(ty pe.getOpti nConsentTy pe()
        1161                                                                                                            .val ue())
        1162                                                                         && typ e.getExpir ationDate( ).after(ne w Date()))  {
        1163                                                                acti veConsentD irectiveRe ferenceTyp e = type;
        1164                                                       }
        1165                                                       if  (NullChec ker.isEmpt y(type.get OptoutTS() )
        1166                                                                         && Con sentType.S SA_AUTHORI ZATION.val ue()
        1167                                                                                           .equals(ty pe.getOpti nConsentTy pe()
        1168                                                                                                            .val ue())
        1169                                                                         && typ e.getExpir ationDate( ).after(ne w Date()))  {
        1170                                                                ssaA ctiveConse ntDirectiv eReference Type = typ e;
        1171                                                       }
        1172                                                       if  (NullChec ker.isEmpt y(type.get OptoutTS() )
        1173                                                                         && Con sentType.N W_HIN_ORGA NIZATION_R ESTRICTION _AUTHORIZA TION
        1174                                                                                           .value().e quals(
        1175                                                                                                            type .getOptinC onsentType ()
        1176                                                                                                                              .value() )) {
        1177                                                                nwhi nOrgRestri ctionsActi veConsentD irectiveRe ferenceTyp e = type;
        1178                                                       }
        1179                                               }
        1180                                      }
        1181  
        1182                    //Po pulate any  attachmen ts for nor mal consen ts.
        1183                    for  (final Con sentWrappe r consent  : consents ) {
        1184                         if (consen t.delayedC onsent ==  null) {
        1185                             try {
        1186                                 fi nal String  optinDocu ment = thi s.getCmsHe lper().ret rieveDocum ent(consen t.normalCo nsent.getC onsentDirI d(), "Auth orize");
        1187  
        1188                                 if  (DASUtil. isDASDocum ent(optinD ocument))  {
        1189                                      consent. setOptInDo cumentAtta chment(Nul lChecker.i sNotEmpty( optinDocum ent));
        1190                                 }  else {
        1191                                      final St ring optin Attachment  = optinDo cument ==  null ? nul l : this.g etDocument Helper().g etPrivacyC onsentDire ctiveAttac hment(opti nDocument) ;
        1192                                      consent. setOptInDo cumentAtta chment(Nul lChecker.i sNotEmpty( optinAttac hment));
        1193                                 }
        1194  
        1195                                 if  (NullChec ker.isNotE mpty(conse nt.normalC onsent.get OptoutTS() )) {
        1196                                      final St ring optou tDocument  = this.get CmsHelper( ).retrieve Document(c onsent.nor malConsent .getConsen tDirId(),  "Revoke");
        1197  
        1198                                      if (DASU til.isDASD ocument(op toutDocume nt)) {
        1199                                          cons ent.hasOpt OutDocumen tAttachmen t(NullChec ker.isNotE mpty(optou tDocument) );
        1200                                      } else {
        1201                                          fina l String o ptoutAttac hment = op toutDocume nt == null  ? null :  this.getDo cumentHelp er().getPr ivacyConse ntDirectiv eAttachmen t(optoutDo cument);
        1202                                          cons ent.hasOpt OutDocumen tAttachmen t(NullChec ker.isNotE mpty(optou tAttachmen t));
        1203                                      }
        1204  
        1205                                 }  else {
        1206                                      consent. hasOptOutD ocumentAtt achment(fa lse);
        1207                                 }
        1208                             } catc h (final T ransformer Exception  ex) {
        1209                                 th row new Se rvletExcep tion(ex);
        1210                             } catc h (final X PathExcept ion ex) {
        1211                                 th row new Se rvletExcep tion(ex);
        1212                             }
        1213                         }
        1214                    }
        1215  
        1216   //                 // Sort the c ombined co nsent refe rences by  date added .
        1217   //                 Co llections. sort(conse nts, new C omparator< ConsentWra pper>() {
        1218   //                      @Overrid e
        1219   //                      public i nt compare (ConsentWr apper o1,  ConsentWra pper o2) {
        1220   //                          retu rn o2.entr yDate().co mpareTo(o1 .entryDate ());
        1221   //                      }
        1222   //                 }) ;
        1223  
        1224                                      session. setAttribu te("consen ts", conse nts);
        1225  
        1226                                      // if th ere is a a ctive cons ent direct ive, then  get the ex cluded
        1227                                      // organ izations
        1228                                      if (nwhi nOrgRestri ctionsActi veConsentD irectiveRe ferenceTyp e != null)  {
        1229                                               final Coll ection<Org anizationT ype> exclu dedOrganiz ations = n whinOrgRes trictionsA ctiveConse ntDirectiv eReference Type
        1230                                                                .get ExcludedOr ganization s();
        1231                                               final List <Organizat ionType> a uthorizedO rganizatio ns = new A rrayList<O rganizatio nType>();
        1232                                               for (final  Organizat ionType or ganization  : allowed Organizati ons) {
        1233                                                       bo olean isEx cluded = f alse;
        1234                                                       fo r (final O rganizatio nType excl udedOrgani zation : e xcludedOrg anizations ) {
        1235                                                                if ( organizati on.getOrgN umber().eq uals(
        1236                                                                                  excluded Organizati on.getOrgN umber()))  {
        1237                                                                         isExcl uded = tru e;
        1238                                                                }
        1239                                                       }
        1240                                                       if  (!isExclu ded) {
        1241                                                                auth orizedOrga nizations. add(organi zation);
        1242                                                       }
        1243                                               }
        1244                         //cast it  to ArrayLi st because  that is s erializabl e and Fort ify won't  complain
        1245                         ArrayList< Organizati onType> ex Org = new  ArrayList< Organizati onType>(ex cludedOrga nizations) ;
        1246  
        1247                                               // Set in  session
        1248                                               session.se tAttribute ("excluded Organizati ons", exOr g);
        1249                                               session.se tAttribute ("authoriz edOrganiza tions",
        1250                                                                auth orizedOrga nizations) ;
        1251                                      }
        1252                                      // Must  be opt-out
        1253                                      session. setAttribu te("consen tDirective ",
        1254                                                       ac tiveConsen tDirective ReferenceT ype);
        1255                                      session. setAttribu te("ssaCon sentDirect ive",
        1256                                                       ss aActiveCon sentDirect iveReferen ceType);
        1257  
        1258                                      session. setAttribu te("isNewA uthorizati onAllowed" , true);
        1259                                      session. setAttribu te("isSSAN ewAuthoriz ationAllow ed", true) ;
        1260                                      session. setAttribu te("nwhinO rganizatio nRestricti onsDirecti ve",
        1261                                                       nw hinOrgRest rictionsAc tiveConsen tDirective ReferenceT ype);
        1262  
        1263                                      session. setAttribu te("optOut Reasons",  this.getCm sHelper()
        1264                                                       .g etOptoutRe asons());
        1265  
        1266                                      // Get t he correla tions sect ion
        1267                                      final Pa tientCorre lationsQue ry patient Correlatio nsQuery =  new Patien tCorrelati onsQuery() ;
        1268                                      patientC orrelation sQuery.set PatientId( icn);
        1269                                      // Get t he correla tions
        1270                                      final Pa tientCorre lationsRes ponse pati entCorrela tionsRespo nse = this .pdqServic e
        1271                                                       .g etCorrelat edFaciliti es(patient Correlatio nsQuery);
        1272                                      final Li st<Facilit y> facilit ies = pati entCorrela tionsRespo nse
        1273                                                       .g etFaciliti es();
        1274                                      final Li st<Map<Str ing, Strin g>> correl ations = n ew ArrayLi st<Map<Str ing, Strin g>>();
        1275                                      if (Null Checker.is NotEmpty(f acilities) ) {
        1276                                               for (final  Facility  facility :  facilitie s) {
        1277                                                       fi nal String  correlate dPatientId  = facilit y
        1278                                                                         .getCo rrelatedPa tientId();
        1279                                                       fi nal String  correlate dFacilityI d = facili ty
        1280                                                                         .getFa cilityId() ;
        1281                                                       fi nal Organi zationType  organizat ion = this
        1282                                                                         .getCm sHelper(). getOrganiz ationByNum ber(
        1283                                                                                           correlated FacilityId );
        1284  
        1285                                                       if  (NullChec ker.isNotE mpty(organ ization))  {
        1286                                                                fina l Map<Stri ng, String > correlat ion = new  HashMap<St ring, Stri ng>();
        1287                                                                fina l String f acilityNam e = organi zation
        1288                                                                                  .getOrgN ame();
        1289                                                                fina l String f acilityNum ber = orga nization
        1290                                                                                  .getOrgN umber();
        1291                                                                fina l String o rgOid = or ganization .getOrgOid ();
        1292                                                                corr elation.pu t("organiz ationOid",  orgOid);
        1293  
        1294                                                                corr elation.pu t("facilit yName", fa cilityName );
        1295                                                                fina l String o id = facil ity
        1296                                                                                  .getAssi gningAutho rityNumber ();
        1297                                                                corr elation.pu t("assigni ngAuthorit yOid", oid );
        1298                                                                corr elation.pu t("facilit yNumber",  facilityNu mber);
        1299                                                                corr elation.pu t("correla tedPatient Id",
        1300                                                                                  correlat edPatientI d);
        1301                                                                corr elations.a dd(correla tion);
        1302                                                       }
        1303                                               }
        1304                                      }
        1305  
        1306                                      // Set t he correla tions int  he session
        1307                                      session. setAttribu te("correl ations", c orrelation s);
        1308  
        1309                                      // get t he comment s for the  patient de tail secti on
        1310                                      final St ring patie ntIen = de mographics .getIcn();
        1311                                      session. setAttribu te("patien tIen", pat ientIen);
        1312                                      List<Pat ientCommen t> patient Comments =  this.getP atientComm entDAO().g etComments ByPatientI en(patient Ien);
        1313                                      session. setAttribu te("patien tComments" , patientC omments);
        1314  
        1315                             } catc h (final P dqExceptio n ex) {
        1316                                      throw ne w ServletE xception(e x);
        1317                             }
        1318                             // SUC CESS
        1319                             this.f orward(req uest, resp onse, "sho w");
        1320                    } el se {
        1321                             this.f orward(req uest, resp onse, "nos how");
        1322                    }
        1323           }
        1324  
        1325       /**
        1326        * Han dles conse nt directi ve file up load
        1327        *
        1328        * @pa ram fileIt ems list o f uploaded  file item s
        1329        * @pa ram reques t http ser vlet reque st
        1330        * @pa ram respon se http se rvlet resp onse
        1331        *
        1332        * @th rows javax .servlet.S ervletExce ption
        1333        * @th rows java. io.IOExcep tion
        1334        */
        1335           pu blic void  upload(fin al List<Fi leItem> fi leItems,
        1336                             final  HttpServle tRequest r equest, fi nal HttpSe rvletRespo nse respon se)
        1337                             throws  ServletEx ception, I OException  {
        1338                    // G et the fie lds
        1339                    fina l Map<Stri ng, String > formFiel ds = FileU ploadUtil
        1340                                      .getForm Fields(fil eItems);
        1341                    // G et the upl oaded file s
        1342                    fina l List<Fil eItem> fil esUploaded  = FileUpl oadUtil
        1343                                      .getFile sUploaded( fileItems) ;
        1344                    if ( NullChecke r.isNotEmp ty(filesUp loaded)) {
        1345                             // Get  the docum ent type a nd the con sent direc tive Id
        1346                             final  String doc umentType  = formFiel ds.get("do cumentType ");
        1347                             final  String con sentDirId  = formFiel ds.get("co nsentDirId ");
        1348                             final  String use rId = User Helper.get UserName(r equest);
        1349                             final  String use rFacilityS tationId =  this.getF acilityHel per()
        1350                                               .getFacilt yStationId ByUserId(u serId);
        1351                             this.g etCmsHelpe r().update Document(c onsentDirI d, documen tType,
        1352                                               filesUploa ded, userI d, userFac ilityStati onId);
        1353                    }
        1354                    this .forward(r equest, re sponse, "s uccess");
        1355           }
        1356  
        1357           /* *
        1358            *  View the  C32 from t he adapter . It makes  a webserv ice reques t to the
        1359            *  adapter,  pulls the  data from  local Vist A systems  and displa ys it to t he
        1360            *  user.
        1361        *
        1362        * @pa ram reques t http ser vlet reque st
        1363        * @pa ram respon se http se rvlet resp onse
        1364        *
        1365        * @th rows javax .servlet.S ervletExce ption
        1366        * @th rows java. io.IOExcep tion
        1367            * /
        1368           pu blic void  view(final  HttpServl etRequest  request,
        1369                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        1370                             IOExce ption {
        1371                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        1372  
        1373                    fina l String i cn = (Stri ng) sessio n.getAttri bute("icn" );
        1374                    if ( NullChecke r.isNotEmp ty(icn)) {
        1375                             try {
        1376                                      // Get t he C32 doc ument from  the adapt er
        1377                                      String d ocument =  this.getDo cumentHelp er().getC3 2Document( icn,
        1378                                                       Us erHelper.g etUserName (request)) ;
        1379                                      if (Null Checker.is Empty(docu ment)) {
        1380                                               throw new  ServletExc eption(
        1381                                                                "The re was an  issue retr ieving hea lth summar y for this  patient w ith ICN:"
        1382                                                                                  + icn);
        1383                                      }
        1384                                      // Remov e xml-styl esheet
        1385                                      document  = documen t
        1386                                                       .r eplaceAll(
        1387                                                                         "<?xml -styleshee t type=\"t ext/xsl\"  href=\"CCD .xsl\"?>",
        1388                                                                         "");
        1389                                      // Get t he style s heets
        1390                                      final St ring style SheetViewT ype = requ est
        1391                                                       .g etParamete r("styleSh eetViewTyp e");
        1392                                      if ("xml ".equals(s tyleSheetV iewType))  {
        1393                                               response.s etContentT ype("text/ xml;charse t=UTF-8");
        1394                                               response.g etWriter() .write(doc ument);
        1395                                      } else {
        1396                                               // Update  session in  the docum ent
        1397                                               final Stri ng html =  this.getDo cumentHelp er().getHt ml(
        1398                                                                docu ment, styl eSheetView Type);
        1399                                               session.se tAttribute ("updatedD ocument",  html);
        1400                                               session.se tAttribute ("document ", documen t);
        1401                                               session.se tAttribute ("isXmlVie wEnabled",  this
        1402                                                                .get DocumentHe lper().isX mlViewEnab led());
        1403                                               this.forwa rd(request , response , "showdoc ");
        1404                                      }
        1405                             } catc h (final A dapterExce ption ex)  {
        1406                                      throw ne w ServletE xception(e x);
        1407                             }
        1408                    } el se {
        1409                             this.f orward(req uest, resp onse, "nos how");
        1410                    }
        1411  
        1412           }
        1413  
        1414           pu blic void  addComment (final Htt pServletRe quest requ est, final  HttpServl etResponse  response)  throws Se rvletExcep tion, IOEx ception {
        1415                final St ring comme nts = requ est.getPar ameter("co mments");
        1416                final St ring conse ntType = r equest.get Parameter( "consentTy pe");
        1417                final St ring conse ntId = req uest.getPa rameter("c onsentId") ;
        1418                final St ring delay edConsentI d = reques t.getParam eter("dela yedConsent Id");
        1419                final St ring userI d = UserHe lper.getUs erName(req uest);
        1420  
        1421                if(NullC hecker.isN otEmpty(co mments)) {
        1422                    //ha ndle comme nts
        1423                    Cons entComment  comment =  new Conse ntComment( );
        1424                    comm ent.setCom ments(comm ents);
        1425                    comm ent.setCon sentType(c onsentType );
        1426                    comm ent.setUse rId(userId );
        1427                    comm ent.setDat eAdded(new  Date());
        1428  
        1429                    //De termine if  comment i s for a de layed or n ormal auth orization
        1430                    if ( NullChecke r.isNullOr Empty(cons entId)) {
        1431                         comment.se tDelayedCo nsentId(Lo ng.parseLo ng(delayed ConsentId) );
        1432                    }
        1433                    else  {
        1434                         comment.se tConsentId (Long.pars eLong(cons entId));
        1435                    }
        1436  
        1437  
        1438                    this .getConsen tCommentDA O().create (comment);
        1439  
        1440                    // S uccess
        1441                    this .forward(r equest, re sponse, "s uccess");
        1442                } else {
        1443                    // V alidate
        1444                    this .forward(r equest, re sponse, "v alidate");
        1445                }
        1446           }
        1447  
        1448           pu blic void  addPatient Comment(fi nal HttpSe rvletReque st request , final Ht tpServletR esponse re sponse) th rows Servl etExceptio n, IOExcep tion {
        1449                final St ring comme nts = requ est.getPar ameter("co mments");
        1450                final St ring patie ntIen = re quest.getP arameter(" patientIen ");
        1451                final St ring userI d = UserHe lper.getUs erName(req uest);
        1452  
        1453                if(NullC hecker.isN otEmpty(co mments)) {
        1454                    //ha ndle comme nts
        1455                    Pati entComment  comment =  new Patie ntComment( );
        1456                    comm ent.setUse rId(userId );
        1457                    comm ent.setDat eAdded(new  Date());
        1458                    comm ent.setCom ments(comm ents);
        1459                    comm ent.setPat ientIen(pa tientIen);
        1460  
        1461                    this .getPatien tCommentDA O().create (comment);
        1462  
        1463                    // S uccess
        1464                    this .forward(r equest, re sponse, "s uccess");
        1465                } else {
        1466                    // V alidate
        1467                    this .forward(r equest, re sponse, "v alidate");
        1468                }
        1469           }
        1470  
        1471           pu blic void  authorizeN wHIN(final  HttpServl etRequest  request,
        1472                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        1473                             IOExce ption {
        1474                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        1475  
        1476                    fina l String i cn = (Stri ng) sessio n.getAttri bute("icn" );
        1477                    if ( NullChecke r.isNotEmp ty(icn)) {
        1478                    } el se {
        1479                    }
        1480           se ssion.setA ttribute(" delayedNwH INAuth", n ull);
        1481                    this .forward(r equest, re sponse, "a uthorizeNw HIN");
        1482           }
        1483  
        1484       public  void auth orizeDelay NwHIN(fina l HttpServ letRequest  request,
        1485                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        1486                             IOExce ption {
        1487                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        1488  
        1489                    fina l String i cn = (Stri ng) sessio n.getAttri bute("icn" );
        1490                    sess ion.setAtt ribute("de layedNwHIN Auth", tru e);
        1491                    this .forward(r equest, re sponse, "a uthorizeDe layNwHIN") ;
        1492           }
        1493  
        1494       public  void auth orizeDelay SSA(final  HttpServle tRequest r equest,
        1495           fi nal HttpSe rvletRespo nse respon se) throws  ServletEx ception,
        1496           IO Exception  {
        1497           fi nal HttpSe ssion sess ion = requ est.getSes sion(false );
        1498           fi nal String  icn = (St ring) sess ion.getAtt ribute("ic n");
        1499           se ssion.setA ttribute(" delayedSSA Auth", tru e);
        1500           th is.forward (request,  response,  "authorize DelaySSA") ;
        1501       }
        1502  
        1503           pu blic void  revokeNwHI N(final Ht tpServletR equest req uest,
        1504                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        1505                             IOExce ption {
        1506                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        1507  
        1508                    fina l String i cn = (Stri ng) sessio n.getAttri bute("icn" );
        1509                    if ( NullChecke r.isNotEmp ty(icn)) {
        1510                    } el se {
        1511                    }
        1512                    this .forward(r equest, re sponse, "r evokeNwHIN ");
        1513           }
        1514  
        1515           pu blic void  authorizeS SA(final H ttpServlet Request re quest,
        1516                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        1517                             IOExce ption {
        1518                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        1519  
        1520                    fina l String i cn = (Stri ng) sessio n.getAttri bute("icn" );
        1521                    if ( NullChecke r.isNotEmp ty(icn)) {
        1522                    } el se {
        1523                    }
        1524           se ssion.setA ttribute(" delayedSSA Auth", nul l);
        1525                    this .forward(r equest, re sponse, "a uthorizeSS A");
        1526           }
        1527  
        1528           pu blic void  revokeSSA( final Http ServletReq uest reque st,
        1529                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        1530                             IOExce ption {
        1531                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        1532  
        1533                    fina l String i cn = (Stri ng) sessio n.getAttri bute("icn" );
        1534                    if ( NullChecke r.isNotEmp ty(icn)) {
        1535                    } el se {
        1536                    }
        1537                    this .forward(r equest, re sponse, "r evokeSSA") ;
        1538           }
        1539  
        1540           pu blic void  authorizeN wHINOrgani zationRest rictions(
        1541                             final  HttpServle tRequest r equest, fi nal HttpSe rvletRespo nse respon se)
        1542                             throws  ServletEx ception, I OException  {
        1543                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        1544  
        1545                    fina l String i cn = (Stri ng) sessio n.getAttri bute("icn" );
        1546                    if ( NullChecke r.isNotEmp ty(icn)) {
        1547                    } el se {
        1548                    }
        1549                    this .forward(r equest, re sponse,
        1550                                      "authori zeNwHINOrg anizationR estriction s");
        1551           }
        1552  
        1553           pu blic void  revokeNwHI NOrganizat ionRestric tions(
        1554                             final  HttpServle tRequest r equest, fi nal HttpSe rvletRespo nse respon se)
        1555                             throws  ServletEx ception, I OException  {
        1556                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        1557  
        1558                    fina l String i cn = (Stri ng) sessio n.getAttri bute("icn" );
        1559                    if ( NullChecke r.isNotEmp ty(icn)) {
        1560                    } el se {
        1561                    }
        1562                    this .forward(r equest, re sponse, "r evokeNwHIN Organizati onRestrict ions");
        1563           }
        1564  
        1565           pu blic void  modifyNwHI NOrganizat ionRestric tions(
        1566                             final  HttpServle tRequest r equest, fi nal HttpSe rvletRespo nse respon se)
        1567                             throws  ServletEx ception, I OException  {
        1568                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        1569  
        1570                    fina l String i cn = (Stri ng) sessio n.getAttri bute("icn" );
        1571                    if ( NullChecke r.isNotEmp ty(icn)) {
        1572                    } el se {
        1573                    }
        1574                    this .forward(r equest, re sponse, "m odifyNwHIN Organizati onRestrict ions");
        1575           }
        1576  
        1577           pu blic void  addComment Form(final  HttpServl etRequest  request, f inal HttpS ervletResp onse respo nse) throw s ServletE xception,  IOExceptio n {
        1578                final Ht tpSession  session =  request.ge tSession(f alse);
        1579  
        1580                final St ring conse ntId = req uest.getPa rameter("c onsentId") ;
        1581                final St ring delay edConsentI d = reques t.getParam eter("dela yedConsent Id");
        1582                final St ring conse ntType = r equest.get Parameter( "consentTy pe");
        1583                session. setAttribu te("consen tId", cons entId);
        1584                session. setAttribu te("delaye dConsentId ", delayed ConsentId) ;
        1585                session. setAttribu te("consen tType", co nsentType) ;
        1586  
        1587                this.for ward(reque st, respon se, "addCo mmentForm" );
        1588           }
        1589  
        1590           pu blic void  addPatient CommentFor m(final Ht tpServletR equest req uest, fina l HttpServ letRespons e response ) throws S ervletExce ption, IOE xception {
        1591                final Ht tpSession  session =  request.ge tSession(f alse);
        1592  
        1593                final St ring patie ntIen = re quest.getP arameter(" patientIen ");
        1594                session. setAttribu te("patien tIen", pat ientIen);
        1595  
        1596                this.for ward(reque st, respon se, "addPa tientComme ntForm");
        1597           }
        1598  
        1599       public  void edit MailDatesF orm(final  HttpServle tRequest r equest, fi nal HttpSe rvletRespo nse respon se) throws  ServletEx ception, I OException , ParseExc eption {
        1600           fi nal HttpSe ssion sess ion = requ est.getSes sion(false );
        1601  
        1602           fi nal String  delayedCo nsentId =  request.ge tParameter ("delayedC onsentId") ;
        1603           fi nal String  consentDi rId = requ est.getPar ameter("co nsentDirId ");
        1604           Li st<MailNot ification>  mailNotif ications =  new Array List<MailN otificatio n>();
        1605  
        1606           if (NullCheck er.isNullO rEmpty(del ayedConsen tId)) {
        1607                //get ma il notific ations by  consentDir Id
        1608                mailNoti fications  = this.get MailNotifi cationDAO( ).findByCo nsentDirId (consentDi rId);
        1609           }  else {
        1610                //get ma il notific ations by  delayedCon sentId
        1611                mailNoti fications  = this.get MailNotifi cationDAO( ).findByDe layedConse ntId(delay edConsentI d);
        1612           }
        1613  
        1614           // TODO: JPS  - get the  logs for t his by con sentDirId  or delayed ConsentId
        1615  
        1616           se ssion.setA ttribute(" mailNotifi cations",  mailNotifi cations);
        1617           se ssion.setA ttribute(" delayedCon sentId", d elayedCons entId);
        1618           se ssion.setA ttribute(" consentDir Id", conse ntDirId);
        1619  
        1620           th is.forward (request,  response,  "editMailD atesForm") ;
        1621           }
        1622  
        1623       public  void edit MailDates( final Http ServletReq uest reque st, final  HttpServle tResponse  response)  throws Ser vletExcept ion, IOExc eption, Pa rseExcepti on, Except ion {
        1624           fi nal HttpSe ssion sess ion = requ est.getSes sion(false );
        1625  
        1626           // get everyt hing from  the form
        1627           fi nal String  delayedCo nsentId =  request.ge tParameter ("delayedC onsentId") ;
        1628           fi nal String  consentDi rId = requ est.getPar ameter("co nsentDirId ");
        1629           fi nal String [] newMail Dates = Nu llChecker. isNullOrEm pty(reques t.getParam eterValues ("mailDate ")) ? new  String[0]  : request. getParamet erValues(" mailDate") ;
        1630           Si mpleDateFo rmat forma tter = new  SimpleDat eFormat("M M/dd/yyyy" );
        1631           fi nal String  userId =  UserHelper .getUserNa me(request );
        1632  
        1633           Li st<MailNot ification>  existingM ailNotific ations = n ew ArrayLi st<MailNot ification> ();
        1634  
        1635           if (NullCheck er.isNullO rEmpty(del ayedConsen tId)) {
        1636                //get ma il notific ations by  consentDir Id
        1637                existing MailNotifi cations =  this.getMa ilNotifica tionDAO(). findByCons entDirId(c onsentDirI d);
        1638           }  else {
        1639                //get ma il notific ations by  delayedCon sentId
        1640                existing MailNotifi cations =  this.getMa ilNotifica tionDAO(). findByDela yedConsent Id(delayed ConsentId) ;
        1641           }
        1642  
        1643           // make a lis t of the o ld dates f or the log  and do th e delete o f all of t hese at th e same tim e
        1644           Ar rayList<Da te> oldDat es = new A rrayList<D ate>();
        1645           fo r(MailNoti fication e m : existi ngMailNoti fications)  {
        1646                oldDates .add(em.ge tSentDate( ));
        1647  
        1648                this.get MailNotifi cationDAO( ).delete(e m);
        1649           }
        1650  
        1651           // make a lis t of all t he new dat es for the  log and d o the inse rt of all  of these a t the same  time
        1652           Ar rayList<Da te> newDat es = new A rrayList<D ate>();
        1653           fo r(String n md : newMa ilDates) {
        1654                if(nmd.l ength() >  0) {
        1655                    newD ates.add(f ormatter.p arse(nmd)) ;
        1656  
        1657                    Mail Notificati on mn = ne w MailNoti fication() ;
        1658                    Date  dt = form atter.pars e(nmd);
        1659                    mn.s etSentDate (dt);
        1660                    mn.s etUserId(u serId);
        1661  
        1662                    if(N ullChecker .isNullOrE mpty(delay edConsentI d)) {
        1663                         ConsentDir ective cd  = this.get ConsentDir ectiveJpaC ontroller( ).findCons entDirecti ve(Long.pa rseLong(co nsentDirId ));
        1664                         mn.setCons entDirId(c d);
        1665                    } el se {
        1666                         DelayedCon sent dc =  this.getDe layedConse ntDAO().fi ndByDelaye dConsentId (Long.pars eLong(dela yedConsent Id));
        1667                         mn.setDela yedConsent Id(dc);
        1668                    }
        1669  
        1670                    this .getMailNo tification DAO().crea te(mn);
        1671                }
        1672           }
        1673  
        1674           // get the lo g entry
        1675           St ring logEn try = this .getLogEnt ry(oldDate s, newDate s, userId) ;
        1676  
        1677           // save the l og entry
        1678           if (!logEntry .isEmpty() ) {
        1679                MailLog  ml = new M ailLog();
        1680                ml.setLo gEntry(log Entry);
        1681                if(NullC hecker.isN ullOrEmpty (delayedCo nsentId))  {
        1682                    Long  conDir =  Long.parse Long(conse ntDirId);
        1683                    ml.s etConsentD irId(conDi r);
        1684                } else {
        1685                    Long  delDir =  Long.parse Long(delay edConsentI d);
        1686                    ml.s etDelayedC onsentId(d elDir);
        1687                }
        1688  
        1689                this.get MailLogDAO ().create( ml);
        1690           }
        1691  
        1692           th is.forward (request,  response,  "success") ;
        1693       }
        1694  
        1695       public  void getL ogEntries( final Http ServletReq uest reque st, final  HttpServle tResponse  response)  throws Ser vletExcept ion, IOExc eption, Pa rseExcepti on, Except ion {
        1696           fi nal HttpSe ssion sess ion = requ est.getSes sion(false );
        1697  
        1698           fi nal String  delayedCo nsentId =  request.ge tParameter ("delayedC onsentId") ;
        1699           fi nal String  consentDi rId = requ est.getPar ameter("co nsentDirId ");
        1700  
        1701           Li st<MailLog > logs = n ew ArrayLi st<MailLog >();
        1702  
        1703           if (NullCheck er.isNullO rEmpty(del ayedConsen tId)) {
        1704                //get ma il logs by  consentDi rId
        1705                logs = t his.getMai lLogDAO(). findByCons entDirId(c onsentDirI d);
        1706           }  else {
        1707                //get ma il logs by  delayedCo nsentId
        1708                logs = t his.getMai lLogDAO(). findByDela yedConsent Id(delayed ConsentId) ;
        1709           }
        1710  
        1711           se ssion.setA ttribute(" logs", log s);
        1712  
        1713           th is.forward (request,  response,  "listMailL ogs");
        1714       }
        1715  
        1716       privat e String g etLogEntry (ArrayList <Date> old Dates, Arr ayList<Dat e> newDate s, String  userId) th rows Parse Exception  {
        1717           St ring log =  "";
        1718           bo olean adde d = false;
        1719           bo olean dele ted = fals e;
        1720           Si mpleDateFo rmat final Date = new  SimpleDat eFormat("M M/dd/yyyy" );
        1721           Si mpleDateFo rmat occur edDateForm atter = ne w SimpleDa teFormat(" MM/dd/yyyy  HH:mm:ss" );
        1722           Li st<Date> o ldDatesToU se = new A rrayList<D ate>(oldDa tes);
        1723           Li st<Date> n ewDatesToU se = new A rrayList<D ate>(newDa tes);
        1724  
        1725           fo r (int i =  oldDatesT oUse.size( ) - 1; i > = 0; i--)  {
        1726                for (int  j = newDa tesToUse.s ize() - 1;  j >=0; j- -) {
        1727                    Stri ng oldDate  = finalDa te.format( oldDatesTo Use.get(i) );
        1728                    Stri ng newDate  = finalDa te.format( newDatesTo Use.get(j) );
        1729                    if ( oldDate.eq uals(newDa te)) {
        1730                         oldDates.r emove(i);
        1731                         newDates.r emove(j);
        1732                    }
        1733                }
        1734           }
        1735  
        1736           if  (oldDates .size() ==  0 && newD ates.size( ) > 0) {
        1737                // Some  new date(s ) were add ed.
        1738                added =  true;
        1739           }  else if (o ldDates.si ze() > 0 & & newDates .size() ==  0) {
        1740                // Some  date(s) we re deleted .
        1741                deleted  = true;
        1742           }  else if (o ldDates.si ze() > 0 & & newDates .size() >  0 ) {
        1743                // Some  date(s) we re added a nd some de leted.
        1744                added =  true;
        1745                deleted  = true;
        1746           }  else {
        1747                // Nothi ng has cha nged.
        1748           }
        1749  
        1750           if  (added) {
        1751                log += " added noti fication d ate" + (ne wDates.siz e() > 1 ?  "s " : " " );
        1752  
        1753                List<Str ing> newDa tesAsStrin gs = new A rrayList<S tring>();
        1754                for(Date  date : ne wDates) {
        1755                    newD atesAsStri ngs.add(fi nalDate.fo rmat(date) );
        1756                }
        1757  
        1758                log += n ewDatesAsS trings.toS tring().re placeAll(" \\[|\\]",  "");
        1759           }
        1760  
        1761           if  (added &&  deleted)  {
        1762                log += "  and ";
        1763           }
        1764  
        1765           if  (deleted)  {
        1766                // Some  date(s) we re deleted .
        1767                log += " deleted no tification  date" + ( oldDates.s ize() > 1  ? "s " : "  ");
        1768  
        1769                List<Str ing> oldDa tesAsStrin gs = new A rrayList<S tring>();
        1770                for(Date  date : ol dDates) {
        1771                    oldD atesAsStri ngs.add(fi nalDate.fo rmat(date) );
        1772                }
        1773                log += o ldDatesAsS trings.toS tring().re placeAll(" \\[|\\]",  "");
        1774           }
        1775  
        1776           if  (log.leng th() > 0)  {
        1777                Date occ uredOn = n ew Date();
        1778                String o ccuredOnFo rmatted =  occuredDat eFormatter .format(oc curedOn);
        1779                log = "O n " + occu redOnForma tted + " C T, user "  + userId +  " " + log  + ".";
        1780           }
        1781  
        1782           re turn log;
        1783       }
        1784  
        1785       /*
        1786           Th is method  commented  out becaus e it shoul d only be  used in de v/test.
        1787           Th ese types  of test ha rnesses sh ould be im plemented  using inte rfaces
        1788           ra ther than  conditiona l logic th at will al ways retur n false in  productio n.
        1789       */
        1790       /*
        1791       privat e void moc kGetDocume ntFromDAS( ServletOut putStream  ostream) t hrows IOEx ception {
        1792           In putStream  is =
        1793                              this. getClass() .getClassL oader().ge tResourceA sStream("g ov/va/nvap /web/das.t xt");
        1794  
        1795           fi nal char[]  buffer =  new char[b ufferSize] ;
        1796           fi nal String Builder ou t = new St ringBuilde r();
        1797           tr y {
        1798                Reader i n = new In putStreamR eader(is,  "UTF-8");
        1799                for (;;)  {
        1800                int rsz  = in.read( buffer, 0,  buffer.le ngth);
        1801                if (rsz  < 0)
        1802                    brea k;
        1803                out.appe nd(buffer,  0, rsz);
        1804              }
        1805           }
        1806           ca tch (Unsup portedEnco dingExcept ion ex) {
        1807           }
        1808           ca tch (IOExc eption ex)  {
        1809           }
        1810           St ring jsonS tring = ou t.toString ();
        1811  
        1812  
        1813           os tream.clos e();
        1814           is .close();
        1815  
        1816           St ring xmlId  = "";
        1817           in t xmlLengt h = 0;
        1818           St ring pdfId  = "";
        1819           in t pdfLengt h = 0;
        1820           tr y {
        1821                JSONObje ct jObject  = new JSO NObject(js onString);
        1822                xmlId =  jObject.ge tString("g ridfsID");
        1823                xmlLengt h = jObjec t.getInt(" gridfsLeng th");
        1824                pdfId =  ((JSONObje ct)jObject .getJSONAr ray("gridf sAttachmen ts").get(0 )).getStri ng("gridfs ID");
        1825                pdfLengt h = ((JSON Object)jOb ject.getJS ONArray("g ridfsAttac hments").g et(0)).get Int("gridf sLength");
        1826           }  catch (JSO NException  ex) {
        1827                Logger.g etLogger(P atientDeta ils.class. getName()) .log(Level .SEVERE, n ull, ex);
        1828           }
        1829  
        1830           is  = this.ge tClass().g etClassLoa der().getR esourceAsS tream("gov /va/nvap/w eb/das.pdf ");
        1831           by te[] buf =  new byte[ bufferSize ];
        1832           in t c = 0;
        1833           wh ile ((c =  is.read(bu f, 0, buf. length)) >  0) {
        1834                    ostr eam.write( buf, 0, c) ;
        1835                    ostr eam.flush( );
        1836           }
        1837       }
        1838       */
        1839  
        1840       public  void gene rateLetter (final Lis t<FileItem > fileItem s, final H ttpServlet Request re quest, fin al HttpSer vletRespon se respons e)
        1841           th rows Servl etExceptio n, IOExcep tion {
        1842  
        1843           fi nal Simple DateFormat  letterFor mat = new  SimpleDate Format("MM /dd/yyyy") ;
        1844           fi nal HttpSe ssion sess ion = requ est.getSes sion(false );
        1845           fi nal String  type = Fi leUploadUt il.getForm Fields(fil eItems).ge t("type");
        1846           In putStream  inputStrea m = null;
        1847           St ring templ ateString  = "";
        1848  
        1849           //  Get the f ields
        1850                    fina l HashMap< String, St ring> form Fields = ( HashMap<St ring, Stri ng>) FileU ploadUtil. getFormFie lds(fileIt ems);
        1851           Ar rayList<Ha shMap<Stri ng,String> > patientD etails = n ew ArrayLi st<HashMap <String,St ring>>();
        1852           Bo olean mail ed = Boole an.parseBo olean(File UploadUtil .getFormFi elds(fileI tems).get( "markMaile d"));
        1853           go v.va.nvap. svc.facili ty.data.Fa cility fac ility = th is.getFaci lityHelper ().getFaci lityByStat ionId(form Fields.get ("authenti catingFaci lity"));
        1854           // Get and pa rse delaye d fields.
        1855           if  (type.equ als("delay ed")) {
        1856                if (sess ion.getAtt ribute("ss aDelay") ! = null) {
        1857                    sess ion.remove Attribute( "ssaDelay" );
        1858                    inpu tStream =  IOUtils.to InputStrea m(this.get MailTempla teDAO().ge tByLetterT ype(3L).ge tText(), " UTF-8");
        1859                }
        1860                else if  (session.g etAttribut e("eheDela y") != nul l) {
        1861                    sess ion.remove Attribute( "eheDelay" );
        1862                    inpu tStream =  IOUtils.to InputStrea m(this.get MailTempla teDAO().ge tByLetterT ype(2L).ge tText(), " UTF-8");
        1863                }
        1864  
        1865                DelayedC onsent dc  = (Delayed Consent)se ssion.getA ttribute(" delayedCon sent");
        1866                try {
        1867  
        1868                    temp lateString  = new Sca nner(input Stream,"UT F-8").useD elimiter(" \\A").next ();
        1869                }
        1870                finally  {
        1871                    if(i nputStream  != null)  {
        1872                         inputStrea m.close();
        1873                    }
        1874                }
        1875                formFiel ds.put("[e ntryDate]" , letterFo rmat.forma t(dc.getDa teAdded()) );
        1876                //Parse  the delaye d reasons.
        1877                String d elayReason String = " ";
        1878                String[]  delayedRe asons = fo rmFields.g et("delayC ollection" ).split(", ");
        1879                for (int  i = 0; i  < delayedR easons.len gth; i++)  {
        1880                    dela yedReasons [i] = dela yedReasons [i].replac eAll("[^0- 9]+", "");
        1881                    dela yedReasons [i] = this .getDelayR easonDAO() .findByDel ayReasonId (Long.pars eLong(dela yedReasons [i])).getN ame();
        1882                }
        1883                for (int  i = 0; i  < delayedR easons.len gth; i++)  {
        1884                    if ( i == 4) {
        1885                         delayReaso nString +=  ",\n                      ";
        1886                    } el se if (i >  0) {
        1887                         delayReaso nString +=  ", ";
        1888                    }
        1889                    dela yReasonStr ing += del ayedReason s[i];
        1890                }
        1891                template String = t emplateStr ing.replac e("[reason sForDelay] ", delayRe asonString );
        1892           }
        1893  
        1894           // Get and pa rse revoke d fields.
        1895           el se if (typ e.equals(" revoked"))  {
        1896                inputStr eam = IOUt ils.toInpu tStream(th is.getMail TemplateDA O().getByL etterType( 1L).getTex t(), "UTF- 8");
        1897                try {
        1898                    temp lateString  = new Sca nner(input Stream,"UT F-8").useD elimiter(" \\A").next ();
        1899                }
        1900                finally  {
        1901                    if(i nputStream  != null)  {
        1902                         inputStrea m.close();
        1903                    }
        1904                }
        1905                ConsentD irective c onsent = ( ConsentDir ective)ses sion.getAt tribute("c onsent");
        1906                formFiel ds.put("[p urpose]",  consent.ge tPurposeOf Use().getP ouValue()) ;
        1907                formFiel ds.put("[o ptoutDate] ", letterF ormat.form at(consent .getOptout Date()));
        1908                formFiel ds.put("[e xpirationD ate]", let terFormat. format(con sent.getEx pirationDa te()));
        1909           }
        1910  
        1911           // Get and pa rse expiri ng fields.
        1912           el se if (typ e.equals(" expiring") ) {
        1913                inputStr eam = IOUt ils.toInpu tStream(th is.getMail TemplateDA O().getByL etterType( 4L).getTex t(), "UTF- 8");
        1914                try {
        1915                    temp lateString  = new Sca nner(input Stream, "U TF-8").use Delimiter( "\\A").nex t();
        1916                }
        1917                finally  {
        1918                    if(i nputStream  != null)  {
        1919                         inputStrea m.close();
        1920                    }
        1921                }
        1922                ConsentD irective c onsent = ( ConsentDir ective)ses sion.getAt tribute("c onsent");
        1923                if (!Nul lChecker.i sNullOrEmp ty(consent )) {
        1924                    if ( consent.ge tOptinCons entType(). getName(). equals("SS A Authoriz ation")) {
        1925                         formFields .put("[con sentDescri ption]", " Authorized  access to  Social Se curity Adm inistratio n");
        1926                         formFields .put("[con sentName]" , consent. getOptinCo nsentType( ).getName( ));
        1927                    } el se if (con sent.getOp tinConsent Type().get Name().equ als("NwHIN  Authoriza tion")) {
        1928                         formFields .put("[con sentDescri ption]", " Authorized  access to  Providers  and Organ izations") ;
        1929                         formFields .put("[con sentName]" , "eHealth  Exchange  Authorizat ion");
        1930                    }
        1931                    form Fields.put ("[purpose ]", consen t.getPurpo seOfUse(). getPouValu e());
        1932                    form Fields.put ("[entryDa te]", lett erFormat.f ormat(cons ent.getOpt inTS()));
        1933                    form Fields.put ("[expirat ionDate]",  letterFor mat.format (consent.g etExpirati onDate())) ;
        1934                }
        1935           }
        1936  
        1937           if (inputStre am != null ) {
        1938                inputStr eam.close( );
        1939           }
        1940  
        1941           // Get patien t details
        1942           Pa tientDemog raphics pa tientDemog raphics =  (PatientDe mographics ) session. getAttribu te("patien tDemograph ics");
        1943           fo rmFields.p ut("[date] ", new Sim pleDateFor mat("dd MM M, yyyy"). format(new  Date()));
        1944           fo rmFields.p ut("[first Name]", pa tientDemog raphics.ge tFirstName ());
        1945           fo rmFields.p ut("[lastN ame]", pat ientDemogr aphics.get LastName() );
        1946           fo rmFields.p ut("[middl eName]", p atientDemo graphics.g etMiddleNa me());
        1947           fo rmFields.p ut("[facil ityName]",  facility. getFacilit yName());
        1948           St ring addre ss1 = (fac ility.getA ddress() ! = null) ?  facility.g etAddress( ) : "";
        1949           fo rmFields.p ut("[facil ityAddress 1]", addre ss1);
        1950           St ring addre ss2 = (fac ility.getC ity() != n ull) ? fac ility.getC ity() + ",  " : "";
        1951           ad dress2 +=  (facility. getState()  != null)  ? facility .getState( ) + " " :  "";
        1952           ad dress2 +=  (facility. getPostalC ode() != n ull) ? fac ility.getP ostalCode( ) : "";
        1953           fo rmFields.p ut("[facil ityAddress 2]", addre ss2);
        1954           St ring phone  = (facili ty.getPhon e() != nul l) ? facil ity.getPho ne() : "";
        1955           if  (!NullChe cker.isNul lOrEmpty(p hone)) {
        1956                phone =  "(" + phon e.substrin g(0, 3) +  ") " + pho ne.substri ng(3, 6) +  "-" + pho ne.substri ng(6);
        1957           }
        1958           fo rmFields.p ut("[facil ityPhone]" , phone);
        1959  
        1960           // Get and fo rmat patie nt address .
        1961           St ring addre ss = patie ntDemograp hics.getSt reetAddres sLine1() +  "\n";
        1962           if  (!NullChe cker.isNul lOrEmpty(p atientDemo graphics.g etStreetAd dressLine2 ())) {
        1963                address  += patient Demographi cs.getStre etAddressL ine2() + " \n";
        1964           }
        1965           if  (!NullChe cker.isNul lOrEmpty(p atientDemo graphics.g etStreetAd dressLine3 ())) {
        1966                address  += patient Demographi cs.getStre etAddressL ine3() + " \n";
        1967           }
        1968  
        1969           ad dress += p atientDemo graphics.g etResidenc eCity() +  ", " + pat ientDemogr aphics.get ResidenceS tate() + "  " +
        1970                patientD emographic s.getResid enceZip4() ;
        1971  
        1972           te mplateStri ng = templ ateString. replace("[ patientAdd ress]", ad dress);
        1973  
        1974           St ring sigFi elds = for mFields.ge t("signatu re");
        1975           te mplateStri ng = templ ateString. replace("[ signature] ", sigFiel ds);
        1976  
        1977           pa tientDetai ls.add(for mFields);
        1978  
        1979           Pd fGenerator  pdfGenera tor = new  PdfGenerat or();
        1980           By teArrayOut putStream  pdfStream  = pdfGener ator.creat e(template String, pa tientDetai ls, type);
        1981  
        1982           re sponse.set ContentTyp e("applica tion/pdf") ;
        1983           re sponse.set ContentLen gth(pdfStr eam.size() );
        1984           re sponse.set Header("Co ntent-Tran sfer-Encod ing", "bin ary");
        1985           re sponse.add Header("Co ntent-Disp osition",  "attachmen t; filenam e=patient_ letter.pdf ");
        1986           re sponse.set Header("pr agma", "em pty");
        1987           re sponse.set Header("Ca che-Contro l", "must- revalidate ");
        1988  
        1989           tr y {
        1990                final Se rvletOutpu tStream os  = respons e.getOutpu tStream();
        1991                Assert.a ssertNotEm pty(os, "O utput Stre am cannot  be null!") ;
        1992                os.write (pdfStream .toByteArr ay());
        1993                os.flush ();
        1994                os.close ();
        1995                if (mail ed) {
        1996                    Mail Notificati on mN = ne w MailNoti fication() ;
        1997                    Mail Log mL = n ew MailLog ();
        1998                    mN.s etSentDate (new Date( ));
        1999                    mN.s etUserId(U serHelper. getUserNam e(request) );
        2000                    Arra yList<Date > date = n ew ArrayLi st<Date>() ;
        2001                    date .add(new D ate());
        2002                    try  {
        2003                         String log  = getLogE ntry(new A rrayList<D ate>(), da te, UserHe lper.getUs erName(req uest));
        2004                         mL.setLogE ntry(log);
        2005                    }
        2006                    catc h (ParseEx ception ex ) {
        2007                         Logger.get Logger(Pat ientDetail s.class.ge tName()).l og(Level.S EVERE, nul l, ex);
        2008                    }
        2009                    if ( type.equal s("delayed ")) {
        2010                         DelayedCon sent dc =  (DelayedCo nsent)sess ion.getAtt ribute("de layedConse nt");
        2011                         mN.setDela yedConsent Id(dc);
        2012                         mL.setDela yedConsent Id(dc.getD elayedCons entId());
        2013                         try {
        2014                             this.g etMailLogD AO().creat e(mL);
        2015                             this.g etMailNoti ficationDA O().create (mN);
        2016                         }
        2017                         catch (Exc eption ex)  {
        2018                         }
        2019                    }
        2020                    else  {
        2021                         ConsentDir ective con sent = (Co nsentDirec tive)sessi on.getAttr ibute("con sent");
        2022                         mN.setCons entDirId(c onsent);
        2023                         mL.setCons entDirId(c onsent.get ConsentDir Id());
        2024                         try {
        2025                             this.g etMailLogD AO().creat e(mL);
        2026                             this.g etMailNoti ficationDA O().create (mN);
        2027                         }
        2028                         catch (Exc eption ex)  {
        2029                         }
        2030                    }
        2031  
        2032                }
        2033           }
        2034           ca tch (final  IOExcepti on ex) {
        2035                             throw  new Servle tException (ex);
        2036           }
        2037       }
        2038  
        2039    private v oid getDoc umentFromD AS(Servlet OutputStre am ostream , String e xternalDoc umentId) t hrows IOEx ception{
        2040       // Bui ld and sen d initial  DAS reques t
        2041       String  dasRetrie veDocument EndPoint =   Constant s.getDasRe trieveDocu mentEndPoi nt();
        2042       String  dasRetrie veOneDocum entEndPoin t =  Const ants.getDa sRetrieveO neDocument EndPoint() ;
        2043       String  dasRetrie veDocument UrlWithDoc Id =  dasR etrieveDoc umentEndPo int + exte rnalDocume ntId;
        2044  
        2045       //Http Client cli ent = Http ClientBuil der.create ().build() ;
        2046       //Http Get reques t = new Ht tpGet(dasR etrieveDoc umentUrlWi thDocId);
        2047       URL ur l = new UR L(dasRetri eveDocumen tUrlWithDo cId);
        2048       Logger .getLogger (PatientDe tails.clas s.getName( )).log(Lev el.INFO, " DAS URL: " +dasRetrie veDocument UrlWithDoc Id);
        2049       HttpsU RLConnecti on conn =  null;
        2050       conn =  (HttpsURL Connection ) url.open Connection ();
        2051       conn.c onnect();
        2052  
        2053       //adde d the resp onse messa ge on fail ure as wel l, because  it can he lp with de bugging po tentially
        2054       if (co nn.getResp onseCode()  != 200) {
        2055           th row new Ru ntimeExcep tion("\nFa iled : HTT P error co de : " + c onn.getRes ponseCode( ) + "\nHTT P response  : " + con n.getRespo nseMessage ());
        2056       }
        2057       InputS tream inpu tStream =   conn.getI nputStream ();
        2058       // Htt pResponse  response =  client.ex ecute(requ est);
        2059       // Htt pEntity en tity = res ponse.getE ntity();
        2060  
        2061       // Rea d DAS resp onse to JS ON string
        2062       if (in putStream  != null) {
        2063  
        2064           fi nal char[]  buffer =  new char[b ufferSize] ;
        2065           fi nal String Builder ou t = new St ringBuilde r();
        2066           tr y {
        2067                Reader i n = new In putStreamR eader(inpu tStream, " UTF-8");
        2068                for (;;)  {
        2069                int rsz  = in.read( buffer, 0,  buffer.le ngth);
        2070                if (rsz  < 0)
        2071                    brea k;
        2072                out.appe nd(buffer,  0, rsz);
        2073              }
        2074           }
        2075           ca tch (Unsup portedEnco dingExcept ion ex) {
        2076                Logger.g etLogger(P atientDeta ils.class. getName()) .log(Level .SEVERE, n ull, ex);
        2077           }
        2078           ca tch (IOExc eption ex)  {
        2079                Logger.g etLogger(P atientDeta ils.class. getName()) .log(Level .SEVERE, n ull, ex);
        2080           }
        2081           St ring jsonS tring = ou t.toString ();
        2082           in putStream. close();
        2083  
        2084           //  Extract e Auth PDF I D from JSO N DAS resp onse
        2085           St ring pdfId  = "";
        2086           in t pdfLengt h = 0;
        2087           tr y {
        2088                JSONObje ct jObject  = new JSO NObject(js onString);
        2089                pdfId =  ((JSONObje ct)jObject .getJSONAr ray("gridf sAttachmen ts").get(0 )).getStri ng("gridfs ID");
        2090                pdfLengt h = ((JSON Object)jOb ject.getJS ONArray("g ridfsAttac hments").g et(0)).get Int("gridf sLength");
        2091           }  catch (JSO NException  ex) {
        2092                Logger.g etLogger(P atientDeta ils.class. getName()) .log(Level .SEVERE, n ull, ex);
        2093           }
        2094  
        2095           if  (pdfLengt h <= 0) {
        2096                Logger.g etLogger(P atientDeta ils.class. getName()) .log(Level .WARNING,
        2097                         "eAuth PDF  length is  not great er than ze ro");
        2098           }
        2099  
        2100           da sRetrieveD ocumentUrl WithDocId  =  dasRetr ieveOneDoc umentEndPo int + pdfI d;
        2101            L ogger.getL ogger(Pati entDetails .class.get Name()).lo g(Level.IN FO, "DAS D oc URL: "+ dasRetriev eDocumentU rlWithDocI d);
        2102           ur l = new UR L(dasRetri eveDocumen tUrlWithDo cId);
        2103           co nn = (Http sURLConnec tion) url. openConnec tion();
        2104           co nn.connect ();
        2105  
        2106           // added the  response m essage on  failure as  well, bec ause it ca n help wit h debuggin g potentia lly
        2107           if  (conn.get ResponseCo de() != 20 0) {
        2108                throw ne w RuntimeE xception(" \nFailed :  HTTP erro r code : "  + conn.ge tResponseC ode() + "\ nHTTP resp onse : " +  conn.getR esponseMes sage());
        2109           }
        2110           In putStream  is =  conn .getInputS tream();
        2111           if  (is != nu ll) {
        2112                // Print  PDF
        2113                byte[] b uf = new b yte[buffer Size];
        2114                int c;
        2115                while (( c = is.rea d(buf, 0,  buf.length )) > 0) {
        2116                    ostr eam.write( buf, 0, c) ;
        2117                    ostr eam.flush( );
        2118                }
        2119                is.close ();
        2120           }  else {
        2121                Logger.g etLogger(P atientDeta ils.class. getName()) .log(Level .WARNING,  "No inner  PDF return ed");
        2122           }
        2123       } else  {
        2124           Lo gger.getLo gger(Patie ntDetails. class.getN ame()).log (Level.WAR NING, "No  documents  returned") ;
        2125       }
        2126    }
        2127   }