32. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 5/1/2018 12:02:03 PM 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.

32.1 Files compared

# Location File Last Modified
1 C:\AraxisMergeCompare\Pri_un\ZIP\JLV_2.6.2.0.3_src\jMeadows\src\main\java\gov\va\med\jmeadows\dataservicehandler MVIServiceHandler.java Thu Mar 29 22:08:33 2018 UTC
2 C:\AraxisMergeCompare\Pri_re\ZIP\JLV_2.6.2.0.3_src\jMeadows\src\main\java\gov\va\med\jmeadows\dataservicehandler MVIServiceHandler.java Tue May 1 13:46:44 2018 UTC

32.2 Comparison summary

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

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

32.4 Active regular expressions

No regular expressions were active.

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