209. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 12/5/2017 12:06:41 PM Central Standard 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.

209.1 Files compared

# Location File Last Modified
1 IV-eHMP_CIF.zip\IMAG_Source\VISA\Java\ImageConversion\main\src\java\gov\va\med\imaging\conversion ImageConversionUtility.java Mon Dec 4 21:34:52 2017 UTC
2 IV-eHMP_CIF.zip\IMAG_Source\VISA\Java\ImageConversion\main\src\java\gov\va\med\imaging\conversion ImageConversionUtility.java Mon Dec 4 22:01:04 2017 UTC

209.2 Comparison summary

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

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

209.4 Active regular expressions

No regular expressions were active.

209.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: May  2, 2008
  6     Site Nam e:  Washin gton OI Fi eld Office , Silver S pring, MD
  7       Developer:          
WERFEJ
  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.con version;
  27  
  28   import gov .va.med.im aging.Stri ngUtil;
  29   import gov .va.med.im aging.conv ersion.enu ms.ImageCo nversionSa tisfaction ;
  30   import gov .va.med.im aging.core .interface s.IImageCo nversionCo nfiguratio n;
  31   import gov .va.med.im aging.core .interface s.ImageSto rageFacade ;
  32   import gov .va.med.im aging.core .interface s.StorageC redentials ;
  33   import gov .va.med.im aging.core .interface s.exceptio ns.Connect ionExcepti on;
  34   import gov .va.med.im aging.core .interface s.exceptio ns.ImageCo nversionEx ception;
  35   import gov .va.med.im aging.core .interface s.exceptio ns.ImageNe arLineExce ption;
  36   import gov .va.med.im aging.core .interface s.exceptio ns.ImageNo tFoundExce ption;
  37   import gov .va.med.im aging.core .interface s.exceptio ns.MethodE xception;
  38   import gov .va.med.im aging.exch ange.busin ess.ImageF ormatAllow ableConver sionList;
  39   import gov .va.med.im aging.exch ange.busin ess.ImageF ormatQuali ty;
  40   import gov .va.med.im aging.exch ange.busin ess.ImageF ormatQuali tyList;
  41   import gov .va.med.im aging.exch ange.busin ess.ImageS treamRespo nse;
  42   import gov .va.med.im aging.exch ange.conve rsion.exce ptions.Ima geConversi onCompress ionExcepti on;
  43   import gov .va.med.im aging.exch ange.conve rsion.exce ptions.Ima geConversi onDecompre ssionExcep tion;
  44   import gov .va.med.im aging.exch ange.conve rsion.exce ptions.Ima geConversi onIOExcept ion;
  45   import gov .va.med.im aging.exch ange.conve rsion.exce ptions.Ima geConversi onInvalidI nputExcept ion;
  46   import gov .va.med.im aging.exch ange.conve rsion.inte rfaces.IIm ageConvers ion;
  47   import gov .va.med.im aging.exch ange.enums .ImageForm at;
  48   import gov .va.med.im aging.exch ange.enums .ImageQual ity;
  49   import gov .va.med.im aging.exch ange.enums .StoragePr oximity;
  50   import gov .va.med.im aging.exch ange.stora ge.ByteBuf ferBackedI mageInputS tream;
  51   import gov .va.med.im aging.exch ange.stora ge.ByteBuf ferBackedI mageStream Response;
  52   import gov .va.med.im aging.exch ange.stora ge.ByteBuf ferBackedI nputStream ;
  53   import gov .va.med.im aging.exch ange.stora ge.ByteBuf ferBackedO bject;
  54   import gov .va.med.im aging.tran sactioncon text.Trans actionCont ext;
  55   import gov .va.med.im aging.tran sactioncon text.Trans actionCont extFactory ;
  56  
  57   import jav a.io.Buffe redReader;
  58   import jav a.io.IOExc eption;
  59   import jav a.io.Input Stream;
  60   import jav a.io.Input StreamRead er;
  61   import jav a.io.Seque nceInputSt ream;
  62   import jav a.util.Has hMap;
  63   import jav a.util.Ite rator;
  64   import jav a.util.Lis t;
  65   import jav a.util.Map ;
  66   import jav a.util.Map .Entry;
  67   import jav a.util.Set ;
  68  
  69   import org .apache.co mmons.io.I OUtils;
  70   import org .apache.lo gging.log4 j.LogManag er;
  71   import org .apache.lo gging.log4 j.Logger;
  72  
  73   /**
  74    * Image c onversion  utility do es the wor k of deter mining wha t the stor ed image t ype is, wh at
  75    * it can  be convert ed into an d then act ually call ing the im age conver sion metho ds to 
  76    * convert  the image
  77    * 
  78    * @author         
WERFEJ
  79    *
  80    */
  81   public cla ss ImageCo nversionUt ility 
  82   {
  83           pr ivate fina l static L ogger logg er = LogMa nager.getL ogger(Imag eConversio nUtility.c lass);
  84           pr ivate fina l ImageSto rageFacade  storageFa cade;
  85           pr ivate fina l ImageCon versionSat isfaction  conversion Satisfacti on;
  86           pr ivate fina l boolean  updateDico mHeaders;
  87  
  88           /* *
  89            *  Create a  new image  conversion  utility f or convert ing a stor ed image i nto the fo rmat reque sted by th e user
  90            *  
  91            *  @param im ageStorage Facade The  storage f acade know s how to o pen the fi le needed.
  92            *  @param co nversionSa tisfaction  Image con version sa tisfaction  level for  this imag e conversi on utility
  93            *  @param up dateDicomH eaders Det ermines if  the DICOM  header sh ould be up dated for  images tha t are stor ed in DICO M
  94            * /
  95           pu blic Image Conversion Utility(Im ageStorage Facade ima geStorageF acade, 
  96                             ImageC onversionS atisfactio n conversi onSatisfac tion,
  97                             boolea n updateDi comHeaders )
  98           {
  99                    supe r();
  100                    this .storageFa cade = ima geStorageF acade;
  101                    this .conversio nSatisfact ion = conv ersionSati sfaction;
  102                    this .updateDic omHeaders  = updateDi comHeaders ;
  103           }
  104  
  105           pr ivate IIma geConversi on getImag eConversio n()
  106           {
  107                    retu rn ImageCo nversionFa ctory.getI mageConver sion();
  108           }
  109  
  110           pr ivate IIma geConversi onConfigur ation getI mageConfig uration()
  111           {
  112                    retu rn ImageCo nversionFa ctory.getI mageConver sionConfig uration();
  113           }
  114           
  115           /* *
  116            *  Retrieves  the image  from the  list of fi le paths u sing the s pecified f ormat qual ity list a nd credent ials
  117            *  @param fi les
  118            *  @param re questForma tQualityLi st The lis t of file  formats to  use when  requesting  the image
  119            *  @param co nvertForma tQualityLi st The lis t of file  formats th e image ca n be retur ned 
  120            *       in -  if the im age is req uested in  a format n ot include d in this  list, then  the image  must be c onverted
  121            *  @param tx tFileAvail able This  determines  if the im age conver sion will  attempt to  download  the TXT fi le, this v alue 
  122            *       has  no impact  if the TXT  file is n ecessary t o generate  a DICOM i mage. This  is only u sed if the  TXT file  might be 
  123            *       incl uded in th e result ( not for co nversion)
  124            *  @return A  stream to  the opene d image
  125            *  @throws I mageNearLi neExceptio n
  126            *  @throws I mageNotFou ndExceptio n
  127            *  @throws I mageConver sionExcept ion
  128            *  @throws C onnectionE xception
  129            * /
  130           pu blic Image StreamResp onse getIm age(List<I mageConver sionFilePa th> files,  
  131                             ImageF ormatQuali tyList req uestFormat QualityLis t, 
  132                             ImageF ormatQuali tyList con vertFormat QualityLis t,
  133                             boolea n txtFileA vailable)
  134           th rows Image NearLineEx ception, I mageNotFou ndExceptio n, ImageCo nversionEx ception,
  135           Co nnectionEx ception, M ethodExcep tion
  136           {
  137                    retu rn getImag e(files, r equestForm atQualityL ist, conve rtFormatQu alityList,
  138                                      txtFileA vailable,  null);
  139           }
  140  
  141           /* *
  142            *  Retrieves  the image  from the  list of fi le paths u sing the s pecified f ormat qual ity list a nd credent ials
  143            *  @param fi les
  144            *  @param re questForma tQualityLi st The lis t of file  formats to  use when  requesting  the image
  145            *  @param co nvertForma tQualityLi st The lis t of file  formats th e image ca n be retur ned 
  146            *       in -  if the im age is req uested in  a format n ot include d in this  list, then  the image  must be c onverted
  147            *  @param tx tFileAvail able This  determines  if the im age conver sion will  attempt to  download  the TXT fi le, this v alue 
  148            *       has  no impact  if the TXT  file is n ecessary t o generate  a DICOM i mage. This  is only u sed if the  TXT file  might be 
  149            *       incl uded in th e result ( not for co nversion)
  150            *  @param st orageCrede ntials The  credentia ls used to  access th e storage  device for  the files
  151            *  @return A  stream to  the opene d image
  152            *  @throws I mageNearLi neExceptio n
  153            *  @throws I mageNotFou ndExceptio n
  154            *  @throws I mageConver sionExcept ion
  155            *  @throws C onnectionE xception
  156            * /
  157           pu blic Image StreamResp onse getIm age(List<I mageConver sionFilePa th> files,  
  158                             ImageF ormatQuali tyList req uestFormat QualityLis t, 
  159                             ImageF ormatQuali tyList con vertFormat QualityLis t,
  160                             boolea n txtFileA vailable,
  161                             Storag eCredentia ls storage Credential s)
  162           th rows Image NearLineEx ception, I mageNotFou ndExceptio n, ImageCo nversionEx ception,
  163           Co nnectionEx ception, M ethodExcep tion
  164           {
  165                    retu rn getImag e(files, r equestForm atQualityL ist, conve rtFormatQu alityList,
  166                                      txtFileA vailable,  storageCre dentials,  null);
  167           }
  168  
  169           /* *
  170            *  Retrieves  the image  from the  list of fi le paths u sing the s pecified f ormat qual ity list a nd credent ials
  171            *  @param fi les
  172            *  @param re questForma tQualityLi st The lis t of file  formats to  use when  requesting  the image
  173            *  @param co nvertForma tQualityLi st The lis t of file  formats th e image ca n be retur ned 
  174            *       in -  if the im age is req uested in  a format n ot include d in this  list, then  the image  must be c onverted
  175            *  @param tx tFileAvail able This  determines  if the im age conver sion will  attempt to  download  the TXT fi le, this v alue 
  176            *       has  no impact  if the TXT  file is n ecessary t o generate  a DICOM i mage. This  is only u sed if the  TXT file  might be 
  177            *       incl uded in th e result ( not for co nversion)
  178            *  @param st orageCrede ntials The  credentia ls used to  access th e storage  device for  the files
  179            *  @param hi sUpdate Th e HIS upda te from th e database
  180            *  @return
  181            *  @throws I mageNearLi neExceptio n
  182            *  @throws I mageNotFou ndExceptio n
  183            *  @throws I mageConver sionExcept ion
  184            *  @throws C onnectionE xception
  185            * /
  186           pu blic Image StreamResp onse getIm age(List<I mageConver sionFilePa th> files,  
  187                             ImageF ormatQuali tyList req uestFormat QualityLis t,
  188                             ImageF ormatQuali tyList con vertFormat QualityLis t,
  189                             boolea n txtFileA vailable,
  190                             Storag eCredentia ls storage Credential s, HashMap <String, S tring> his Update)
  191           th rows Image NearLineEx ception, I mageNotFou ndExceptio n, ImageCo nversionEx ception, 
  192           Co nnectionEx ception, M ethodExcep tion
  193           {
  194                    try
  195                    {
  196                             for(Im ageConvers ionFilePat h filePath  : files)
  197                             {
  198                                      ImageStr eamRespons e response  = retriev eAndCompre ssImage(fi lePath, 
  199                                                       re questForma tQualityLi st, conver tFormatQua lityList,
  200                                                       tx tFileAvail able, stor ageCredent ials, hisU pdate);
  201                                      if(respo nse != nul l)
  202                                               return res ponse;
  203                             }
  204                             return  null;
  205                    }
  206                    fina lly
  207                    {
  208                             if(sto rageFacade  != null)
  209                             {
  210                                      // be su re to clea r the buff ers when d one with t he convers ion (alway s clear th em)
  211                                      storageF acade.clea rBuffers() ;
  212                             }
  213                    }
  214           }
  215  
  216           pr ivate Imag eStreamRes ponse retr ieveAndCom pressImage (ImageConv ersionFile Path fileP ath, 
  217                             ImageF ormatQuali tyList req uestFormat QualityLis t, 
  218                             ImageF ormatQuali tyList con vertFormat QualityLis t,
  219                             boolea n txtFileA vailable,
  220                             Storag eCredentia ls storage Credential s, HashMap <String, S tring> his Update)
  221           th rows Image NearLineEx ception, I mageNotFou ndExceptio n, ImageCo nversionEx ception, 
  222           Co nnectionEx ception, M ethodExcep tion
  223           {
  224                    // j ust to be  sure every thing is c lean
  225                    //re turnBuffer s();
  226                    try 
  227                    {
  228                             String  imageFile name = fil ePath.getF ilePath();
  229                             logger .info("Ope ning input  stream to  image ["  + imageFil ename + "] ");
  230  
  231                             if(ima geFilename .startsWit h("."))
  232                             {
  233                                      logger.e rror("Imag e starts w ith a '.',  cannot ac cess or re trieve can ned images  from acce lerator");
  234                                      return n ull;
  235                             }
  236                             Transa ctionConte xt transac tionContex t = Transa ctionConte xtFactory. get();
  237                             transa ctionConte xt.addDebu gInformati on("Openin g image wi th path '"  + imageFi lename + " '.");
  238                             ByteBu fferBacked ImageStrea mResponse  response =  storageFa cade.openI mageStream (imageFile name, 
  239                                               storageCre dentials,  filePath.g etStorageP roximity() , requestF ormatQuali tyList);
  240                             ImageF ormat stor edFormat =  response. getImageFo rmat();
  241                             
  242                             ImageQ uality sto redQuality  = respons e.getImage Quality();
  243                             if(sto redQuality  == null)
  244                                      storedQu ality = fi lePath.get ImageQuali ty();
  245                             if(res ponse.getI mageQualit y() == nul l)
  246                                      response .setImageQ uality(sto redQuality );
  247                             
  248                             
  249                             if(sto redFormat  != null)
  250                             {
  251                                      transact ionContext .setDataSo urceImageF ormatRecei ved(stored Format.toS tring());
  252                             }
  253                             if(sto redQuality  != null)
  254                             {
  255                                      transact ionContext .setDataSo urceImageQ ualityRece ived(store dQuality.t oString()) ;
  256                             }
  257  
  258                             logger .debug("st oredFormat : " + stor edFormat);
  259                             
  260                             // spe cial case  if we can' t determin e the form at of the  file, just  want to r eturn it i f allowed
  261                             if(sto redFormat  == ImageFo rmat.ORIGI NAL)
  262                             {
  263                                      logger.i nfo("Unabl e to deter mine the f ormat of f ile [" + i mageFilena me + "]");
  264                                      if(reque stAllowsOr iginalImag eType(conv ertFormatQ ualityList ))
  265                                      {
  266                                               logger.inf o("Unknown  format is  allowed b ecause [OR IGINAL] is  in reques t, returni ng ORIGINA L image fo rmat");
  267                                               // want to  set the i mage quali ty in the  response a lso...
  268                                               // do anyt hing speci al if inco rrect imag e quality?  probably  can't!
  269                                               if(respons e.getImage Quality()  == null)
  270                                                       re sponse.set ImageQuali ty(storedQ uality);
  271                                               if((stored Quality !=  ImageQual ity.THUMBN AIL) &&
  272                                                                (res ponse.getT xtStream()  == null)  && (!Image Format.isD ICOMFormat (response. getImageFo rmat()))
  273                                                                && ( txtFileAva ilable))
  274                                               {
  275                                                       By teBufferBa ckedInputS tream txtS tream = 
  276                                                                getT xtStreamHa ndleExcept ion(imageF ilename, s torageCred entials, h isUpdate);
  277                                                       re sponse.set TxtStream( txtStream) ;
  278                                                       //  can't do  the DICOM  header upd ate since  we don't k now what t he format  of the ima ge is
  279                                               }
  280                                               return res ponse;
  281                                      }
  282                                      logger.d ebug("requ estAllowsO riginalIma geType ret urned Fals e.");
  283                             }
  284                             
  285                             if(isS toredForma tInRequest (requestFo rmatQualit yList, sto redFormat)  
  286                                               && storedQ uality ==  ImageQuali ty.DIAGNOS TICUNCOMPR ESSED){
  287                                      
  288                                      logger.i nfo("Deter mined stor ed Format  [" + store dFormat +
  289                                                       "]  matches a nd image q uality is  100. Passi ng image \ "as is\"." );
  290                                      if(respo nse.getIma geQuality( ) == null)
  291                                               response.s etImageQua lity(store dQuality);
  292                                      if(store dQuality ! = ImageQua lity.THUMB NAIL)
  293                                      {
  294                                               setImageSt reamRespon seTextFile IfNecessar y(response , storedFo rmat, imag eFilename,  
  295                                                                stor ageCredent ials, hisU pdate, txt FileAvaila ble);                                           
  296                                               if((ImageF ormat.isDI COMFormat( storedForm at)) && (u pdateDicom Headers))
  297                                               {
  298                                                       //  if DICOM  then try t o update t he DICOM h eader with  the lates t values
  299                                                       re turn updat eDICOMHead erHandleEx ceptions(r esponse, s toredForma t, storedQ uality);
  300                                               }
  301                                      }
  302                                      return r esponse;                                   
  303                             }
  304  
  305                             Iterat or<ImageFo rmatQualit y> qualiti esIterator  = convert FormatQual ityList.it erator();
  306                             boolea n canCompr essStoredF ormat = ca nCompressF ormat(stor edFormat);
  307                             logger .debug("ca nCompressS toredForma t returned  " + canCo mpressStor edFormat);
  308  
  309  
  310                             // if  satisfy to p request  is false t hen try to  just retu rn the out put if pos sible
  311                             // we  would want  to just r eturn the  data witho ut convert ing it if  it matches  the 
  312                             // req uested for mats
  313                             //if(! isSatisfyT opRequest( ))
  314                             if(con versionSat isfaction  == ImageCo nversionSa tisfaction .SATISFY_A NY_REQUEST )
  315                             {
  316                                      logger.i nfo("Check ing to see  if image  in format  [" + store dFormat +  "] can be  returned i n current  format");
  317                                      if(isSto redFormatI nRequest(c onvertForm atQualityL ist, store dFormat, s toredQuali ty))
  318                                      {
  319                                               logger.inf o("Image i n format [ " + stored Format + " ] and can  be returne d in this  format, re turning");
  320                                               if(respons e.getImage Quality()  == null)
  321                                                       re sponse.set ImageQuali ty(storedQ uality);
  322                                               if(storedQ uality !=  ImageQuali ty.THUMBNA IL)
  323                                               {
  324                                                       se tImageStre amResponse TextFileIf Necessary( response,  storedForm at, imageF ilename, 
  325                                                                         storag eCredentia ls, hisUpd ate, txtFi leAvailabl e);                                           
  326                                                       if ((ImageFor mat.isDICO MFormat(st oredFormat )) && (upd ateDicomHe aders))
  327                                                       {
  328                                                                // i f DICOM th en try to  update the  DICOM hea der with t he latest  values
  329                                                                retu rn updateD ICOMHeader HandleExce ptions(res ponse, sto redFormat,  storedQua lity);
  330                                                       }
  331                                               }
  332                                               return res ponse;
  333                                      }
  334                             }
  335                             else i f(conversi onSatisfac tion == Im ageConvers ionSatisfa ction.SATI SFY_ALLOWE D_COMPRESS ION)
  336                             {
  337                                      // if th e image is  stored in  a compres sed format  and that  format is  in the req uested for mat list
  338                                      // then  the image  can be ret urned rega rdless of  where it i s in the l ist.
  339                                      if(store dFormat.is Compressed ())
  340                                      {
  341                                               logger.inf o("Image i s stored i n format [ " + stored Format + " ] which is  compresse d, checkin g to see i f image ca n be retur ned in thi s format") ;
  342                                               if(isStore dFormatInR equest(con vertFormat QualityLis t, storedF ormat, sto redQuality ))
  343                                               {
  344                                                       lo gger.info( "Image in  format ["  + storedFo rmat + "]  and can be  returned  in this fo rmat, retu rning");
  345                                                       if (response. getImageQu ality() ==  null)
  346                                                                resp onse.setIm ageQuality (storedQua lity);
  347                                                       if (storedQua lity != Im ageQuality .THUMBNAIL )
  348                                                       {
  349                                                                setI mageStream ResponseTe xtFileIfNe cessary(re sponse, st oredFormat
  350                                                                                  imageFil ename, sto rageCreden tials, his Update, tx tFileAvail able);                                            
  351                                                                if(( ImageForma t.isDICOMF ormat(stor edFormat))  && (updat eDicomHead ers))
  352                                                                {
  353                                                                         // if  DICOM then  try to up date the D ICOM heade r with the  latest va lues
  354                                                                         return  updateDIC OMHeaderHa ndleExcept ions(respo nse, store dFormat, s toredQuali ty);
  355                                                                }
  356                                                       }
  357                                                       re turn respo nse;
  358                                               }
  359                                      }
  360                             }
  361                             ImageF ormatQuali ty quality  = getNext AllowableI mageFormat Quality(st oredFormat , qualitie sIterator) ;
  362                             
  363                             while( quality !=  null)
  364                             {
  365                                      logger.i nfo("Attem pting to g enerate im age of typ e '" + qua lity.getIm ageFormat( ) + "'.");
  366                                      if(((sto redFormat  == quality .getImageF ormat()) |
  367                                                       (q uality.get ImageForma t() == Ima geFormat.O RIGINAL))
  368                                                       &&  ((storedQ uality ==  quality.ge tImageQual ity()) || 
  369                                                                         (!canC ompressSto redFormat) ))
  370                                      {
  371                                               logger.inf o("Image f ormat [" +  storedFor mat + "] m atches req uest forma t, returni ng image") ;
  372                                               if(respons e.getImage Quality()  == null)
  373                                                       re sponse.set ImageQuali ty(quality .getImageQ uality());
  374                                               if(quality .getImageQ uality() ! = ImageQua lity.THUMB NAIL)
  375                                               {
  376                                                       se tImageStre amResponse TextFileIf Necessary( response,  storedForm at, 
  377                                                                         imageF ilename, s torageCred entials, h isUpdate,  txtFileAva ilable);                                            
  378                                                       if ((ImageFor mat.isDICO MFormat(st oredFormat )) && (upd ateDicomHe aders))
  379                                                       {
  380                                                                // i f DICOM th en try to  update the  DICOM hea der with t he latest  values
  381                                                                retu rn updateD ICOMHeader HandleExce ptions(res ponse, sto redFormat,  storedQua lity);
  382                                                       }
  383                                               }
  384                                               return res ponse;
  385                                      }       
  386  
  387                                      // if th e original  file type  is not in  the right  quality b ut the cur rent conve rsion
  388                                      // is "o riginal",  then just  return wha t we have.  Original  should alw ays happen  last
  389                                      // so th is is a la st resort  and the us er said th ey could h andle the  original f ormat
  390                                      if(quali ty.getImag eFormat()  == ImageFo rmat.ORIGI NAL)
  391                                      {
  392                                               logger.inf o("Image i s in forma t [" + sto redFormat  + "] and [ ORIGINAL]  can be ret urned, ret urning sto red image" );
  393                                               if(respons e.getImage Quality()  == null)
  394                                                       re sponse.set ImageQuali ty(storedQ uality);
  395                                               if(quality .getImageQ uality() ! = ImageQua lity.THUMB NAIL)
  396                                               {
  397                                                       se tImageStre amResponse TextFileIf Necessary( response,  storedForm at, imageF ilename, 
  398                                                                         storag eCredentia ls, hisUpd ate, txtFi leAvailabl e);                                                                                       
  399                                                       if ((ImageFor mat.isDICO MFormat(st oredFormat )) && (upd ateDicomHe aders))
  400                                                       {
  401                                                                // i f DICOM th en try to  update the  DICOM hea der with t he latest  values
  402                                                                retu rn updateD ICOMHeader HandleExce ptions(res ponse, sto redFormat,  storedQua lity);
  403                                                       }
  404                                               }
  405                                               return res ponse;
  406                                      }
  407  
  408                                      // if we  get to he re, we hav e to do a  conversion , put it i nto the bu ffer?
  409                                      
  410                                      // at th is point w e know we  need to do  some conv ersion, so  make sure  the image  
  411                                      // is in  a buffer  in case we  need to r euse it.
  412                                      
  413                                      // no lo nger need  to put int o buffer,  will be ha ndled inte rnally (ri ght?)
  414                                      
  415                                      //respon se = stora geFacade.p utStreamIn toBuffer(i mageFilena me, respon se);         
  416                                      
  417  
  418                                      logger.i nfo("Able  to convert  from [" +  storedFor mat + "] t o [" + qua lity.getIm ageFormat( ) + "]");
  419                                      transact ionContext .addDebugI nformation ("Converti ng from '"  + storedF ormat + "'  to '" + q uality.get ImageForma t() + "'." );
  420                                      try
  421                                      {
  422                                               // if requ ested qual ity format  is DICOM  then we ne ed the TXT  file befo re we call  compress  and conver t (to buil d the head er)
  423                                               if(ImageFo rmat.isDIC OMFormat(q uality.get ImageForma t()))
  424                                               {
  425                                                       if (isDecompr ess(stored Format, qu ality.getI mageFormat ()))
  426                                                       {
  427                                                                Imag eStreamRes ponse conv ertedRespo nse = deco mpressImag e(response , quality) ;
  428                                                                if(c onvertedRe sponse !=  null)
  429                                                                {
  430                                                                         return  converted Response;
  431                                                                }
  432                                                       }
  433                                                       el se
  434                                                       {
  435                                                                // d o conversi on
  436                                                                if(r esponse.ge tTxtStream () == null )
  437                                                                {
  438                                                                         ByteBu fferBacked InputStrea m txtStrea m = 
  439                                                                                  getTxtSt reamHandle Exception( imageFilen ame, stora geCredenti als, hisUp date);
  440                                                                         respon se.setTxtS tream(txtS tream);
  441                                                                }
  442                                                                Imag eStreamRes ponse conv ertedRespo nse = comp ressAndCon vertImage( response,  quality);
  443                                                                if(c onvertedRe sponse !=  null)
  444                                                                {
  445                                                                         return  converted Response;
  446                                                                }
  447                                                       }
  448                                               }
  449                                               else
  450                                               {
  451                                                       //  check to  see if sho uld do a d ecompressi on rather  than compr ession
  452                                                       if (isDecompr ess(stored Format, qu ality.getI mageFormat ()))
  453                                                       {
  454                                                                // n ot creatin g a DICOM  file so on ly doing c ompression , return T XT file af ter making  the image
  455                                                                Imag eStreamRes ponse conv ertedRespo nse = deco mpressImag e(response , quality) ;
  456                                                                if(c onvertedRe sponse !=  null)
  457                                                                {
  458                                                                         if((qu ality.getI mageQualit y() != Ima geQuality. THUMBNAIL)
  459                                                                                           && (conver tedRespons e.getTxtSt ream() ==  null)
  460                                                                                           && (!Image Format.isD ICOMFormat (response. getImageFo rmat())))
  461                                                                         {
  462                                                                                  ByteBuff erBackedIn putStream  txtStream 
  463                                                                                           getTxtStre amHandleEx ception(im ageFilenam e, storage Credential s, hisUpda te);
  464                                                                                  converte dResponse. setTxtStre am(txtStre am);
  465                                                                         }
  466                                                                         return  converted Response;
  467                                                                }
  468                                                       }
  469                                                       el se
  470                                                       {                                                             
  471                                                                Stri ng modalit y = null;
  472                                                                // o nly get th e modality  if the re quested qu ality is n ot thumbna il
  473                                                                if(q uality.get ImageQuali ty() != Im ageQuality .THUMBNAIL )
  474                                                                {
  475                                                                         // get  modality  code from  TXT file f or non-DIC OM compres sion
  476                                                                         ByteBu fferBacked InputStrea m txtStrea m = respon se.getTxtS tream();
  477                                                                         if(txt Stream ==  null)
  478                                                                                  txtStrea m = getTxt StreamHand leExceptio n(imageFil ename, sto rageCreden tials, his Update);
  479                                                                         modali ty = getTX TModality( txtStream) ; // get m odality co de and clo se partial ly consume d stream!
  480                                                                }
  481                                                                // n ot creatin g a DICOM  file so on ly doing c ompression , return T XT file af ter making  the image
  482                                                                Imag eStreamRes ponse conv ertedRespo nse = comp ressImage( imageFilen ame, respo nse, quali ty, modali ty);
  483                                                                if(c onvertedRe sponse !=  null)
  484                                                                {
  485                                                                         if((qu ality.getI mageQualit y() != Ima geQuality. THUMBNAIL)
  486                                                                                           && (conver tedRespons e.getTxtSt ream() ==  null)
  487                                                                                           && (!Image Format.isD ICOMFormat (response. getImageFo rmat()))
  488                                                                                           && (txtFil eAvailable ))
  489                                                                         {
  490                                                                                  ByteBuff erBackedIn putStream  txtStream 
  491                                                                                           getTxtStre amHandleEx ception(im ageFilenam e, storage Credential s, hisUpda te);
  492                                                                                  converte dResponse. setTxtStre am(txtStre am);
  493                                                                         }
  494                                                                         return  converted Response;
  495                                                                }
  496                                                       }
  497                                               }
  498                                      }
  499                                      catch(Im ageConvers ionDecompr essionExce ption icdX )
  500                                      {
  501                                               logger.err or("Decomp ression er ror during  convertin g image ["  + imageFi lename + " ]", icdX);
  502                                               transactio nContext.a ddDebugInf ormation(" ImageConve rsionDecom pressionEx ception co nverting i mage, " +  icdX.getMe ssage() +  ".");
  503                                      }
  504                                      catch(Im ageConvers ionCompres sionExcept ion iccX)
  505                                      {
  506                                               logger.err or("Compre ssion erro r during c onverting  image [" +  imageFile name + "]" , iccX);
  507                                               transactio nContext.a ddDebugInf ormation(" ImageConve rsionCompr essionExce ption conv erting ima ge, " + ic cX.getMess age() + ". ");
  508                                      }
  509                                      catch(Im ageConvers ionIOExcep tion icioX )
  510                                      {
  511                                               logger.err or("IO err or during  converting  image ["  + imageFil ename + "] ", icioX);
  512                                               transactio nContext.a ddDebugInf ormation(" ImageConve rsionIOExc eption con verting im age, " + i cioX.getMe ssage() +  ".");
  513                                      }
  514                                      catch(Im ageConvers ionInvalid InputExcep tion iciiX )
  515                                      {
  516                                               logger.err or("Input  data error  during co nverting i mage [" +  imageFilen ame + "]",  iciiX);
  517                                               transactio nContext.a ddDebugInf ormation(" ImageConve rsionInval idInputExc eption con verting im age, " + i ciiX.getMe ssage() +  ".");
  518                                      }
  519                                      catch(IO Exception  ioX)
  520                                      {
  521                                               logger.err or("IOExce ption whil e converti ng image [ " + imageF ilename +  "]", ioX);
  522                                               transactio nContext.a ddDebugInf ormation(" IOExceptio n converti ng image,  " + ioX.ge tMessage()  + ".");
  523                                      }
  524  
  525                                      logger.i nfo("Not a ble to con vert from  [" + store dFormat +  "] to [" +  quality.g etImageFor mat() + "] , trying n ext conver sion optio n");
  526                                      // its n ot necessa ry to clos e the inpu t stream,  if we got  here then  we tried t o do conve rsions
  527                                      // which  means the  image was  buffered  so the buf fering han dled closi ng the inp ut streams
  528                                      logger.i nfo("Re-op ening imag e stream") ;
  529                                      // not r eally sure  if this i s necessar y anymore
  530                                      response  = storage Facade.ope nImageStre am(imageFi lename, 
  531                                                       st orageCrede ntials, St orageProxi mity.OFFLI NE, reques tFormatQua lityList);
  532                                      storedFo rmat = res ponse.getI mageFormat ();
  533                                      storedQu ality = re sponse.get ImageQuali ty();
  534                                      if(store dQuality = = null)
  535                                               storedQual ity = file Path.getIm ageQuality ();
  536                                      if(respo nse.getIma geQuality( ) == null)
  537                                               response.s etImageQua lity(store dQuality);
  538                                      quality  = getNextA llowableIm ageFormatQ uality(sto redFormat,  qualities Iterator);
  539                    
  540                             }
  541                             // if  we got her e then we  couldn't d o anything  to the im age to sat isfy the r equest
  542                             String  msg = "Co uldn't per form accep table [" +  storedFor mat + 
  543                             "] dat a conversi on to matc h requeste d format(s ) [" + con vertFormat QualityLis t.getAccep tString(fa lse) + "]" ;
  544                             //logg er.info(,  throwing I mageConver sionExcept ion");
  545                             logger .error(msg );
  546                             logger .info("Clo sing possi bly still  open image  and TXT s treams");
  547                             if(res ponse.getI mageStream () != null )
  548                                      response .getImageS tream().cl oseSafely( );
  549                             if(res ponse.getT xtStream()  != null)
  550                                      response .getTxtStr eam().clos eSafely();
  551                             throw  new ImageC onversionE xception(m sg);
  552                    }
  553                    fina lly
  554                    {
  555                             //retu rnBuffers( );
  556                    }
  557           }
  558  
  559           /* *
  560            *  This meth od parses  an opened  TXT file s tream for  DICOM Moda lity code.
  561            *  Before re turning th e modality  code the  partially  read strea m is close d.
  562            *  @param tx tstream
  563            *                         A sized  InputStrea m referrin g to TXT s tream and  its length
  564            *  @throws I mageConver sionIOExce ption
  565            * /
  566           pr ivate Stri ng getTXTM odality(By teBufferBa ckedInputS tream txtS tream) {
  567                    Stri ng mty="";
  568                String t extLine =  "";
  569                int byte sRead=0;
  570                    if ( (txtStream  == null)  || (!txtSt ream.isRea dable()))
  571                             return  mty;
  572                    try 
  573                    {
  574                             int fs ize = txtS tream.getS ize();
  575                             if (fs ize > 0) {
  576                                 Bu fferedRead er buffer  = new Buff eredReader (new Input StreamRead er(txtStre am.getInpu tStream()) );
  577                                 do {// parse  for "MODAL ITY=" or " Modality|1 ,1|" and t ake the ne xt 2 bytes
  578                                      do{ // g et next li ne
  579                                               if (bytesR ead >= fsi ze)
  580                                                       re turn mty;
  581                                          text Line = buf fer.readLi ne();
  582                                               if(textLin e == null)  // EOF
  583                                               return mty ;
  584                                               bytesRead  += textLin e.length() ;
  585                                      } while  (textLine. equals("") );
  586                                 }  while( !(( textLine.s tartsWith( "MODALITY" )) || (tex tLine.star tsWith("00 08,0060|Mo dality")))  );
  587                                 if  (textLine .startsWit h("MODALIT Y"))
  588                                      mty=text Line.subst ring(textL ine.indexO f("=")+1);
  589                                 el se
  590                                      mty=text Line.subst ring(textL ine.lastIn dexOf("|") +1);
  591                             }
  592                    } 
  593                    catc h (IOExcep tion ioX)  {
  594                             logger .error("Er ror extrac ting Modal ity code f rom TXT st ream", ioX );
  595                    }
  596                    fina lly 
  597                    {
  598                             txtStr eam.closeS afely();
  599                    }
  600                    retu rn mty;
  601           }
  602           
  603           pr ivate bool ean canCom pressForma t(ImageFor mat imageF ormat)
  604           {
  605                    if(i mageFormat  == null){
  606                             logger .debug("im ageFormat  is null.") ;
  607                             return  false;
  608                    }
  609                    Imag eFormatAll owableConv ersionList  conversio nList = ge tImageConf iguration( ).getForma tConfigura tion(image Format);
  610                    if(c onversionL ist == nul l){
  611                             logger .debug("co nversionLi st is null .");
  612                             return  false;
  613                    }
  614                    retu rn convers ionList.is CanCompres s();
  615           }
  616  
  617           /* *
  618            *  Retrieves  a TXT str eam from t he storage  facade.
  619            *  
  620            *  @param im ageFilenam e
  621            *  @param st orageCrede ntials
  622            *  @param hi sUpdate Ha shmap cont aining nam e/value pa irs of the  HIS updat e of patie nt data.
  623            *  @return
  624            * /
  625           pu blic ByteB ufferBacke dInputStre am GetTxtS tream(Stri ng imageFi lename, St orageCrede ntials sto rageCreden tials, 
  626                             HashMa p<String,  String> hi sUpdate)
  627           th rows Image NotFoundEx ception, I mageNearLi neExceptio n, Connect ionExcepti on, Method Exception
  628           {
  629                    logg er.info("O pening str eam to TXT  file for  image [" +  imageFile name + "]" );
  630                    Byte BufferBack edInputStr eam txtStr eam = stor ageFacade. openTXTStr eam(imageF ilename, 
  631                                      storageC redentials , null);
  632                    logg er.info("G ot stream  to TXT fil e for imag e [" + ima geFilename  + "]");
  633                    retu rn appendT xtStreamWi thHisUpdat e(txtStrea m, hisUpda te);
  634           }
  635           
  636           pr ivate Byte BufferBack edInputStr eam getTxt StreamHand leExceptio n(String i mageFilena me, 
  637                             Storag eCredentia ls storage Credential s, HashMap <String, S tring> his Update)
  638           {
  639                    try
  640                    {
  641                             return  GetTxtStr eam(imageF ilename, s torageCred entials, h isUpdate);
  642                    }
  643                    catc h(ImageNot FoundExcep tion infX)
  644                    {
  645                             logger .error("TX T File for  image ["  + imageFil ename + "]  not found ", infX);
  646                    }
  647                    catc h(ImageNea rLineExcep tion inlX)
  648                    {
  649                             logger .error("TX T File for  image ["  + imageFil ename + "]  nearline  exception" , inlX);
  650                    }
  651                    catc h(Connecti onExceptio n cX)
  652                    {
  653                             logger .error("TX T File for  image ["  + imageFil ename + "]  connectio n exceptio n", cX);
  654                    }
  655                    catc h(MethodEx ception mX )
  656                    {
  657                             logger .error("TX T File for  image ["  + imageFil ename + "]  method ex ception",  mX);
  658                    }
  659                    retu rn null;
  660           }
  661  
  662           pr ivate Byte BufferBack edInputStr eam append TxtStreamW ithHisUpda te(ByteBuf ferBackedI nputStream  txtStream
  663                             HashMa p<String,  String> hi sUpdate)
  664           {                 
  665                    /*
  666                    if(( hisUpdate  == null) | | (hisUpda te.size()  <= 0))
  667                             return  txtStream ;
  668                     */
  669                    int  bytesRead  = 0;
  670  
  671                    Stri ngBuilder  sb = new S tringBuild er();
  672  
  673                    sb.a ppend("$$B EGIN HIS U PDATE");
  674                    sb.a ppend("\n" );
  675  
  676                    Stri ng lastKey  = "";
  677                    int  keyCount =  1;
  678                    if(h isUpdate ! = null)
  679                    {
  680                             Set<Ma p.Entry<St ring, Stri ng>> entri es = hisUp date.entry Set();
  681                             for(En try<String , String>  entry : en tries)
  682                             {
  683                                      String k ey = entry .getKey();
  684                                      if(key.e quals(last Key))
  685                                      {
  686                                               keyCount++ ;
  687                                      }
  688  
  689                                      String l ine = key  + StringUt il.STICK +  StringUti l.STICK +  keyCount +  ",1" + St ringUtil.S TICK + ent ry.getValu e();
  690                                      lastKey  = key;
  691                                      sb.appen d(line + " \n");
  692                             }
  693                    }
  694                    sb.a ppend("$$E ND HIS UPD ATE\n");
  695                    byte sRead = sb .length();
  696                    Inpu tStream hi sStream =  IOUtils.to InputStrea m(sb.toStr ing());
  697  
  698                    Byte BufferBack edInputStr eam sizedS tream = nu ll;
  699                    if(t xtStream = = null)
  700                    {
  701                             logger .info("app endTxtStre amWithHisU pdate, txt  stream is  null, ret urning str eam contai ning only  HIS update ");
  702                             sizedS tream = ne w ByteBuff erBackedIn putStream( hisStream,  bytesRead );
  703                    }
  704                    else
  705                    {
  706                             logger .info("Com bining HIS  stream wi th TXT str eam");
  707                             InputS tream text InputStrea m = txtStr eam.getInp utStream() ;
  708                             Sequen ceInputStr eam seqStr eam = new  SequenceIn putStream( textInputS tream, his Stream);
  709                             logger .info("HIS  Stream ha s been joi ned with T XT stream" );
  710                             sizedS tream = ne w ByteBuff erBackedIn putStream( seqStream,  bytesRead  + txtStre am.getSize ());                        
  711                    }
  712                    retu rn sizedSt ream;
  713           }
  714  
  715           /* *
  716            *  Open the  TXT file s tream
  717            *  @param tx tFilename  The txt fi le to open
  718            *  @param st orageCrede ntials the  storage c redentials  used to a ccess the  image shar e
  719            *  @return T he input s tream to t he file 
  720            *  @throws I mageNotFou ndExceptio n Occurs i f the file  is not fo und or acc essible
  721            *  @throws I mageNearLi neExceptio n Occurs i f the file  is not ac cessible b ut is on a  nearline  storage de vice
  722            * /
  723           /*
  724           pr ivate Size dInputStre am getTXTS tream(Stri ng txtFile name, Stor ageCredent ials stora geCredenti als)
  725           th rows Image NotFoundEx ception, I mageNearLi neExceptio n
  726           {                 
  727                    retu rn SmbStor ageUtility .openFileS tream(txtF ilename, s torageCred entials, S torageProx imity.OFFL INE);              
  728           }
  729            * /
  730  
  731           /* *
  732            *  Returns t he next al lowable im age format  quality f or the sto red format .  
  733            *  @param st oredFormat  the forma t of the s tored imag e
  734            *  @param qu alitiesIte rator The  iterator o f the qual ities requ ested by t he user
  735            *  @return A n image fo rmat quali ty that wa s requeste d by the c lient and  is allowab le for the  stored im age format .
  736            *  Returns n ull if no  format can  be found  that is al lowed for  the stored  format
  737            * /
  738           pr ivate Imag eFormatQua lity getNe xtAllowabl eImageForm atQuality( ImageForma t storedFo rmat, 
  739                             Iterat or<ImageFo rmatQualit y> qualiti esIterator )
  740           {
  741                    logg er.info("F inding nex t allowabl e conversi on type fo r format [ " + stored Format + " ]");
  742                    Imag eFormatAll owableConv ersionList  formatAll owedList =  getImageC onfigurati on().getFo rmatConfig uration(st oredFormat );
  743                    // i f the list  of allowa ble conver sions is n ull, then  no definit ions for t his format  type
  744                    // r eturning f alse to no t allow th e conversi on, not su re if that  is correc t?
  745                    if(f ormatAllow edList ==  null)
  746                    {
  747                             // JMW  2/21/2011  if the im age format  is not in  the confi guration f ile, then  simply ind icate it c an
  748                             // be  converted  into itsel f so if th e user all ows anythi ng, it can  be return ed
  749                             //logg er.warn("L ist of all owed forma ts to conv ert to is  null, retu rning null ");
  750                             logger .warn("Lis t of allow ed formats  to conver t '" + sto redFormat  + "' is nu ll, not fo und in con figuration  file. Cre ating list  only cont aining thi s format") ;
  751                             format AllowedLis t = new Im ageFormatA llowableCo nversionLi st(storedF ormat, fal se);
  752                             // JMW  6/25/2013  - add thi s format a s an allow ed format  to convert  to (conve rt from se lf to self )
  753                             format AllowedLis t.add(stor edFormat);
  754                             //retu rn null;
  755                    }
  756                    whil e(qualitie sIterator. hasNext())
  757                    {
  758                             ImageF ormatQuali ty quality  = qualiti esIterator .next();
  759  
  760                             if((qu ality.getI mageFormat () == Imag eFormat.OR IGINAL) ||
  761                                               (formatAll owedList.i sFormatCon versionAll owed(quali ty.getImag eFormat()) ))
  762                             {
  763                                      logger.i nfo("Found  allowed a nd request ed format  [" + quali ty.getImag eFormat()  + "]");
  764                                      return q uality;
  765                             }
  766                    }
  767                    logg er.info("C ould not f ind any mo re formats  to conver t [" + sto redFormat  + "] into" );
  768                    retu rn null;
  769           }
  770  
  771           /* *
  772            *  Determine s if the s tored form at is comp ressed and  the targe t format i s not comp ressed.
  773            *  
  774            *  @param st oredFormat
  775            *  @param ta rgetFormat
  776            *  @return T rue if the  stored fo rmat is co mpressed a nd target  format is  not compre ssed, fals e otherwis e
  777            * /
  778           pr ivate bool ean isDeco mpress(Ima geFormat s toredForma t, ImageFo rmat targe tFormat)
  779           {
  780                    if(( storedForm at.isCompr essed()) 
  781                                      && (!tar getFormat. isCompress ed()))
  782                    {
  783                             return  true;
  784                    }
  785                    retu rn false;
  786           }
  787  
  788           pr ivate Byte BufferBack edImageStr eamRespons e decompre ssImage(By teBufferBa ckedImageS treamRespo nse stored Image, 
  789                             ImageF ormatQuali ty quality )
  790           th rows Image Conversion InvalidInp utExceptio n, ImageCo nversionIO Exception,  
  791           Im ageConvers ionDecompr essionExce ption, IOE xception
  792           {
  793                    Imag eFormat st oredFormat  = storedI mage.getIm ageFormat( );
  794                    Imag eFormat ta rgetFormat  = quality .getImageF ormat();
  795                    logg er.info("d ecompress  from [" +  storedForm at + "] to  [" + targ etFormat +  "]");                  
  796                    Imag eQuality i mageQualit y = qualit y.getImage Quality();
  797                    IIma geConversi on convers ion = getI mageConver sion();
  798  
  799                    Byte BufferBack edImageInp utStream o utStream =  
  800                             conver sion.Decom pressImage (storedFor mat, targe tFormat, s toredImage .getImageS tream().to BufferedOb ject());
  801                    retu rn new Byt eBufferBac kedImageSt reamRespon se(outStre am, imageQ uality);
  802           }
  803  
  804           pr ivate Byte BufferBack edImageStr eamRespons e compress Image(Stri ng imageFi lename, 
  805                             ByteBu fferBacked ImageStrea mResponse  storedImag e, ImageFo rmatQualit y quality,  String mo dality)
  806           th rows Image Conversion Decompress ionExcepti on, ImageC onversionI OException
  807           Im ageConvers ionInvalid InputExcep tion, Imag eConversio nCompressi onExceptio n,
  808           IO Exception
  809           {
  810                    Imag eFormat st oredFormat  = storedI mage.getIm ageFormat( );
  811                    Imag eFormat ta rgetFormat  = quality .getImageF ormat();
  812                    logg er.info("c ompress fr om [" + st oredFormat  + "] to [ " + target Format + " ]");
  813                             
  814                    Imag eQuality i mageQualit y = qualit y.getImage Quality();
  815                    IIma geConversi on convers ion = getI mageConver sion();
  816  
  817                    Byte BufferBack edImageInp utStream o utStream =  conversio n.Compress Image(imag eQuality,  storedForm at, 
  818                                      targetFo rmat, stor edImage.ge tImageStre am().toBuf feredObjec t(), modal ity);
  819                    retu rn new Byt eBufferBac kedImageSt reamRespon se(outStre am, imageQ uality);
  820           }
  821  
  822           /* *
  823            *  This upda tes the DI COM header  of an exi sting imag e that was  not conve rted. This  ensures t he header
  824            *  for the i mage is co rrect and  up to date .
  825            *  @param st oredImage
  826            *  @param st oredFormat
  827            *  @param im ageQuality
  828            *  @return
  829            *  @throws I mageConver sionDecomp ressionExc eption
  830            *  @throws I mageConver sionIOExce ption
  831            *  @throws I mageConver sionInvali dInputExce ption
  832            *  @throws I mageConver sionCompre ssionExcep tion
  833            * /
  834           pr ivate Byte BufferBack edImageStr eamRespons e updateDI COMHeader( ByteBuffer BackedImag eStreamRes ponse stor edImage, 
  835                             ImageF ormat stor edFormat,  ImageQuali ty imageQu ality)
  836           th rows Image Conversion Decompress ionExcepti on, ImageC onversionI OException
  837           Im ageConvers ionInvalid InputExcep tion, Imag eConversio nCompressi onExceptio n,
  838           IO Exception
  839           {
  840                    // J MW 4/18/20 111 P104 -  Laurel Br idge 3.3.2 2c fix mak es it poss ible for u s to
  841                    // u pdate the  header in  DICOM JPG  images pro perly - th ey are no  longer exc luded
  842                    
  843                    // J MW 12/23/2 010 p104 -  the image  conversio n code has  trouble u pdating DI COM JPG im age header s
  844                    // a void issue s and just  don't bot her updati ng them
  845                    /*
  846                    if(s toredForma t == Image Format.DIC OMJPEG)
  847                    {
  848                             logger .warn("Ima ge stored  in DICOMJP EG format,  not able  to update  DICOM head er for thi s format,  returning  image as s tored.");
  849                             return  storedIma ge;
  850                    }*/
  851                    
  852                    logg er.info("U pdate head er of stor ed format  [" + store dFormat +  "]");            
  853                    IIma geConversi on convers ion = getI mageConver sion();
  854                    Byte BufferBack edImageInp utStream o utStream =  null;
  855                    if(s toredImage .getTxtStr eam() == n ull){
  856                             outStr eam = conv ersion.Upd ateVAImage (storedFor mat, store dImage.get ImageStrea m().toBuff eredObject (),
  857                                               null);
  858                             
  859                    }
  860                    else {
  861                    outS tream = co nversion.U pdateVAIma ge(storedF ormat, sto redImage.g etImageStr eam().toBu fferedObje ct(), 
  862                                               storedImag e.getTxtSt ream().toB ufferedObj ect());
  863                    }
  864                    
  865                    retu rn new Byt eBufferBac kedImageSt reamRespon se(outStre am, imageQ uality);
  866           }
  867           
  868           /* *
  869            *  This meth od updates  the DICOM  image and  handles a ny excepti ons. This  should alw ays return  the image  although  it might
  870            *  be the or iginal ima ge unchang ed 
  871            *  
  872            *  @param st oredImage
  873            *  @param st oredFormat
  874            *  @param im ageQuality
  875            *  @return
  876            * /
  877           pr ivate Imag eStreamRes ponse upda teDICOMHea derHandleE xceptions( ByteBuffer BackedImag eStreamRes ponse stor edImage,
  878                             ImageF ormat stor edFormat,  ImageQuali ty imageQu ality)
  879           {
  880                    // i f DICOM th en try to  update the  DICOM hea der with t he latest  values
  881                    try
  882                    {
  883                             logger .info("Ima ge is in D ICOM forma t, updatin g DICOM he ader with  TXT file a nd HIS upd ates");
  884                             ImageS treamRespo nse update dResponse  = updateDI COMHeader( storedImag e, storedF ormat, ima geQuality) ;
  885                             if(upd atedRespon se == null )
  886                                      logger.e rror("Resp onse from  updating D ICOM heade r was null , this sho uld NEVER  happen!");
  887                             else
  888                                      return u pdatedResp onse;
  889                             // if  got to her e then the  result wa s null (sh ouldn't ha ppen), 
  890                             // but  the curre nt respons e object s hould stil l contain  the image  and text 
  891                             // fil e (since i t was buff ered), so  it shouldn 't have to  do anythi ng
  892                    }
  893                    catc h(IOExcept ion ioX)
  894                    {
  895                             logger .error("IO Exception  updating D ICOM heade r, " + ioX .getMessag e() + ". W ill return  image as  stored.");
  896                             // exc eption occ urred but  the curren t response  object sh ould still  contain t he image a nd text 
  897                             // fil e (since i t was buff ered), so  it shouldn 't have to  do anythi ng, we can  just retu rn that
  898                    }
  899                    catc h(ImageCon versionDec ompression Exception  icdX)
  900                    {
  901                             logger .error("Im ageConvers ionDecompr essionExce ption upda ting DICOM  header, "  + icdX.ge tMessage()  + ". Will  return im age as sto red.");
  902                             // exc eption occ urred but  the curren t response  object sh ould still  contain t he image a nd text 
  903                             // fil e (since i t was buff ered), so  it shouldn 't have to  do anythi ng, we can  just retu rn that
  904                    }
  905                    catc h(ImageCon versionCom pressionEx ception ic cX)
  906                    {
  907                             logger .error("Im ageConvers ionCompres sionExcept ion updati ng DICOM h eader, " +  iccX.getM essage() +  ". Will r eturn imag e as store d.");
  908                             // exc eption occ urred but  the curren t response  object sh ould still  contain t he image a nd text 
  909                             // fil e (since i t was buff ered), so  it shouldn 't have to  do anythi ng, we can  just retu rn that
  910                    }
  911                    catc h(ImageCon versionInv alidInputE xception i ciiX)
  912                    {
  913                             logger .error("Im ageConvers ionInvalid InputExcep tion updat ing DICOM  header, "  + iciiX.ge tMessage()  + ". Will  return im age as sto red.", ici iX);
  914                             // exc eption occ urred but  the curren t response  object sh ould still  contain t he image a nd text 
  915                             // fil e (since i t was buff ered), so  it shouldn 't have to  do anythi ng, we can  just retu rn that
  916                    }
  917                    catc h(ImageCon versionIOE xception i cioX)
  918                    {
  919                             logger .error("Im ageConvers ionIOExcep tion updat ing DICOM  header, "  + icioX.ge tMessage()  + ". Will  return im age as sto red.");
  920                             // exc eption occ urred but  the curren t response  object sh ould still  contain t he image a nd text 
  921                             // fil e (since i t was buff ered), so  it shouldn 't have to  do anythi ng, we can  just retu rn that
  922                    }
  923                    retu rn storedI mage;
  924           }
  925           
  926           pr ivate void  setImageS treamRespo nseTextFil eIfNecessa ry(ByteBuf ferBackedI mageStream Response s toredImage ,
  927                             ImageF ormat stor edFormat,  String ima geFilename , StorageC redentials  storageCr edentials,  
  928                             HashMa p<String,  String> hi sUpdate, b oolean txt FileAvaila ble)
  929           {
  930                    if(( storedImag e.getTxtSt ream() ==  null) && ( txtFileAva ilable))
  931                    {
  932                             boolea n getTextF ile = fals e;
  933                             if(Ima geFormat.i sDICOMForm at(storedF ormat))
  934                             {
  935                                      if(updat eDicomHead ers)
  936                                      {
  937                                               getTextFil e = true;
  938                                      }
  939                             }
  940                             else
  941                             {
  942                                      getTextF ile = true ;
  943                             }
  944                             if(get TextFile)
  945                             {
  946                                      ByteBuff erBackedIn putStream  txtStream  = getTxtSt reamHandle Exception( imageFilen ame, 
  947                                                       st orageCrede ntials, hi sUpdate);
  948                                      storedIm age.setTxt Stream(txt Stream);
  949                             }
  950                    }        
  951           }
  952  
  953           /* *
  954            *  This meth od is for  compressin g and conv erting ima ges into D ICOM
  955            *  @param st oredImage
  956            *  @param qu ality
  957            *  @return
  958            *  @throws I mageConver sionDecomp ressionExc eption
  959            *  @throws I mageConver sionIOExce ption
  960            *  @throws I mageConver sionInvali dInputExce ption
  961            *  @throws I mageConver sionCompre ssionExcep tion
  962            *  @throws I OException
  963            * /
  964           pr ivate Imag eStreamRes ponse comp ressAndCon vertImage( ByteBuffer BackedImag eStreamRes ponse stor edImage, 
  965                             ImageF ormatQuali ty quality )
  966           th rows Image Conversion Decompress ionExcepti on, ImageC onversionI OException
  967           Im ageConvers ionInvalid InputExcep tion, Imag eConversio nCompressi onExceptio n,
  968           IO Exception
  969           {                 
  970                    Imag eFormat st oredFormat  = storedI mage.getIm ageFormat( );
  971                    Imag eFormat ta rgetFormat  = quality .getImageF ormat();
  972                    logg er.info("c ompress an d convert  from [" +  storedForm at + "] to  [" + targ etFormat +  "]");
  973                    
  974                    if(s toredForma t == targe tFormat)
  975                    {
  976                             // the  stored fo rmat is DI COM
  977                             if(upd ateDicomHe aders)
  978                             {
  979                                      logger.i nfo("Store d format i s the same  as target  format, u pdating DI COM header  and retur ning image .");
  980                                      // if DI COM then t ry to upda te the DIC OM header  with the l atest valu es
  981                                      return u pdateDICOM HeaderHand leExceptio ns(storedI mage, stor edFormat,  quality.ge tImageQual ity());
  982                             }
  983                             logger .info("Sto red format  is the sa me as targ et format,  returning  input.");
  984                             return  storedIma ge;
  985                    }
  986                    
  987                    else  if (targe tFormat ==  ImageForm at.ORIGINA L)
  988                    {
  989                             logger .info("Tar get format  is ORIGIN AL, return ing input" );
  990                             return  storedIma ge;
  991                    }
  992                    Imag eQuality i mageQualit y = qualit y.getImage Quality();
  993                    IIma geConversi on convers ion = getI mageConver sion();
  994                    Byte BufferBack edObject t xtObject =  null;
  995                    if(s toredImage .getTxtStr eam() != n ull)
  996                             txtObj ect = stor edImage.ge tTxtStream ().toBuffe redObject( );
  997                    if(i mageQualit y == Image Quality.TH UMBNAIL)
  998                    {
  999                             
  1000                             ByteBu fferBacked ImageInput Stream out Stream = c onversion. ConvertIma ge(storedF ormat, tar getFormat,  
  1001                                               imageQuali ty, stored Image.getI mageStream ().toBuffe redObject( ), txtObje ct);
  1002                             return  new ByteB ufferBacke dImageStre amResponse (outStream , imageQua lity);
  1003                    }
  1004                    else
  1005                    {
  1006                             ImageF ormat conv ertFormat  = targetFo rmat;
  1007                             /*
  1008                              // JM W 9/4/2009  - no long er do this  - VRad ne eds DICOM  without do ing J2K, r equestor s hould know  what they  want!
  1009                             if((ta rgetFormat  == ImageF ormat.DICO M)
  1010                                               || (target Format ==  ImageForma t.DICOMJPE G)
  1011                                               || (target Format ==  ImageForma t.DICOMJPE G2000))
  1012                             {
  1013                                      logger.i nfo("Reque st was for  a DICOM t ype, chang ing to DIC OM JPEG 20 00");
  1014                                      convertF ormat = Im ageFormat. DICOMJPEG2 000;
  1015                             }*/
  1016                             ByteBu fferBacked ImageInput Stream out Stream = c onversion. ConvertIma ge(storedF ormat, con vertFormat
  1017                                               imageQuali ty, stored Image.getI mageStream ().toBuffe redObject( ), txtObje ct);
  1018                             return  new ByteB ufferBacke dImageStre amResponse (outStream , imageQua lity);
  1019                    }
  1020           }
  1021  
  1022           pr ivate bool ean reques tAllowsOri ginalImage Type(Image FormatQual ityList re questForma tQualityLi st)
  1023           {
  1024                    if(r equestForm atQualityL ist == nul l){
  1025                             logger .debug("Im ageFormatQ ualityList  is null." );
  1026                             return  false;
  1027                    }
  1028                    
  1029                    for( ImageForma tQuality q uality : r equestForm atQualityL ist)
  1030                    {
  1031                             if(qua lity.getIm ageFormat( ) == Image Format.ORI GINAL){
  1032                                      logger.d ebug("Foun d matched  ImageForma t in Image FormatQual ityList");
  1033                                      return t rue;
  1034                             }
  1035                    }
  1036                    logg er.debug(" Found no m atch in Im ageFormatQ ualityList ");
  1037                    retu rn false;
  1038           }
  1039  
  1040           pr ivate bool ean isStor edFormatIn Request(Im ageFormatQ ualityList  requestFo rmatQualit yList, 
  1041                             ImageF ormat stor edFormat,  ImageQuali ty storedQ uality)
  1042           {
  1043                    if(r equestForm atQualityL ist == nul l)
  1044                             return  false;
  1045                    for( ImageForma tQuality q uality : r equestForm atQualityL ist)
  1046                    {
  1047                             // JMW  1/26/2009  - change  to this fu nction, us ed to comp are format  and quali ty directl y
  1048                             // now , if forma t is the s ame and st oredQualit y >= quali ty, then r eturn true
  1049                             // qua lity must  be better  than or eq ual to to  be true.                    
  1050                             if(qua lity.getIm ageFormat( ) == store dFormat)
  1051                             {
  1052                                      if(quali ty.getImag eQuality() .getCanoni cal() <= s toredQuali ty.getCano nical())
  1053                                               return tru e;
  1054                             }                
  1055                    }
  1056                    retu rn false;
  1057           }
  1058  
  1059           
  1060           pr ivate bool ean isStor edFormatIn Request(Im ageFormatQ ualityList  requestFo rmatQualit yList, 
  1061                             ImageF ormat stor edFormat)
  1062           {
  1063                    if(r equestForm atQualityL ist == nul l)
  1064                             return  false;
  1065                    for( ImageForma tQuality q uality : r equestForm atQualityL ist)
  1066                    {
  1067                             // JMW  1/26/2009  - change  to this fu nction, us ed to comp are format  and quali ty directl y
  1068                             // now , if forma t is the s ame and st oredQualit y >= quali ty, then r eturn true
  1069                             // qua lity must  be better  than or eq ual to to  be true.                    
  1070                             if(qua lity.getIm ageFormat( ) == store dFormat)
  1071                             {
  1072                                      return t rue;
  1073                             }                
  1074                    }
  1075                    retu rn false;
  1076           }
  1077  
  1078  
  1079           /*
  1080           pr ivate Stor ageProximi ty getStor ageProximi tyFromVist aLocation( String img Location)
  1081           {
  1082                    if(I MAGE_LOCAT ION_MAGNET IC.equals( imgLocatio n))
  1083                    {
  1084                             return  StoragePr oximity.ON LINE;
  1085                    }
  1086           }
  1087            * /
  1088   }