4312. EPMO Open Source Coordination Office Redaction File Detail Report

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

4312.1 Files compared

# Location File Last Modified
1 Fri Jun 9 19:51:27 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\report InboundDocumentReport.java Fri Apr 21 20:15:58 2017 UTC

4312.2 Comparison summary

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

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

4312.4 Active regular expressions

No regular expressions were active.

4312.5 Comparison detail

        1   /*
        2    * To chan ge this te mplate, ch oose Tools  | Templat es
        3    * and ope n the temp late in th e editor.
        4    */
        5   package go v.va.nvap. web.report ;
        6  
        7   import gov .va.med.nh in.adapter .audit.Act ionType;
        8   import gov .va.med.nh in.adapter .audit.Act ionValuesT ype;
        9   import gov .va.med.nh in.adapter .audit.Aud itType;
        10   import gov .va.med.nh in.adapter .audit.Fie ldType;
        11   import gov .va.med.nh in.adapter .audit.Get Audits;
        12   import gov .va.med.nh in.adapter .audit.Get AuditsResp onse;
        13   import gov .va.med.nh in.adapter .audit.Pag eInfoType;
        14   import gov .va.med.nh in.adapter .audit.Sor tDirection ;
        15   import gov .va.med.nh in.adapter .audit.Sor tFieldType ;
        16   import gov .va.med.nh in.adapter .audit.Sor tFieldsTyp e;
        17   import gov .va.med.nh in.adapter .audit.Str ingValuesT ype;
        18   import gov .va.nvap.c ommon.date .Gregorian DateUtil;
        19   import gov .va.nvap.c ommon.vali dation.Nul lChecker;
        20   import gov .va.nvap.s ervice.ada pter.audit .AdapterAu ditManager ;
        21   import gov .va.nvap.s ervice.ada pter.doc.A dapterExce ption;
        22   import gov .va.nvap.s ervice.aud it.AuditEx ception;
        23   import gov .va.nvap.w eb.app.Res ponseDispa tcherHttpS ervlet;
        24   import gov .va.nvap.w eb.dao.Fac ilityDAO;
        25   import gov .va.nvap.w eb.dao.Pur poseOfUseD AO;
        26   import gov .va.nvap.w eb.dao.Use rDocumentD AO;
        27   import gov .va.nvap.w eb.entitie s.PurposeO fUse;
        28   import gov .va.nvap.w eb.helper. document.D ocumentHel per;
        29   import gov .va.nvap.w eb.helper. facility.F acilityHel per;
        30   import gov .va.nvap.w eb.helper. privacy.Co nsentManag ementHelpe r;
        31   import gov .va.nvap.w eb.helper. report.Rep ortHelper;
        32   import gov .va.nvap.w eb.patient .ExcelGene ratorThrea d;
        33   import gov .va.nvap.w eb.user.Us erHelper;
        34   import gov .va.nvap.w eb.util.Co nstants;
        35   import gov .va.nvap.w eb.util.xl s.CsvExpor ter;
        36   import gov .va.nvap.w eb.util.xl s.ExcelExp orter;
        37  
        38   import jav a.io.IOExc eption;
        39   import jav a.io.Strin gWriter;
        40   import jav a.util.Arr ayList;
        41   import jav a.util.Col lection;
        42   import jav a.util.Dat e;
        43   import jav a.util.Has hMap;
        44   import jav a.util.Lin kedHashMap ;
        45   import jav a.util.Lis t;
        46   import jav a.util.Map ;
        47   import jav a.util.log ging.Level ;
        48   import jav a.util.log ging.Logge r;
        49   import jav ax.ejb.EJB ;
        50  
        51   import jav ax.servlet .ServletEx ception;
        52   import jav ax.servlet .http.Http ServletReq uest;
        53   import jav ax.servlet .http.Http ServletRes ponse;
        54   import jav ax.servlet .http.Http Session;
        55   import org .apache.po i.ss.userm odel.Workb ook;
        56  
        57   import org .json.JSON Exception;
        58   import org .json.JSON Object;
        59  
        60   /**
        61    * Documen ts that ar e received  by the VA  from exte rnal partn ers.
        62    *
        63    * @author  Asha Amri traj
        64    */
        65   public cla ss Inbound DocumentRe port exten ds Respons eDispatche rHttpServl et {
        66           /* *
        67            *  Serial UI D.
        68            * /
        69           pr ivate stat ic final l ong serial VersionUID  = 1512959 0652186530 85L;
        70  
        71       privat e final St ring REPOR T_TITLE =  "Received  eHealth Ex change Doc uments Det ail Report ";
        72  
        73       privat e AdapterA uditManage r adapterA uditManage r;
        74           pu blic Conse ntManageme ntHelper g etCmsHelpe r() {
        75                    fina l ConsentM anagementH elper cmsH elper = th is.getBean ("cmsHelpe r",
        76                                      ConsentM anagementH elper.clas s);
        77                    retu rn cmsHelp er;
        78           }
        79  
        80           /* *
        81            *  Get the f acility he lper from  Spring.
        82            * /
        83           pu blic Facil ityHelper  getFacilit yHelper()  {
        84                    fina l Facility Helper fac ilityHelpe r = this.g etBean("fa cilityHelp er",
        85                                      Facility Helper.cla ss);
        86                    retu rn facilit yHelper;
        87           }
        88  
        89       privat e ReportHe lper getRe portHelper () {
        90           re turn this. getBean("r eportHelpe r", Report Helper.cla ss);
        91       }
        92  
        93           @O verride
        94           pr otected vo id unspeci fied(final  HttpServl etRequest  request,
        95                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        96                             IOExce ption {
        97                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        98  
        99                    sess ion.remove Attribute( "results") ;
        100  
        101                    requ est.setAtt ribute("fa cilities",  this.getF acilityHel per()
        102                                      .getAllV istAFacili ties());
        103                    //re quest.setA ttribute(" organizati ons", this .getCmsHel per()
        104                    //                .getAllo wedOrganiz ations());
        105           th is.getRepo rtHelper() .getReceiv edDocsOrgL ists(reque st);
        106  
        107                    if ( Constants. PURPOSE_OF _USE_FLAG) {
        108                             final  PurposeOfU seDAO purp oseOfUseDA O = this.g etBean(
        109                                               "purposeOf UseDAO", P urposeOfUs eDAO.class );
        110                             Collec tion<Purpo seOfUse> p ous = purp oseOfUseDA O.findPurp oseOfUse() ;
        111                             reques t.setAttri bute("pous ", pous);
        112                    }
        113                    requ est.setAtt ribute("po uFlag", Co nstants.PU RPOSE_OF_U SE_FLAG);
        114           Re portHelper .setDefaul tSearchDat es(session );
        115  
        116                    this .forward(r equest, re sponse, "s how");
        117           }
        118  
        119       public  void doSe arch(final  HttpServl etRequest  request, f inal HttpS ervletResp onse respo nse) throw s AuditExc eption, IO Exception,  ServletEx ception{
        120           fi nal HttpSe ssion sess ion = requ est.getSes sion(false );
        121  
        122           se ssion.setA ttribute(" results",  encodeInto JSON(getRe sults(requ est, false ), request .getParame ter("draw" )));
        123  
        124           th is.forward (request,  response,  "searchRes ultsJSON") ;
        125       }
        126  
        127       /**
        128        * gat hers searc h results  based on r equest par ameters an d returns  in a packa ged form.  Boolean is  check to  see if all  data shou ld
        129        * be  returned o r only spe cified amo unt
        130        * @pa ram reques t
        131        * @pa ram getAll
        132        * @re turn
        133        * @th rows Audit Exception
        134        */
        135       privat e SearchPa ckage getR esults(fin al HttpSer vletReques t request,  boolean e xporting)  throws Aud itExceptio n {
        136  
        137                    fina l String s sn = reque st.getPara meter("ssn ");
        138                    fina l String l astName =  request.ge tParameter ("lastName ");
        139                    fina l String f irstName =  request.g etParamete r("firstNa me");
        140           fi nal String  userId =  request.ge tParameter ("userId") ;
        141                    fina l Date sd  = ReportHe lper.getSt artDate(re quest.getP arameter(" startDate" ));
        142                    fina l Date ed  = ReportHe lper.getEn dDate(requ est.getPar ameter("en dDate"));
        143                    fina l String f acility =  request.ge tParameter ("facility ");
        144                    fina l String p urposeOfUs e = reques t.getParam eter("purp oseOfUse") ;
        145                    fina l String r emoteOrgan ization =  request.ge tParameter ("remoteOr ganization ");
        146                    fina l int pati entTypes =  Integer.p arseInt(re quest.getP arameter(" patientTyp es"));
        147                    // s ort
        148                    fina l String i nboundSort Value = (r equest.get Parameter( "order[0][ column]")  != null)
        149                    ? ge tSortValue (request.g etParamete r("order[0 ][column]" )): getSor tValue(req uest.getPa rameter("s ortBy"));
        150                    fina l String i nboundSort Direction  = (request .getParame ter("order [0][dir]")  != null)
        151                    ? re quest.getP arameter(" order[0][d ir]"): req uest.getPa rameter("s ortOrder") ;
        152  
        153  
        154                    fina l GetAudit s getAudit sRequest =  new GetAu dits();
        155                    if ( NullChecke r.isNotEmp ty(sd)) {
        156                             getAud itsRequest .setFromDa te(Gregori anDateUtil
        157                                               .getGregor ianCalenda rByDate(sd ));
        158                    }
        159                    if ( NullChecke r.isNotEmp ty(ed)) {
        160                             getAud itsRequest .setToDate (Gregorian DateUtil
        161                                               .getGregor ianCalenda rByDate(ed ));
        162                    }
        163  
        164           //  Set Patie nt Types
        165           ge tAuditsReq uest.setPa tientTypes (patientTy pes);
        166  
        167                    /*
        168                     * / / Set Pati ent Ids if  (NullChec ker.isNotE mpty(icn))  { final
        169                     * S tringValue sType pati entIds = n ew StringV aluesType( );
        170                     * p atientIds. getValue() .add(icn);  patientId s.setNotIn (false);
        171                     * g etAuditsRe quest.setP atientIds( patientIds ); }
        172                     */
        173                    // S et SSN
        174                    if ( NullChecke r.isNotEmp ty(ssn)) {
        175                             final  StringValu esType pat ientSSNs =  new Strin gValuesTyp e();
        176                             patien tSSNs.getV alue().add (ssn);
        177                             patien tSSNs.setN otIn(false );
        178                             getAud itsRequest .setPatien tSSNs(pati entSSNs);
        179                    }
        180                    // S et Last Na me
        181                    if ( NullChecke r.isNotEmp ty(lastNam e)) {
        182                             final  StringValu esType pat ientLastNa mes = new  StringValu esType();
        183                             patien tLastNames .getValue( ).add(last Name);
        184                             patien tLastNames .setNotIn( false);
        185                             getAud itsRequest .setPatien tLastNames (patientLa stNames);
        186                    }
        187                    // S et First N ame
        188                    if ( NullChecke r.isNotEmp ty(firstNa me)) {
        189                             final  StringValu esType pat ientFirstN ames = new  StringVal uesType();
        190                             patien tFirstName s.getValue ().add(fir stName);
        191                             patien tFirstName s.setNotIn (false);
        192                             getAud itsRequest .setPatien tGivenName s(patientF irstNames) ;
        193                    }
        194                    // S et User ID
        195           if  (NullChec ker.isNotE mpty(userI d)) {
        196                final St ringValues Type userI dValue = n ew StringV aluesType( );
        197                userIdVa lue.getVal ue().add(u serId);
        198                userIdVa lue.setNot In(false);
        199                getAudit sRequest.s etUserIds( userIdValu e);
        200           }
        201                    // S et Purpose  of Use
        202                    if ( !NullCheck er.isNullO rEmpty(pur poseOfUse)  ) {
        203                             final  StringValu esType pur poseForUse s = new St ringValues Type();
        204                             purpos eForUses.g etValue(). add(purpos eOfUse);
        205                             purpos eForUses.s etNotIn(fa lse);
        206                             getAud itsRequest .setPurpos eForUses(p urposeForU ses);
        207                    }
        208  
        209                    // S et Facilit y Ids
        210                    if ( NullChecke r.isNotEmp ty(facilit y)) {
        211                             final  StringValu esType fac ilityIds =  new Strin gValuesTyp e();
        212                             facili tyIds.setN otIn(false );
        213                             facili tyIds.getV alue().add (facility) ;
        214                             getAud itsRequest .setPatien tFacilityN umbers(fac ilityIds);
        215                    }
        216  
        217                    /*
        218                     * / / Set Orga nization I ds final S tringValue sType orga nizationId s = new
        219                     * S tringValue sType(); o rganizatio nIds.setNo tIn(false) ;
        220                     * g etAuditsRe quest.setO rganizatio nIds(organ izationIds );
        221                     */
        222  
        223                    // S et Remote  Organizati on Ids
        224                    if ( NullChecke r.isNotEmp ty(remoteO rganizatio n)) {
        225                             final  StringValu esType rem oteOrganiz ationIds =  new Strin gValuesTyp e();
        226                             remote Organizati onIds.setN otIn(false );
        227                             remote Organizati onIds.getV alue().add (remoteOrg anization) ;
        228                             getAud itsRequest .setRemote Organizati onIds(remo teOrganiza tionIds);
        229                    }
        230  
        231                    // s orting
        232                    if ( NullChecke r.isNotEmp ty(inbound SortValue) ) {
        233                             final  SortFieldT ype sortFi eld = new  SortFieldT ype();
        234                             sortFi eld.setFie ld(FieldTy pe.fromVal ue(inbound SortValue) );
        235                             if ("D ESC".equal sIgnoreCas e(inboundS ortDirecti on)) {
        236                                      sortFiel d.setDirec tion(SortD irection.D ESC);
        237                             } else  {
        238                                      sortFiel d.setDirec tion(SortD irection.A SC);
        239                             }
        240                             final  SortFields Type sortF ieldsType  = new Sort FieldsType ();
        241                             sortFi eldsType.g etSortFiel d().add(so rtField);
        242                             getAud itsRequest .setSortFi elds(sortF ieldsType) ;
        243                    }
        244  
        245                    // S et Actions
        246                    fina l ActionVa luesType a ctionsType  = new Act ionValuesT ype();
        247                    acti onsType.ge tValue().a dd(ActionT ype.RETRIE VE_DOCUMEN T_OUT);
        248                    getA uditsReque st.setActi ons(action sType);
        249  
        250                    // S et Page in formation
        251                    fina l PageInfo Type pageI nfoType =  new PageIn foType();
        252  
        253           pa geInfoType .setPageNu mber((requ est.getPar ameter("st art") != n ull) ? Int eger.parse Int(reques t.getParam eter("star t"))/Integ er.parseIn t(request. getParamet er("length ")) : 0);
        254           pa geInfoType .setPageSi ze((reques t.getParam eter("leng th") != nu ll) ? Inte ger.parseI nt(request .getParame ter("lengt h")): -1);
        255  
        256                    getA uditsReque st.setPage Info(pageI nfoType);
        257  
        258                    fina l List<Map <String, O bject>> re sults = ne w ArrayLis t<Map<Stri ng, Object >>();
        259           Ge tAuditsRes ponse quer yResponse  = new GetA uditsRespo nse();
        260           Lo ng totalCo unt = new  Long(0); / /default i t to zero,  but we se t it below
        261                    Stri ng resultI cn = "";
        262  
        263                    try  {
        264                             try {
        265                    quer yResponse  = this.ada pterAuditM anager.get Audits(get AuditsRequ est);
        266                    if(q ueryRespon se.getPage Info() !=  null) {
        267                         totalCount  = exporti ng ? 0 : n ew Long(qu eryRespons e.getPageI nfo().getT otalSize() );
        268                    }
        269                } catch( Exception  e) {
        270                    thro w new Audi tException ();
        271                }
        272  
        273                             if (Nu llChecker. isNotEmpty (queryResp onse)
        274                                               && NullChe cker.isNot Empty(quer yResponse. getAudits( ))
        275                                               && NullChe cker.isNot Empty(quer yResponse. getAudits( )
        276                                                                .get Audit()))  {
        277                                      final Li st<AuditTy pe> auditT ypeList =  queryRespo nse.getAud its()
        278                                                       .g etAudit();
        279                    Faci lityHelper  facilityH elper = th is.getFaci lityHelper ();
        280                    Stri ng userIdS tring;
        281                                      for (fin al AuditTy pe auditTy pe : audit TypeList)  {
        282                                               // final S tring pati entId = au ditType.ge tPatientId ();
        283  
        284                                               // final P atientDemo graphicsQu ery patien tDemograph icsQuery =
        285                                               // new Pat ientDemogr aphicsQuer y();
        286                                               // patient Demographi csQuery.se tPatientId (patientId );
        287                                               // final P atientDemo graphicsRe sponse res ponse =
        288                                               // this.pd qService
        289                                               // .getPat ientDemogr aphics(pat ientDemogr aphicsQuer y);
        290  
        291                                               final Map< String, Ob ject> resu ltMap = ne w HashMap< String, Ob ject>();
        292  
        293                                               ReportData Processor. addSsnToRe sultMap(re sultMap, a uditType.g etPatientS SN());
        294  
        295                                               resultMap. put("patie ntICN", Re portDataPr ocessor
        296                                                                .nul lEmptyRepl aceWithUnk nown(audit Type
        297                                                                                  .getPati entId()));
        298  
        299                                               // A) Repl ace this w ith B
        300                                               resultMap. put("audit Time", Gre gorianDate Util
        301                                                                .get DateFromGr egorianCal endar(audi tType
        302                                                                                  .getAudi tTime()));
        303  
        304                                               // B) The  following  logic coul d supplant  the previ ous one, A
        305                                               resultMap. put("audit TimeFormat ted", this .getReport Helper().g etFormatte dDateTime( GregorianD ateUtil
        306                                                                .get DateFromGr egorianCal endar(audi tType
        307                                                                                  .getAudi tTime()))) ;
        308  
        309                                               resultMap. put("purpo seForUse",  ReportDat aProcessor
        310                                                                .nul lEmptyRepl aceWithUnk nown(audit Type
        311                                                                                  .getPurp oseForUse( )));
        312  
        313                         resultMap. put("userF acilityCod e", "");
        314                         resultMap. put("userF acilityNam e", "");
        315  
        316                         userIdStri ng = Repor tDataProce ssor.nullE mptyReplac eWithUnkno wn(auditTy pe.getUser Id()).repl ace(" ? ",  " ");
        317                         resultMap. put("userI d", userId String);
        318  
        319                         //Parse th e user id  field for  facility c ode and us er name.
        320                         if (userId String.sub string(0,4 ).matches( "^\\d{3}:" )){
        321                             result Map.put("u serFacilit yCode", us erIdString .substring (0,3));
        322                             result Map.put("u serFacilit yName", fa cilityHelp er.getFaci lityNameBy StationId( userIdStri ng.substri ng(0,3)));
        323                         }
        324  
        325                         if (userId String.ind exOf("CN=" ) > 0){
        326                             result Map.put("u serName",u serIdStrin g.substrin g((userIdS tring.inde xOf("CN=")  + 3),
        327                                 us erIdString .indexOf(" ,", userId String.ind exOf("CN=" ))));
        328                         }
        329  
        330                                               // resultM ap.put("pa tient",
        331                                               // respons e.getPatie ntDemograp hics());
        332  
        333                                               resultMap. put("lastN ame", Repo rtDataProc essor
        334                                                                .nul lEmptyRepl aceWithUnk nown(audit Type
        335                                                                                  .getPati entLastNam e()));
        336                                               resultMap. put("first Name", Rep ortDataPro cessor
        337                                                                .nul lEmptyRepl aceWithUnk nown(audit Type
        338                                                                                  .getPati entGivenNa me()));
        339                                               resultMap. put("patie ntFacility Name", Rep ortDataPro cessor
        340                                                                .fix Station(au ditType.ge tPatientFa cilityName ()));
        341                                               resultMap. put("patie ntFacility Number", R eportDataP rocessor
        342                                                                .nul lEmptyRepl aceWithUnk nown(audit Type
        343                                                                                  .getPati entFacilit yNumber()) );
        344  
        345                         resultMap. put("remot eOrganizat ionName",  this.getRe portHelper ().findOrg anizationB yOid(audit Type.getRe moteOrgani zationId() , auditTyp e.getRemot eOrganizat ionName()) );
        346  
        347                         resultMap. put("remot eFacilityO id", Repor tDataProce ssor
        348                                                                .nul lEmptyRepl aceWithUnk nown(audit Type
        349                                                                                  .getRemo teOrganiza tionId())) ;
        350                                               /*
        351                                                * resultM ap.put( "r emoteFacil ity", this .getCmsHel per()
        352                                                * .getOrg anizationB yHomeCommu nityId(
        353                                                * auditTy pe.getRemo teOrganiza tionId())) ;
        354                                                * resultM ap.put("re moteDocRep ositoryId" ,
        355                                                * auditTy pe.getRemo teDocument Repository Id());
        356                                                */
        357  
        358                                               resultMap. put("docum entId", Re portDataPr ocessor
        359                                                                .nul lEmptyRepl aceWithUnk nown(audit Type
        360                                                                                  .getDocu mentId())) ;
        361                                               resultMap. put("docum entTitle",  ReportDat aProcessor
        362                                                                .nul lEmptyRepl aceWithUnk nown(audit Type
        363                                                                                  .getDocu mentTitle( )));
        364                                               resultMap. put("roleN ame", Repo rtDataProc essor
        365                                                                .nul lEmptyRepl aceWithUnk nown(audit Type
        366                                                                                  .getRole Name()));
        367                                               results.ad d(resultMa p);
        368                                      }
        369  
        370                                      // TODO:  Move sett ing of ses sion varia bles to a  different  method
        371                                      // Check  if any of  the patie nt match c riteria ex ists
        372                                      if (Null Checker.is NotEmpty(s sn)
        373                                                       ||  NullCheck er.isNotEm pty(lastNa me)
        374                                                       ||  NullCheck er.isNotEm pty(firstN ame)) {
        375                                               if (NullCh ecker.isNo tEmpty(aud itTypeList )) {
        376                                                       fi nal AuditT ype result  = auditTy peList.get (0);
        377                                                       re sultIcn =  result.get PatientId( );
        378  
        379                                                       if  (NullChec ker.isNotE mpty(resul tIcn)) {
        380                                                                for  (final Aud itType aud itType : a uditTypeLi st) {
        381                                                                         if (!r esultIcn.e quals(audi tType.getP atientId() )) {
        382                                                                                  resultIc n = "Multi ple ICNs";
        383                                                                                  break;
        384                                                                         }
        385                                                                }
        386                                                       }  else if (N ullChecker .isNotEmpt y(result
        387                                                                         .getPa tientGiven Name())
        388                                                                         && Nul lChecker.i sNotEmpty( result
        389                                                                                           .getPatien tLastName( ))
        390                                                                         && Nul lChecker.i sNotEmpty( result
        391                                                                                           .getPatien tSSN())) {
        392                                                                fina l String p atientGive nName = re sult
        393                                                                                  .getPati entGivenNa me();
        394                                                                fina l String p atientLast Name = res ult
        395                                                                                  .getPati entLastNam e();
        396                                                                fina l String p atientSsn  = result.g etPatientS SN();
        397                                                                bool ean multip leIcns = f alse;
        398                                                                for  (final Aud itType aud itType : a uditTypeLi st) {
        399                                                                         if (!p atientGive nName.equa ls(auditTy pe
        400                                                                                           .getPatien tGivenName ())
        401                                                                                           || !patien tLastName. equals(aud itType
        402                                                                                                            .get PatientLas tName())
        403                                                                                           || !patien tSsn.equal s(auditTyp e
        404                                                                                                            .get PatientSSN ())) {
        405                                                                                  multiple Icns = tru e;
        406                                                                                  break;
        407                                                                         }
        408                                                                }
        409                                                                if ( multipleIc ns) {
        410                                                                         result Icn = "Mul tiple ICNs ";
        411                                                                } el se {
        412                                                                         result Icn = this .getReport Helper().r esolveICN(
        413                                                                                           result.get PatientGiv enName(),
        414                                                                                           result.get PatientLas tName(),
        415                                                                                           result.get PatientSSN ());
        416                                                                }
        417                                                       }
        418                                               } else if  (NullCheck er.isNotEm pty(ssn)
        419                                                                && N ullChecker .isNotEmpt y(lastName )
        420                                                                && N ullChecker .isNotEmpt y(firstNam e)) {
        421                                                       //  Try to ge t from wha t was type d
        422                                                       re sultIcn =  this.getRe portHelper ().resolve ICN(
        423                                                                         firstN ame, lastN ame, ssn);
        424                                               }
        425                                               // Set in  Session
        426                                               if (NullCh ecker.isEm pty(result Icn)) {
        427                                                       re sultIcn =  "Unknown";
        428                                               }
        429                                      }
        430                                      //return  results;
        431                             }
        432                    } ca tch (final  AuditExce ption ex)  {
        433                             throw  new AuditE xception() ;
        434                    } //  catch (fi nal PdqExc eption ex)  {
        435                             // thr ow new Run timeExcept ion(ex);
        436                    // }
        437           Se archPackag e sp = new  SearchPac kage(resul ts, result Icn);
        438           sp .setTotalC ount(total Count);
        439  
        440                    retu rn sp;
        441           }
        442  
        443       @EJB(b eanInterfa ce = Adapt erAuditMan ager.class , mappedNa me = "Adap terAuditMa nager")
        444           pu blic void  setAdapter AuditManag er(
        445                             final  AdapterAud itManager  adapterAud itManager)  {
        446                    this .adapterAu ditManager  = adapter AuditManag er;
        447           }
        448  
        449       /**
        450        * Cha nges resul t map into  json obje ct as stri ng, adding  any addit ion inform ation that  will be n eeded on f ront end.
        451        * @pa ram packag edResults
        452        * @re turn
        453        */
        454       privat e String e ncodeIntoJ SON(Search Package pa ckagedResu lts, Strin g draw){
        455           St ring retur nValue = " ";
        456  
        457           tr y {
        458                StringWr iter json  = new Stri ngWriter() ;
        459                JSONObje ct obj = n ew JSONObj ect();
        460                List<Lis t> data =  new ArrayL ist<List>( );
        461  
        462                for (Map <String,Ob ject> curr entRow: pa ckagedResu lts.getRes ults()) {
        463                    List <String> d ataItem =  new ArrayL ist<String >();
        464  
        465                    data Item.add(c urrentRow. get("ssnMa sked").toS tring());
        466                    data Item.add(c urrentRow. get("lastN ame").toSt ring());
        467                    data Item.add(c urrentRow. get("first Name").toS tring());
        468                    data Item.add(c urrentRow. get("audit TimeFormat ted").toSt ring());
        469                    data Item.add(c urrentRow. get("docum entTitle") .toString( ));
        470                    data Item.add(c urrentRow. get("patie ntFacility Name").toS tring());
        471                    data Item.add(c urrentRow. get("patie ntFacility Number").t oString()) ;
        472                    data Item.add(c urrentRow. get("remot eOrganizat ionName"). toString() );
        473                    data Item.add(c urrentRow. get("userI d").toStri ng());
        474                    data Item.add(c urrentRow. get("purpo seForUse") .toString( ));
        475                    data Item.add(c urrentRow. get("roleN ame").toSt ring());
        476                    data Item.add(c urrentRow. get("ssn") .toString( ));
        477                    data Item.add(c urrentRow. get("patie ntICN").to String());
        478                    data Item.add(c urrentRow. get("docum entId").to String());
        479  
        480                    data .add(dataI tem);
        481                }
        482  
        483                obj.put( "data", da ta);
        484                obj.put( "inboundIc n", packag edResults. getInbound Icn());
        485                obj.put( "recordsTo tal", pack agedResult s.getTotal Count());
        486                obj.put( "recordsFi ltered", p ackagedRes ults.getTo talCount() );
        487                obj.put( "draw", dr aw);
        488  
        489                obj.writ e(json);
        490  
        491                returnVa lue = json .toString( );
        492           }  catch (JSO NException  ex) {
        493                Logger.g etLogger(I nboundDocu mentReport .class.get Name()).lo g(Level.SE VERE, null , ex);
        494           }
        495  
        496           re turn retur nValue;
        497       }
        498  
        499       /**
        500        * Tak es in colu mn number  and return s proper s ort value
        501        * @pa ram colNum ber
        502        * @re turn
        503        */
        504       privat e String g etSortValu e(String c olNumber){
        505           St ring sortV alue = "";
        506  
        507           sw itch(Integ er.parseIn t(colNumbe r)){
        508                case 0:
        509                    sort Value = "p atientSSN" ;
        510                    brea k;
        511                case 1:
        512                    sort Value = "p atientLast Name";
        513                    brea k;
        514                case 2:
        515                    sort Value = "p atientGive nName";
        516                    brea k;
        517                case 3:
        518                    sort Value = "a uditTime";
        519                    brea k;
        520                case 4:
        521                    sort Value = "d ocumentTit le";
        522                    brea k;
        523                case 5:
        524                    sort Value = "p atientFaci lityName";
        525                    brea k;
        526                case 6:
        527                    sort Value = "p atientFaci lityNumber ";
        528                    brea k;
        529                case 7:
        530                    sort Value = "r emoteOrgan izationNam e";
        531                    brea k;
        532                case 8:
        533                    sort Value = "u serId";
        534                    brea k;
        535                case 9:
        536                    sort Value = "p urposeForU se";
        537                    brea k;
        538           }
        539           re turn sortV alue;
        540       }
        541  
        542       /**
        543        * doc ument view
        544        * @pa ram reques t
        545        * @pa ram respon se
        546        * @th rows Servl etExceptio n
        547        * @th rows IOExc eption
        548        */
        549       public  void view (final Htt pServletRe quest requ est,
        550                             final  HttpServle tResponse  response)  throws Ser vletExcept ion,
        551                             IOExce ption {
        552                    fina l HttpSess ion sessio n = reques t.getSessi on(false);
        553                    fina l String i cn = reque st.getPara meter("pat ientICN");
        554                    fina l String d ocumentUni queId = re quest
        555                                      .getPara meter("doc umentUniqu eId");
        556                    fina l String s tyleSheetV iewType =  request
        557                                      .getPara meter("sty leSheetVie wType");
        558  
        559                    Stri ng documen t = null;
        560                    try  {
        561                             docume nt = this. getDocumen tHelper(). getDocumen t(icn,
        562                                               documentUn iqueId, Us erHelper.g etUserName (request),
        563                                               this.getCm sHelper(). getComplet eHomeCommu nityId());
        564                    } ca tch (final  AdapterEx ception ex ) {
        565                             throw  new Servle tException (ex);
        566                    }
        567  
        568                    sess ion.setAtt ribute("ic n", icn);
        569                    sess ion.setAtt ribute("do cumentUniq ueId", doc umentUniqu eId);
        570                    sess ion.setAtt ribute("do cument", d ocument);
        571                    sess ion.setAtt ribute("is XmlViewEna bled", thi s.getDocum entHelper( )
        572                                      .isXmlVi ewEnabled( ));
        573  
        574                    if ( "xml".equa ls(styleSh eetViewTyp e)) {
        575                             docume nt = docum ent
        576                                               .replaceAl l(
        577                                                                "<?x ml-stylesh eet type=\ "text/xsl\ " href=\"C CD.xsl\"?> ",
        578                                                                "");
        579                             respon se.setCont entType("t ext/xml;ch arset=UTF- 8");
        580                             respon se.getWrit er().write (document) ;
        581                    } el se {
        582                             // Upd ate sessio n in the d ocument
        583                             final  String htm l = this.g etDocument Helper().g etHtml(doc ument,
        584                                               styleSheet ViewType);
        585  
        586                             sessio n.setAttri bute("upda tedDocumen t", html);
        587                             this.f orward(req uest, resp onse, "sho wInboundDo cumentRepo rtDocument ");
        588                    }
        589           }
        590  
        591       public  DocumentH elper getD ocumentHel per() {
        592                    retu rn this.ge tBean("ada pterDocume ntHelper",  DocumentH elper.clas s);
        593           }
        594  
        595       /**
        596        * Exp ort to exc el - This  method is  called whe n the user  clicks on  the excel  icon in t he JSP. Re flection i s used in  the
        597        * Res ponseDispa tcherHttpS ervlet to  call this  method bas ed on the  http param eters.
        598        *
        599        * @pa ram reques t HTTP Req uest
        600        * @pa ram respon se HTTP Re sponse
        601        * @th rows Servl etExceptio n
        602        * @th rows IOExc eption
        603        */
        604       public  void expo rtToExcel( final Http ServletReq uest reque st,
        605           fi nal HttpSe rvletRespo nse respon se) throws  ServletEx ception,
        606           IO Exception  {
        607  
        608                    // C reate a ma p of key w hich is ba sed on the  result da ta key and  the
        609           //  heading v alue
        610           //  The headi ng is used  to create  the colum n headers  and the ke y is used
        611           //  to pull t he data fr om the res ults
        612           fi nal Map<St ring, Stri ng> inboun dDocumentM ap = new L inkedHashM ap<String,  String>() ;
        613  
        614           fi nal Date s tartDateSt r = Report Helper.get StartDate( request.ge tParameter ("startDat e"));
        615           fi nal Date e ndDateStr  = ReportHe lper.getEn dDate(requ est.getPar ameter("en dDate"));
        616  
        617           //  Generate  filters.
        618           fi nal Map<St ring, List <Object>>  filterMap  = new Link edHashMap< String, Li st<Object> >();
        619           fi nal Linked HashMap<St ring, Obje ct> filter s = new Li nkedHashMa p<String,  Object>();
        620  
        621           fi lters.put( "SSN", req uest.getPa rameter("s sn"));
        622           fi lters.put( "Last Name ", request .getParame ter("lastN ame"));
        623           fi lters.put( "First Nam e", reques t.getParam eter("firs tName"));
        624           fi lters.put( "User ID",  request.g etParamete r("userId" ));
        625           fi lters.put( "Start Dat e", this.g etReportHe lper().get FormattedD ate( start DateStr));
        626           fi lters.put( "End Date" , this.get ReportHelp er().getFo rmattedDat e(endDateS tr));
        627           fi lters.put( "Purpose o f Use", Ex celExporte r.getFilte rValue(req uest.getPa rameter("p urposeOfUs e")));
        628           fi lters.put( "Patient P referred F acility",  ExcelExpor ter.getPat ientPrefer redFacilit yFilter(ge tFacilityD AO(), requ est.getPar ameter("fa cility"))) ;
        629           fi lters.put( "eHealth E xchange Or g", ExcelE xporter.ge tFilterVal ue(request .getParame ter("organ izationNam e")));
        630           Ex celExporte r.populate FilterMapF orExport(r equest, fi lters, fil terMap, re quest.getP arameter(" patientTyp es"));
        631  
        632           in boundDocum entMap.put ("ssn", "S SN");
        633           in boundDocum entMap.put ("lastName ", "Patien t Last Nam e");
        634           in boundDocum entMap.put ("firstNam e", "Patie nt First N ame");
        635           in boundDocum entMap.put ("auditTim eFormatted ", "Date R eceived (C T)");
        636           in boundDocum entMap.put ("document Title", "D ocument Ti tle");
        637           in boundDocum entMap.put ("patientF acilityNam e", "Patie nt Preferr ed Facilit y");
        638           in boundDocum entMap.put ("patientF acilityNum ber", "Pat ient Prefe rred Facil ity Statio n ID");
        639           in boundDocum entMap.put ("remoteOr ganization Name", "eH ealth Exch ange Organ ization");
        640           in boundDocum entMap.put ("remoteFa cilityOid" , "OID");
        641           in boundDocum entMap.put ("userId",  "User ID" );
        642           in boundDocum entMap.put ("userFaci lityCode",  "User Fac ility Code ");
        643           in boundDocum entMap.put ("userFaci lityName",  "User Fac ility");
        644           in boundDocum entMap.put ("userName ", "User N ame");
        645           in boundDocum entMap.put ("purposeF orUse", "P urpose of  Use");
        646           in boundDocum entMap.put ("roleName ", "User R ole");
        647  
        648           in t minimumT hreshold =  Integer.p arseInt((S tring) thi s.getServl etContext( ).getAttri bute("sche duledExpor tMin"));
        649           in t total =  Integer.pa rseInt(req uest.getPa rameter("t otalRows") );
        650  
        651           // Start a sc heduled ex port with  its own th read if gr eater than  the minim um thresho ld
        652           if  (total >=  minimumTh reshold) {
        653                ExcelGen eratorThre ad exGenTh read = new  ExcelGene ratorThrea d("exGenTh read");
        654                exGenThr ead.setFil terMap(fil terMap);
        655                exGenThr ead.setRep ortMap(inb oundDocume ntMap);
        656  
        657                // Set n ames for E xcel gener ator threa d
        658                exGenThr ead.setTit le(REPORT_ TITLE);
        659  
        660                exGenThr ead.setExc elExporter (this.getE xcelExport er());
        661                exGenThr ead.setAda pterAuditM anager(ada pterAuditM anager);
        662                exGenThr ead.setRep ortHelper( getReportH elper());
        663                exGenThr ead.setFac ilityHelpe r(getFacil ityHelper( ));
        664                exGenThr ead.setUse rId(UserHe lper.getUs erName(req uest));
        665                exGenThr ead.setUse rDocumentD ao(getUser DocumentDA O());
        666  
        667                // Set s earch attr ibutes for  getting a udit resul ts
        668                exGenThr ead.setAtt ributes(ma pSessionAt tributes(r equest));
        669  
        670                exGenThr ead.run();
        671           }
        672           // Otherwise  generate a nd downloa d the expo rt directl y
        673           el se {
        674                // Creat e workbook
        675                List<Map <String, O bject>> re sults;
        676                InboundD ocumentRep ort.Search Package pa ckedResult s;
        677                packedRe sults = th is.getResu lts(reques t, true);
        678                results  = packedRe sults.getR esults();
        679  
        680                final Wo rkbook wb  = this.get ExcelExpor ter().expo rtToExcel( REPORT_TIT LE, REPORT _TITLE, in boundDocum entMap, re sults, fil terMap, nu ll);
        681  
        682                // Write  Excel wor kbook to S tream
        683                this.get ExcelExpor ter().writ eExcelToSt ream(REPOR T_TITLE.re place(" ",  "_"), wb,  response) ;
        684           }
        685       }
        686  
        687  
        688       privat e Map<Stri ng, Object > mapSessi onAttribut es(HttpSer vletReques t request)  {
        689           Ma p<String,  Object> at tributes =  new HashM ap<String,  Object>() ;
        690  
        691           at tributes.p ut("ssn",  request.ge tParameter ("ssn"));
        692           at tributes.p ut("lastNa me", reque st.getPara meter("las tName"));
        693           at tributes.p ut("firstN ame", requ est.getPar ameter("fi rstName")) ;
        694           at tributes.p ut("userId ", request .getParame ter("userI d"));
        695           at tributes.p ut("startD ate", Repo rtHelper.g etStartDat e(request. getParamet er("startD ate")));
        696           at tributes.p ut("endDat e", Report Helper.get EndDate(re quest.getP arameter(" endDate")) );
        697           at tributes.p ut("facili ty", reque st.getPara meter("fac ility"));
        698           at tributes.p ut("purpos eOfUse", r equest.get Parameter( "purposeOf Use"));
        699           at tributes.p ut("remote Organizati on", reque st.getPara meter("rem oteOrganiz ation"));
        700           at tributes.p ut("patien tTypes", I nteger.par seInt(requ est.getPar ameter("pa tientTypes ")));
        701           //  sort
        702           at tributes.p ut("sortVa lue", getS ortValue(r equest.get Parameter( "sortBy")) );
        703           at tributes.p ut("sortDi rection",  request.ge tParameter ("sortOrde r"));
        704  
        705           //  Set Actio n Types
        706           fi nal Action ValuesType  actionsTy pe = new A ctionValue sType();
        707           ac tionsType. getValue() .add(Actio nType.RETR IEVE_DOCUM ENT_OUT);
        708           at tributes.p ut("action sType", ac tionsType) ;
        709  
        710           re turn attri butes;
        711       }
        712  
        713         publ ic void ex portToCsv( final Http ServletReq uest reque st,
        714           fi nal HttpSe rvletRespo nse respon se) throws  ServletEx ception, I OException  {
        715  
        716  
        717           Ma p<String,  String> cs vReportMap  = new Lin kedHashMap <String, S tring>();
        718           cs vReportMap .put("SSN" , "ssn");
        719           cs vReportMap .put("Pati ent Last N ame", "las tName");
        720           cs vReportMap .put("Pati ent First  Name", "fi rstName");
        721           cs vReportMap .put("Date  Received  (CT)", "au ditTimeFor matted");
        722           cs vReportMap .put("Docu ment Title ", "docume ntTitle");
        723           cs vReportMap .put("Pati ent Prefer red Facili ty", "pati entFacilit yName");
        724           cs vReportMap .put("Pati ent Prefer red Facili ty Station  ID", "pat ientFacili tyNumber") ;
        725           cs vReportMap .put("eHea lth Exchan ge Organiz ation", "r emoteOrgan izationNam e");
        726           cs vReportMap .put("OID" , "remoteF acilityOid ");
        727           cs vReportMap .put("User  ID", "use rId");
        728           cs vReportMap .put("User  Facility  Code", "us erFacility Code");
        729           cs vReportMap .put("User  Facility" , "userFac ilityName" );
        730           cs vReportMap .put("User  Name", "u serName");
        731           cs vReportMap .put("Purp ose of Use ", "purpos eForUse");
        732           cs vReportMap .put("User  Role", "r oleName");
        733  
        734           in t minimumT hreshold =  Integer.p arseInt((S tring) thi s.getServl etContext( ).getAttri bute("sche duledExpor tMin"));
        735           in t total =  Integer.pa rseInt(req uest.getPa rameter("t otalRows") );
        736  
        737           // Start a sc heduled ex port with  its own th read if gr eater than  the minim um thresho ld
        738           if  (total >=  minimumTh reshold) {
        739                ExcelGen eratorThre ad csvGenT hread = ne w ExcelGen eratorThre ad("csvGen Thread");
        740                csvGenTh read.setDo cumentType ("csv");
        741                csvGenTh read.setRe portMap(cs vReportMap );
        742  
        743                csvGenTh read.setTi tle(REPORT _TITLE);
        744                csvGenTh read.setUs erId(UserH elper.getU serName(re quest));
        745                csvGenTh read.setAd apterAudit Manager(ad apterAudit Manager);
        746                csvGenTh read.setRe portHelper (getReport Helper());
        747                csvGenTh read.setFa cilityHelp er(getFaci lityHelper ());
        748                csvGenTh read.setUs erDocument Dao(getUse rDocumentD AO());
        749                csvGenTh read.setCs vExport(ne w CsvExpor ter());
        750  
        751                // Set s earch attr ibutes for  getting a udit resul ts
        752                csvGenTh read.setAt tributes(m apSessionA ttributes( request));
        753  
        754                csvGenTh read.start ();
        755           }
        756           // Otherwise  generate a nd downloa d the expo rt directl y
        757           el se{
        758                List<Map <String, O bject>> re sults;
        759                SearchPa ckage pack edResults;
        760  
        761                packedRe sults = th is.getResu lts(reques t, true);
        762                results  = packedRe sults.getR esults();
        763  
        764                CsvExpor ter csvExp orter = ne w CsvExpor ter();
        765                csvExpor ter.export ToCSV(resp onse, REPO RT_TITLE.r eplace(" " , "_"), re sults, (Li nkedHashMa p<String,  String>) c svReportMa p);
        766           }
        767       }
        768  
        769       privat e Facility DAO getFac ilityDAO()  {
        770           re turn this. getBean("F acilityDAO ", Facilit yDAO.class );
        771       }
        772  
        773  
        774       privat e UserDocu mentDAO ge tUserDocum entDAO() {
        775           re turn this. getBean("U serDocumen tDAO", Use rDocumentD AO.class);
        776       }
        777  
        778           /* *
        779            *  Get the e xcel expor ter class  from Sprin g.
        780            *
        781            *  @return t he excel e xporter ob ject
        782            * /
        783           pu blic Excel Exporter g etExcelExp orter() {
        784                    fina l ExcelExp orter exce lExporter  = this.get Bean("exce lExporter" ,
        785                                      ExcelExp orter.clas s);
        786                    retu rn excelEx porter;
        787           }
        788  
        789       /**
        790        * Org anizationa l class to  pack para meters nea tly togeth er
        791        */
        792       privat e class Se archPackag e{
        793           Li st<Map<Str ing,Object >> results ;
        794           St ring inbou ndIcn;
        795           Lo ng totalCo unt;
        796  
        797           pu blic Searc hPackage(L ist<Map<St ring, Obje ct>> resul ts, String  inboundIc n) {
        798                this.res ults = res ults;
        799                this.inb oundIcn =  inboundIcn ;
        800           }
        801  
        802           pu blic List< Map<String , Object>>  getResult s() {
        803                return r esults;
        804           }
        805  
        806           pu blic void  setResults (List<Map< String, Ob ject>> res ults) {
        807                this.res ults = res ults;
        808           }
        809  
        810           pu blic Strin g getInbou ndIcn() {
        811                return i nboundIcn;
        812           }
        813  
        814           pu blic void  setInbound Icn(String  inboundIc n) {
        815                this.inb oundIcn =  inboundIcn ;
        816           }
        817  
        818           pu blic Long  getTotalCo unt() {
        819                return t otalCount;
        820           }
        821  
        822           pu blic void  setTotalCo unt(Long t otalCount)  {
        823                this.tot alCount =  totalCount ;
        824           }
        825       }
        826  
        827   }