34. EPMO Open Source Coordination Office Redaction File Detail Report

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

34.1 Files compared

# Location File Last Modified
1 JLV_2.6.zip\JLV_2.6\JLV_2.6\Joint Legacy Viewer\jMeadows\src\main\java\gov\va\med\jmeadows\dataservicehandler MVIServiceHandler.java Thu Aug 31 12:13:08 2017 UTC
2 JLV_2.6.zip\JLV_2.6\JLV_2.6\Joint Legacy Viewer\jMeadows\src\main\java\gov\va\med\jmeadows\dataservicehandler MVIServiceHandler.java Thu Aug 31 13:29:00 2017 UTC

34.2 Comparison summary

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

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

34.4 Active regular expressions

No regular expressions were active.

34.5 Comparison detail

  1   /*
  2    * Janus 4 .0 (c)
  3    * Copyrig ht (c) 201 3 Hawaii R esource Gr oup LLC. A ll Rights  Reserved.
  4    * Develop ed for the  Pacific T elehealth  & Technolo gy Hui and  the Pacif ic Joint I nformation  Technolog y Center
  5    * Contrib utors:
  6    *      Ho norable Se nator Dani el K. Inou ye
  7    *      VA  Pacific I slands Hea lth Care S ystem
  8    *      Tr ipler Army  Medical C enter
  9    */
  10  
  11   package go v.va.med.j meadows.da taserviceh andler;
  12  
  13   import gov .va.med.jm eadows.com mon.JMeado wsExceptio n;
  14   import gov .va.med.jm eadows.dao .beans.*;
  15   import gov .va.med.jm eadows.dao .hdd.VLERS iteCache;
  16   import gov .va.med.jm eadows.dao .patient.A uditDao;
  17   import gov .va.med.jm eadows.sit e.Sites;
  18   import gov .va.med.mv i.*;
  19   import gov .va.med.mv i.ObjectFa ctory;
  20   import gov .va.med.vd s.webservi ce.*;
  21  
  22   import jav a.io.Seria lizable;
  23   import jav a.io.Strin gWriter;
  24   import jav a.math.Big Integer;
  25   import jav a.text.Sim pleDateFor mat;
  26   import jav a.util.Arr ayList;
  27   import jav a.util.Dat e;
  28   import jav a.util.Has hSet;
  29   import jav a.util.Ite rator;
  30   import jav a.util.Lis t;
  31   import jav a.util.Loc ale;
  32   import jav a.util.Map ;
  33   import jav a.util.Set ;
  34   import jav a.util.Str ingTokeniz er;
  35  
  36   import jav ax.xml.bin d.JAXBCont ext;
  37   import jav ax.xml.bin d.JAXBElem ent;
  38   import jav ax.xml.bin d.JAXBExce ption;
  39   import jav ax.xml.bin d.Marshall er;
  40   import jav ax.xml.nam espace.QNa me;
  41   import jav ax.xml.ws. BindingPro vider;
  42   import jav ax.xml.ws. WebService Exception;
  43   import jav ax.xml.ws. handler.Ha ndler;
  44  
  45   import gov .va.med.vh ahon.commo n.Utils;
  46   import org .apache.co mmons.coll ections4.C ollectionU tils;
  47   import org .apache.co mmons.lang 3.StringUt ils;
  48   import org .slf4j.Log ger;
  49   import org .slf4j.Log gerFactory ;
  50   import org .w3c.dom.E lement;
  51   import org .w3c.dom.N ode;
  52  
  53   public cla ss MVIServ iceHandler  extends D ataService Handler {
  54       privat e static f inal Logge r LOGGER =  LoggerFac tory.getLo gger(MVISe rviceHandl er.class);
  55       privat e static f inal Strin g OID_EDIP I = "2.16. 840.1.1138 83.3.42.10 001.100001 .12";
  56  
  57       privat e static i nt lastGoo dURLindex  = 0;
  58       privat e VAIdM mv iService;
  59       privat e JAXBCont ext jaxbCo ntext = nu ll;
  60  
  61       protec ted static  final Sit es SITES =  Sites.get Instance() ;
  62  
  63       public  MVIServic eHandler(S tring url)  {
  64           su per();
  65  
  66           se rviceURL =  url;
  67           se rviceName  = "MVI_Ser vice";
  68             serviceNam espace = " http://web service.mv iws. URL         ";
  69           qS erviceName  = new QNa me(service Namespace,  serviceNa me);
  70  
  71           mv iService =  new VAIdM ();
  72       }
  73  
  74       privat e VAIdMPor t getMVIPo rt() {
  75           VA IdMPort po rt = mviSe rvice.getV AIdMPort() ;
  76  
  77           //  serviceUR L can be a  set of UR Ls to try  like: URL; URL;URL
  78           St ring curre ntURL = se rviceURL;
  79           if  (serviceU RL != null  && servic eURL.index Of(';') >  -1) {
  80                String[]  urls = se rviceURL.s plit(";");
  81                if (last GoodURLind ex < urls. length) {
  82                    curr entURL = u rls[lastGo odURLindex ];
  83                } else {
  84                    curr entURL = u rls[0];
  85                    last GoodURLind ex = 0;
  86                }
  87           }
  88           Bi ndingProvi der prov =  (BindingP rovider) p ort;
  89           pr ov.getRequ estContext ().put(Bin dingProvid er.ENDPOIN T_ADDRESS_ PROPERTY,  currentURL );
  90           pr ov.getRequ estContext ().put("co m.sun.xml. internal.w s.connect. timeout",  serviceCon nectionTim eoutMS);
  91           pr ov.getRequ estContext ().put("co m.sun.xml. internal.w s.request. timeout",  serviceReq uestTimeou tMS);
  92           pr ov.getRequ estContext ().put("co m.sun.xml. ws.connect .timeout",  serviceCo nnectionTi meoutMS);
  93           pr ov.getRequ estContext ().put("co m.sun.xml. ws.request .timeout",  serviceRe questTimeo utMS);
  94  
  95           //  SOAP mess age loggin g - Enable  to show l ogging in  output win dow
  96           if  ("test".e qualsIgnor eCase(APP_ CONFIG.get AppEnviron ment()) ||  "developm ent".equal sIgnoreCas e(APP_CONF IG.getAppE nvironment ())) {
  97                prov.get Binding(). getHandler Chain().ad d(new SOAP LoggingHan dler());
  98                List<Han dler> hand lerList =  prov.getBi nding().ge tHandlerCh ain();
  99                handlerL ist.add(ne w SOAPLogg ingHandler ());
  100                prov.get Binding(). setHandler Chain(hand lerList);
  101           }
  102  
  103           re turn port;
  104       }
  105  
  106       public  ResponseP atientSele ct getPati entIds(JMe adowsQuery  queryBean , Map<Stri ng, Site>  siteMap) t hrows JMea dowsExcept ion {
  107           St ring error Message =  "";
  108           bo olean done  = false;
  109  
  110           Re sponsePati entSelect  responsePa tientSelec t = new Re sponsePati entSelect( );
  111           Li st<Externa lID> exter nalIDs = n ew ArrayLi st<Externa lID>();
  112  
  113           if  (jaxbCont ext == nul l) {
  114                try {
  115                    jaxb Context =  JAXBContex t.newInsta nce(PRPAIN 201309UV02 .class);
  116                } catch  (JAXBExcep tion e) {
  117                    jaxb Context =  null;
  118                    incL astGoodURL index();
  119  
  120                    erro rMessage =  "VA Patie nt Identit y Service  is unavail able. VA d ata may no t display. ";
  121  
  122                    resp onsePatien tSelect.se tSuccess(f alse);
  123                    resp onsePatien tSelect.se tErrorMsg( errorMessa ge);
  124  
  125                    logA ndAuditExc eption(e,  errorMessa ge, queryB ean, false );
  126  
  127                    done  = true;
  128                }
  129           }
  130           if  (!done) {
  131                try {
  132                    // G enerate PR PAIN201309 UV02 reque st message
  133                    PRPA IN201309UV 02 request  = generat eRequest(q ueryBean);
  134  
  135                    PRPA IN201310UV 02 respons e = getMVI Port().prp aIN201309U V02(reques t);
  136  
  137                    // P arse respo nse into p atient IDs  map
  138                    List <String> p atientIds  = parseRes ponseToPat ientIds(re sponse);
  139  
  140                    Pati ent patien t = new Pa tient();
  141  
  142                    Iter ator<Strin g> iterato r = patien tIds.itera tor();
  143                    whil e (iterato r.hasNext( )) {
  144                         // Corresp onding IDs  format: I D^TYPE^SOU RCE^ISSUER ^STATUS
  145                         StringToke nizer toke nizer = ne w StringTo kenizer(it erator.nex t(), "^");
  146                         if (tokeni zer.countT okens() ==  5) // Acc ording to  format, th ere should  only be 5  tokens
  147                         {
  148                             String  id = toke nizer.next Token();
  149                             String  type = to kenizer.ne xtToken();
  150                             String  source =  tokenizer. nextToken( );
  151                             String  issuer =  tokenizer. nextToken( );
  152                             String  status =  tokenizer. nextToken( );
  153  
  154                             // Mak es sure ea ch relevan t token is  not null  or blank a nd status  is "A" for  active
  155                             if (St ringUtils. isNotBlank (id) && St ringUtils. isNotBlank (type)
  156                                      && Strin gUtils.isN otBlank(so urce) && S tringUtils .isNotBlan k(issuer)
  157                                      && Strin gUtils.isN otBlank(st atus)) {
  158                                 if  ("NI".equ alsIgnoreC ase(type))  {
  159                                      // Natio nal patien t identifi er
  160                                      if ("200 DOD".equal sIgnoreCas e(source)  && "USDOD" .equalsIgn oreCase(is suer) && " A".equalsI gnoreCase( status)) {
  161                                          // D oD EDIPI
  162                                          if ( "EDIPI".eq ualsIgnore Case(query Bean.getSt atus())) {
  163                                               id = query Bean.getIt emId();
  164                                          }
  165                                          pati ent.setEDI PI(id);
  166                                      } else i f ("200M". equalsIgno reCase(sou rce) && "U SVHA".equa lsIgnoreCa se(issuer)  && "P".eq ualsIgnore Case(statu s)) {
  167                                          // V A ICN
  168                                          pati ent.setICN (id);
  169                                      } else {
  170                                          exte rnalIDs.ad d(new Exte rnalID(id,  type, sou rce, issue r));
  171                                      }
  172                                 }  else if (" PI".equals IgnoreCase (type)) {
  173                                      // Local  facility  patient id entifier
  174                                      if ("USV HA".equals IgnoreCase (issuer) & & "A".equa lsIgnoreCa se(status) ) {
  175                                          // V A DFN (IEN )
  176                                          if ( siteMap !=  null) {
  177                                               Site site  = siteMap. get(source );
  178                                               if (site = = null) {
  179                                                   LOGGER .debug("Si te with si te code "  + source +  " not fou nd in site s map");
  180                                               } else {
  181                                                   patien t.getVista Sites().ad d(site);
  182  
  183                                                   // Add  patient's  VA IEN an d correspo nding site  code to k ey-value p air list
  184                                                   KeyVal uePair kvp  = new Key ValuePair( );
  185                                                   kvp.se tKey(sourc e);
  186                                                   kvp.se tValue(id) ;
  187                                                   patien t.getPatie ntIens().a dd(kvp);
  188                                               }
  189                                          }
  190                                      } else {
  191                                          exte rnalIDs.ad d(new Exte rnalID(id,  type, sou rce, issue r));
  192                                      }
  193                                 }
  194                             }
  195                         } else {
  196                             LOGGER .debug("In valid corr esponding  ID string  format");
  197                         }
  198                    }
  199  
  200                    // V A user res trict flag  is set. C heck to se e if VA us er is sele cting a Do D-only pat ient
  201                    if ( "TRUE".equ alsIgnoreC ase(APP_CO NFIG.getVa UserRestri ct())
  202                             && APP _CONFIG.ge tAgencyVA( ).equalsIg noreCase(q ueryBean.g etUser().g etHostSite ().getAgen cy()) && p atient.get ICN() == n ull
  203                             && pat ient.getPa tientIens( ).isEmpty( )) {
  204                         responsePa tientSelec t.setVARes tricted(tr ue);
  205  
  206                         if ("TRUE" .equalsIgn oreCase(AP P_CONFIG.g etVaUserAl lowRestric tAccess()) ) {
  207                             respon sePatientS elect.setA llowVAAcce ss(true);
  208                         }
  209                    }
  210  
  211                    exte rnalIDs =  getVLERSit eNames(ext ernalIDs);
  212  
  213                    resp onsePatien tSelect.se tSuccess(t rue);
  214                    resp onsePatien tSelect.se tPatient(p atient);
  215                    resp onsePatien tSelect.se tExternalI Ds(externa lIDs);
  216   //             } catc h (JAXBExc eption e)  {
  217   //                 in cLastGoodU RLindex();
  218   //                 er rorMessage  = "VA Pat ient Ident ity Servic e is unava ilable. VA  data may  not displa y.";
  219   //
  220   //                 re sponsePati entSelect. setSuccess (false);
  221   //                 re sponsePati entSelect. setErrorMs g(errorMes sage);
  222   //
  223   //                 lo gAndAuditE xception(e , errorMes sage, quer yBean, fal se);
  224                } catch  (JMeadowsE xception e ) {
  225                    // I f VA user,  they do n ot need to  see the e rror messa ge. GUI ch ecks for e mpty strin g and skip s message.
  226                    if ( APP_CONFIG .getAgency VA().equal sIgnoreCas e(queryBea n.getUser( ).getAgenc y())) {
  227                         errorMessa ge = "";
  228                    } el se {
  229                         errorMessa ge = "This  patient i s currentl y not know n to the V A Master V eterans In dex, and t herefore n o VA"
  230                                 +  " data wil l be displ ayed.<br/> <br/>If th is patient  is a vete ran, pleas e notify t he help de sk of"
  231                                 +  " this iss ue.";
  232                    }
  233  
  234                    resp onsePatien tSelect.se tSuccess(f alse);
  235                    resp onsePatien tSelect.se tErrorMsg( errorMessa ge);
  236  
  237                    logA ndAuditExc eption(e,  errorMessa ge, queryB ean, false );
  238                } catch  (Exception  e) {
  239                    incL astGoodURL index();
  240                    erro rMessage =  "VA Patie nt Identit y Service  is unavail able. VA d ata may no t display. ";
  241  
  242                    resp onsePatien tSelect.se tSuccess(f alse);
  243                    resp onsePatien tSelect.se tErrorMsg( errorMessa ge);
  244  
  245                    logA ndAuditExc eption(e,  errorMessa ge, queryB ean, true) ;
  246                    // C ommenting  out below  line will  not pass f ortify(?)  scan, but  leaving it  in breaks  functiona lity
  247                    // t o continue  showing D oD patient  data when  there is  an issue w ith the MV I service.  Revisit.  -Jimi
  248                    //              throw new  JMeadowsEx ception("M VI Applica tion Error : " + erro rMessage);
  249                }
  250  
  251                // MVI w as unsucce ssful, at  least keep  original  identifier
  252                if (!res ponsePatie ntSelect.i sSuccess() ) {
  253  
  254                    Pati ent patien t = new Pa tient();
  255  
  256                    Stri ng type =  queryBean. getStatus( );
  257                    Stri ng id = qu eryBean.ge tItemId();
  258                    Stri ng source  = queryBea n.getRecor dSiteCode( );
  259  
  260                    if ( "EDIPI".eq ualsIgnore Case(type) ) {
  261                         patient.se tEDIPI(id) ;
  262                    } el se if ("IC N".equalsI gnoreCase( type)) {
  263                         patient.se tICN(id);
  264                    } el se if ("VA IEN".equal sIgnoreCas e(type) &&  siteMap ! = null) {
  265                         Site site  = siteMap. get(source );
  266                         if (site ! = null) {
  267                             patien t.getVista Sites().ad d(site);
  268  
  269                             // Add  patient's  VA IEN an d correspo nding site  code to k ey-value p air list
  270                             KeyVal uePair kvp  = new Key ValuePair( );
  271                             kvp.se tKey(sourc e);
  272                             kvp.se tValue(id) ;
  273                             patien t.getPatie ntIens().a dd(kvp);
  274                         }
  275                    }
  276  
  277                    // V A user res trict flag  is set. C heck to se e if VA us er is sele cting DoD- only patie nt
  278                    if ( "TRUE".equ alsIgnoreC ase(APP_CO NFIG.getVa UserRestri ct())
  279                             && APP _CONFIG.ge tAgencyVA( ).equalsIg noreCase(q ueryBean.g etUser().g etHostSite ().getAgen cy())
  280                             && pat ient.getIC N() == nul l && patie nt.getPati entIens(). isEmpty())  {
  281                         responsePa tientSelec t.setVARes tricted(tr ue);
  282                         responsePa tientSelec t.setAllow VAAccess(t rue);
  283                    }
  284  
  285                    resp onsePatien tSelect.se tErrorMsg( errorMessa ge);
  286                    resp onsePatien tSelect.se tPatient(p atient);
  287                }
  288           }
  289           re turn respo nsePatient Select;
  290       }
  291  
  292       public  ResponseP atientQuer y lookupPa tient(PDWS QueryBean  queryBean,  Map<Strin g, Site> s iteMap) {
  293           Re sponsePati entQuery r pq = new R esponsePat ientQuery( );
  294  
  295           tr y {
  296                PRPAIN20 1305UV02 s earchReque st = gener ateSearchR equest(que ryBean);
  297  
  298                String a ppEnv = AP P_CONFIG.g etAppEnvir onment();
  299                //print  request xm l
  300                if ("tes t".equalsI gnoreCase( appEnv) ||  "developm ent".equal sIgnoreCas e(appEnv))  {
  301                    jaxb Context =  JAXBContex t.newInsta nce(PRPAIN 201305UV02 .class.get Package(). getName()) ;
  302                    Mars haller jax bMarshalle r = jaxbCo ntext.crea teMarshall er();
  303                    jaxb Marshaller .setProper ty(Marshal ler.JAXB_F ORMATTED_O UTPUT, Boo lean.TRUE) ;
  304                    Stri ngWriter s tringWrite r = new St ringWriter ();
  305                    jaxb Marshaller .marshal(n ew JAXBEle ment<PRPAI N201305UV0 2>(new QNa me("uri",  "PRPAIN201 305UV02"),  PRPAIN201 305UV02.cl ass, searc hRequest),  stringWri ter);
  306                    LOGG ER.debug(s tringWrite r.toString ());
  307                }
  308                //end pr intout;
  309  
  310                PRPAIN20 1306UV02 r esponse =  getMVIPort ().prpaIN2 01305UV02( searchRequ est);
  311  
  312                //print  response x ml
  313                if ("tes t".equalsI gnoreCase( appEnv) ||  "developm ent".equal sIgnoreCas e(appEnv))  {
  314                    jaxb Context =  JAXBContex t.newInsta nce(PRPAIN 201306UV02 .class.get Package(). getName()) ;
  315                    Mars haller jax bMarshalle r2 = jaxbC ontext.cre ateMarshal ler();
  316                    jaxb Marshaller 2 = jaxbCo ntext.crea teMarshall er();
  317                    jaxb Marshaller 2.setPrope rty(Marsha ller.JAXB_ FORMATTED_ OUTPUT, Bo olean.TRUE );
  318                    jaxb Marshaller 2.marshal( new JAXBEl ement<PRPA IN201306UV 02>(new QN ame("uri",  "PRPAIN20 1306UV02") , PRPAIN20 1306UV02.c lass, resp onse), Sys tem.out);
  319                }
  320                //end pr intout;
  321  
  322  
  323                List<Pat ient> pati ents = par seResponse ToPatientL ookup(resp onse, site Map, query Bean.getUs er().getRe strictedSi teCodesLis t());
  324                if (pati ents.size( ) > 0) {
  325                    Stri ng msg = p atients.ge t(0).getNa me();
  326                    if ( msg.contai ns("MVI Er ror:") ||  msg.contai ns("MVI Me ssage:"))  {
  327                         //remove p refix for  dialog req uested in  JLV-69
  328                         if (msg.st artsWith(" MVI Messag e: Patient  not found  with sear ch element s entered" ))
  329                             msg =  msg.substr ing("MVI M essage: ". length());
  330                         rpq.setErr orMsg(msg) ;
  331                         rpq.setSuc cess(false );
  332                         return rpq ;
  333                    }
  334                }
  335                rpq.setP atients(pa tients);
  336                rpq.setS uccess(tru e);
  337  
  338           }  catch (Web ServiceExc eption e){
  339                LOGGER.e rror("Erro r with MVI  Lookup: "  + e.getMe ssage());
  340                rpq.setE rrorMsg("E rror with  MVI Lookup :  The MVI  Search ca pability a ppears to  be down at  this time .");
  341           }  catch (Exc eption e)  {
  342                LOGGER.e rror("Erro r with MVI  Lookup: "  + e.getMe ssage());
  343                rpq.setE rrorMsg("T here was a n error wi th the MVI  patient l ookup quer y.");
  344           }
  345           re turn rpq;
  346       }
  347  
  348       privat e static v oid incLas tGoodURLin dex() {
  349           ++ lastGoodUR Lindex;
  350       }
  351  
  352  
  353       privat e PRPAIN20 1309UV02 g enerateReq uest(JMead owsQuery q ueryBean)  {
  354           Ob jectFactor y factory;
  355           PR PAIN201309 UV02 reque st;
  356           MC CIMT000100 UV01Receiv er receive r;
  357           MC CIMT000100 UV01Device  device;
  358           MC CIMT000100 UV01Sender  sender;
  359           PR PAIN201309 UV02QUQIMT 021001UV01 ControlAct Process co ntrolActPr ocess;
  360           PR PAMT201307 UV02QueryB yParameter  queryByPa rameter;
  361           PR PAMT201307 UV02Parame terList pa rameterLis t;
  362           PR PAMT201307 UV02Patien tIdentifie r patientI dentifier;
  363           Si mpleDateFo rmat simpl eDateForma t;
  364           II  ii;
  365           TS  ts;
  366           CS  cs;
  367           CD  cd;
  368           Da te date;
  369           St ring statu s;
  370           St ring oid;
  371           St ring id;
  372           St ring type;
  373           St ring sourc e;
  374           St ring issue r;
  375  
  376           fa ctory = ne w ObjectFa ctory();
  377           re quest = fa ctory.crea tePRPAIN20 1309UV02() ;
  378           da te = new D ate();
  379  
  380           // id
  381           si mpleDateFo rmat = new  SimpleDat eFormat("y yyyMMdd",  Locale.get Default()) ;
  382           ii  = factory .createII( );
  383           ii .setRoot(" 2.16.840.1 .113883.3. 933");
  384           ii .setExtens ion("MCID_ JANUS_DEV_ T1_" + sim pleDateFor mat.format (date));
  385           re quest.setI d(ii);
  386  
  387           // creationTi me
  388           ts  = factory .createTS( );
  389           si mpleDateFo rmat = new  SimpleDat eFormat("y yyyMMddhhm mss", Loca le.getDefa ult());
  390           ts .setValue( simpleDate Format.for mat(date)) ;
  391           re quest.setC reationTim e(ts);
  392  
  393           // interactio nId
  394           ii  = factory .createII( );
  395           ii .setRoot(" 2.16.840.1 .113883.1. 6");
  396           ii .setExtens ion("PRPA_ IN201309UV 02");
  397           re quest.setI nteraction Id(ii);
  398  
  399           // processing Code
  400           cs  = factory .createCS( );
  401           if  ("product ion".equal sIgnoreCas e(APP_CONF IG.getAppE nvironment ())) {
  402                cs.setCo de("P");
  403           }  else {
  404                cs.setCo de("T");
  405           }
  406           re quest.setP rocessingC ode(cs);
  407  
  408           // processing ModeCode
  409           cs  = factory .createCS( );
  410           cs .setCode(" T");
  411           re quest.setP rocessingM odeCode(cs );
  412  
  413           // acceptAckC ode
  414           cs  = factory .createCS( );
  415           cs .setCode(" AL");
  416           re quest.setA cceptAckCo de(cs);
  417  
  418           // receiver
  419           re ceiver = f actory.cre ateMCCIMT0 00100UV01R eceiver();
  420           re quest.getR eceiver(). add(receiv er);
  421  
  422           // receiver/t ypeCode
  423           re ceiver.set TypeCode(C ommunicati onFunction Type.RCV);
  424  
  425           // receiver/d evice
  426           de vice = fac tory.creat eMCCIMT000 100UV01Dev ice();
  427           re ceiver.set Device(dev ice);
  428  
  429           // receiver/d evice/clas sCode
  430           de vice.setCl assCode(En tityClassD evice.DEV) ;
  431  
  432           // receiver/d evice/dete rminerCode
  433           de vice.setDe terminerCo de("INSTAN CE");
  434  
  435           // receiver/d evice/id
  436           ii  = factory .createII( );
  437           ii .setRoot(" 2.16.840.1 .113883.4. 349");
  438           ii .setExtens ion("200M" );
  439           de vice.getId ().add(ii) ;
  440  
  441           // sender
  442           se nder = fac tory.creat eMCCIMT000 100UV01Sen der();
  443           re quest.setS ender(send er);
  444  
  445           // sender/typ eCode
  446           se nder.setTy peCode(Com munication FunctionTy pe.SND);
  447  
  448           // sender/dev ice
  449           de vice = fac tory.creat eMCCIMT000 100UV01Dev ice();
  450           se nder.setDe vice(devic e);
  451  
  452           // sender/dev ice/classC ode
  453           de vice.setCl assCode(En tityClassD evice.DEV) ;
  454  
  455           // sender/dev ice/determ inerCode
  456           de vice.setDe terminerCo de("INSTAN CE");
  457  
  458           // sender/dev ice/id
  459           ii  = factory .createII( );
  460           ii .setRoot(" 2.16.840.1 .113883.4. 349");
  461           ii .setExtens ion(APP_CO NFIG.getMV ISndDevId( ));
  462           de vice.getId ().add(ii) ;
  463  
  464           // controlAct Process
  465           co ntrolActPr ocess = fa ctory.crea tePRPAIN20 1309UV02QU QIMT021001 UV01Contro lActProces s();
  466           re quest.setC ontrolActP rocess(con trolActPro cess);
  467  
  468           // controlAct Process/cl assCode
  469           co ntrolActPr ocess.setC lassCode(A ctClassCon trolAct.CA CT);
  470  
  471           // controlAct Process/mo odCode
  472           co ntrolActPr ocess.setM oodCode(XA ctMoodInte ntEvent.EV N);
  473  
  474           // controlAct Process/co de
  475           cd  = factory .createCD( );
  476           cd .setCode(" PRPA_TE201 309UV02");
  477           co ntrolActPr ocess.setC ode(cd);
  478  
  479           // controlAct Process/co deSystem
  480           cd .setCodeSy stem("2.16 .840.1.113 883.1.6");
  481  
  482           // controlAct Process/qu eryByParam eter
  483           qu eryByParam eter = fac tory.creat ePRPAMT201 307UV02Que ryByParame ter();
  484           co ntrolActPr ocess.setQ ueryByPara meter(fact ory.create PRPAIN2013 09UV02QUQI MT021001UV 01ControlA ctProcessQ ueryByPara meter(quer yByParamet er));
  485  
  486           // controlAct Process/qu eryByParam eter/query Id
  487           ii  = factory .createII( );
  488           ii .setRoot(" 2.16.840.1 .113883.3. 933");
  489           ii .setExtens ion("33452 ");
  490           qu eryByParam eter.setQu eryId(ii);
  491  
  492           // controlAct Process/qu eryByParam eter/statu sCode
  493           cs  = factory .createCS( );
  494           cs .setCode(" new");
  495           qu eryByParam eter.setSt atusCode(c s);
  496  
  497           // controlAct Process/qu eryByParam eter/respo nsePriorit yCode
  498           cs  = factory .createCS( );
  499           cs .setCode(" I");
  500           qu eryByParam eter.setRe sponsePrio rityCode(c s);
  501  
  502           // controlAct Process/qu eryByParam eter/param eterList
  503           pa rameterLis t = factor y.createPR PAMT201307 UV02Parame terList();
  504           qu eryByParam eter.setPa rameterLis t(paramete rList);
  505  
  506           // controlAct Process/qu eryByParam eter/param eterList/p atientIden tifier
  507           pa tientIdent ifier = fa ctory.crea tePRPAMT20 1307UV02Pa tientIdent ifier();
  508           pa rameterLis t.getPatie ntIdentifi er().add(p atientIden tifier);
  509  
  510           // controlAct Process/qu eryByParam eter/param eterList/p atientIden tifier/val ue
  511           ii  = factory .createII( );
  512           st atus = que ryBean.get Status();
  513           if  ("EDIPI". equalsIgno reCase(sta tus)) {
  514                // Get i dentifiers  by DoD ED IPI
  515                oid = "2 .16.840.1. 113883.3.3 64";
  516                id = que ryBean.get ItemId();
  517                type = " NI";
  518                source =  "200DOD";
  519                issuer =  "USDOD";
  520  
  521                ii.setRo ot(oid);
  522                ii.setEx tension(id  + "^" + t ype + "^"  + source +  "^" + iss uer);
  523  
  524                LOGGER.d ebug("Gett ing corres ponding pa tient iden tifiers vi a EDIPI");
  525           }  else if (" ICN".equal sIgnoreCas e(status))  {
  526                // Get i dentifiers  by VA ICN
  527                oid = "2 .16.840.1. 113883.4.3 49";
  528                id = que ryBean.get ItemId();
  529                type = " NI";
  530  
  531                ii.setRo ot(oid);
  532                ii.setEx tension(id  + "^" + t ype);
  533  
  534                LOGGER.d ebug("Gett ing corres ponding pa tient iden tifiers vi a ICN");
  535           }  else if (" VAIEN".equ alsIgnoreC ase(status )) {
  536                // Get i dentifiers  by VA IEN
  537                oid = "2 .16.840.1. 113883.4.3 49";
  538                id = que ryBean.get ItemId();
  539                type = " PI";
  540                source =  queryBean .getRecord SiteCode() ;
  541                issuer =  "USVHA";
  542  
  543                ii.setRo ot(oid);
  544                ii.setEx tension(id  + "^" + t ype + "^"  + source +  "^" + iss uer);
  545  
  546                LOGGER.d ebug("Gett ing corres ponding pa tient iden tifiers vi a VA IEN") ;
  547           }
  548   //         else
  549   //         {
  550   //             logger .error("Co uld not qu ery with i dentifier  number typ e: " + sta tus);
  551   //         }
  552           pa tientIdent ifier.getV alue().add (ii);
  553  
  554           // controlAct Process/qu eryByParam eter/param eterList/p atientIden tifier/sem anticsText
  555           pa tientIdent ifier.setS emanticsTe xt("Patien t.id");
  556  
  557           re turn reque st;
  558       }
  559  
  560       privat e PRPAIN20 1305UV02 g enerateSea rchRequest (PDWSQuery Bean query Bean) {
  561           Ob jectFactor y factory;
  562           PR PAIN201305 UV02 reque st;
  563           MC CIMT000100 UV01Receiv er receive r;
  564           MC CIMT000100 UV01Device  device;
  565           MC CIMT000100 UV01Sender  sender;
  566           PR PAIN201305 UV02QUQIMT 021001UV01 ControlAct Process co ntrolActPr ocess;
  567           PR PAMT201306 UV02QueryB yParameter  queryByPa rameter;
  568           PR PAMT201306 UV02Parame terList pa rameterLis t;
  569           // PRPAMT2013 0UV02Patie ntIdentifi er patient Identifier ;
  570           Si mpleDateFo rmat simpl eDateForma t;
  571           II  ii;
  572           TS  ts;
  573           CS  vc;
  574           TE L tel;
  575           CS  cs;
  576           CD  cd;
  577           Da te date;
  578           St ring query ID;
  579           St ring statu s;
  580           St ring oid;
  581           St ring id;
  582           St ring type;
  583           St ring sourc e;
  584           St ring issue r;
  585  
  586           fa ctory = ne w ObjectFa ctory();
  587           re quest = fa ctory.crea tePRPAIN20 1305UV02() ;
  588           da te = new D ate();
  589  
  590           tr y {
  591                //id
  592                simpleDa teFormat =  new Simpl eDateForma t("yyyyMMd dHHmmss",  Locale.get Default()) ;
  593                ii = fac tory.creat eII();
  594                ii.setRo ot("2.16.8 40.1.11388 3.3.933");
  595                queryID  = "MCID_JA NUS_DEV_T1 _" + simpl eDateForma t.format(d ate);
  596                ii.setEx tension(qu eryID);
  597                request. setId(ii);
  598  
  599                //creati onTime
  600                ts = fac tory.creat eTS();
  601                simpleDa teFormat =  new Simpl eDateForma t("yyyyMMd dhhmmss",  Locale.get Default()) ;
  602                ts.setVa lue(simple DateFormat .format(da te));
  603                request. setCreatio nTime(ts);
  604  
  605                //versio nCode
  606                vc = fac tory.creat eCS();
  607                vc.setCo de("3.0");
  608                request. setVersion Code(vc);
  609  
  610                //intera ctionId
  611                ii = fac tory.creat eII();
  612                ii.setRo ot("2.16.8 40.1.11388 3.1.6");
  613                ii.setEx tension("P RPA_IN2013 05UV02");
  614                request. setInterac tionId(ii) ;
  615  
  616                //proces singCode
  617                cs = fac tory.creat eCS();
  618                if ("pro duction".e qualsIgnor eCase(APP_ CONFIG.get AppEnviron ment())) {
  619                    cs.s etCode("P" );
  620                } else {
  621                    cs.s etCode("T" );
  622                }
  623                request. setProcess ingCode(cs );
  624  
  625                //proces singModeCo de
  626                cs = fac tory.creat eCS();
  627                cs.setCo de("T");
  628                request. setProcess ingModeCod e(cs);
  629  
  630                //accept AckCode
  631                cs = fac tory.creat eCS();
  632                cs.setCo de("AL");
  633                request. setAcceptA ckCode(cs) ;
  634  
  635                //receiv er
  636                receiver  = factory .createMCC IMT000100U V01Receive r();
  637                request. getReceive r().add(re ceiver);
  638  
  639                //receiv er/typeCod e
  640                receiver .setTypeCo de(Communi cationFunc tionType.R CV);
  641  
  642                //receiv er/device
  643                device =  factory.c reateMCCIM T000100UV0 1Device();
  644                receiver .setDevice (device);
  645  
  646                //receiv er/device/ classCode
  647                device.s etClassCod e(EntityCl assDevice. DEV);
  648  
  649                //receiv er/device/ determiner Code
  650                device.s etDetermin erCode("IN STANCE");
  651  
  652                //receiv er/device/ id
  653                ii = fac tory.creat eII();
  654                ii.setRo ot("1.2.84 0.114350.1 .13.999.23 4");
  655                device.g etId().add (ii);
  656  
  657                //receiv er/device/ telcom
  658                tel = fa ctory.crea teTEL();
  659                tel.setV alue("http ://service location/P DQuery");
  660                device.g etTelecom( ).add(tel) ;
  661  
  662                //sender
  663                sender =  factory.c reateMCCIM T000100UV0 1Sender();
  664                request. setSender( sender);
  665  
  666                //sender /typeCode
  667                sender.s etTypeCode (Communica tionFuncti onType.SND );
  668  
  669                //sender /device
  670                device =  factory.c reateMCCIM T000100UV0 1Device();
  671                sender.s etDevice(d evice);
  672  
  673                //sender /device/cl assCode
  674                device.s etClassCod e(EntityCl assDevice. DEV);
  675  
  676                //sender /device/de terminerCo de
  677                device.s etDetermin erCode("IN STANCE");
  678  
  679                //sender /device/id
  680                ii = fac tory.creat eII();
  681                ii.setRo ot("2.16.8 40.1.11388 3.4.349");
  682                ii.setEx tension(AP P_CONFIG.g etMVISndDe vId());
  683                device.g etId().add (ii);
  684  
  685                //contro lActProces s
  686                controlA ctProcess  = factory. createPRPA IN201305UV 02QUQIMT02 1001UV01Co ntrolActPr ocess();
  687                request. setControl ActProcess (controlAc tProcess);
  688  
  689                //contro lActProces s/classCod e
  690                controlA ctProcess. setClassCo de(ActClas sControlAc t.CACT);
  691  
  692                //contro lActProces s/moodCode
  693                controlA ctProcess. setMoodCod e(XActMood IntentEven t.EVN);
  694  
  695                //contro lActProces s/dataEnte rer
  696                QUQIMT02 1001UV01Da taEnterer  de = facto ry.createQ UQIMT02100 1UV01DataE nterer();
  697                controlA ctProcess. getDataEnt erer().add (de);
  698                de.setCo ntextContr olCode("AP ");
  699                de.getTy peCode().a dd("ENT");
  700  
  701                COCTMT09 0100UV01As signedPers on aPerson  = factory .createCOC TMT090100U V01Assigne dPerson();
  702                de.setAs signedPers on(aPerson );
  703  
  704                //contro lActProces s/dataEnte rer/assign edPerson
  705                aPerson. setClassCo de("ASSIGN ED");
  706  
  707  
  708                //contro lActProces s/dataEnte rer/assign edPerson/i d
  709                String p ersonID =  "";
  710                String u serNameLas t = "";
  711                String u serNameFir st = "";
  712                String i dRoot = "2 .16.840.1. 113883.4.3 49";
  713  
  714                if (quer yBean.getU ser() != n ull) {
  715                    User  user = qu eryBean.ge tUser();
  716                    if ( user.getCa rdId() !=  null && "D OD".equals IgnoreCase (user.getA gency()))  {
  717                         personID =  user.getC ardId() +  "^NI^200DO D^USDOD";
  718                         idRoot = " 2.16.840.1 .113883.3. 42.10001.1 00001.12";
  719                    } el se if("VA" .equalsIgn oreCase(us er.getAgen cy())){
  720                         personID =  user.getU serId() +  "^PN^" + u ser.getHos tSite().ge tSiteCode( ) + "^USVH A";
  721                    }
  722  
  723                    Stri ng userNam eFull = us er.getName ();
  724                    if ( !StringUti ls.isEmpty (userNameF ull)) {
  725                         userNameLa st = Utils .getFirstN ame(userNa meFull).to UpperCase( Locale.get Default()) ;
  726                         userNameFi rst = Util s.getLastN ame(userNa meFull).to UpperCase( Locale.get Default()) ;
  727                    }
  728                }
  729  
  730                II aPers onId = fac tory.creat eII();
  731                aPersonI d.setExten sion(perso nID);
  732                aPersonI d.setRoot( idRoot);
  733                aPerson. getId().ad d(aPersonI d);
  734  
  735                //contro lActProces s/dataEnte rer/assign edPerson/
  736                COCTMT09 0100UV01Pe rson aPers onPerson =  factory.c reateCOCTM T090100UV0 1Person();
  737                aPersonP erson.getC lassCode() .add("PSN" );
  738                aPersonP erson.setD eterminerC ode("INSTA NCE");
  739  
  740                //contro lActProces s/dataEnte rer/assign edPerson/n ame
  741                EN aPers onPersonNa me = facto ry.createE N();
  742                aPersonP ersonName. getContent ().add(fac tory.creat eENFamily( userNameLa st));
  743                aPersonP ersonName. getContent ().add(fac tory.creat eENGiven(u serNameFir st));
  744                aPersonP erson.getN ame().add( aPersonPer sonName);
  745                aPerson. setAssigne dPerson(fa ctory.crea teCOCTMT09 0100UV01As signedPers onAssigned Person(aPe rsonPerson ));
  746  
  747                //contro lActProces s/code
  748                cd = fac tory.creat eCD();
  749                cd.setCo de("PRPA_T E201305UV0 2");
  750                controlA ctProcess. setCode(cd );
  751  
  752                //contro lActProces s/codeSyst em
  753                cd.setCo deSystem(" 2.16.840.1 .113883.1. 6");
  754  
  755                //contro lActProces s/queryByP arameter
  756                queryByP arameter =  factory.c reatePRPAM T201306UV0 2QueryByPa rameter();
  757                controlA ctProcess. setQueryBy Parameter( factory.cr eatePRPAIN 201305UV02 QUQIMT0210 01UV01Cont rolActProc essQueryBy Parameter( queryByPar ameter));
  758  
  759                //contro lActProces s/queryByP arameter/q ueryId
  760                ii = fac tory.creat eII();
  761                ii.setRo ot("1.2.84 0.114350.1 .13.28.1.1 8.5.999");
  762                ii.setEx tension(qu eryID);
  763                queryByP arameter.s etQueryId( ii);
  764  
  765                //contro lActProces s/queryByP arameter/s tatusCode
  766                cs = fac tory.creat eCS();
  767                cs.setCo de("new");
  768                queryByP arameter.s etStatusCo de(cs);
  769  
  770                //contro lActProces s/queryByP arameter/m odifyCode
  771                CS csMod Code = fac tory.creat eCS();
  772                csModCod e.setCode( "MVI.COMP1 ");
  773                queryByP arameter.s etModifyCo de(csModCo de);
  774  
  775                //contro lActProces s/queryByP arameter/p arameterLi st
  776                paramete rList = fa ctory.crea tePRPAMT20 1306UV02Pa rameterLis t();
  777                queryByP arameter.s etParamete rList(para meterList) ;
  778  
  779                //the am ount of re sults to r eturn from  a search  query
  780                //contro lActProces s/queryByP arameter/i nitialQuan tity
  781                INT init Qty = fact ory.create INT();
  782                initQty. setValue(B igInteger. valueOf(AP P_CONFIG.g etMVISearc hQty()));
  783                queryByP arameter.s etInitialQ uantity(in itQty);
  784  
  785  
  786                //patien t
  787  
  788                //parame ter: livin gSubjectAd ministrati veGender    M/F
  789                //contro lActProces s/queryByP arameter/p arameterLi st/livingS ubjectAdmi nistrative Gender
  790                if (Stri ngUtils.is NotEmpty(q ueryBean.g etGender() )) {
  791                    PRPA MT201306UV 02LivingSu bjectAdmin istrativeG ender saGe nder = fac tory.creat ePRPAMT201 306UV02Liv ingSubject Administra tiveGender ();
  792                    CE g enderValue  = factory .createCE( );
  793                    gend erValue.se tCode(quer yBean.getG ender());
  794                    saGe nder.getVa lue().add( genderValu e);
  795                    saGe nder.setSe manticsTex t("Gender" );
  796                    para meterList. getLivingS ubjectAdmi nistrative Gender().a dd(saGende r);
  797                }
  798  
  799                //parame ter: livin gSubjectBi rthTime  Y YYYMMDD
  800                //contro lActProces s/queryByP arameter/p arameterLi st/livingS ubjectBirt hTime
  801                String d obStr = qu eryBean.ge tDob();
  802                if (Stri ngUtils.is NotEmpty(d obStr)) {
  803                    dobS tr = Utils .shortDate (Utils.get Cal(dobStr ));
  804                    PRPA MT201306UV 02LivingSu bjectBirth Time bt =  factory.cr eatePRPAMT 201306UV02 LivingSubj ectBirthTi me();
  805                    IVLT S dob = fa ctory.crea teIVLTS();
  806                    dob. setValue(d obStr);
  807                    bt.g etValue(). add(dob);
  808                    bt.s etSemantic sText("Dat e of Birth ");
  809                    para meterList. getLivingS ubjectBirt hTime().ad d(bt);
  810                }
  811  
  812                //parame ter: livin gSubjectId   (SSN)
  813                //contro lActProces s/queryByP arameter/p arameterLi st/livingS ubjectId
  814                if (Stri ngUtils.is NotEmpty(q ueryBean.g etPatientI d())) {
  815                    PRPA MT201306UV 02LivingSu bjectId ls Id = facto ry.createP RPAMT20130 6UV02Livin gSubjectId ();
  816                    II l sIdValue =  factory.c reateII();
  817                    lsId Value.setR oot("2.16. 840.1.1138 83.4.1");
  818                    lsId Value.setE xtension(q ueryBean.g etPatientI d());
  819                    lsId .getValue( ).add(lsId Value);
  820                    lsId .setSemant icsText("S SN");
  821                    para meterList. getLivingS ubjectId() .add(lsId) ;
  822                }
  823  
  824                //parame ter: livin gSubjectNa me
  825                //contro lActProces s/queryByP arameter/p arameterLi st/livingS ubjectName
  826                PRPAMT20 1306UV02Li vingSubjec tName lsNa me = facto ry.createP RPAMT20130 6UV02Livin gSubjectNa me();
  827                EN lsNam eEN = fact ory.create EN();
  828                lsNameEN .getUse(). add("L");
  829                lsNameEN .getConten t().add(fa ctory.crea teENFamily (queryBean .getLastNa me()));
  830                lsNameEN .getConten t().add(fa ctory.crea teENGiven( queryBean. getFirstNa me()));
  831                lsName.s etSemantic sText("Leg al Name");
  832                lsName.g etValue(). add(lsName EN);
  833                paramete rList.getL ivingSubje ctName().a dd(lsName) ;
  834  
  835                //parame ter: patie ntTelecom
  836                //contro lActProces s/queryByP arameter/p arameterLi st/patient Telecom
  837                if (Stri ngUtils.is NotEmpty(q ueryBean.g etTel()))  {
  838                    PRPA MT201306UV 02PatientT elecom tel ecom = fac tory.creat ePRPAMT201 306UV02Pat ientTeleco m();
  839                    TEL  pTel = fac tory.creat eTEL();
  840                    pTel .setValue( queryBean. getTel());
  841                    pTel .getUse(). add("HP");
  842                    tele com.getVal ue().add(p Tel);
  843                    para meterList. getPatient Telecom(). add(teleco m);
  844                }
  845  
  846                //parame ter: patie ntAddress
  847                //contro lActProces s/queryByP arameter/p arameterLi st/patient Address
  848                if (Stri ngUtils.is NotEmpty(q ueryBean.g etAddress( )) || Stri ngUtils.is NotEmpty(q ueryBean.g etCity())
  849                         || StringU tils.isNot Empty(quer yBean.getS tate()) ||  StringUti ls.isNotEm pty(queryB ean.getZip ())) {
  850                    PRPA MT201306UV 02PatientA ddress pat Address =  factory.cr eatePRPAMT 201306UV02 PatientAdd ress();
  851                    AD p atAd = fac tory.creat eAD();
  852                    patA d.getUse() .add("HP") ;
  853                    if ( !StringUti ls.isEmpty (queryBean .getAddres s()))
  854                         patAd.getC ontent().a dd(factory .createADS treetAddre ssLine(que ryBean.get Address()) );
  855                    if ( !StringUti ls.isEmpty (queryBean .getCity() ))
  856                         patAd.getC ontent().a dd(factory .createADC ity(queryB ean.getCit y()));
  857                    if ( !StringUti ls.isEmpty (queryBean .getState( )))
  858                         patAd.getC ontent().a dd(factory .createADS tate(query Bean.getSt ate()));
  859                    if ( !StringUti ls.isEmpty (queryBean .getZip()) )
  860                         patAd.getC ontent().a dd(factory .createADP ostalCode( queryBean. getZip())) ;
  861                    patA ddress.get Value().ad d(patAd);
  862                    para meterList. getPatient Address(). add(patAdd ress);
  863                }
  864  
  865                PRPAMT20 1306UV02Ot herIDsScop ingOrganiz ation othe rOrg = fac tory.creat ePRPAMT201 306UV02Oth erIDsScopi ngOrganiza tion();
  866                II other OrgValue =  factory.c reateII();
  867                otherOrg Value.setE xtension(" VA_DOD");
  868                otherOrg Value.setR oot("2.16. 840.1.1138 83.4.349") ;
  869                otherOrg .getValue( ).add(othe rOrgValue) ;
  870                otherOrg .setSemant icsText("M VI.REGISTR ATION");
  871                paramete rList.getO therIDsSco pingOrgani zation().a dd(otherOr g);
  872  
  873           }  catch (Exc eption e)  {
  874                e.printS tackTrace( System.out );
  875           }
  876  
  877           re turn reque st;
  878       }
  879  
  880       privat e List<Str ing> parse ResponseTo PatientIds (PRPAIN201 310UV02 re sponse) th rows JMead owsExcepti on {
  881           It erator<MCC IMT000300U V01Acknowl edgement>  acknowledg ementItera tor;
  882           MC CIMT000300 UV01Acknow ledgement  acknowledg ement;
  883           It erator<MCC IMT000300U V01Acknowl edgementDe tail> ackn owledgemen tDetailIte rator;
  884           MC CIMT000300 UV01Acknow ledgementD etail ackn owledgemen tDetail;
  885           It erator<PRP AIN201310U V02MFMIMT7 00711UV01S ubject1> s ubjectIter ator;
  886           PR PAIN201310 UV02MFMIMT 700711UV01 Subject1 s ubject;
  887           PR PAMT201304 UV02Patien t patient;
  888           It erator<II>  iiIterato r;
  889           II  ii;
  890  
  891           Li st<String>  patientId s = new Ar rayList<St ring>();
  892           St ring error Message =  "No Acknow ledgement  detail was  provided  in MVI rep sonse.";
  893  
  894           //  Check for  errors
  895           ac knowledgem entIterato r = respon se.getAckn owledgemen t().iterat or();
  896           wh ile (ackno wledgement Iterator.h asNext())  {
  897                acknowle dgement =  acknowledg ementItera tor.next() ;
  898                if (!"AA ".equalsIg noreCase(a cknowledge ment.getTy peCode().g etCode()))  {
  899                    ackn owledgemen tDetailIte rator = ac knowledgem ent.getAck nowledgeme ntDetail() .iterator( );
  900                    whil e (acknowl edgementDe tailIterat or.hasNext ()) {
  901                         acknowledg ementDetai l = acknow ledgementD etailItera tor.next() ;
  902                         errorMessa ge = ackno wledgement Detail.get Text();
  903                         break;
  904                    }
  905                    //me lcolm todo : error lo gs are rep orting: "C orrelation  Does Not  Exist:IQI"   filter t hese out f rom error  log
  906                    //re turn null?
  907                    thro w new JMea dowsExcept ion("MVI A pplication  Error: "  + errorMes sage);
  908                }
  909           }
  910  
  911           //  Parse out  patient i dentifiers
  912           su bjectItera tor = resp onse.getCo ntrolActPr ocess().ge tSubject() .iterator( );
  913           wh ile (subje ctIterator .hasNext() ) {
  914                subject  = subjectI terator.ne xt();
  915                patient  = subject. getRegistr ationEvent ().getSubj ect1().get Patient();
  916  
  917                iiIterat or = patie nt.getId() .iterator( );
  918                while (i iIterator. hasNext())  {
  919                    ii =  iiIterato r.next();
  920                    pati entIds.add (ii.getExt ension());
  921                }
  922           }
  923  
  924           re turn patie ntIds;
  925       }
  926  
  927       privat e List<Pat ient> pars eResponseT oPatientLo okup(PRPAI N201306UV0 2 response , Map<Stri ng, Site>  siteMap, L ist<Object > restrict edSiteCode sList) thr ows JMeado wsExceptio n {
  928           Li st<Patient > patients  = new Arr ayList<Pat ient>();
  929  
  930  
  931           It erator<MCC IMT000300U V01Acknowl edgement>  acknowledg ementItera tor;
  932           MC CIMT000300 UV01Acknow ledgement  acknowledg ement;
  933           It erator<MCC IMT000300U V01Acknowl edgementDe tail> ackn owledgemen tDetailIte rator;
  934           MC CIMT000300 UV01Acknow ledgementD etail ackn owledgemen tDetail;
  935           It erator<PRP AIN201306U V02MFMIMT7 00711UV01S ubject1> s ubjectIter ator;
  936           PR PAIN201306 UV02MFMIMT 700711UV01 Subject1 s ubject;
  937           PR PAMT201310 UV02Patien t mviPatie nt;
  938           It erator<II>  iiIterato r;
  939           II  ii;
  940  
  941   //         List<Strin g> patient Ids = new  ArrayList< String>();
  942           St ring error Message =  "No Acknow ledgement  detail was  provided  in MVI rep sonse.";
  943   //
  944   //         // Check f or errors
  945           ac knowledgem entIterato r = respon se.getAckn owledgemen t().iterat or();
  946           wh ile (ackno wledgement Iterator.h asNext())  {
  947                acknowle dgement =  acknowledg ementItera tor.next() ;
  948                if (!"AA ".equalsIg noreCase(a cknowledge ment.getTy peCode().g etCode()))  {
  949                    ackn owledgemen tDetailIte rator = ac knowledgem ent.getAck nowledgeme ntDetail() .iterator( );
  950                    erro rMessage =  "";
  951                    whil e (acknowl edgementDe tailIterat or.hasNext ()) {
  952                         acknowledg ementDetai l = acknow ledgementD etailItera tor.next() ;
  953                         errorMessa ge += ackn owledgemen tDetail.ge tText() +  "; ";
  954                         break;
  955                    }
  956                    if(" AR".equals IgnoreCase (acknowled gement.get TypeCode() .getCode() )){
  957                         Patient pa tient = ne w Patient( );
  958                         if(errorMe ssage.cont ains("DOD  Error")){
  959                             errorM essage = " Please mod ify your s earch para meters and  try again .";
  960                         }
  961                         patient.se tName("MVI  Error: Ap plication  Reject. Th ere was an  error att empting to  process y our query.  " + error Message);
  962                         patients.a dd(patient );
  963                         return pat ients;
  964                    } el se if("AE" .equalsIgn oreCase(ac knowledgem ent.getTyp eCode().ge tCode())){
  965                         Patient pa tient = ne w Patient( );
  966                         patient.se tName("MVI  Error: Ap plication  Error. The re was an  error atte mpting to  process yo ur query.  " + errorM essage);
  967                         patients.a dd(patient );
  968                         return pat ients;
  969                    }
  970                    //me lcolm todo : handle t his differ ently, so  that user  is informe d of prope r errors f rom MVI
  971                    //re turn null?
  972                    thro w new JMea dowsExcept ion("MVI A pplication  Error: "  + errorMes sage);
  973                }
  974           }
  975  
  976           // query resp onse code:  QE - too  many resul ts, AE - a pplication  error, NF  - no reco rds found
  977           St ring qrc =  "";
  978           if (response. getControl ActProcess () != null  &&
  979                    resp onse.getCo ntrolActPr ocess().ge tQueryAck( ) != null  &&
  980                    resp onse.getCo ntrolActPr ocess().ge tQueryAck( ).getQuery ResponseCo de() != nu ll){
  981                qrc = re sponse.get ControlAct Process(). getQueryAc k().getQue ryResponse Code().get Code();
  982                if("QE". equalsIgno reCase(qrc )) {
  983                    Pati ent patien t = new Pa tient();
  984                    pati ent.setNam e("MVI Err or: Your q uery yield s too many  results.  Please mod ify your s earch para meters to  narrow the  search.") ;
  985                    pati ents.add(p atient);
  986                    retu rn patient s;
  987                } else i f("AE".equ alsIgnoreC ase(qrc))  {
  988                    Pati ent patien t = new Pa tient();
  989                    pati ent.setNam e("MVI Err or: There  was an err or attempt ing to pro cess your  query.");
  990                    pati ents.add(p atient);
  991                    retu rn patient s;
  992                } else i f("NF".equ alsIgnoreC ase(qrc))  {
  993                    Pati ent patien t = new Pa tient();
  994                    pati ent.setNam e("MVI Mes sage: Pati ent not fo und with s earch elem ents enter ed, please  provide a dditional  " +
  995                             "patie nt identif ying infor mation and  search ag ain");
  996                    pati ents.add(p atient);
  997                    retu rn patient s;
  998                }
  999           }
  1000  
  1001           su bjectItera tor = resp onse.getCo ntrolActPr ocess().ge tSubject() .iterator( );
  1002           wh ile (subje ctIterator .hasNext() ) {
  1003                Patient  patient =  new Patien t();
  1004                subject  = subjectI terator.ne xt();
  1005                mviPatie nt = subje ct.getRegi strationEv ent().getS ubject1(). getPatient ();
  1006  
  1007                // Parse  out patie nt identif iers
  1008                List<Str ing> patie ntIds = ne w ArrayLis t<String>( );
  1009                iiIterat or = mviPa tient.getI d().iterat or();
  1010                while (i iIterator. hasNext())  {
  1011                    ii =  iiIterato r.next();
  1012                    if(S tringUtils .isNotEmpt y(ii.getRo ot()) && O ID_EDIPI.e quals(ii.g etRoot())
  1013                             && Str ingUtils.i sNotEmpty( ii.getExte nsion()) & & ii.getEx tension(). length() = = 10){
  1014                         patient.se tEDIPI(ii. getExtensi on());
  1015                    } el se {
  1016                         patient =  parsePatie ntId(ii.ge tExtension (), siteMa p, patient );
  1017                    }
  1018                }
  1019  
  1020                // Parse  patientPe rson
  1021                PRPAMT20 1310UV02Pe rson patie ntPerson =  mviPatien t.getPatie ntPerson() .getValue( );
  1022                if (pati entPerson  != null) {
  1023                    CE c e;
  1024                    TS t s;
  1025                    CS c s;
  1026  
  1027                    // P atient gen der
  1028                    ce =  patientPe rson.getAd ministrati veGenderCo de();
  1029                    if ( ce != null ) {
  1030                         patient.se tGender(ce .getCode() );
  1031                    }
  1032  
  1033                    // P atient dat e of birth
  1034                    ts =  patientPe rson.getBi rthTime();
  1035                    if ( ts != null ) {
  1036                         patient.se tDob(ts.ge tValue());
  1037                    }
  1038  
  1039                    // P atient nam e
  1040                    if ( patientPer son.getNam e() != nul l) {
  1041                         for (PN pn  : patient Person.get Name()) {
  1042                             if (pn .getUse()  == null) {  continue;  }
  1043                             for (S tring use  : pn.getUs e()) {
  1044                                 if  ("L".equa lsIgnoreCa se(use)) {
  1045                                      patient. setName(pa rseName(pn ));
  1046                                 }
  1047                             }
  1048                         }
  1049                    }
  1050  
  1051                    // P atient SSN
  1052                    if ( patientPer son.getAsO therIDs()  != null) {
  1053                         for (PRPAM T201310UV0 2OtherIDs  otherIDs :  patientPe rson.getAs OtherIDs() ) {
  1054                             if (ot herIDs.get Id() == nu ll) { cont inue; }
  1055                             for (I I otherId  : otherIDs .getId())  {
  1056                                 if  ("2.16.84 0.1.113883 .4.1".equa lsIgnoreCa se(otherId .getRoot() )){
  1057                                      patient. setSSN(oth erId.getEx tension()) ;
  1058                                 }
  1059                             }
  1060                         }
  1061                    }
  1062                }
  1063  
  1064                boolean  unrestrict edPatient  = true;
  1065                // if th ere is a r estricted  site list,  only add  patients w ith an id  at at leas t one vist a site in  the list
  1066                if (Coll ectionUtil s.isNotEmp ty(restric tedSiteCod esList)) {
  1067                    // s ince there  is a rest ricted lis t, at firs t assume t his patien t is not a llowed to  be added t o lookup
  1068                    unre strictedPa tient = fa lse;
  1069                    for  (Site vist aSite : pa tient.getV istaSites( )) {
  1070                         // patient 's vistaSi tes added  to patient .getVistaS ites() dur ing parsin g of ident ifiers; ch eck those  sites agai nst restri cted list
  1071                         if (restri ctedSiteCo desList.co ntains(vis taSite.get SiteCode() )) {
  1072                             // thi s patient  has an id  at a vista  site in t he site li st so set  this patie nt back to  unrestric ted
  1073                             unrest rictedPati ent = true ;
  1074                             break;
  1075                         }
  1076                    }
  1077                    if ( !unrestric tedPatient  && APP_CO NFIG.useEn hancedDebu g()) {
  1078                         StringBuil der debugS tring = ne w StringBu ilder("!!!  VBAUSER S ITERESTRIC TED: ");
  1079                         // Log tha t a patien t was filt ered out.
  1080                         debugStrin g.append(" Removing f rom search  PATIENT:  ");
  1081                         debugStrin g.append(p atient.get Name());
  1082                         debugStrin g.append("    Restric ted SITES:  ");
  1083                         for (Objec t restrict edSiteCode  : restric tedSiteCod esList) {
  1084                             debugS tring.appe nd(restric tedSiteCod e);
  1085                             debugS tring.appe nd(" ");
  1086                         }
  1087                         debugStrin g.append("   Patient  SITES: ");
  1088                         for (Site  site : pat ient.getVi staSites() ) {
  1089                             debugS tring.appe nd(site.ge tSiteCode( ));
  1090                             debugS tring.appe nd(" ");
  1091                         }
  1092                         LOGGER.deb ug(debugSt ring.toStr ing());
  1093                    }
  1094                }
  1095  
  1096                // add o nly unrest ricted pat ients to l ookup list
  1097                if (unre strictedPa tient) {
  1098                    pati ents.add(p atient);
  1099                }
  1100           }
  1101  
  1102           re turn patie nts;
  1103       }
  1104  
  1105       privat e Patient  parsePatie ntId(Strin g idString , Map<Stri ng, Site>  siteMap, P atient pat ient){
  1106  
  1107           //  Correspon ding IDs f ormat: ID^ TYPE^SOURC E^ISSUER^S TATUS
  1108           St ringTokeni zer tokeni zer = new  StringToke nizer(idSt ring, "^") ;
  1109  
  1110           Li st<Externa lID> exter nalIDs = n ew ArrayLi st<Externa lID>();
  1111  
  1112           if  (tokenize r.countTok ens() >= 4 ) // Accor ding to fo rmat, ther e should o nly be 5 t okens
  1113           {
  1114                String i d = tokeni zer.nextTo ken();
  1115                String t ype = toke nizer.next Token();
  1116                String s ource = to kenizer.ne xtToken();
  1117                String i ssuer = to kenizer.ne xtToken();
  1118                String s tatus = "" ;
  1119                if(token izer.hasMo reTokens() ) {
  1120                   statu s = tokeni zer.nextTo ken();
  1121                }
  1122  
  1123                // Makes  sure each  relevant  token is n ot null or  blank and  status is  "A" for a ctive
  1124                if (Stri ngUtils.is NotBlank(i d) && Stri ngUtils.is NotBlank(t ype)
  1125                         && StringU tils.isNot Blank(sour ce) && Str ingUtils.i sNotBlank( issuer)) {
  1126                    if ( "NI".equal sIgnoreCas e(type)) {
  1127                         // Nationa l patient  identifier
  1128                         if ("200DO D".equalsI gnoreCase( source) &&  "USDOD".e qualsIgnor eCase(issu er)
  1129                                 &&  ("A".equa lsIgnoreCa se(status)  || String Utils.isBl ank(status ))) {
  1130                             patien t.setEDIPI (id);
  1131                         } else if  ("200M".eq ualsIgnore Case(sourc e) && "USV HA".equals IgnoreCase (issuer)
  1132                                 &&  ("P".equa lsIgnoreCa se(status)  || String Utils.isBl ank(status ))) {
  1133                             // VA  ICN
  1134                             patien t.setICN(i d);
  1135                         } else {
  1136                             extern alIDs.add( new Extern alID(id, t ype, sourc e, issuer) );
  1137                         }
  1138                    } el se if ("PI ".equalsIg noreCase(t ype)) {
  1139                         // Local f acility pa tient iden tifier
  1140                         if ("USVHA ".equalsIg noreCase(i ssuer) &&  ("A".equal sIgnoreCas e(status)  || StringU tils.isBla nk(status) )) {
  1141                             // VA  DFN (IEN)
  1142                             if (si teMap != n ull) {
  1143                                 Si te site =  siteMap.ge t(source);
  1144                                 if  (site ==  null) {
  1145                                      LOGGER.d ebug("Site  with site  code " +  source + "  not found  in sites  map");
  1146                                 }  else {
  1147                                      patient. getVistaSi tes().add( site);
  1148  
  1149                                      // Add p atient's V A IEN and  correspond ing site c ode to key -value pai r list
  1150                                      KeyValue Pair kvp =  new KeyVa luePair();
  1151                                      kvp.setK ey(source) ;
  1152                                      kvp.setV alue(id);
  1153                                      patient. getPatient Iens().add (kvp);
  1154                                 }
  1155                             }
  1156                         } else {
  1157                             extern alIDs.add( new Extern alID(id, t ype, sourc e, issuer) );
  1158                         }
  1159                    }
  1160                }
  1161           }  else {
  1162                LOGGER.d ebug("Inva lid corres ponding ID  string fo rmat");
  1163           }
  1164           re turn patie nt;
  1165       }
  1166  
  1167       privat e void log AndAuditEx ception(Th rowable e,  String au ditMsg, JM eadowsQuer y qb, bool ean isAudi t) {
  1168           Au ditDao aud itDao = ne w AuditDao ();
  1169   //         StringWrit er sw = ne w StringWr iter();
  1170   //         PrintWrite r pw = new  PrintWrit er(sw);
  1171  
  1172           //  Log error
  1173           if  (e != nul l) {
  1174   //             e.prin tStackTrac e(pw);
  1175   //             logger .error(sw. toString() );
  1176                LOGGER.e rror(e.get Message(),  e);
  1177           }
  1178  
  1179           //  Audit err or
  1180           if  (isAudit)  {
  1181                String r equestingA pp = qb.ge tRequestin gApp();
  1182                String s iteCode =  null;
  1183                String u serIen = n ull;
  1184                String u serNPI = n ull;
  1185                String u serName =  null;
  1186                String p atId;
  1187                String s iteMoniker  = qb.getS iteMoniker ();
  1188                String s iteAgency  = qb.getSi teAgency() ;
  1189                String r ecordID =  qb.getItem Id();
  1190                String c omplexTran saction =  qb.getComp lexTransac tion();
  1191                User use r = qb.get User();
  1192  
  1193                if (user  != null)  {
  1194                    site Code = use r.getHostS ite().getS iteCode();
  1195                    user Ien = user .getUserIe n();
  1196  
  1197                    if ( StringUtil s.isNotBla nk(user.ge tProviderI en())) {
  1198                         userIen +=  "^" + use r.getProvi derIen();
  1199                    }
  1200  
  1201                    user NPI = user .getNPI();
  1202                    user Name = use r.getName( );
  1203                }
  1204  
  1205                patId =  qb.getItem Id();
  1206                if (Stri ngUtils.is NotBlank(q b.getRecor dSiteCode( ))) {
  1207                    patI d += "^" +  qb.getRec ordSiteCod e();
  1208                }
  1209  
  1210                try {
  1211                    audi tDao.setAu dit(siteCo de, siteMo niker, sit eAgency, r ecordID, u serIen, us erNPI, use rName, pat Id, auditM sg, reques tingApp, n ull, null,  complexTr ansaction) ;
  1212                } catch  (JMeadowsE xception e xception)  {
  1213   //                 ex ception.pr intStackTr ace(pw);
  1214   //                 lo gger.error (sw.toStri ng());
  1215                    if ( e != null)  {
  1216                         LOGGER.err or(e.getMe ssage(), e );
  1217                    }
  1218                }
  1219           }
  1220       }
  1221  
  1222       privat e List<Ext ernalID> g etVLERSite Names(List <ExternalI D> ids) {
  1223           fo r (Externa lID id : i ds) {
  1224                if (id.g etSource()  != null)  {
  1225                    Code  code = VL ERSiteCach e.getCode( "", id.get Source(),  "");
  1226                    if ( code != nu ll && code .getDispla y() != nul l) {
  1227                         id.setSour ceName(cod e.getDispl ay());
  1228                    }
  1229                }
  1230           }
  1231           re turn ids;
  1232       }
  1233  
  1234       privat e String p arseName(E N en) {
  1235           St ringBuilde r familyNa me = new S tringBuild er();
  1236           St ringBuilde r givenNam e = new St ringBuilde r();
  1237           St ringBuilde r prefixNa me = new S tringBuild er();
  1238           St ringBuilde r suffixNa me = new S tringBuild er();
  1239           Li st<Seriali zable> ser ializableL ist1;
  1240           Li st<Seriali zable> ser ializableL ist2;
  1241           St ring rtc;
  1242           Ob ject objec t;
  1243  
  1244           se rializable List1 = en .getConten t();
  1245           if  (serializ ableList1  == null) {
  1246                rtc = nu ll;
  1247           }  else {
  1248  
  1249                for (Ser ializable  serializab le1 : seri alizableLi st1) {
  1250                    if ( !(serializ able1 inst anceof JAX BElement))  { continu e; }
  1251  
  1252                    obje ct = ((JAX BElement)  serializab le1).getVa lue();
  1253                    if ( object ==  null) { co ntinue; }
  1254  
  1255                    if ( "family".e quals(( (J AXBElement ) serializ able1).get Name().get LocalPart( )))  {
  1256                         if(familyN ame.length ()>0){
  1257                             family Name.appen d(" ");
  1258                         }
  1259                       f amilyName. append(obj ect);
  1260                    } el se if ("gi ven".equal s(( (JAXBE lement) se rializable 1).getName ().getLoca lPart()))   {
  1261                         if(givenNa me.length( )>0){
  1262                             givenN ame.append (" ");
  1263                         }
  1264                         givenName. append(obj ect);
  1265                    } el se if ("pr efix".equa ls(( (JAXB Element) s erializabl e1).getNam e().getLoc alPart()))  {
  1266                         if(prefixN ame.length ()>0){
  1267                             prefix Name.appen d(" ");
  1268                         }
  1269                         prefixName .append(ob ject);
  1270                    } el se if ("su ffix".equa ls(( (JAXB Element) s erializabl e1).getNam e().getLoc alPart()))  {
  1271                         if(suffixN ame.length ()>0){
  1272                             suffix Name.appen d(" ");
  1273                         }
  1274                         suffixName .append(ob ject);
  1275                    }
  1276                }
  1277  
  1278                // add p refix befo re given n ame
  1279                if (pref ixName.len gth() > 0)  {
  1280                    give nName = pr efixName.a ppend(give nName);
  1281                }
  1282  
  1283                // add s uffix afte r given na me
  1284                if (suff ixName.len gth() > 0)  {
  1285                    give nName = gi venName.ap pend(suffi xName);
  1286                }
  1287  
  1288                rtc = fa milyName.t oString(). trim() + " ," + given Name.toStr ing().trim ();
  1289           }
  1290           re turn rtc;
  1291       }
  1292  
  1293       privat e String p arsePhoneN umber(Stri ng telecom ) {
  1294           St ringBuilde r phoneNum ber = new  StringBuil der();
  1295           St ringTokeni zer tokeni zer = new  StringToke nizer(tele com, " ");
  1296           St ring token ;
  1297           ch ar code;
  1298  
  1299           wh ile (token izer.hasMo reTokens() ) {
  1300                token =  tokenizer. nextToken( );
  1301                code = t oken.toLow erCase(Loc ale.getDef ault()).ch arAt(0);
  1302                // Do no t accept t okens that  begin wit h (p)riori ty, (y)es  text, (n)o  text
  1303                if ((cod e != 'p')  && (code ! = 'y') &&  (code != ' n')) {
  1304                    phon eNumber.ap pend(token );
  1305                    phon eNumber.ap pend(" ");
  1306                }
  1307           }
  1308  
  1309           re turn phone Number.toS tring().tr im();
  1310       }
  1311   }