35. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 6/5/2018 10:24:12 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.

35.1 Files compared

# Location File Last Modified
1 patch_205_build_9.zip\Java\MIXCommon\main\src\java\gov\va\med\imaging\mix\webservices\translator\v1 MixTranslatorV1.java Wed May 30 14:35:29 2018 UTC
2 patch_205_build_9.zip\Java\MIXCommon\main\src\java\gov\va\med\imaging\mix\webservices\translator\v1 MixTranslatorV1.java Mon Jun 4 15:56:18 2018 UTC

35.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 3 2676
Changed 2 4
Inserted 0 0
Removed 0 0

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

35.4 Active regular expressions

No regular expressions were active.

35.5 Comparison detail

  1   /**
  2    * 
  3     Package:  MAG - Vis tA Imaging
  4     WARNING:  Per VHA D irective 2 004-038, t his routin e should n ot be modi fied.
  5     Date Cre ated: Sep  27, 2010
  6     Site Nam e:  Washin gton OI Fi eld Office , Silver S pring, MD
  7       Developer:     PII
  8     Descript ion: 
  9  
  10           ;;  +-------- ---------- ---------- ---------- ---------- ---------- ---------- +
  11           ;;  Property  of the US  Government .
  12           ;;  No permis sion to co py or redi stribute t his softwa re is give n.
  13           ;;  Use of un released v ersions of  this soft ware requi res the us er
  14           ;;   to execu te a writt en test ag reement wi th the Vis tA Imaging
  15           ;;   Developm ent Office  of the De partment o f Veterans  Affairs,
  16           ;;   telephon e (301) 73 4-0100.
  17           ;;
  18           ;;  The Food  and Drug A dministrat ion classi fies this  software a s
  19           ;;  a Class I I medical  device.  A s such, it  may not b e changed
  20           ;;  in any wa y.  Modifi cations to  this soft ware may r esult in a n
  21           ;;  adulterat ed medical  device un der 21CFR8 20, the us e of which
  22           ;;  is consid ered to be  a violati on of US F ederal Sta tutes.
  23           ;;  +-------- ---------- ---------- ---------- ---------- ---------- ---------- +
  24  
  25    */
  26   package go v.va.med.i maging.mix .webservic es.transla tor.v1;
  27  
  28   import jav a.text.Dat eFormat;
  29   import jav a.text.Par seExceptio n;
  30   import jav a.text.Sim pleDateFor mat;
  31   import jav a.util.Arr ayList;
  32   import jav a.util.Dat e;
  33   import jav a.util.Has hMap;
  34   import jav a.util.Ite rator;
  35   import jav a.util.Lis t;
  36   import jav a.util.Loc ale;
  37   import jav a.util.Map ;
  38   import jav a.util.Set ;
  39   import jav a.util.Sor tedSet;
  40   import jav a.util.Tre eSet;
  41   import jav a.util.Map .Entry;
  42  
  43   import org .apache.lo gging.log4 j.LogManag er;
  44   import org .apache.lo gging.log4 j.Logger;
  45   import sta tic org.ap ache.commo ns.lang.St ringEscape Utils.esca peHtml;
  46  
  47   import gov .va.med.*;
  48   import gov .va.med.ex ceptions.G lobalArtif actIdentif ierFormatE xception;
  49   import gov .va.med.im aging.Bhie ImageURN;
  50   //import g ov.va.med. imaging.Bh ieStudyURN ;
  51   import gov .va.med.im aging.Date Util;
  52   import gov .va.med.im aging.Dico mDateForma t;
  53   import gov .va.med.im aging.Imag eURN;
  54   import gov .va.med.im aging.Stri ngUtil;
  55   import gov .va.med.im aging.Stud yURN;
  56   import gov .va.med.im aging.arti factsource .ArtifactS ource;
  57   import gov .va.med.im aging.exce ptions.Stu dyURNForma tException ;
  58   import gov .va.med.im aging.exce ptions.URN FormatExce ption;
  59   import gov .va.med.im aging.exch ange.busin ess.Artifa ctResultEr ror;
  60   import gov .va.med.im aging.exch ange.busin ess.Image;
  61   import gov .va.med.im aging.exch ange.busin ess.Series ;
  62   import gov .va.med.im aging.exch ange.busin ess.Site;
  63   import gov .va.med.im aging.exch ange.busin ess.Study;
  64   import gov .va.med.im aging.exch ange.busin ess.StudyS etResult;
  65   import gov .va.med.im aging.exch ange.enums .ArtifactR esultError Code;
  66   import gov .va.med.im aging.exch ange.enums .ArtifactR esultError Severity;
  67   import gov .va.med.im aging.exch ange.enums .ArtifactR esultStatu s;
  68   import gov .va.med.im aging.exch ange.enums .ObjectOri gin;
  69   import gov .va.med.im aging.exch ange.enums .StudyDele tedImageSt ate;
  70   import gov .va.med.im aging.exch ange.enums .StudyLoad Level;
  71   import gov .va.med.im aging.exch ange.enums .VistaImag eType;
  72   import gov .va.med.im aging.exch ange.trans lation.exc eptions.Tr anslationE xception;
  73   import gov .va.med.im aging.exch ange.busin ess.StudyF ilter;
  74   import gov .va.med.im aging.exch ange.busin ess.util.E xchangeUti l;
  75   import gov .va.med.im aging.mix. MixArtifac tResultErr or;
  76   import gov .va.med.im aging.mix. VAStudyID;
  77   import gov .va.med.im aging.mix. webservice s.rest.typ es.v1.Code Type;
  78   import gov .va.med.im aging.mix. webservice s.rest.typ es.v1.Codi ngType;
  79   import gov .va.med.im aging.mix. webservice s.rest.typ es.v1.Diag nosticRepo rt;
  80   import gov .va.med.im aging.mix. webservice s.rest.typ es.v1.ModC odeType;
  81   import gov .va.med.im aging.mix. webservice s.rest.typ es.v1.Refe renceType;
  82   import gov .va.med.im aging.mix. webservice s.rest.typ es.v1.Shal lowStudy;
  83   import gov .va.med.im aging.mix. webservice s.rest.typ es.v1.Text Type;
  84  
  85   /**
  86    * @author   PII
  87    *
  88    */
  89   @SuppressW arnings("d eprecation ")
  90   public cla ss MixTran slatorV1
  91   {
  92           pr ivate fina l static L ogger logg er = LogMa nager.getL ogger(MixT ranslatorV 1.class);
  93                    
  94           pr ivate stat ic Map<Art ifactResul tErrorCode , gov.va.m ed.imaging .mix.webse rvices.res t.types.v1 .ErrorCode Type> erro rCodeMap;
  95           pr ivate stat ic Map<Art ifactResul tErrorSeve rity, gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Sever ityType> s everityMap ;
  96           
  97           st atic
  98           {
  99                    erro rCodeMap =  new HashM ap<Artifac tResultErr orCode, go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Err orCodeType >();
  100                    erro rCodeMap.p ut(Artifac tResultErr orCode.aut horization Exception,  gov.va.me d.imaging. mix.webser vices.rest .types.v1. ErrorCodeT ype.Author izationExc eption);
  101                    erro rCodeMap.p ut(Artifac tResultErr orCode.int ernalExcep tion, gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Error CodeType.I nternalExc eption);
  102                    erro rCodeMap.p ut(Artifac tResultErr orCode.inv alidReques tException , gov.va.m ed.imaging .mix.webse rvices.res t.types.v1 .ErrorCode Type.Inval idRequestE xception);
  103                    erro rCodeMap.p ut(Artifac tResultErr orCode.tim eoutExcept ion, gov.v a.med.imag ing.mix.we bservices. rest.types .v1.ErrorC odeType.Ti meoutExcep tion);
  104                    
  105                    seve rityMap =  new HashMa p<Artifact ResultErro rSeverity,  gov.va.me d.imaging. mix.webser vices.rest .types.v1. SeverityTy pe>();
  106                    seve rityMap.pu t(Artifact ResultErro rSeverity. error, gov .va.med.im aging.mix. webservice s.rest.typ es.v1.Seve rityType.e rror);
  107                    seve rityMap.pu t(Artifact ResultErro rSeverity. warning, g ov.va.med. imaging.mi x.webservi ces.rest.t ypes.v1.Se verityType .warning);
  108           }
  109           
  110           pu blic stati c StudySet Result tra nslate(
  111                             gov.va .med.imagi ng.mix.web services.r est.types. v1.ReportS tudyListRe sponseType  reportStu dyListResp onseType,
  112                             Site s ite, 
  113                             StudyF ilter stud yFilter,
  114                             List<S tring> emp tyStudyMod alities)
  115           {
  116                    if(r eportStudy ListRespon seType ==  null)
  117                             return  null;
  118                    
  119                    Arti factResult Status art ifactResul tStatus =  (reportStu dyListResp onseType.i sPartialRe sponse() ?  ArtifactR esultStatu s.partialR esult : Ar tifactResu ltStatus.f ullResult) ;
  120                    List <ArtifactR esultError > artifact ResultErro rs = trans late(repor tStudyList ResponseTy pe.getErro rs());
  121                    Sort edSet<Stud y> studies  = transla te(reportS tudyListRe sponseType .getStudie s(), site,  
  122                                      studyFil ter, empty StudyModal ities);
  123                    
  124                    retu rn StudySe tResult.cr eate(studi es, artifa ctResultSt atus, arti factResult Errors);
  125           }
  126           
  127           pu blic stati c String t ranslate(g ov.va.med. imaging.mi x.webservi ces.rest.t ypes.v1.Re portType r eport)
  128           {
  129                    Stri ng result  = "1^^\n"  + (report  == null ?  "" : repor t.getRadio logyReport ());
  130                    retu rn result;
  131           }
  132           
  133           pr ivate stat ic SortedS et<Study>  translate(
  134                             gov.va .med.imagi ng.mix.web services.r est.types. v1.StudyTy pe [] stud ies,
  135                             Site s ite, 
  136                             StudyF ilter stud yFilter, 
  137                             List<S tring> emp tyStudyMod alities)
  138           {
  139                    if(s tudies ==  null)
  140                             return  null;
  141                    
  142                    Sort edSet<Stud y> result  = new Tree Set<Study> ();
  143                    Stri ng filterS tudyAsStri ng = study Filter !=  null && st udyFilter. getStudyId () != null  ?
  144                                      studyFil ter.getStu dyId() ins tanceof St udyURN ? ( (StudyURN) studyFilte r.getStudy Id()).toSt ring(SERIA LIZATION_F ORMAT.NATI VE) : stud yFilter.ge tStudyId() .toString( ) : 
  145                                      null;
  146                    for( gov.va.med .imaging.m ix.webserv ices.rest. types.v1.S tudyType s tudyType :  studies)
  147                    {
  148                             Study  study = nu ll;
  149                             if( st udyFilter  != null &&  studyFilt er.getStud yId() != n ull )
  150                             {
  151                                      if(filte rStudyAsSt ring.equal s(studyTyp e.getStudy Id()))
  152                                               study = tr anslate(st udyType, s ite, empty StudyModal ities);
  153                             }
  154                             else
  155                             {
  156                                      study =  translate( studyType,  site, emp tyStudyMod alities);
  157                             }
  158                             if(stu dy != null )
  159                             {
  160                                      result.a dd(study);
  161                             }
  162                    }                                  
  163                    retu rn result;
  164           }
  165           
  166           pr ivate stat ic Study t ranslate(g ov.va.med. imaging.mi x.webservi ces.rest.t ypes.v1.St udyType st udyType, 
  167                             Site s ite, List< String> em ptyStudyMo dalities)
  168           {
  169                    if(s tudyType = = null)
  170                             return  null;
  171                    Stri ng studyId  = studyTy pe.getStud yId();
  172                    Stud y study =  null;
  173                    Stud yURN study Identifier  = null;
  174  
  175                    try
  176                    {
  177                             studyI dentifier  = URNFacto ry.create( studyId, S tudyURN.cl ass);
  178                    }
  179                    catc h (URNForm atExceptio n x1)
  180                    {
  181                             logger .error("Un able to cr eate Study  instance  because gl obal artif act identi fier '" +  studyId +  "' is unid entifiable .", x1);
  182                             return  null;
  183                    }
  184                    if(s tudyIdenti fier == nu ll)
  185                    {
  186                             try
  187                             {
  188                                      GlobalAr tifactIden tifier ide ntifier =  GlobalArti factIdenti fierFactor y.create(s tudyId);
  189                                      if(ident ifier inst anceof Stu dyURN)
  190                                               studyIdent ifier = (S tudyURN)id entifier;
  191                             }
  192                             catch  (GlobalArt ifactIdent ifierForma tException  x)
  193                             {
  194                                      logger.e rror("Unab le to crea te Study i nstance be cause glob al artifac t identifi er '" + st udyId + "'  is uniden tifiable." , x);
  195                                      return n ull;
  196                             }
  197                             logger .info("Stu dy Identif ier '" + s tudyIdenti fier.toStr ing() + 
  198                                      "' creat ed by Glob alArtifact Identifier Factory.") ;
  199                    }
  200                    else
  201                             logger .info("Stu dy Identif ier '" + s tudyIdenti fier.toStr ing() + 
  202                                      "' creat ed by URNF actory.");
  203                             
  204                    
  205                    // B HIE identi fiers are  unique in  that the p atient ID  must be se t explicit ly rather  than
  206                    // a s part of  the string ified repr esentation  of the ID
  207                    // s et the pat ient ID re gardless o f whether  the URN is  a BHIE or  VA
  208                    try
  209                    {
  210                             studyI dentifier. setPatient Id(studyTy pe.getPati entId());
  211                             studyI dentifier. setPatient Identifier TypeIfNece ssary(Pati entIdentif ierType.ic n);
  212                    }
  213                    catc h (StudyUR NFormatExc eption x)
  214                    {
  215                             logger .error("Un able to cr eate Study  instance  because pa tient ID ' " + studyT ype.getPat ientId() +  "' is not  in a vali d format." , x);
  216                             return  null;
  217                    }
  218                    
  219                    logg er.info("T ranslating  study, gl obal artif act identi fier '" +  studyIdent ifier.toSt ring() + " ' is of ty pe '" + st udyIdentif ier.getCla ss().getSi mpleName()  + "'; Stu dy Id = '"  + studyId  + "'.");
  220                    // v 2 does not  include t he report
  221                    stud y = Study. create(stu dyIdentifi er, StudyL oadLevel.S TUDY_AND_I MAGES, 
  222                                      StudyDel etedImageS tate.canno tIncludeDe letedImage s);
  223                    logg er.debug("   Study '"  + studyId entifier.t oString()  + "' is cr eated with  loadlevel  STUDY_AND _IMAGES.") ;
  224  
  225                    stud y.setAlien SiteNumber (studyType .getSiteNu mber());
  226                    logg er.debug("   Study Al ienSiteNum ber = " +  study.getA lienSiteNu mber());
  227                    stud y.setDescr iption(stu dyType.get Descriptio n() == nul l ? "" : s tudyType.g etDescript ion());
  228                    logg er.debug("   Study De scription  = " + stud y.getDescr iption());
  229                    if ( (studyType .getDescri ption() !=  null) &&  (!studyTyp e.getDescr iption().i sEmpty())  && 
  230                             studyT ype.getDes cription() .startsWit h(StringUt il.LEFT_BR ACKET))
  231                    {  
  232                             // 3/5 /18 CPT: " [xxxx-yyyy yyyy] <des c.text>" i s the expe cted forma t -- extra ct externa l content  ID (altern ateExamNum ber) from  [] 
  233                             String [] parts =  StringUti l.split(st udyType.ge tDescripti on(), Stri ngUtil.RIG HT_BRACKET );
  234                             String  alternate ExamNumber  = parts[0 ];
  235                             altern ateExamNum ber = alte rnateExamN umber.subs tring(1).t rim(); //  <-- xxxx-y yyyyyyy
  236                             if (al ternateExa mNumber.co ntains(Str ingUtil.DA SH)) {     // keep yy yyyyyy onl y
  237                                      String[]  dashedPar ts = Strin gUtil.spli t(alternat eExamNumbe r, StringU til.DASH);
  238                                      alternat eExamNumbe r = dashed Parts[part s.length-1 ]; // <--  yyyyyyyy
  239                             }
  240                             study. setAlterna teExamNumb er(alterna teExamNumb er); 
  241                             logger .info("Stu dy Alterna teExamNumb er: " + al ternateExa mNumber);
  242                    }
  243                    stud y.setStudy Uid(studyT ype.getDic omUid());
  244                    logg er.debug("   Study UI D = " + st udy.getStu dyUid());
  245                    stud y.setImage Count(stud yType.getI mageCount( ));
  246                    logg er.debug("   Study Im age Count  = " + stud y.getImage Count());
  247  
  248                    //Th e BHIE fra mework is  not capabl e of provi ding the p atient nam e for now
  249                    if ( studyType. getPatient Name() ==  null)
  250                             study. setPatient Name("");
  251                    else
  252                             study. setPatient Name(study Type.getPa tientName( ).replaceA ll("\\^",  " "));
  253                    logg er.debug("   Study Pa tient Name  = " + stu dy.getPati entName()) ;
  254  
  255                    stud y.setProce dureDate(t ranslateDI COMDateToD ate(studyT ype.getPro cedureDate ()));
  256                    logg er.debug("   Study Pr ocedure Da te = " + s tudy.getPr ocedureDat e());
  257                    stud y.setProce dure(study Type.getPr ocedureDes cription()  == null ?  "" : stud yType.getP rocedureDe scription( ));
  258                    logg er.debug("   Study Pr ocedure =  " + study. getProcedu re());
  259                             
  260                    stud y.setRadio logyReport (studyType .getReport Content()) ; // Note:  Exchange  v2 did not  include s tudy repor t; added n ow!!!
  261                    logg er.debug("   Study Ra diology Re port = " +  study.get RadiologyR eport());
  262                    
  263                    
  264                    stud y.setSiteN ame(studyT ype.getSit eName() ==  null ? ""  : studyTy pe.getSite Name());
  265                    logg er.debug("   Study Si te Name =  " + study. getSiteNam e());
  266                    stud y.setSpeci alty(study Type.getSp ecialtyDes cription()  == null ?  "" : stud yType.getS pecialtyDe scription( ));
  267                    logg er.debug("   Study Sp ecialty =  " + study. getSpecial ty());
  268                    
  269                    if(s tudyIdenti fier.toStr ing().cont ains(":200 ")) // ins tanceof Bh ieStudyURN )
  270                    {
  271                             study. setOrigin( "DOD"); //  hard code  the origi n to the D OD so it d isplays on  the Displ ay client  image list  window
  272                             study. setSiteAbb r("DOD");  // needed  because CP S test rig  no longer  passes us  useful in formation
  273                    }
  274                    else
  275                    {
  276                             study. setSiteAbb r(site.get SiteAbbr() );
  277                             study. setOrigin( site.getSi teAbbr());
  278                    }
  279                    logg er.debug("   Study Si te Abbr =  " + study. getSiteAbb r());
  280                    logg er.debug("   Study Or igin = " +  study.get Origin());
  281                    
  282                    Imag e firstIma ge = null;                  
  283                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Serie sType[] se ries = stu dyType.get ComponentS eries().ge tSeries();
  284                    if(s eries != n ull) {
  285                             logger .debug("   Study - lo oking for  first Imag e ... #Ser ies = " +  series.len gth );
  286                             for(in t i = 0; i  < series. length; i+ +) {
  287                                      logger.d ebug("  St udy - tran slating Se ries[" + ( i+1) + "]  ...");
  288                                      Series n ewSeries =  translate (series[i] , study, s ite);
  289                                      logger.d ebug("  St udy - newS eries[" +  (i+1) + "]  info " +  newSeries. toString() );
  290                                      logger.d ebug("  St udy - #ser ies before  adding ne w one = "  + study.ge tSeries(). size());
  291                                      study.ad dSeries(ne wSeries);
  292                                      logger.d ebug("  St udy - adde d Series["  + (i+1) +  "]");
  293                                      // first  series
  294                                      if(i ==  0) {
  295                                               Iterator<I mage> imag eIter = ne wSeries.it erator();
  296                                               if(imageIt er.hasNext ()) {
  297                                                       fi rstImage =  imageIter .next();
  298                                               }
  299                                      }
  300                             }
  301                    }
  302                    if(f irstImage  == null)
  303                    {
  304                             logger .info("Cre ating fake  first ima ge for stu dy '" + st udy.getStu dyUrn().to String() +  "', study  has '" +  study.getI mageCount( ) + "' ima ges.");
  305                             firstI mage = cre atedCanned FirstImage (study, si te);
  306                    } el se
  307                             logger .debug("   Study - fi rst Image  found!");
  308  
  309                    stud y.setFirst Image(firs tImage);
  310                    
  311                    if(s tudyType.g etModaliti es() != nu ll) // --  *** invest igate this  section f or DAS!!
  312                    {                 
  313                             String [] modalit ies = stud yType.getM odalities( ).getModal ity();
  314                             String  modList =  "";
  315                             for (S tring mty  : modaliti es) {
  316                                      if (modL ist.isEmpt y()) modLi st = mty;
  317                                      else mod List += ", " + mty;
  318                             }
  319                             logger .debug("   Contained  Modalities  = " + mod List);
  320                             if(mod alities !=  null) 
  321                             {
  322                                      // JMW 4 /11/2011 P 04
  323                                      // a stu dy from th e DoD may  have multi ple modali ties.  If  it does, o ne or more  of them
  324                                      // might  be on the  emptyStud yModality  list indic ating ther e are no i mages for  that
  325                                      // modal ity.  But  if there i s a modali ty on this  list and  one that i s not on t his list
  326                                      // in a  single stu dy, then t here shoul d be image s in the s tudy and t he empty m odality
  327                                      // shoul d be ignor ed
  328                                      
  329                                      boolean  emptyStudy ModalityFo und = fals e;
  330                                      boolean  nonEmptySt udyModalit yFound = f alse;
  331                                      for(int  i = 0; i <  modalitie s.length;  i++) 
  332                                      {
  333                                               study.addM odality(mo dalities[i ]);
  334                                               // JMW 1/1 1/2010 P10 4 - specia l case for  PR modali ty studies
  335                                               // these s tudies hav e no image , set the  image coun t to 0 reg ardless of  what the  BIA says
  336                                               // JMW 4/1 1/2011 P10 4
  337                                               boolean th isModality EmptyStudy Found = fa lse;
  338                                               for(String  emptyStud yModality  : emptyStu dyModaliti es)
  339                                               {
  340                                                       if (modalitie s[i].equal s(emptyStu dyModality ))
  341                                                       {
  342                                                                // f ound a mod ality that  does not  contain an y images
  343                                                                empt yStudyModa lityFound  = true;
  344                                                                this ModalityEm ptyStudyFo und = true ;
  345                                                       }
  346                                               }
  347                                               // JMW 4/1 1/2011 P10 4
  348                                               // if this  specific  modality w as not fou nd to be e mpty, then  at least  one modali ty
  349                                               // in this  study sho uld contai n images
  350                                               if(!thisMo dalityEmpt yStudyFoun d)
  351                                                       no nEmptyStud yModalityF ound = tru e;
  352                                      }
  353                                      // JMW 4 /11/2011 P 104
  354                                      // if th ere is one  or more m odality th at does no t contain  images and  no modali ty 
  355                                      // that  does conta in images  in the stu dy, set th e study to  not have  any images
  356                                      if(empty StudyModal ityFound & & !nonEmpt yStudyModa lityFound)
  357                                      {
  358                                               study.setI mageCount( 0);
  359                                               if(firstIm age != nul l)
  360                                               {
  361                                                       fi rstImage.s etAbsFilen ame("-1");
  362                                                       fi rstImage.s etFullFile name("-1") ;
  363                                                       fi rstImage.s etBigFilen ame("-1");
  364                                               }
  365                                      }
  366                             }
  367                    }                         
  368                    
  369                    if(s tudyType.g etProcedur eCodes() ! = null)
  370                    {
  371                             // The  DoD may p rovide mor e than one  cpt code,  we are on ly going t o grab the  first one
  372                             String  [] cptCod es = study Type.getPr ocedureCod es().getCp tCode();
  373                             if((cp tCodes !=  null) && ( cptCodes.l ength > 0) )
  374                             {
  375                                      study.se tCptCode(c ptCodes[0] );
  376                                      if(cptCo des.length  > 1)
  377                                      {
  378                                               logger.deb ug("Got '"  + cptCode s.length +  "' CPT Co des from D oD");
  379                                               for(String  cptCode :  cptCodes)
  380                                               {
  381                                                       lo gger.debug ("\t" + cp tCode);
  382                                               }
  383                                      }
  384                             }
  385                    }
  386                    logg er.info("  Study '" +  studyIden tifier.toS tring() +  "' is tran slated.");
  387                    
  388                    retu rn study;
  389           }
  390           
  391           /* *
  392            *  In some c ases we ar e seeing s tudies com e back fro m the BIA  that do no t have any  images in  them.
  393            *  Most of t hese are f rom Landst uhl.  The  CVIX in Fe deration V 4 and the  Clinical D isplay cli ent both
  394            *  do not ha ndle a nul l first im age in the  study.  T o fix this  issue we  create a " fake" imag e for the  first
  395            *  image fie ld but it  is not act ually incl uded in th e study
  396            *  @param st udy
  397            *  @return
  398            * /
  399           pr ivate stat ic Image c reatedCann edFirstIma ge(Study s tudy, Arti factSource  artifactS ource)
  400           {
  401                    Imag eURN image Urn = null ;
  402                    Stud yURN study Urn = stud y.getStudy Urn();                  
  403                    
  404                    try
  405                    {
  406                             
  407                             String Builder fa keBhieUrn  = new Stri ngBuilder( );
  408                             fakeBh ieUrn.appe nd("urn:") ;
  409                             fakeBh ieUrn.appe nd(BhieIma geURN.getM anagedName space().ge tNamespace ());
  410                             fakeBh ieUrn.appe nd(":");
  411                             fakeBh ieUrn.appe nd("fakeIm age");
  412                             
  413                             imageU rn = URNFa ctory.crea te(fakeBhi eUrn.toStr ing(), Ima geURN.clas s);
  414                             imageU rn.setStud yId(studyU rn==null ?  null : st udyUrn.get StudyId()) ;
  415                             imageU rn.setPati entId(stud y.getPatie ntId());
  416                             imageU rn.setPati entIdentif ierTypeIfN ecessary(s tudy.getPa tientIdent ifierType( ));
  417                             imageU rn.setImag eModality( "");
  418                    }
  419                    catc h (URNForm atExceptio n urnfX)
  420                    {
  421                             logger .error("UR NFormatExc eption mak ing a fake  first ima ge URN for  study '"  + studyUrn .toString( ) + "'", u rnfX);
  422                             return  null;
  423                    }
  424                    
  425                    Imag e image =  Image.crea te(imageUr n);
  426                    imag e.setAbsFi lename("-1 ");
  427                    imag e.setFullF ilename("- 1");
  428                    imag e.setBigFi lename("-1 ");
  429                    imag e.setImage Number("") ;
  430                    imag e.setImage Uid("");
  431                    imag e.setDescr iption(stu dy.getDesc ription()) ;
  432                    //im age.setPat ientName(s tudyType.g etPatientN ame());
  433                    imag e.setPatie ntName(stu dy.getPati entName()) ;
  434                    imag e.setProce dureDate(s tudy.getPr ocedureDat e());
  435                    imag e.setProce dure(study .getProced ure());
  436                    
  437                    //im age.setSit eAbbr(stud yType.getS iteAbbrevi ation());
  438                    if(  WellKnownO ID.BHIE_RA DIOLOGY.is Applicable (imageUrn. getHomeCom munityId() ) ||
  439                             WellKn ownOID.HAI MS_DOCUMEN T.isApplic able(image Urn.getHom eCommunity Id()) )
  440                    {
  441                             image. setSiteAbb r("DOD");  // needed  because CP S test rig  no longer  passes us  useful in formation
  442                             image. setObjectO rigin(Obje ctOrigin.D OD);
  443                    }
  444                    else  
  445                    {
  446                             if(art ifactSourc e instance of Site)
  447                                      image.se tSiteAbbr(  ((Site)ar tifactSour ce).getSit eAbbr() );
  448                             image. setObjectO rigin(Obje ctOrigin.V A);
  449                    }
  450                    
  451                    //im age.setSit eNumber(st udyType.ge tSiteNumbe r());
  452                    //im age.setSit eNumber(si te.getSite Number());
  453                    imag e.setAlien SiteNumber (study.get AlienSiteN umber());
  454                    imag e.setFullL ocation("A ");
  455                    imag e.setAbsLo cation("M" );
  456                    imag e.setDicom ImageNumbe rForDispla y("");
  457                    imag e.setDicom SequenceNu mberForDis play("");
  458                    imag e.setImgTy pe(VistaIm ageType.DI COM.getIma geType());  // radiol ogy
  459                    
  460                    retu rn image;
  461                    
  462                    
  463           }
  464           
  465           pr ivate stat ic Series  translate(
  466                             gov.va .med.imagi ng.mix.web services.r est.types. v1.SeriesT ype series Type,
  467                             Study  study,
  468                             Site s ite) 
  469           {
  470                    logg er.debug("     Transl ate Series  ...");
  471                    if(s eriesType  == null ||  study ==  null || si te == null )
  472                    {
  473                             logger .warn("Tra nslate(Ser iesType, S tudy, Site ) called w ith " + 
  474                                      seriesTy pe == null  ? "null s eries" : " " + 
  475                                      study ==  null ? "n ull study  " : "" +
  476                                      site ==  null ? "nu ll site "  : "");
  477                             return  null;
  478                    }
  479                    logg er.debug("     Creati ng new Ser ies ...");
  480                    Seri es series  = Series.c reate(
  481                             Exchan geUtil.isS iteDOD(sit e) ? Objec tOrigin.DO D : Object Origin.VA,  
  482                             series Type.getSe riesId(), 
  483                             series Type.getDi comUid()
  484                    );
  485                    seri es.setSeri esNumber(s eriesType. getDicomSe riesNumber () == null  ? "" : se riesType.g etDicomSer iesNumber( ) + "");
  486                    logg er.debug("         Se ries Numbe r   = " +  series.get SeriesNumb er());
  487                    if ( series.get SeriesNumb er() == "" )
  488                             series .setSeries Ien("1");
  489                    else
  490                             series .setSeries Ien(series .getSeries Number());
  491                    logg er.debug("         Se ries IEN       = " +  series.get SeriesIen( ));
  492                    seri es.setSeri esUid(seri esType.get DicomUid()  == null ?  "" : seri esType.get DicomUid() );
  493                    logg er.debug("         Se ries UID       = " +  series.get SeriesUid( ));
  494                    seri es.setModa lity(serie sType.getM odality()) ;
  495                    logg er.debug("         Se ries Modal ity = " +  series.get Modality() );
  496                    
  497                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Insta nceType []  instances  = 
  498                             series Type.getCo mponentIns tances().g etInstance ();
  499                    if(i nstances ! = null) {
  500                             for(in t i = 0; i  < instanc es.length;  i++) {
  501                                      logger.d ebug("         Series  - transla ting Image [" + (i+1)  + "] ..." );
  502                                      Image im age = tran slate(inst ances[i],  site, stud y, series) ;
  503                                      series.a ddImage(im age);
  504                                      logger.d ebug("         Series  - added I mage[" + ( i+1) + "]. ");
  505                             }
  506                    }
  507                    logg er.debug("     Transl ated Serie s!");
  508                    retu rn series;
  509           }
  510           
  511           pr ivate stat ic Image t ranslate(
  512                             gov.va .med.imagi ng.mix.web services.r est.types. v1.Instanc eType inst ance,
  513                             Artifa ctSource a rtifactSou rce,
  514                             Study  study,
  515                             Series  series) 
  516           {
  517                    logg er.debug("                 Trans late Image  ...");
  518                    if(i nstance ==  null || s eries == n ull || stu dy == null )
  519                    {
  520                             logger .warn("Nul l Instance Type, Seri es or Stud y paramete r passed t o transfro mImage()." );
  521                             return  null;
  522                    }
  523                    
  524                    Imag eURN image Urn = null ;
  525                    Stud yURN study Urn = stud y.getStudy Urn();                  
  526                    logg er.debug("                 Insta nce ImageU RN = " + i nstance.ge tImageUrn( ));
  527                    
  528                    try
  529                    {
  530                             imageU rn = URNFa ctory.crea te(instanc e.getImage Urn(), Ima geURN.clas s);
  531                             imageU rn.setStud yId(studyU rn==null ?  null : st udyUrn.get StudyId()) ;
  532                             imageU rn.setPati entId(stud y.getPatie ntId());
  533                             imageU rn.setPati entIdentif ierTypeIfN ecessary(s tudy.getPa tientIdent ifierType( ));
  534                             imageU rn.setImag eModality( series.get Modality()  == null ?  "" : seri es.getModa lity());
  535                    }
  536                    catc h (URNForm atExceptio n urnfX)
  537                    {
  538                             logger .error("Er ror making  URN from  image ID ' " + instan ce.getImag eUrn() + " '", urnfX) ;
  539                             return  null;
  540                    }
  541                    logg er.debug("                 Image URN = " +  imageUrn);
  542                    
  543                    //St ring image Id = Base3 2Conversio nUtility.b ase32Encod e(instance .getImageU rn());
  544                    Imag e image =  null;
  545                    // s ite.getSit eNumber(),  imageId,  studyType. getStudyId (), studyT ype.getPat ientId(),  seriesType .getModali ty()
  546                    imag e = Image. create(ima geUrn);
  547                    
  548                    imag e.setImage Number(ins tance.getD icomInstan ceNumber()  + "");
  549                    //im age.setIen (instance. getImageId ());
  550                    imag e.setImage Uid(instan ce.getDico mUid() ==  null ? ""  : instance .getDicomU id());
  551                    imag e.setDescr iption(stu dy.getDesc ription()) ;
  552                    //im age.setPat ientName(s tudyType.g etPatientN ame());
  553                    imag e.setPatie ntName(stu dy.getPati entName()) ;
  554                    imag e.setProce dureDate(s tudy.getPr ocedureDat e());
  555                    imag e.setProce dure(study .getProced ure());
  556                    
  557                    imag e.setSiteA bbr(study. getSiteAbb r());
  558                    if(s tudy.getSt udyUrn().t oString(). contains(" :200")) //  instanceo f BhieStud yURN)
  559   //               if(  WellKnownO ID.BHIE_RA DIOLOGY.is Applicable (imageUrn. getHomeCom munityId() ) ||
  560   //                        WellKn ownOID.HAI MS_DOCUMEN T.isApplic able(image Urn.getHom eCommunity Id()) )
  561                    {
  562                             image. setSiteAbb r("DOD");  // needed  because CP S test rig  no longer  passes us  useful in formation
  563                             image. setObjectO rigin(Obje ctOrigin.D OD);
  564                    }
  565                    else  
  566                    {
  567                             if(art ifactSourc e instance of Site)
  568                                      image.se tSiteAbbr(  ((Site)ar tifactSour ce).getSit eAbbr() );
  569                             image. setObjectO rigin(Obje ctOrigin.V A);
  570                    }
  571                    
  572                    //im age.setSit eNumber(st udyType.ge tSiteNumbe r());
  573                    //im age.setSit eNumber(si te.getSite Number());
  574                    imag e.setAlien SiteNumber (study.get AlienSiteN umber());
  575                    imag e.setFullL ocation("A ");
  576                    imag e.setAbsLo cation("M" );
  577                    imag e.setDicom ImageNumbe rForDispla y(instance .getDicomI nstanceNum ber() == n ull ? "" :  instance. getDicomIn stanceNumb er() + "") ;
  578                    imag e.setDicom SequenceNu mberForDis play(serie s.getSerie sNumber()) ;
  579                    imag e.setImgTy pe(VistaIm ageType.DI COM.getIma geType());  // radiol ogy
  580                    
  581                    logg er.debug("                 Trans lated Imag e!");
  582                    retu rn image;
  583           }
  584           
  585           pr ivate stat ic Date tr anslateDIC OMDateToDa te(String  dicomDate)
  586           {
  587                    if(( dicomDate  == null) | | (dicomDa te.equals( ""))) {
  588                             return  null;// D ate();
  589                    }
  590                    if(d icomDate.l ength() <  8) {
  591                             return  null;
  592                    }
  593                    
  594                    //TO DO: update  this func tion to ha ndle if on ly part of  the date  is given ( no month,  etc)
  595                    //TO DO: month  and day ar e now requ ired, do a  check for  length an d parse on  that
  596                    //TO DO: if the  date is i nvalid, sh ould this  throw an e xception o r always g et full li st of stud ies?
  597                    //St ring dicom Date = "20 0610181436 43.655321+ 0200";
  598                    //Si mpleDateFo rmat sdf =  new Simpl eDateForma t("yyyyMMd dHHmmss",  Locale.US) ;
  599                    
  600                    Stri ng format  = getDateF ormat(dico mDate);
  601                    if(" ".equals(f ormat))
  602                             return  null;
  603                    //Si mpleDateFo rmat sdf =  new Simpl eDateForma t("yyyyMMd d", Locale .US);
  604                    Simp leDateForm at sdf = n ew SimpleD ateFormat( format, Lo cale.US);
  605                    Date  d = null;
  606                    try 
  607                    {
  608                             d = sd f.parse(di comDate);
  609                             return  d;
  610                    }
  611                    catc h(ParseExc eption pX)  {
  612                             logger .error(pX) ;
  613                             return  null;    
  614                    }
  615           }
  616           
  617           /* *
  618            *  Determine s the stri ng format  of the dat e based on  the lengt h of the d ate. Assum es date is  in a DICO M format b ut not sur e how many  levels of  precision  it contai ns
  619            *  @param da te DICOM d ate with u nknown amo unt of pre cision
  620            *  @return A  formatter  string fo r parsing  the date 
  621            * /
  622           pr ivate stat ic String  getDateFor mat(String  date) {
  623                    if(d ate == nul l)
  624                             return  "";
  625                    swit ch(date.le ngth()) {
  626                             case 4 :
  627                                      return " yyyy";
  628                             case 6 :
  629                                      return " yyyyMM";
  630                             case 8 :
  631                                      return " yyyyMMdd";
  632                             case 1 0:
  633                                      return " yyyyMMddHH ";
  634                             case 1 2:
  635                                      return " yyyyMMddHH mm";
  636                             case 1 4:
  637                                      return " yyyyMMddHH mmss";
  638                             defaul t:
  639                                      return " yyyyMMddHH mmss";                                   
  640                    }                         
  641           }
  642           
  643           /* *
  644            *  Translate  Date into  a JSON fo rmatted St ring date[ Time].
  645            *  
  646            *  @param da te
  647            *  @return
  648            *  @throws P arseExcept ion
  649            * /
  650           pu blic stati c String t ranslateDa teToJSON(D ate date) 
  651   //      th rows Parse Exception
  652           {  // TODO ma ke this re ally produ ce yyyy-MM -ddTHH:MI: SS+HH:MI ( UTC time)
  653                    Stri ng dateStr ingAsJSON  = "";
  654                    if ( date!=null
  655                    {
  656                             DateFo rmat jsonD ate = new  SimpleDate Format("yy yy-MM-dd'T 'HH:mm:ssZ "); // yyy y-MM-dd'T' HH:mm:ss.S SSZ
  657                             dateSt ringAsJSON  = jsonDat e.format(d ate);
  658                             // thi s produces  'yyyy-MM- ddTHH:mm:s s+HHmm' or  '...-HHmm ' --> 24 c hars
  659                             // ins ert ':' to  UTC part
  660                             if (da teStringAs JSON.lengt h()==24) {
  661                                      String b eg = dateS tringAsJSO N.substrin g(0,22);
  662                                      String e nd = dateS tringAsJSO N.substrin g(22,24);
  663                                      dateStri ngAsJSON =  beg + ":"  + end;
  664                             }
  665                    }
  666                    retu rn dateStr ingAsJSON;
  667           }
  668  
  669           /* *
  670            *  Translate  a DICOM s tyle Strin g date int o a JSON f ormatted S tring date .
  671            *  
  672            *  @param da teString
  673            *  @return
  674            *  @throws P arseExcept ion
  675            * /
  676           pu blic stati c String t ranslateDa teToJSON(S tring date String) 
  677           th rows Parse Exception
  678           {
  679                    Stri ng dateStr ingAsJSON  = "";
  680                    if ( dateString  != null)
  681                    {
  682                             String  trimmedDa teString =  dateStrin g.trim();
  683                             if (tr immedDateS tring.leng th() > 0)
  684                             {
  685                                      DicomDat eFormat di comDateFor mat = new  DicomDateF ormat();
  686                                      // post  patch 59 d ates inclu de time-of -day segme nt
  687                                      DateForm at jsonDat eFormat =  new Simple DateFormat ("yyyy-MM- dd'T'HH:mm :ssZ"); 
  688                                      Date dat e = dicomD ateFormat. parse(trim medDateStr ing);
  689                                      dateStri ngAsJSON =  jsonDateF ormat.form at(date);
  690                             }
  691                    }
  692                    retu rn dateStr ingAsJSON;
  693           }
  694  
  695           pr ivate stat ic List<Ar tifactResu ltError> t ranslate(g ov.va.med. imaging.mi x.webservi ces.rest.t ypes.v1.Er rorResultT ype [] err ors)
  696           {
  697                    if(e rrors == n ull)
  698                             return  null;
  699                    List <ArtifactR esultError > result =  new Array List<Artif actResultE rror>();
  700                    
  701                    for( gov.va.med .imaging.m ix.webserv ices.rest. types.v1.E rrorResult Type error  : errors)
  702                    {
  703                             result .add(trans late(error ));
  704                    }                 
  705                    
  706                    retu rn result;
  707           }
  708           
  709           pr ivate stat ic Artifac tResultErr or transla te(gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.ErrorRes ultType er ror)
  710           {
  711                    Arti factResult ErrorCode  errorCode  = translat e(error.ge tErrorCode ());
  712                    Arti factResult ErrorSever ity severi ty = trans late(error .getSeveri ty()); 
  713                    retu rn new Mix ArtifactRe sultError( error.getC odeContext (), error. getLocatio n(), 
  714                                      errorCod e, severit y);
  715           }
  716           
  717           pu blic stati c gov.va.m ed.imaging .mix.webse rvices.res t.types.v1 .FilterTyp e translat e(StudyFil ter studyF ilter)
  718           {
  719                    Stud yURN study Urn = (Stu dyURN)stud yFilter.ge tStudyId() ;
  720                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Filte rType ft =  studyFilt er == null  ? 
  721                                      new gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Filte rType() : 
  722                                      new gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Filte rType(
  723                                                       st udyFilter. getFromDat e() == nul l ? null :  DateUtil. getDicomDa teFormat() .format(st udyFilter. getFromDat e()), 
  724                                                                         studyF ilter.getT oDate() ==  null ? nu ll : DateU til.getDic omDateForm at().forma t(studyFil ter.getToD ate()), 
  725                                               studyUrn = = null ? n ull : stud yUrn.toStr ing(SERIAL IZATION_FO RMAT.NATIV E));
  726                                      return f t;
  727           }
  728           
  729           pu blic stati c gov.va.m ed.imaging .mix.webse rvices.res t.types.v1 .ReportStu dyListResp onseType t ranslate(
  730                             StudyS etResult s tudySetRes ult)
  731           th rows Trans lationExce ption
  732           {
  733                    if(s tudySetRes ult == nul l)
  734                             return  null;
  735                    // c onsistent  with V1 tr anslator
  736                    if(( studySetRe sult.getAr tifacts()  == null) | | (studySe tResult.ge tArtifacts ().size()  == 0))
  737                             return  null;
  738                    
  739                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Repor tStudyList ResponseTy pe result 
  740                             new go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Rep ortStudyLi stResponse Type();
  741                    
  742                    resu lt.setPart ialRespons e(studySet Result.isP artialResu lt());
  743                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Study Type [] st udyTypes =  
  744                             transl ate(studyS etResult.g etArtifact s());
  745                    logg er.info("T ranslated  studies in to '" + (s tudyTypes  == null ?  "null" : s tudyTypes. length) +  "' study t ypes to re turn in Ex change int erface");
  746                    resu lt.setStud ies(studyT ypes);
  747                    resu lt.setErro rs(transla te(studySe tResult.ge tArtifactR esultError s()));
  748                    
  749                    retu rn result;
  750           }
  751           
  752           pu blic stati c Diagnost icReport[]  convertSt udies(Stud ySetResult  studySetR esult)
  753           th rows Trans lationExce ption
  754           {
  755                    if(s tudySetRes ult == nul l)
  756                             return  null;
  757                    // c onsistent  with V1 tr anslator
  758                    if(( studySetRe sult.getAr tifacts()  == null) | | (studySe tResult.ge tArtifacts ().size()  == 0))
  759                             return  null;
  760                    
  761                    List  <Diagnost icReport>  dRs = null ;
  762                             
  763                    // r esult.setP artialResp onse(study SetResult. isPartialR esult());
  764                    dRs  = groupStu diesByRepo rt(studySe tResult.ge tArtifacts ());
  765  
  766                    int  numAllStud ies = 0;
  767                    if ( (dRs != nu ll) && (dR s.size() >  0))
  768                    {
  769                             for(Di agnosticRe port dR :  dRs)
  770                             {
  771                                      numAllSt udies += d R.getShall owStudy(). length;
  772                             }
  773                    }
  774                    logg er.info("T ranslated  '" + numAl lStudies +  "' studie s into '"  + ((dRs ==  null) ? " 0" : dRs.s ize()) + " ' Diagnost icReport g roup(s) to  return in  MIX inter face");
  775                    // r esult.addS hallowStud ies(Shallo wStudies);
  776                    // r esult.setE rrors(tran slate(stud ySetResult .getArtifa ctResultEr rors()));
  777                    
  778                    // c onvert Lis t to array
  779                    Diag nosticRepo rt[] dRArr ay = new D iagnosticR eport[dRs. size()];
  780                    for  (int i=0;  i<dRs.size (); i++) {
  781                             dRArra y[i] = dRs .get(i);
  782                    }
  783                    retu rn dRArray ;
  784           }
  785           pr ivate stat ic gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.ErrorRes ultType[]  translate(
  786                             List<A rtifactRes ultError>  artifactRe sultErrors )
  787           {
  788                    if(a rtifactRes ultErrors  == null)
  789                             return  null;
  790                    
  791                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Error ResultType  []result  =
  792                             new go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Err orResultTy pe[artifac tResultErr ors.size() ];
  793                    
  794                    int  i = 0;
  795                    for( ArtifactRe sultError  artifactRe sultError  : artifact ResultErro rs)
  796                    {
  797                             result [i] = tran slate(arti factResult Error);
  798                             i++;
  799                    }
  800                    
  801                    retu rn result;
  802           }
  803           
  804           pr ivate stat ic gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.ErrorRes ultType tr anslate(
  805                             Artifa ctResultEr ror artifa ctResultEr ror)
  806           {
  807                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Error ResultType  result = 
  808                             new go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Err orResultTy pe();
  809                    
  810                    resu lt.setCode Context(ar tifactResu ltError.ge tCodeConte xt());
  811                    resu lt.setLoca tion(artif actResultE rror.getLo cation());
  812                    resu lt.setErro rCode(tran slate(arti factResult Error.getE rrorCode() ));
  813                    resu lt.setSeve rity(trans late(artif actResultE rror.getSe verity())) ;
  814                    
  815                    retu rn result;
  816           }
  817           
  818           pr ivate stat ic Artifac tResultErr orCode tra nslate(gov .va.med.im aging.mix. webservice s.rest.typ es.v1.Erro rCodeType  errorCodeT ype)
  819           {
  820                    for( Entry<Arti factResult ErrorCode,  gov.va.me d.imaging. mix.webser vices.rest .types.v1. ErrorCodeT ype> entry  : errorCo deMap.entr ySet())
  821                    {
  822                             if(ent ry.getValu e() == err orCodeType )
  823                                      return e ntry.getKe y();
  824                    }
  825                    retu rn Artifac tResultErr orCode.int ernalExcep tion;
  826           }
  827           
  828           pr ivate stat ic gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.ErrorCod eType tran slate(Arti factResult ErrorCode  artifactRe sultErrorC ode)
  829           {
  830                    for( Entry<Arti factResult ErrorCode,  gov.va.me d.imaging. mix.webser vices.rest .types.v1. ErrorCodeT ype> entry  : errorCo deMap.entr ySet())
  831                    {
  832                             if(ent ry.getKey( ) == artif actResultE rrorCode)
  833                                      return e ntry.getVa lue();
  834                    }
  835                    retu rn gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.ErrorCod eType.Inte rnalExcept ion;
  836           }
  837           
  838           pr ivate stat ic gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.Severity Type trans late(Artif actResultE rrorSeveri ty artifac tResultErr orSeverity )
  839           {
  840                    for( Entry<Arti factResult ErrorSever ity, gov.v a.med.imag ing.mix.we bservices. rest.types .v1.Severi tyType> en try : seve rityMap.en trySet())
  841                    {
  842                             if(ent ry.getKey( ) == artif actResultE rrorSeveri ty)
  843                             {
  844                                      return e ntry.getVa lue();
  845                             }
  846                    }
  847                    retu rn gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.Severity Type.error ;
  848           }
  849           
  850           pr ivate stat ic Artifac tResultErr orSeverity  translate (gov.va.me d.imaging. mix.webser vices.rest .types.v1. SeverityTy pe severit yType)
  851           {
  852                    for( Entry<Arti factResult ErrorSever ity, gov.v a.med.imag ing.mix.we bservices. rest.types .v1.Severi tyType> en try : seve rityMap.en trySet())
  853                    {
  854                             if(ent ry.getValu e() == sev erityType)
  855                             {
  856                                      return e ntry.getKe y();
  857                             }
  858                    }
  859                    retu rn Artifac tResultErr orSeverity .error;
  860           }
  861           
  862           pr ivate stat ic gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.StudyTyp e [] trans late(Sorte dSet<Study > studies)
  863           th rows Trans lationExce ption
  864           {
  865                    // n ot all stu dies in th e result m ight be in cluded (de leted or e rror studi es are not  included)
  866                    
  867                    List <gov.va.me d.imaging. mix.webser vices.rest .types.v1. StudyType>  result = 
  868                             new Ar rayList<go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Stu dyType>();
  869                    
  870                    for( Study stud y : studie s)
  871                    {
  872                             gov.va .med.imagi ng.mix.web services.r est.types. v1.StudyTy pe studyTy pe = trans late(study );
  873                             if(stu dyType !=  null)
  874                                      result.a dd(studyTy pe);
  875                    }
  876                    
  877                    retu rn result. toArray(ne w gov.va.m ed.imaging .mix.webse rvices.res t.types.v1 .StudyType [result.si ze()]);
  878           }
  879           
  880           //  processSt udy: 
  881           //  if no mat ching repo rt, make n ew dR with  shallowSt udy, popul ate dR fie lds,
  882           //  on dR fou nd add new  shallowSt udy only
  883           pr ivate stat ic void pr ocessStudy (List <Dia gnosticRep ort> dRs,  Study stud y)
  884           th rows Trans lationExce ption
  885           {
  886                    // l ook for ex isting dR
  887                    bool ean isNewD R = true;
  888                    Diag nosticRepo rt theDR=n ull;
  889                    Date  issued =  null;
  890                    Stri ng id = "" ;
  891                    Stri ng theRepo rt = "";
  892                    if ( study.getR adiologyRe port()!=nu ll) {
  893                             id= In teger.toHe xString(st udy.getRad iologyRepo rt().hashC ode());
  894                             issued  = study.g etDocument Date();
  895                             theRep ort = stud y.getRadio logyReport ();
  896                    }
  897                    for( Diagnostic Report dR  : dRs)
  898                    {         
  899                             if (dR .getId().e quals(id))  {
  900                                      theDR =  dR;
  901                                      isNewDR  = false;
  902                                      break;
  903                             }
  904                    }
  905                    if ( theDR == n ull) { //  isNewDR
  906                             // dR  not found  -->  creat e one, and  populate  content
  907                             theDR= new Diagno sticReport ();
  908  
  909                             theDR. setId(id);
  910                             
  911                             String  escapedRe port=""; / / empty re port
  912                             if (!t heReport.i sEmpty())  {
  913                                      escapedR eport = es capeHtml(t heReport);  // make s ure ", &,  <, > are e scaped
  914                                      escapedR eport.repl ace(" ", " %20"); //  make sure  spaces are  escaped t oo
  915                             }
  916                             TextTy pe text =  new TextTy pe("additi onal", "<d iv>" + esc apedReport  + "</div> ");
  917                             theDR. setText(te xt);
  918  
  919                             // [{\ "code\": [ {\"coding\ ": {\"syst em\": \"ht tp://hl7.o rg/fhir/v2 /0074/\",  \"code\":\ "" + categ ory + "\"} ]]
  920                             Coding Type codin g = new Co dingType(" http://hl7 .org/fhir/ v2/0074/",  "RAD", nu ll); // TO DO set pro per code w hen specia lty is dif ferent!
  921                             Coding Type[] cod ingArray =  new Codin gType[1];
  922                             coding Array[0] =  coding;
  923                             CodeTy pe code =  new CodeTy pe(codingA rray);
  924                             theDR. setCategor y(code); 
  925                             
  926                             // [{\ "code\": [ {\"coding\ ": {\"syst em\": \"ht tp://www.a ma-assn.or g/go/cpt/\ ", \"code\ ":\"" + co de + "\",  \"display\ ": \"Radio logy Repor t\"}]
  927                             Coding Type codin g2 = new C odingType( "http://ww w.ama-assn .org/go/cp t/", study .getCptCod e(), "Radi ology Repo rt"); // T ODO set pr oper code  when speci alty is di fferent!
  928                             Coding Type[] cod ingArray2  = new Codi ngType[1];
  929                             coding Array2[0]  = coding2;
  930                             CodeTy pe code2 =  new CodeT ype(coding Array2);
  931                             theDR. setCode(co de2);
  932                             
  933                             Refere nceType su bject = ne w Referenc eType("Pat ient/"+stu dy.getPati entId());
  934                             theDR. setSubject (subject);
  935                             
  936   //                        try {
  937   //                                 theDR.se tEffective DateTime(t ranslateDa teToJSON(s tudy.getPr ocedureDat eString()) );
  938   //                                 theDR.se tIssued(tr anslateDat eToJSON(st udy.getPro cedureDate String())) ;
  939   //                        }
  940   //                        catch  (ParseExce ption pe)  {
  941   //                                 throw ne w Translat ionExcepti on("Unable  to parse  study proc edure date , " + pe.g etMessage( ), pe);
  942   //                        }
  943                             theDR. setEffecti veDateTime (translate DateToJSON (study.get ProcedureD ate()));
  944                             theDR. setIssued( translateD ateToJSON( issued));
  945                             
  946                             Refere nceType pe rformer =  new Refere nceType("O rganizatio n/VHA"); / / agreed u pon as VHA  or DOD
  947                             theDR. setPerform er(perform er);
  948                    }
  949                    
  950                    Shal lowStudy s hallowStud y = conver tShallowSt udy(study) ;
  951                    if(s hallowStud y != null)
  952                             theDR. addShallow Study(shal lowStudy);
  953                    
  954                    if ( isNewDR)
  955                             dRs.ad d(theDR);
  956           }
  957           
  958           //  Loop thro ugh studie s and crea ted DR wit h shallow  studies st ructure --  sorted: l atest stud y (procedu reDate) fi rst
  959           pr ivate stat ic List<Di agnosticRe port> grou pStudiesBy Report(Sor tedSet<Stu dy> studie s)
  960           th rows Trans lationExce ption
  961           {
  962                    // n ot all stu dies in th e result m ight be in cluded (de leted or e rror studi es are not  included)
  963                    List  <Diagnost icReport>  dRs = null
  964                    
  965                    for( Study stud y : studie s)
  966                    {
  967                             if (dR s==null) 
  968                                      dRs = ne w ArrayLis t<Diagnost icReport>( );
  969           
  970                             proces sStudy(dRs , study);
  971                    }
  972                    
  973                    retu rn dRs; //  .toArray( new gov.va .med.imagi ng.mix.web services.f hir.types. v1.Shallow Study[resu lt.size()] );
  974           }
  975           
  976           pr ivate stat ic gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.StudyTyp e translat e(Study st udy)
  977           th rows Trans lationExce ption
  978           {
  979                    if(s tudy == nu ll)
  980                             return  null;
  981                    // d on't retur n the stud y if there  is a ques tionable i ntegrity/e rror condi tion
  982                    if(s tudy.hasEr rorMessage ())
  983                    {
  984                             logger .debug("St udy [" + s tudy.getSt udyIen() +  "] has er ror messag e, excludi ng from re sults.");
  985                             return  null;
  986                    }
  987                    if(s tudy.isDel eted())
  988                    {
  989                             logger .debug("St udy [" + s tudy.getSt udyIen() +  "] is del eted, excl uding from  results." );
  990                             return  null;
  991                    }
  992                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Study Type resul t = 
  993                             new go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Stu dyType();
  994                    
  995                    Stud yURN study URN = stud y.getStudy Urn();
  996                    
  997                    resu lt.setStud yId( study URN.toStri ng() );
  998                    resu lt.setDesc ription(st udy.getDes cription() );
  999                    resu lt.setProc edureCodes (translate CptCodeToS tudyProced ureCode(st udy.getCpt Code()));
  1000                    try
  1001                    {
  1002                    resu lt.setProc edureDate( translate( study.getP rocedureDa te()));
  1003                    }
  1004                    catc h(ParseExc eption pX)
  1005                    {
  1006                             throw  new Transl ationExcep tion("Unab le to pars e study pr ocedure da te, " + pX .getMessag e(), pX);
  1007                    }
  1008                    
  1009                    resu lt.setProc edureDescr iption(stu dy.getProc edure());
  1010                    resu lt.setPati entId(stud y.getPatie ntId());
  1011                    resu lt.setPati entName(st udy.getPat ientName() );
  1012                    resu lt.setSite Number(stu dy.getSite Number());
  1013                    resu lt.setSite Abbreviati on(study.g etSiteAbbr ());
  1014                    resu lt.setSpec ialtyDescr iption(stu dy.getSpec ialty());
  1015                    resu lt.setRepo rtContent( study.getR adiologyRe port()); / / added fo r MIX
  1016                    resu lt.setSite Name(study .getSiteNa me());
  1017                    
  1018                    // r eturn null  for the U ID instead  of the em pty string  to be con sistent wi th the WSD L - DKB; * ** check f or MIX!
  1019                    if ( study.getS tudyUid()  != null &&  study.get StudyUid() .trim().le ngth() > 0 )
  1020                    {
  1021                             result .setDicomU id(study.g etStudyUid ());
  1022                    }
  1023                    
  1024                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Study TypeCompon entSeries  wrapper = 
  1025                             new go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Stu dyTypeComp onentSerie s();
  1026                    
  1027                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Serie sType[] co mponentSer ies = 
  1028                             transl ate(study. getSeries( ), study);
  1029  
  1030                    // J MW 7/16/08  accuratel y get the  number of  images by  actually c ounting th e images f rom each
  1031                    // s eries
  1032                    // T his has to  be done t his way be cause whil e the inte rnal count  of images  is now ac curate, 
  1033                    // w e might no t give all  of the in ternal ima ges throug h this int erface, th is interfa ce exclude s
  1034                    // a ll questio nable inte grity imag es and stu dies/image s with oth er problem s.
  1035                    int  imageCount  = 0;
  1036                    for( gov.va.med .imaging.m ix.webserv ices.rest. types.v1.S eriesType  series : c omponentSe ries)
  1037                    {
  1038                             imageC ount += se ries.getIm ageCount() ;
  1039                    }
  1040                    resu lt.setImag eCount(ima geCount);
  1041                    
  1042                    // s eries with  no instan ces will b e suppress ed, so the  only way  to know th e correct
  1043                    // s eries coun t is to us e the leng th of the  returned a rray - DKB
  1044                    resu lt.setSeri esCount(co mponentSer ies.length );
  1045                    
  1046                    wrap per.setSer ies(compon entSeries) ;
  1047                    resu lt.setComp onentSerie s(wrapper) ;
  1048                    
  1049                    if(s tudy.getMo dalities()  != null)
  1050                    {
  1051                             String  modalitie s[] = new  String[stu dy.getModa lities().s ize()];
  1052                             int i  = 0;
  1053                             for(St ring modal ity : stud y.getModal ities())
  1054                             {
  1055                                      modaliti es[i] = mo dality;
  1056                                      i++;
  1057                             }
  1058                             gov.va .med.imagi ng.mix.web services.r est.types. v1.Modalit iesType mo dalitiesTy pe = 
  1059                                      new gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Modal itiesType( modalities );
  1060                             result .setModali ties(modal itiesType) ;
  1061                    }
  1062                    
  1063                    retu rn result;
  1064           }
  1065           
  1066           pr ivate stat ic gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.ShallowS tudy conve rtShallowS tudy(Study  study)
  1067           th rows Trans lationExce ption
  1068           {
  1069                    if(s tudy == nu ll)
  1070                             return  null;
  1071                    // d on't retur n the stud y if there  is a ques tionable i ntegrity/e rror condi tion
  1072                    if(s tudy.hasEr rorMessage ())
  1073                    {
  1074                             logger .debug("St udy [" + s tudy.getSt udyIen() +  "] has er ror messag e, excludi ng from re sults.");
  1075                             return  null;
  1076                    }
  1077                    if(s tudy.isDel eted())
  1078                    {
  1079                             logger .debug("St udy [" + s tudy.getSt udyIen() +  "] is del eted, excl uding from  results." );
  1080                             return  null;
  1081                    }
  1082                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Shall owStudy re sult = 
  1083                             new go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Sha llowStudy( );
  1084                    
  1085                    // c reate a MI X smart st udy URN th at is pass es as stud y UID
  1086                    Stud yURN study URN = stud y.getStudy Urn();
  1087                    VASt udyID vaSt udyID = ne w VAStudyI D();
  1088                    Stri ng theMIXS tudyUid="" ;
  1089                    try  {
  1090                             theMIX StudyUid =  vaStudyID .create(st udyURN.get Originatin gSiteId(),  studyURN. getStudyId (), studyU RN.getPati entId());  // patient ICN !!!
  1091                    }
  1092                    catc h (URNForm atExceptio n ufe) {
  1093                             throw  new Transl ationExcep tion("URN  translatio n exceptio n, " + ufe .getMessag e(), ufe);
  1094                             
  1095                    }
  1096                    resu lt.setUid(  theMIXStu dyUid );
  1097                    resu lt.setProc edure(stud y.getProce dure());
  1098                    resu lt.setStar ted(transl ateDateToJ SON(study. getProcedu reDate())) ; // yyyyM Mddhhmmss. SSSSSS > y yyy-MM-ddT HH:MI+HH:M I !!!
  1099  
  1100                    // g ov.va.med. imaging.mi x.webservi ces.fhir.t ypes.v1.St udyTypeCom ponentSeri es wrapper  = 
  1101                    //       new go v.va.med.i maging.mix .webservic es.fhir.ty pes.v1.Stu dyTypeComp onentSerie s();
  1102                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Serie sType[] co mponentSer ies = 
  1103                             transl ate(study. getSeries( ), study);
  1104  
  1105                    // J MW 7/16/08  accuratel y get the  number of  images by  actually c ounting th e images f rom each
  1106                    // s eries
  1107                    // T his has to  be done t his way be cause whil e the inte rnal count  of images  is now ac curate, 
  1108                    // w e might no t give all  of the in ternal ima ges throug h this int erface, th is interfa ce exclude s
  1109                    // a ll questio nable inte grity imag es and stu dies/image s with oth er problem s.
  1110                    int  imageCount  = 0;
  1111                    for( gov.va.med .imaging.m ix.webserv ices.rest. types.v1.S eriesType  series : c omponentSe ries)
  1112                    {
  1113                             imageC ount += se ries.getIm ageCount() ;
  1114                    }
  1115                    resu lt.setNumb erOfInstan ces(imageC ount);
  1116                    
  1117                    // s eries with  no instan ces will b e suppress ed, so the  only way  to know th e correct
  1118                    // s eries coun t is to us e the leng th of the  returned a rray - DKB
  1119                    resu lt.setNumb erOfSeries (component Series.len gth);
  1120                                      
  1121                    if(s tudy.getMo dalities()  != null)
  1122                    {
  1123                             // [{\ "code\": \ " + modali ty + \"}]
  1124                             int nu mMods = st udy.getMod alities(). size();
  1125  
  1126                             ModCod eType[] mo dCodeArray  = new Mod CodeType[n umMods];
  1127                             
  1128                             int i= 0;
  1129                             for(St ring modal ity : stud y.getModal ities())
  1130                             {
  1131                                      modCodeA rray[i] =  new ModCod eType(moda lity);
  1132                                      i++;
  1133                             }
  1134  
  1135                             result .setModali tiesInStud y(modCodeA rray);
  1136                    }
  1137                    
  1138                    retu rn result;
  1139           }
  1140  
  1141           pr ivate stat ic gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.SeriesTy pe[] trans late(
  1142                             Set<Se ries> seri eses, Stud y study)
  1143           th rows Trans lationExce ption
  1144           {
  1145                    List <gov.va.me d.imaging. mix.webser vices.rest .types.v1. SeriesType > result =  
  1146                             new Ar rayList<go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Ser iesType>() ;
  1147                    
  1148                    for( Series ser ies : seri eses)
  1149                    {
  1150                             // Fil ter series  with no i mages from  the resul t set - DK B
  1151                             if(ser ies.getIma geCount()  > 0)
  1152                             {
  1153                                      gov.va.m ed.imaging .mix.webse rvices.res t.types.v1 .SeriesTyp e seriesTy pe = 
  1154                                               translate( series, st udy);        
  1155                                      if(serie sType != n ull)
  1156                                               result.add (seriesTyp e);
  1157                             }
  1158                    }
  1159                    
  1160                    retu rn result. toArray(ne w gov.va.m ed.imaging .mix.webse rvices.res t.types.v1 .SeriesTyp e[result.s ize()]);
  1161           }
  1162           
  1163           pr ivate stat ic gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.SeriesTy pe transla te(Series  series,
  1164                             Study  study)
  1165           th rows Trans lationExce ption
  1166           {
  1167                    if(s eries == n ull)
  1168                             return  null;
  1169                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Serie sType resu lt = 
  1170                             new go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Ser iesType();
  1171                    
  1172                    List <gov.va.me d.imaging. mix.webser vices.rest .types.v1. InstanceTy pe> validI nstances =  
  1173                             new Ar rayList<go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Ins tanceType> (series.ge tImageCoun t());
  1174                    
  1175                    
  1176                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Insta nceType[]  seriesInst ances = nu ll;
  1177  
  1178                    for( Image imag e : series )
  1179                    {
  1180                             gov.va .med.imagi ng.mix.web services.r est.types. v1.Instanc eType inst anceType =  translate (image);
  1181                             if(ins tanceType  != null)
  1182                                      validIns tances.add (instanceT ype);
  1183                    }
  1184                    seri esInstance s = 
  1185                             validI nstances.t oArray(new  gov.va.me d.imaging. mix.webser vices.rest .types.v1. InstanceTy pe[validIn stances.si ze()]);
  1186                    
  1187                    //TO DO: retrie ve series  through Vi stA if pos sible (ava ilable in  DICOM txt  files)
  1188                    resu lt.setDesc ription(st udy.getDes cription() );
  1189  
  1190                    resu lt.setModa lity(serie s.getModal ity());
  1191                    // r eturn null  for the U ID instead  of the em pty string  to be con sistent wi th the WSD L - DKB
  1192                    if ( series.get SeriesUid( ) != null  && series. getSeriesU id().trim( ).length()  > 0)
  1193                    {
  1194                             result .setDicomU id(series. getSeriesU id());
  1195                    }
  1196                    
  1197                    if(! "".equals( series.get SeriesNumb er())) {
  1198                             int se rNum = Int eger.parse Int(series .getSeries Number());
  1199                             result .setDicomS eriesNumbe r(serNum);
  1200                    }
  1201                    //TO DO: do we  want to ha ve a serie s URN or s hould we j ust use th e series I EN from Vi stA?
  1202                    resu lt.setSeri esId(serie s.getSerie sIen());
  1203                    resu lt.setImag eCount(ser iesInstanc es.length) ;
  1204   //               gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Serie sTypeCompo nentInstan ces instan cesWrapper  = 
  1205   //                        new go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Ser iesTypeCom ponentInst ances();
  1206   //               inst ancesWrapp er.setInst ance(serie sInstances );
  1207   //               resu lt.setComp onentInsta nces(insta ncesWrappe r);
  1208                    
  1209                    retu rn result;
  1210           }
  1211           
  1212           pr ivate stat ic gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.Instance Type trans late(Image  image)
  1213           th rows Trans lationExce ption
  1214           {
  1215                    if(i mage == nu ll)
  1216                             return  null;
  1217                    // J MW 7/17/08  - if the  image has  an error m essage the n don't pr ovide the  image to t he DOD
  1218                    if(i mage.hasEr rorMessage ())
  1219                    {
  1220                             logger .debug("Im age [" + i mage.getIe n() + "] h as error m essage, ex cluding fr om results .");
  1221                             return  null;
  1222                    }
  1223                    if(i mage.isDel eted())
  1224                    {
  1225                             logger .debug("Im age [" + i mage.getIe n() +"] is  deleted,  excluding  from resul ts.");
  1226                             return  null;
  1227                    }
  1228                    
  1229                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Insta nceType in stanceType  = 
  1230                             new go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Ins tanceType( );
  1231                    
  1232                    if(i mage.getGl obalArtifa ctIdentifi er() insta nceof Imag eURN)
  1233                             instan ceType.set ImageUrn(i mage.getGl obalArtifa ctIdentifi er().toStr ing());
  1234                    else  if(image. getGlobalA rtifactIde ntifier()  instanceof  BhieImage URN)
  1235                             instan ceType.set ImageUrn(  ((BhieImag eURN)image .getGlobal ArtifactId entifier() ).toString ());
  1236                    else
  1237                             try
  1238                             {
  1239                                      instance Type.setIm ageUrn( (I mageURNFac tory.creat e(image.ge tSiteNumbe r(), 
  1240                                                       im age.getIen (), image. getStudyIe n(), image .getPatien tId(), ima ge.getImag eModality( ), ImageUR N.class)). toString()  );
  1241                             }
  1242                             catch  (URNFormat Exception  x)
  1243                             {
  1244                                      throw ne w Translat ionExcepti on(x);
  1245                             }
  1246                    
  1247                    // r eturn null  for the U ID instead  of the em pty string  to be con sistent wi th the WSD L - DKB
  1248                    if ( image.getI mageUid()! = null &&  image.getI mageUid(). trim().len gth() > 0)
  1249                    {
  1250                             instan ceType.set DicomUid(i mage.getIm ageUid().t rim());
  1251                    }
  1252                    
  1253                    
  1254                    if ( image.getD icomImageN umberForDi splay()!=  null && im age.getIma geNumber() .trim().le ngth() > 0 )
  1255                    {
  1256                             try
  1257                             {
  1258                                      Integer  imageNumbe r = new In teger(imag e.getImage Number());
  1259                                      instance Type.setDi comInstanc eNumber(im ageNumber) ;
  1260                             }
  1261                             catch  (NumberFor matExcepti on ex)
  1262                             {
  1263                                      // not a  number -  return nul l
  1264                                      instance Type.setDi comInstanc eNumber(nu ll);
  1265                             }
  1266                    }
  1267                    else
  1268                    {
  1269                             instan ceType.set DicomInsta nceNumber( null);
  1270                    }
  1271                    
  1272                    retu rn instanc eType;
  1273           }
  1274           
  1275           pu blic stati c gov.va.m ed.imaging .mix.webse rvices.res t.types.v1 .ReportTyp e translat eToStudyRe port(Study  study)
  1276           th rows Trans lationExce ption
  1277           {
  1278                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Repor tType resu lt = 
  1279                             new go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Rep ortType();
  1280                    
  1281                    resu lt.setPati entId(stud y.getPatie ntId());
  1282                    resu lt.setProc edureCodes (translate CptCodeToR eportProce dureCode(s tudy.getCp tCode()));
  1283                    try
  1284                    {
  1285                             result .setProced ureDate(tr anslate(st udy.getPro cedureDate ()));
  1286                    }
  1287                    catc h(ParseExc eption pX)
  1288                    {
  1289                             throw  new Transl ationExcep tion("Pars eException  unable to  translate  study pro cedure dat e, " + pX. getMessage (), pX);
  1290                    }
  1291                    //TO DO: what t o do if re port is mi ssing or s omething?
  1292                    resu lt.setRadi ologyRepor t(study.ge tRadiology Report());
  1293                    resu lt.setSite Abbreviati on(study.g etSiteAbbr ());
  1294                    resu lt.setSite Name(study .getSiteNa me());
  1295                    resu lt.setSite Number(stu dy.getSite Number());
  1296                    resu lt.setStud yId(study. getStudyUr n().toStri ng());
  1297                    retu rn result;
  1298           }
  1299           
  1300           pr ivate stat ic gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.ReportTy peProcedur eCodes tra nslateCptC odeToRepor tProcedure Code(Strin g cptCode)
  1301           {
  1302                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Repor tTypeProce dureCodes  result = 
  1303                             new go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Rep ortTypePro cedureCode s();
  1304                    
  1305                    Stri ng [] cptC odes = new  String[1] ;
  1306                    
  1307                    // c annot be n ull value  (according  to the WS DL)
  1308                    cptC odes[0] =  (cptCode = = null ? " " : cptCod e);
  1309                    resu lt.setCptC ode(cptCod es);
  1310                    
  1311                    retu rn result;
  1312           }
  1313           
  1314           pr ivate stat ic gov.va. med.imagin g.mix.webs ervices.re st.types.v 1.StudyTyp eProcedure Codes tran slateCptCo deToStudyP rocedureCo de(String  cptCode)
  1315           {                 
  1316                    gov. va.med.ima ging.mix.w ebservices .rest.type s.v1.Study TypeProced ureCodes r esult = 
  1317                             new go v.va.med.i maging.mix .webservic es.rest.ty pes.v1.Stu dyTypeProc edureCodes ();
  1318                    
  1319                    Stri ng [] cptC odes = new  String[1] ;
  1320                    
  1321                    // c annot be n ull value  (according  to the WS DL)
  1322                    cptC odes[0] =  (cptCode = = null ? " " : cptCod e);
  1323                    resu lt.setCptC ode(cptCod es);
  1324                    
  1325                    retu rn result;
  1326           }
  1327           
  1328           pr ivate stat ic String  translate( Date proce dureDate) 
  1329           th rows Parse Exception
  1330           {
  1331                    Stri ng procedu reDateStri ngAsDicom  = "";
  1332                    if(p rocedureDa te != null )
  1333                    {
  1334                             DateFo rmat dicom DateFormat  = new Dic omDateForm at();
  1335                             proced ureDateStr ingAsDicom  = dicomDa teFormat.f ormat(proc edureDate) ;
  1336                    }
  1337                    retu rn procedu reDateStri ngAsDicom;
  1338           }
  1339  
  1340   }