789. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 10/18/2018 2:02:20 PM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

789.1 Files compared

# Location File Last Modified
1 VIX_SIV_v3_0_patch_201_build_8.zip\v3.0_patch_201_build_8\VISA\Java\ImagingExchangeImageConversion\main\src\java\gov\va\med\imaging\exchange\conversion ImageConversion.java Thu Oct 11 13:30:18 2018 UTC
2 VIX_SIV_v3_0_patch_201_build_8.zip\v3.0_patch_201_build_8\VISA\Java\ImagingExchangeImageConversion\main\src\java\gov\va\med\imaging\exchange\conversion ImageConversion.java Wed Oct 17 18:56:49 2018 UTC

789.2 Comparison summary

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

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

789.4 Active regular expressions

No regular expressions were active.

789.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: Augu st 10, 200 6
  6     Site Nam e:  Washin gton OI Fi eld Office , Silver S pring, MD
  7       Developer:     P I
I
  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   package go v.va.med.i maging.exc hange.conv ersion;
  26  
  27   import gov .va.med.im aging.Size dInputStre am;
  28   import gov .va.med.im aging.core .interface s.IImageCo nversionCo nfiguratio n;
  29   import gov .va.med.im aging.core .interface s.IImageLo ssyCompres sionConfig uration;
  30   import gov .va.med.im aging.dico m.utilitie s.api.reco nstitution .interface s.DicomObj ectReconst itutionFac ade;
  31   import gov .va.med.im aging.dico m.utilitie s.exceptio ns.Generic DicomRecon stitutionE xception;
  32   import gov .va.med.im aging.exch ange.conve rsion.exce ptions.Ima geConversi onCompress ionExcepti on;
  33   import gov .va.med.im aging.exch ange.conve rsion.exce ptions.Ima geConversi onDecompre ssionExcep tion;
  34   import gov .va.med.im aging.exch ange.conve rsion.exce ptions.Ima geConversi onIOExcept ion;
  35   import gov .va.med.im aging.exch ange.conve rsion.exce ptions.Ima geConversi onInvalidI nputExcept ion;
  36   import gov .va.med.im aging.exch ange.conve rsion.inte rfaces.IIm ageConvers ion;
  37   import gov .va.med.im aging.exch ange.enums .ImageForm at;
  38   import gov .va.med.im aging.exch ange.enums .ImageQual ity;
  39   import gov .va.med.im aging.exch ange.stora ge.ByteBuf ferBackedI mageInputS tream;
  40   import gov .va.med.im aging.exch ange.stora ge.ByteBuf ferBackedI mageStream Response;
  41   import gov .va.med.im aging.exch ange.stora ge.ByteBuf ferBackedO bject;
  42  
  43   import jav a.io.IOExc eption;
  44   import jav a.nio.Byte Buffer;
  45  
  46   import org .apache.lo gging.log4 j.LogManag er;
  47   import org .apache.lo gging.log4 j.Logger;
  48  
  49   import com .aware.j2k .codec.eng ine.AwJ2k;
  50   import com .aware.j2k .codec.eng ine.AwJ2kC riticalExc eption;
  51   import com .aware.j2k .codec.eng ine.AwJ2kE xception;
  52   import com .aware.j2k .codec.eng ine.AwJ2kP arameters;
  53   import com .aware.j2k .codec.eng ine.AwOutp utImageVal ue;
  54  
  55   /**
  56    * @author   P I
I
  57    * The Ima ge Convers ion class  shields al l DICOM an d compress ion relate d details  from the
  58    * rest of  the syste m. It uses  streams t o communic ate with V istA Imagi ng legacy  and with
  59    * the out side world . It confo rms to the  VA-DOD El  Paso NDAA  Image Sha ring proje cts's
  60    * require ments in t erm of ima ge convers ions and t o ViX-to-V iX operati ons.
  61    * 
  62    * Note: S pring supp lied singl eton
  63    */
  64   public cla ss ImageCo nversion 
  65   implements  IImageCon version 
  66   {
  67           pr ivate IIma geConversi onConfigur ation imag eConversio nConfigura tion = nul l;
  68           pr ivate IIma geLossyCom pressionCo nfiguratio n imageLos syCompress ionConfigu ration = n ull;
  69  
  70       privat e static f inal Logge r LOGGER =  LogManage r.getLogge r (ImageCo nversion.c lass);
  71  
  72           pr ivate Dico mObjectRec onstitutio nFacade di comUtiliti es;
  73           
  74           pu blic Image Conversion (IImageCon versionCon figuration  imageConv ersionConf iguration,
  75                             IImage LossyCompr essionConf iguration  imageLossy Compressio nConfigura tion)
  76           {
  77                    this .imageConv ersionConf iguration  = imageCon versionCon figuration ;
  78                    this .imageLoss yCompressi onConfigur ation = im ageLossyCo mpressionC onfigurati on;
  79           }
  80           
  81       /**
  82        * Usi ng Spring  Factory.   Set DicomO bjectRecon stitutionF acade.
  83        * @pa ram dicomR econFacade  represent s the Spri ng Factory  selected  object
  84        */
  85       public  void setD icomUtilit ies(DicomO bjectRecon stitutionF acade dico mReconFaca de) 
  86       {
  87           th is.dicomUt ilities =  dicomRecon Facade;
  88       }
  89       
  90           /* *
  91            *  ConvertIm age is bid irectional . VA Input  thumbnail s can be T GA, TIFF o r JPEG,
  92            *  the DoD t humbnails  are JPEG,  final thum bnails are  always in  JPEG (los sy).
  93            *  VA input  images are  TGA+TXT o r DICOM, D oD input i mages as w ell as all  output
  94            *  images ar e DICOM (J PEG/J2K).  DoD delive red images  are alway s in DICOM  format
  95            *  
  96            *  @param so urceImageF ormat
  97            *                         DOWNSAMP LEDTGA, TG A, TIFF, J PEG, DICOM JPEG or DI COMJPEG200 0
  98            *  @param ta rgetImageF ormat
  99            *                         DOWNSAMP LEDTGA, TG A, DICOMJP EG or DICO MJPEG2000,  DICOM (fo r VA REF/D IAG TGA wi th TXT fil e) 
  100            *  @param Im ageQuality
  101            *                         DIAGNOST IC, REFERE NCE, THUMB NAIL
  102            *  @param so urceStream 1
  103            *                         SizedInp utStream o f image (J PEG, TGA o r DICOM),  with bytes ize
  104            *  @param so urceStream 2
  105            *                         Optional  SizedInpu tStream of  TXT file  or null, w ith bytesi ze
  106            *  @return S izedInputS tream
  107            *                         Stream o f image (J PEG, DICOM , maybe TG A), with b ytesize
  108            *  @throws I mageConver sionInvali dInputExce ption on i nvalid inp ut paramet ers
  109            *  @throws I mageConver sionIOExce ption
  110            *  @throws I mageConver sionCompre ssionExcep tion
  111            *  @throws I mageConver sionDecomp ressionExc eption
  112            * /
  113           /*  (non-Java doc)
  114            *  @see gov. va.med.ima ging.excha nge.conver sion.inter faces.IIma geConversi on#Convert Image(gov. va.med.ima ging.excha nge.enums. ImageForma t, gov.va. med.imagin g.exchange .enums.Ima geFormat,  gov.va.med .imaging.e xchange.en ums.ImageQ uality, go v.va.med.i maging.Siz edInputStr eam, gov.v a.med.imag ing.SizedI nputStream , gov.va.m ed.imaging .SizedInpu tStream)
  115            * /
  116           pu blic ByteB ufferBacke dImageInpu tStream Co nvertImage (
  117                             ImageF ormat sour ceImageFor mat,  // n ever null  as input
  118                             ImageF ormat targ etImageFor mat,  // n ever null  as input
  119                             ImageQ uality qua lity,                     // nev er null as  input
  120                             ByteBu fferBacked Object ima geObject,      // nev er null as  input
  121                             ByteBu fferBacked Object txt Object)        // can  be null f or thumbna ils and Do D2VA only
  122   //                        HashMa p theHISCh anges)                    // it  was used f or VA2DoD  only, not  for thumbn ails
  123           th rows Image Conversion InvalidInp utExceptio n, ImageCo nversionIO Exception,
  124                       I mageConver sionCompre ssionExcep tion, Imag eConversio nDecompres sionExcept ion
  125       //
  126           //  op-s and  buffer han dling:
  127           //
  128           //  DoD2VA: N OOP for TN /REF/DIAG:  sourceStr eeam1 -> b uf1 -> tar getStream1
  129           //       or [ op1: decom press] & [ op2: DICOM  sanitize] ]
  130           //          ( sS1 -> [bu f1 -> [op1  ->] buf2)  & (buf2 - > [op2 ->] ] tS)         - dcm
  131       //
  132           //  VA2DOD: [ op1: (toDi com & upda te) or (up date only) ] & [op2:  compress]
  133           //          ( sS1[[+sS2]  -> op1 ->  buf1) & ( op2 -> buf 2] -> tS)                - dcmjx x
  134           //       or f or thumbna ils: sS1 - > buf1 [->  op2 ] ->  tS                       - jpg
  135           {
  136           
  137           // ByteBuffer BackedImag eInputStre am targetS tream = nu ll;
  138                    Byte BufferBack edObject c onvertedOb ject = nul l;
  139           
  140  
  141                    try 
  142                    {
  143                             // che ck input p arameters  for sanity
  144                             if ( ( sourceImag eFormat ==  null) ||  (targetIma geFormat = = null) ||
  145                                       (qualit y == null)  || (image Object ==  null)) 
  146                             {
  147                                      String g uiltList =  "";
  148                                      if (sour ceImageFor mat == nul l) guiltLi st += "sou rceImageFo rmat, ";
  149                                      if (targ etImageFor mat == nul l) guiltLi st += "tar getImageFo rmat, ";
  150                                      if (qual ity == nul l) guiltLi st += "qua lity, ";
  151                                      if (imag eObject ==  null) gui ltList +=  "sizedSour ceStream1,  ";
  152                                      if (guil tList.leng th() > 2)  guiltList  = guiltLis t.substrin g(0, guilt List.lengt h()-2);
  153                             LOGGER .error("Im ageConvers ion has in valid (nul l) input p arameter(s ): " + gui ltList);
  154                                      throw ne w ImageCon versionInv alidInputE xception(" Image Conv ersion has  invalid ( null) inpu t paramete r" + guilt List);
  155                             }
  156                             
  157                             if ( ( sourceImag eFormat ==  ImageForm at.DICOMJP EG) ||
  158                                       (source ImageForma t == Image Format.DIC OMJPEG2000 ) ) 
  159                             {        
  160                                      // DoD2V A or fancy  V2V conve rsion
  161                                      if ( (ta rgetImageF ormat != I mageFormat .DICOMJPEG ) &&
  162                                                (targetIm ageFormat  != ImageFo rmat.DICOM JPEG2000)  &&
  163                                                (targetIm ageFormat  != ImageFo rmat.DICOM ) ) 
  164                                      {                //  fancy V2V  non-DICOM  conversio n
  165                                               return new  ByteBuffe rBackedIma geInputStr eam(dicomC ompress(im ageObject,  
  166                                                                qual ity, targe tImageForm at, true)) ;     
  167                                      }
  168                                      else if  ((sourceIm ageFormat  == targetI mageFormat
  169                                                       &&  (txtObjec t == null)
  170                                      {
  171                                               return new  ByteBuffe rBackedIma geInputStr eam(imageO bject);
  172                                      }
  173                                      else {   // somethi ng to do
  174                                              
  175                                               if ( (txtO bject != n ull)) 
  176                                               {       //  V2V DICOM  header up date from  TXT file                           
  177                                                       //  txt in st ream 2, DI COM in str eam 1; out put to buf fer1
  178                                                       co nvertedObj ect = upda teDicomObj ect(imageO bject, txt Object);
  179                                               }                
  180                                               else 
  181                                               {
  182                                                       co nvertedObj ect = imag eObject;
  183                                               } // buffe r1 has str eam1
  184                                               if (source ImageForma t == targe tImageForm at) 
  185                                               {                                                   
  186                                                       //  forward b uffer1 to  target str eam
  187                                                       // toTargetSt ream(targe tStream, b ufs, 1);
  188                                                       //  do nothin g, targetS tream alre ady set fr om previou s step
  189                                                       re turn new B yteBufferB ackedImage InputStrea m(converte dObject);
  190                                              
  191                                               else if (  ( (sourceI mageFormat  == ImageF ormat.DICO MJPEG) &&
  192                                                           (targetIm ageFormat  == ImageFo rmat.DICOM JPEG2000))  || 
  193                                                           ( (source ImageForma t == Image Format.DIC OMJPEG2000 ) &&
  194                                                             (target ImageForma t == Image Format.DIC OMJPEG) )  )  
  195                                               {       //  fancy V2V  DICOM con version
  196                                                       //  DICOM tra nsfer synt ax convers ion (to lo ssy or los sless) 
  197                                                       //  with opti onal quali ty down gr ade -- REF  or DIAG ( no DIAGUC  here!!!)
  198                                                       //  from buff er1 to tar getStream/ output usi ng buffer  2
  199                                                       re turn new B yteBufferB ackedImage InputStrea m(dicomCom press(conv ertedObjec t, 
  200                                                                         qualit y, targetI mageFormat , true));
  201                                               }
  202                                               else 
  203                                               {       //  DoD2VA DI COM decomp ress to ra w DICOM fo rmat (opti onal in fu ture),
  204                                                       //  use buffe r1, output  to buffer 2
  205                                                       co nvertedObj ect = deco mpressDico mData(imag eObject);
  206                                                                                                   
  207                                                       //  optionall y, look fo r offendin g elements  (icon ima ge, etc.)  in DICOM d ata 
  208                                                       //  and remov e them (in put from b uffer2, ou tput to tS ]
  209                                                       re turn new B yteBufferB ackedImage InputStrea m(sanitize DicomData( convertedO bject)); / /pass thro ugh dicom  data
  210                                               }
  211                                      }
  212                             } 
  213                             else 
  214                             {                                                                                                                 //  VA2DoD or  thumbnail                    
  215                                      if (qual ity != Ima geQuality. THUMBNAIL)  
  216                                      {
  217                                               // VA2DoD  DICOM oper ations (on  REFERENTI AL or DIAG NOSTIC ima ges) 
  218  
  219                                               //               -- T XT file ca nnot be nu ll! (8/14/ 08 - cpt)
  220                                               if (txtObj ect == nul l) 
  221                                               {
  222                                                       th row new Im ageConvers ionInvalid InputExcep tion(
  223                                                       "I mage Conve rsion rece ived null  input para meter for  TXT file s tream (siz edSourceSt ream2 or s izedSource Stream2.ge tInStream( ))");
  224                                               }                                          
  225                                               if ((sourc eImageForm at==ImageF ormat.DICO M)) 
  226                                               {
  227                                                       //  DICOM inp ut: update  DICOM hea der only ( from end o f stream2) , output t o buffer1
  228                                                       co nvertedObj ect = upda teDicomObj ect(imageO bject, txt Object);
  229                                               }
  230                                               else 
  231                                               {
  232                                                       //  reconstit ute TGA an d TXT file s to DICOM  and updat e header f rom end of  TXT2,
  233                                                       co nvertedObj ect = crea teDicomObj ect(imageO bject, txt Object); 
  234                                               }
  235  
  236                                               if ((quali ty==ImageQ uality.DIA GNOSTICUNC OMPRESSED)  ||   // b ypass comp ression fo r Diagnost ic with qu ality=100
  237                                                       (i mageConver sionConfig uration.is NoLossless Compressio n() &&
  238                                                                         (quali ty==ImageQ uality.DIA GNOSTIC))  ||           // no co mpress if  appconfig  flag set 
  239                                                        ( targetImag eFormat ==  ImageForm at.DICOM))  
  240                                               {                // n on-compres sed DICOM  specifical ly asked 
  241                                                       //  funnel bu ffer1 to o utput
  242                                                       //  do nothin g, targetS tream alre ady set
  243                                                       re turn new B yteBufferB ackedImage InputStrea m(converte dObject);
  244                                               }
  245                                               else 
  246                                               {
  247                                                       re turn new B yteBufferB ackedImage InputStrea m(dicomCom press(conv ertedObjec t, 
  248                                                                         qualit y, targetI mageFormat , true));
  249                                               }
  250                                      }
  251                                      else 
  252                                      {                
  253                                               // Thumbna il operati ons
  254                                               if (source ImageForma t != Image Format.JPE G) 
  255                                               {
  256                                                       //  compress  TGA, TIFF  or BMP to  JPEG
  257                                                       //  sS1 input  to buf1,  output to  Ts1 
  258                                                       re turn thumb nailCompre ss(imageOb ject);
  259                                              
  260                                               else 
  261                                               {
  262                                                       //  no conver sion to do : funnel i nput to ou tput                            
  263                                                       re turn new B yteBufferB ackedImage InputStrea m(imageObj ect);
  264                                               }
  265                                      } 
  266                             }        
  267                    }
  268                    catc h (OutOfMe moryError  oome) 
  269                    {
  270                    LOGG ER.error(" ImageConve rsion Out  of Memory  error: ",  oome);
  271                             throw  new ImageC onversionI OException ("ImageCon version Ou t of Memor y error: " , oome);
  272                    }
  273           }
  274  
  275           /* *
  276            *  CompressI mage is fo r ViX2ViX  performanc e boost su pport over  WAN lines  when 
  277            *  DICOM con version/up date is no t required . Expected  Reference /Diagnosti c quality
  278            *  input ima ge types a re BMP, TI FF, DICOM,  TGA (most ly for Thu mbnails).  Thumbnail
  279            *  compressi on does th e same con version Co nvertImage  does, pro ducing JPE G (lossy)
  280            *  output on ly.
  281            *  Already c ompressed  inputs and  failed J2 K compress ion attemp ts throw e xception.
  282            *  Note: LZW  compresse d TIFF ima ges will f ail.
  283            *  
  284            *  @param Im ageQuality
  285            *                         THUMBNAI L, REFEREN CE, DIAGNO STIC  
  286            *  @param so urceImageF ormat
  287            *                         BMP, TIF F, TGA, JP EG, DICOM
  288            *  @param ta rgetImageF ormat
  289            *                         JPEG (Th umbnail de fault), J2 K (default ), DICOMJP EG or DICO MJPEG2000
  290            *  @param im ageObject
  291            *                         SizedInp utStream o f image (J PEG, BMP,  TIFF, DICO M, TGA), w ith bytesi ze
  292            *  @param mo dality
  293            *                DICOM  modality t ype if ava ilable, el se null
  294            *  @param mo dality
  295            *                         2 byte D ICOM Modal ity code;  needed for  non-DICOM  input if  possible
  296            *  @return S izedInputS tream
  297            *                         Stream o f image (J PEG, J2K,  DICOMJPEG,  DICOMJ2K) , with byt esize
  298            *  @throws I mageConver sionInvali dInputExce ption on i nvalid inp ut paramet ers
  299            *  @throws I mageConver sionCompre ssionExcep tion
  300            * /
  301           /*  (non-Java doc)
  302            *  @see gov. va.med.ima ging.excha nge.conver sion.inter faces.IIma geConversi on#Compres sImage(gov .va.med.im aging.exch ange.enums .ImageQual ity, gov.v a.med.imag ing.exchan ge.enums.I mageFormat , gov.va.m ed.imaging .SizedInpu tStream)
  303            * /
  304           pu blic ByteB ufferBacke dImageInpu tStream Co mpressImag e(
  305                                                 ImageQua lity quali ty,                    // THUMBN AIL, REFER ENCE, DIAG NOSTIC
  306                                                 ImageFor mat source ImageForma t, // BMP,  TIFF, TGA , JPEG, DI COM
  307                                                 ImageFor mat target ImageForma t, // JPEG , J2K, DIC OMJPEG, DI COMJ2K
  308                                                 ByteBuff erBackedOb ject image Object,
  309                                                 String m odality)                                  / / needed f or non-DIC OM input t o guide co mpression  Ratio/Qual ity
  310           th rows Image Conversion InvalidInp utExceptio n, ImageCo nversionIO Exception,
  311           Im ageConvers ionCompres sionExcept ion
  312           {        
  313                    // c heck input  parameter s for sani ty
  314                    if (  (sourceIm ageFormat  == null) | | (targetI mageFormat  == null)  ||
  315                              (qual ity == nul l) ||
  316                              (imag eObject ==  null) ) {
  317                             String  guiltList  = "";
  318                             if (so urceImageF ormat == n ull) guilt List += "s ourceImage Format, ";
  319                             if (ta rgetImageF ormat == n ull) guilt List += "t argetImage Format, ";
  320                             if (qu ality == n ull) guilt List += "q uality, ";
  321                             if (im ageObject  == null) g uiltList + = "sourceS tream, ";
  322                             if (gu iltList.le ngth() > 2 ) guiltLis t = guiltL ist.substr ing(0, gui ltList.len gth()-2);
  323                    LOGG ER.error(" CompressIm age has in valid (nul l) input p arameter(s ): " + gui ltList);
  324                             throw  new ImageC onversionI nvalidInpu tException (
  325                                      "Compres sImage has  invalid ( null) inpu t paramete r" + guilt List);
  326                    }
  327                    if ( sourceImag eFormat==t argetImage Format) 
  328                    { //  do nothin g: funnel  input to o utput
  329                             return  new ByteB ufferBacke dImageInpu tStream(im ageObject) ;
  330                    }
  331                    if ( quality==I mageQualit y.THUMBNAI L) 
  332                    {         // fo rce JPEG ( lossy) out put
  333                             return  thumbnail Compress(i mageObject );
  334                    }
  335  
  336                    if ( (targetIma geFormat!= ImageForma t.J2K) &&
  337                             (targe tImageForm at!=ImageF ormat.DICO MJPEG2000)  &&
  338                             (targe tImageForm at!=ImageF ormat.JPEG ) &&
  339                             (targe tImageForm at!=ImageF ormat.DICO MJPEG)) 
  340                    {
  341                    LOGG ER.error(" CompressIm age got in valid targ etImageFor mat " + ta rgetImageF ormat.getT ype());
  342                             throw  new ImageC onversionI nvalidInpu tException (
  343                                      "Compres sImage got  invalid t argetImage Format " +  targetIma geFormat.g etType());   
  344                    }
  345  
  346                    // D IAGNOSTIC  or REFEREN CE
  347                    if ( (sourceIma geFormat== ImageForma t.BMP) ||
  348                             (sourc eImageForm at==ImageF ormat.TGA)  ||
  349                             (sourc eImageForm at==ImageF ormat.TIFF )|| 
  350                             (sourc eImageForm at==ImageF ormat.JPEG )) 
  351                    { 
  352                             // mak e sure out put is not  DICOM
  353                             if ((t argetImage Format==Im ageFormat. DICOMJPEG)  ||
  354                                      (targetI mageFormat ==ImageFor mat.DICOMJ PEG2000))  {
  355                             LOGGER .error("Co mpressImag e cannot c reate DICO M compress ed output  for " + so urceImageF ormat.getT ype() + "  input!");
  356                                      throw ne w ImageCon versionInv alidInputE xception(
  357                                               "CompressI mage canno t create D ICOM compr essed outp ut for " +  sourceIma geFormat.g etType() +  " input!" );  
  358                             }
  359                             // Com press BMP,  TGA, TIFF  or JPEG i nput to J2 K or JPEG  format
  360                             // do  compress
  361                             return  Compress( imageObjec t, quality , targetIm ageFormat,  modality,  false);                        
  362                    }
  363                    else  if (sourc eImageForm at==ImageF ormat.DICO M) 
  364                    {
  365                             // sen d from buf fer1 to co mpressor t o buffer2  to tStream
  366                             if ((t argetImage Format==Im ageFormat. DICOMJPEG)  ||
  367                                               (targetIma geFormat== ImageForma t.DICOMJPE G2000)) 
  368                             {
  369                                      return n ew ByteBuf ferBackedI mageInputS tream(dico mCompress( imageObjec t, quality , targetIm ageFormat,  false));
  370                             } 
  371                             else 
  372                             { // J PEG or J2K  output
  373                                      return C ompress(im ageObject,  quality,  targetImag eFormat, m odality, f alse);                                                                    
  374                             }
  375                    }
  376                    else  if(source ImageForma t==ImageFo rmat.DICOM JPEG2000){
  377                             ByteBu fferBacked ImageInput Stream out Stream = n ull;
  378                             ByteBu fferBacked Object out Object = n ull;
  379                             //deco mpress the  stream.
  380                             try {
  381                                      outStrea m = 
  382                                                       De compressIm age(source ImageForma t, ImageFo rmat.DICOM , imageObj ect);
  383                                      outObjec t = outStr eam.toBuff eredObject ();
  384                             } catc h (ImageCo nversionDe compressio nException  icdX) {
  385                             LOGGER .error("Im age Decomp ression Ex ception: " , icdX);
  386                             LOGGER .error("Fa iled to de compress i mage from  [" + sourc eImageForm at + "] to  [" + targ etImageFor mat +"]");
  387                                      throw ne w ImageCon versionCom pressionEx ception(
  388                                               "Failed to  decompres s image fr om [" + so urceImageF ormat + "]  to [" + t argetImage Format +"] ");
  389                             } catc h (IOExcep tion ioX)  {
  390                             LOGGER .error("Fa iled to de compress i mage from  [" + sourc eImageForm at + "] to  [" + targ etImageFor mat +"]");
  391                             LOGGER .error("IO  Exception  while Ima ge Decompr ession: ",  ioX);
  392                                      throw ne w ImageCon versionCom pressionEx ception(
  393                                               "Failed to  decompres s image fr om [" + so urceImageF ormat + "]  to [" + t argetImage Format +"] ");
  394                             }
  395                             //if t arget is D ICOM, retu rn the dec ompress st ream.
  396                             if(tar getImageFo rmat == Im ageFormat. DICOM){
  397                                      return o utStream;
  398                             }
  399                             //if t arget is J PEG,
  400                                      //conver t DICOM st ream to a  JPEG strea m and retu rn
  401                             else i f(targetIm ageFormat  == ImageFo rmat.JPEG) {
  402                                      return C ompress(ou tObject, q uality, ta rgetImageF ormat, mod ality, fal se);
  403                             }
  404                             else{
  405                             LOGGER .error("In valid targ etImageFor mat " + ta rgetImageF ormat.getT ype());
  406                                      throw ne w ImageCon versionInv alidInputE xception(
  407                                               "Invalid t argetImage Format " +  targetIma geFormat.g etType());                               
  408                             }
  409                    }
  410                    else  
  411                    {        // inv alid input  type
  412                    LOGG ER.error(" Invalid so urceImageF ormat " +  sourceImag eFormat.ge tType());
  413                             throw  new ImageC onversionI nvalidInpu tException (
  414                                      "Invalid  sourceIma geFormat "  + sourceI mageFormat .getType() );
  415                    }         
  416           }
  417  
  418           /* *
  419            *  Decompres sImage is  for ViX2Vi X when cli ent reques ts uncompr essed data  from 
  420            *  remote si te. Only D iagnostic  and Refere nce qualit y compress ed data is  expected.
  421            *  Expected  input stre am formats  are J2K,  JPEG, DICO MJ2K and D ICOMJPEG.
  422            *  Expected  output typ es are TIF F, TGA, BM P (for JPE G and J2K  input) and  DICOM 
  423            *  (for DICO MJ2K and D ICOMJPEG).
  424            *  Uncompres sed inputs  and faile d J2K deco mpression  attempts t hrow excep tion.
  425            *  
  426            *  @param so urceFormat
  427            *                         J2K, JPE G, DICOMJ2 K and DICO MJPEG
  428            *  @param ta rgetFormat
  429            *                          BMP, TI FF, TGA, D ICOM
  430            *  @param im ageObject
  431            *                         SizedInp utStream o f input im age, with  bytesize
  432            *  @return S izedInputS tream
  433            *                         Stream o f image (T IFF, BMP,  DICOM, may be TGA), w ith bytesi ze
  434            *  @throws I mageConver sionInvali dInputExce ption on i nvalid inp ut paramet ers
  435            *  @throws I mageConver sionDecomp ressionExc eption
  436            * /
  437           /*  (non-Java doc)
  438            *  @see gov. va.med.ima ging.excha nge.conver sion.inter faces.IIma geConversi on#Decompr essImage(g ov.va.med. imaging.ex change.enu ms.ImageFo rmat, gov. va.med.ima ging.excha nge.enums. ImageForma t, gov.va. med.imagin g.SizedInp utStream)
  439            * /
  440           pu blic ByteB ufferBacke dImageInpu tStream De compressIm age(
  441                                                                         ImageF ormat sour ceImageFor mat, // JP EG, J2K, D ICOMJPEG,  DICOMJ2K
  442                                                                         ImageF ormat targ etImageFor mat, // BM P, TIFF, T GA, DICOM
  443                                                                         ByteBu fferBacked Object ima geObject)
  444           th rows Image Conversion InvalidInp utExceptio n, ImageCo nversionIO Exception,
  445           Im ageConvers ionDecompr essionExce ption
  446           {
  447                    // c heck input  parameter s for sani ty
  448                    if (  (sourceIm ageFormat  == null) | | (targetI mageFormat  == null)  ||
  449                              (imag eObject ==  null)  ) 
  450                    {
  451                             String  guiltList  = "";
  452                             if (so urceImageF ormat == n ull) guilt List += "s ourceImage Format, ";
  453                             if (ta rgetImageF ormat == n ull) guilt List += "t argetImage Format, ";
  454                             if (im ageObject  == null) g uiltList + = "sourceS tream, ";
  455                             if (gu iltList.le ngth() > 2 ) guiltLis t = guiltL ist.substr ing(0, gui ltList.len gth()-2);
  456                    LOGG ER.error(" Decompress Image has  invalid (n ull) input  parameter (s): " + g uiltList);
  457                             throw  new ImageC onversionI nvalidInpu tException (
  458                                      "Decompr essImage h as invalid  (null) in put parame ter" + gui ltList);
  459                    }
  460                    if ( sourceImag eFormat==t argetImage Format) 
  461                    { //  do nothin g: funnel  input to o utput
  462                             return  new ByteB ufferBacke dImageInpu tStream(im ageObject) ;
  463                    }
  464                    
  465                    if ( (sourceIma geFormat!= ImageForma t.J2K) &&
  466                             (sourc eImageForm at!=ImageF ormat.DICO MJPEG2000)  &&
  467                             (sourc eImageForm at!=ImageF ormat.JPEG ) &&
  468                             (sourc eImageForm at!=ImageF ormat.DICO MJPEG)) 
  469                    {
  470                    LOGG ER.error(" Decompress Image got  invalid so urceImageF ormat " +  sourceImag eFormat);
  471                             throw  new ImageC onversionI nvalidInpu tException (
  472                                      "Decompr essImage g ot invalid  sourceIma geFormat "  + sourceI mageFormat );  
  473                    }
  474                    if ( (targetIma geFormat!= ImageForma t.BMP) &&
  475                             (targe tImageForm at!=ImageF ormat.TIFF ) &&
  476                             (targe tImageForm at!=ImageF ormat.TGA)  &&
  477                             (targe tImageForm at!=ImageF ormat.DICO M)) 
  478                    {
  479                    LOGG ER.error(" Decompress Image got  invalid ta rgetImageF ormat " +  targetImag eFormat.ge tType());
  480                             throw  new ImageC onversionI nvalidInpu tException (
  481                                      "Decompr essImage g ot invalid  targetIma geFormat "  + targetI mageFormat .getType() );        
  482                    }
  483                    bool ean badCom pany=false ;
  484                    if ( targetImag eFormat==I mageFormat .DICOM) {
  485                             badCom pany = ((s ourceImage Format!=Im ageFormat. DICOMJPEG2 000) &&
  486                                               (sourceIma geFormat!= ImageForma t.DICOMJPE G));
  487                    }
  488                    else  { // BMP,  TIFF, TGA  input
  489                             badCom pany = ((s ourceImage Format!=Im ageFormat. J2K) &&
  490                                               (sourceIma geFormat!= ImageForma t.JPEG));
  491                    }
  492                    if ( badCompany ) {
  493                    LOGG ER.error(" Decompress Image got  ImageForma t pair --  " + 
  494                                      sourceIm ageFormat  + " in & "  + targetI mageFormat  + " out!" );
  495                             throw  new ImageC onversionI nvalidInpu tException (
  496                                      "Decompr essImage g ot invalid  ImageForm at pair --  " + 
  497                                      sourceIm ageFormat  + " in & "  + targetI mageFormat  + " out!" );    
  498                    }                         
  499                    retu rn decompr essStream( targetImag eFormat, i mageObject );                          
  500           }
  501  
  502           /* *
  503            *  UpdateVAI mage retur ns a DICOM  stream th at is upda ted by VA  TXT input  stream. It  does 
  504            *  not apply  compressi on. VA Ref erential o r Diagnost ic quality  Input is  assumed (T GA+TXT
  505            *  or DICOM+ TXT), the  same quali ty is retu rned.
  506            *  
  507            *  @param so urceImageF ormat
  508            *                         DOWNSAMP LEDTGA, TG A, DICOM,  DICOMJPEG
  509            *  @param so urceStream 1
  510            *                         SizedInp utStream o f image (T GA or DICO M...), wit h bytesize
  511            *  @param so urceStream 2
  512            *                         SizedInp utStream o f TXT file , with byt esize
  513            *  @return S izedInputS tream
  514            *                         Stream o f raw DICO M or DICOM JPEG image , with byt esize
  515            *  @throws I mageConver sionInvali dInputExce ption on i nvalid inp ut paramet ers
  516            *  @throws I mageConver sionIOExce ption
  517            * /     
  518           /*  (non-Java doc)
  519            *  @see gov. va.med.ima ging.excha nge.conver sion.inter faces.IIma geConversi on#UpdateV AImage(gov .va.med.im aging.exch ange.enums .ImageForm at, gov.va .med.imagi ng.exchang e.enums.Im ageFormat,  gov.va.me d.imaging. exchange.e nums.Image Quality, g ov.va.med. imaging.Si zedInputSt ream, gov. va.med.ima ging.Sized InputStrea m, gov.va. med.imagin g.SizedInp utStream)
  520            * /
  521           pu blic ByteB ufferBacke dImageInpu tStream Up dateVAImag e(
  522                             ImageF ormat sour ceImageFor mat,                    // never  null as i nput
  523                             ByteBu fferBacked Object ima geObject,      // nev er null as  input
  524                             ByteBu fferBacked Object txt Object)        // nev er null as  input
  525           th rows Image Conversion InvalidInp utExceptio n, ImageCo nversionIO Exception
  526       //
  527           //  op-s and  buffer han dling:
  528           //
  529           //  VA2xxx: o p: (toDico m & update ) or (upda te only)
  530           //         (s S1+sS2 ->  op -> buf1  -> tS)                - dcm
  531           {
  532                    try 
  533                    {
  534                             // che ck input p arameters  for sanity
  535                             if ( ( sourceImag eFormat ==  null) || 
  536                                       (imageO bject == n ull) || 
  537                                       (txtObj ect == nul l) ) {
  538                                      String g uiltList =  "";
  539                                      if (sour ceImageFor mat == nul l) guiltLi st += "sou rceImageFo rmat, ";
  540                                      if (imag eObject ==  null) gui ltList +=  "sizedSour ceStream1,  ";                             
  541                                      if (txtO bject == n ull) guilt List += "s izedSource Stream2, " ;
  542                                      if (guil tList.leng th() > 2)  guiltList  = guiltLis t.substrin g(0, guilt List.lengt h()-2);
  543                             LOGGER .error("Up dateVAImag e has inva lid (null)  input par ameter(s):  " + guilt List);
  544                                      throw ne w ImageCon versionInv alidInputE xception(" Image Conv ersion has  invalid ( null) inpu t paramete r" + guilt List);
  545                             } 
  546                             else i f ( (sourc eImageForm at != Imag eFormat.DO WNSAMPLEDT GA) && (so urceImageF ormat != I mageFormat .TGA) &&
  547                                                 (sourceI mageFormat  != ImageF ormat.DICO M) && (sou rceImageFo rmat != Im ageFormat. DICOMJPEG)  ) {
  548                             LOGGER .error("Up dateVAImag e has inva lid source ImageForma t: " + sou rceImageFo rmat.toStr ing());
  549                                      throw ne w ImageCon versionInv alidInputE xception(" Image Conv ersion has  sourceIma geFormat:  " + source ImageForma t.toString ());
  550                             }
  551                             
  552                             if ( ( sourceImag eFormat ==  ImageForm at.DICOM)  || (source ImageForma t == Image Format.DIC OMJPEG) ) 
  553                             {
  554                                      // updat e DCM stre am with TX T data
  555                                      return n ew ByteBuf ferBackedI mageInputS tream(upda teDicomObj ect(imageO bject, 
  556                                                       tx tObject));
  557                             }
  558                             else 
  559                             {
  560                                      // recon stitute TG A and TXT  files to D ICOM and u pdate head er from en d of TXT2,
  561                                      return n ew ByteBuf ferBackedI mageInputS tream(crea teDicomObj ect(imageO bject, 
  562                                                       tx tObject));
  563                             }
  564                    }
  565                    catc h (OutOfMe moryError  oome) 
  566                    {
  567                    LOGG ER.error(" UpdateVAIm age Out of  Memory er ror: ", oo me);
  568                             throw  new ImageC onversionI OException ("UpdateVA Image Out  of Memory  error: ",  oome);
  569                    }                 
  570           }
  571  
  572  
  573           //  ========= ========== ========== ======== P rivate (De )Compressi on methods  ========= ========== ========== ========== ==
  574           
  575           /*  (non-Java doc)
  576            *  @see gov. va.med.ima ging.excha nge.conver sion.inter faces.IIma geConversi on#createD icomObject (gov.va.me d.imaging. SizedInput Stream, go v.va.med.i maging.Siz edInputStr eam, gov.v a.med.imag ing.exchan ge.convers ion.ImageB uffers)
  577            * /
  578           pr ivate Byte BufferBack edImageInp utStream t humbnailCo mpress(Byt eBufferBac kedObject  imageObjec t)
  579           th rows Image Conversion IOExceptio n, ImageCo nversionCo mpressionE xception
  580           {
  581                    // c ompress TG A, BMP, or  TIFF to J PEG
  582                    // s S1 input t o buf1, ou tput to Ts
  583  
  584           LO GGER.info( "JPEG comp ress Thumb nail and s tream it") ;
  585           Aw J2k codec  = null;
  586           
  587                try 
  588                {
  589                    code c = new Aw J2k();
  590                    AwJ2 k.AwJ2kEna bleErrorPr otectionMo de(true);
  591  
  592                    code c.AwJ2kSet InputImage (imageObje ct.getBuff er().array (), imageO bject.getS ize());
  593  
  594                    code c.AwJ2kSet OutputType (AwJ2kPara meters.AW_ J2K_FORMAT _JPG);
  595  
  596                    AwOu tputImageV alue value Obj = code c.AwJ2kGet OutputImag e();
  597                    // m ust copy o ut data fr om compres sor buffer  before le aving :-(
  598                    
  599                    Byte Buffer out put = Byte Buffer.all ocate(valu eObj.getIm ageLength( ));
  600                    outp ut.put(val ueObj.getI mage());
  601                    retu rn new Byt eBufferBac kedImageIn putStream( output, va lueObj.get ImageLengt h());
  602                }
  603                catch (A wJ2kExcept ion e) 
  604                {
  605                    LOGG ER.error(" ThumbnailC ompress -  Compressio n Exceptio n: " + e.g etMessage( )
  606                                                + " (" +  imageObjec t.getSize( ) + " byte s in)");
  607                    thro w new Imag eConversio nCompressi onExceptio n("Thumbna ilCompress  - Compres sion Excep tion: ", e );
  608                }
  609                    catc h (AwJ2kCr iticalExce ption  ce)  {
  610                    LOGG ER.error(" ThumbnailC ompress -  critical e xception "  + ce.getM essage());
  611                             throw  new ImageC onversionC ompression Exception( "Thumbnail Compress -  critical  exception" , ce);
  612                    }
  613                    catc h (Excepti on e) {
  614                    LOGG ER.error(" ThumbnailC ompress -  generic ex ception "  + e.getMes sage());
  615                             throw  new ImageC onversionC ompression Exception( "Thumbnail Compress -  generic e xception",  e);
  616                    }
  617                    fina lly 
  618                    {
  619                             try
  620                             {
  621                                      if (code c!=null)
  622                                               codec.AwJ2 kDestroy() ;
  623   //                                 mutex.un lock();
  624                             } 
  625                             catch  (AwJ2kExce ption ex) 
  626                             {
  627                             LOGGER .error("Th umbnailCom press - AW J2K Destro y Exceptio n: " + ex. getMessage ()
  628                                                + " (" +  imageObjec t.getSize( ) + " byte s in)");
  629   //                                 mutex.un lock();
  630                             throw  new ImageC onversionC ompression Exception( "Thumbnail Compress -  AWJ2K Des troy Excep tion: ", e x);
  631                             }
  632                    }
  633           }        
  634           
  635           /*  (non-Java doc)
  636            *  @see gov. va.med.ima ging.excha nge.conver sion.inter faces.IIma geConversi on#dicomCo mpress(gov .va.med.im aging.exch ange.enums .ImageQual ity, gov.v a.med.imag ing.exchan ge.enums.I mageFormat , gov.va.m ed.imaging .SizedInpu tStream, g ov.va.med. imaging.ex change.con version.Im ageBuffers )
  637            * /
  638           pr ivate Byte BufferBack edObject d icomCompre ss(ByteBuf ferBackedO bject imag eObject,
  639                             ImageQ uality qua lity, Imag eFormat ta rgetFormat , boolean  xChangeUse
  640           th rows Image Conversion IOExceptio n, ImageCo nversionCo mpressionE xception 
  641           {
  642                    // D ICOM image  compressi on (not th umbnail) t o DICOMJPE G2000 or D ICOMJPEG
  643                    // f rom buffer 1 to compr essor to b uffer2 to  tStream
  644  
  645                    LOGG ER.info("C ompress Di com Object (" + image Object.get Size() + " ) and stre am it");
  646                    int  autoLevel= -1; // Aut omatically  determine s the best  number of  compressi on levels  for J2K
  647                    floa t lossyCom pressionRa tio;
  648                    int  lossyJpgQu ality;
  649                    AwJ2 k codec =  null;
  650  
  651                try 
  652                {
  653                    Stri ng modalit y = getDic omModality (imageObje ct.getBuff er());
  654                         codec = ne w AwJ2k();
  655                    AwJ2 k.AwJ2kEna bleErrorPr otectionMo de(true);
  656  
  657                    code c.AwJ2kSet InputImage (imageObje ct.getBuff er().array (), imageO bject.getS ize());
  658           
  659                    if ( targetForm at == Imag eFormat.DI COMJPEG200 0)
  660                    {
  661                             if (qu ality == I mageQualit y.REFERENC E) 
  662                             {
  663                                      lossyCom pressionRa tio=
  664                                               imageLossy Compressio nConfigura tion.getMo dalityLoss yJPEG2000R atio(modal ity,
  665                                                                imag eObject.ge tSize(), x ChangeUse) ;
  666                                 co dec.AwJ2kS etOutputJ2 kRatio(los syCompress ionRatio);
  667                             }
  668                             else 
  669                             { // I mageQualit y.DIAGNOST IC
  670                                 co dec.AwJ2kS etOutputJ2 kXform(AwJ 2kParamete rs.AW_J2K_ WV_TYPE_R5 3, autoLev el);
  671                                 co dec.AwJ2kS etOutputJ2 kRatio(0);  // lossle ss compres sion
  672                             }
  673                             codec. AwJ2kSetOu tputType(A wJ2kParame ters.AW_J2 K_FORMAT_D CMJ2K); 
  674                    }
  675                    else  
  676                    {    // do regu lar JPEG
  677                             if (qu ality == I mageQualit y.REFERENC E) 
  678                             {
  679                                      lossyJpg Quality=
  680                                               imageLossy Compressio nConfigura tion.getMo dalityLoss yJPEGQuali ty(modalit y,
  681                                                                imag eObject.ge tSize(), x ChangeUse) ;
  682                                 co dec.AwJ2kS etOutputJp egOptions( lossyJpgQu ality);
  683                             }
  684                             else 
  685                             { // I mageQualit y.DIAGNOST IC
  686                                 co dec.AwJ2kS etOutputJp egOptions( -1); // lo ssless com pression
  687                             }
  688                             codec. AwJ2kSetOu tputType(A wJ2kParame ters.AW_J2 K_FORMAT_D CMJPG); //  0x0059                         
  689                    }
  690                    AwOu tputImageV alue value Obj = code c.AwJ2kGet OutputImag e();
  691                    // m ust copy o ut data fr om compres sor buffer  before le aving :-(
  692                    Byte Buffer out put = Byte Buffer.all ocate(valu eObj.getIm ageLength( ));
  693                    outp ut.put(val ueObj.getI mage());
  694                    retu rn new Byt eBufferBac kedObject( output, va lueObj.get ImageLengt h());
  695                }
  696                catch (A wJ2kExcept ion ae) 
  697                {
  698                    LOGG ER.error(" dicomCompr ess - Comp ression Ex ception: "  + ae.getM essage());
  699                    thro w new Imag eConversio nCompressi onExceptio n("dicomCo mpress - C ompression  Exception : ", ae);
  700                }
  701                    catc h (AwJ2kCr iticalExce ption  ce)  
  702                    {
  703                    LOGG ER.error(" dicomCompr ess - crit ical excep tion " + c e.getMessa ge());
  704                             throw  new ImageC onversionC ompression Exception( "dicomComp ress - cri tical exce ption", ce );
  705                    }
  706                    catc h (Excepti on e) 
  707                    {
  708                    LOGG ER.error(" dicomCompr ess - gene ric except ion " + e. getMessage ());
  709                             throw  new ImageC onversionC ompression Exception( "dicomComp ress - gen eric excep tion", e);
  710                    }
  711                    fina lly 
  712                    {
  713                             try
  714                             {
  715                                      if (code c!=null)
  716                                               codec.AwJ2 kDestroy() ;
  717                             } 
  718                             catch  (AwJ2kExce ption ex) 
  719                             {
  720                             LOGGER .error("di comCompres s - AWJ2K  Destroy Ex ception: "  + ex.getM essage());
  721                             throw  new ImageC onversionC ompression Exception( "dicomComp ress - AWJ 2K Destroy  Exception : ", ex);
  722                             }
  723                    }
  724           }
  725           
  726           /*  (non-Java doc)
  727            *  @see gov. va.med.ima ging.excha nge.conver sion.inter faces.IIma geConversi on#Compres s(gov.va.m ed.imaging .exchange. enums.Imag eQuality,  gov.va.med .imaging.e xchange.en ums.ImageF ormat, gov .va.med.im aging.exch ange.enums .ImageForm at, gov.va .med.imagi ng.SizedIn putStream,  gov.va.me d.imaging. SizedInput Stream, go v.va.med.i maging.exc hange.conv ersion.Ima geBuffers)
  728            * /
  729           pr ivate Byte BufferBack edImageInp utStream C ompress(By teBufferBa ckedObject  imageObje ct,
  730                             ImageQ uality qua lity, Imag eFormat ta rgetFormat , String m odality, b oolean xCh angeUse) 
  731           th rows Image Conversion IOExceptio n, ImageCo nversionCo mpressionE xception 
  732           {
  733                    // I mage compr ession (no t thumbnai l) of BMP,  TGA, TIFF , JPEG, DI COM to J2K  or JPEG
  734                    // f rom buffer 1 to compr essor to b uffer2 to  tStream
  735  
  736                    LOGG ER.info("C ompress Ob ject(" + i mageObject .getSize()  + ") and  stream it" );
  737                    int  autoLevel= -1; // Aut omatically  determine s the best  number of  compressi on levels  for J2K
  738                    floa t lossyCom pressionRa tio;
  739                    int  lossyJpgQu ality; //  , bpp=0; / / for down sizing bit  depth
  740                    AwJ2 k codec =  null;
  741  
  742                try 
  743                {
  744                         codec = ne w AwJ2k();
  745                    AwJ2 k.AwJ2kEna bleErrorPr otectionMo de(true);
  746                    code c.AwJ2kSet InputImage (imageObje ct.getBuff er().array (), imageO bject.getS ize());
  747           
  748                    if ( targetForm at == Imag eFormat.J2 K)
  749                    {
  750                             if (qu ality == I mageQualit y.REFERENC E) 
  751                             {
  752                                      lossyCom pressionRa tio=
  753                                               imageLossy Compressio nConfigura tion.getMo dalityLoss yJPEG2000R atio(modal ity,
  754                                                                imag eObject.ge tSize(), x ChangeUse) ;
  755                                 co dec.AwJ2kS etOutputJ2 kRatio(los syCompress ionRatio);
  756                             }
  757                             else 
  758                             { // I mageQualit y.DIAGNOST IC
  759                                 co dec.AwJ2kS etOutputJ2 kXform(AwJ 2kParamete rs.AW_J2K_ WV_TYPE_R5 3, autoLev el);
  760                                 co dec.AwJ2kS etOutputJ2 kRatio(0);  // lossle ss compres sion
  761                             }
  762                             codec. AwJ2kSetOu tputType(A wJ2kParame ters.AW_J2 K_FORMAT_J 2K);    
  763                    }
  764                    else  
  765                    {    // do regu lar JPEG
  766                             if (qu ality == I mageQualit y.REFERENC E) {
  767   //                        // 02/ 18/09 - cp t - un-com ment these  7 lines i f bit dept h reductio n is desir ed!!!
  768   //                                          bpp=codec. AwJ2kGetIn putChannel Bpp(0); 
  769   //                                          if (bpp >  8) { // :  render to  8 bit JPEG  if source  has more  than 8 bit s
  770   //                                          //      co dec.AwJ2kS etOutputCo mBitDepthS calingPara meters(AwJ 2kParamete rs.AW_J2K_ SELECT_ALL _CHANNELS,
  771   //                                          //                        AwJ2kP arameters. AW_J2K_BIT _DEPTH_SCA LING_LINEA R_METHOD,
  772   //                                          //                        AwJ2kP arameters. AW_J2K_BIT _DEPTH_SCA LING_AUTO_ CALC,
  773   //                                          //                        AwJ2kP arameters. AW_J2K_BIT _DEPTH_SCA LING_AUTO_ CALC);
  774   //                                                  co dec.AwJ2kS etOutputCo mBitDepth( AwJ2kParam eters.AW_J 2K_SELECT_ ALL_CHANNE LS, 8);
  775   //                                          }
  776                                      lossyJpg Quality=
  777                                               imageLossy Compressio nConfigura tion.getMo dalityLoss yJPEGQuali ty(modalit y,
  778                                                                imag eObject.ge tSize(), x ChangeUse) ;
  779                                 co dec.AwJ2kS etOutputJp egOptions( lossyJpgQu ality);
  780                             }
  781                             else 
  782                             { // I mageQualit y.DIAGNOST IC
  783                                 co dec.AwJ2kS etOutputJp egOptions( quality.ge tCanonical ()); // lo ssless com pression
  784                             }
  785                             codec. AwJ2kSetOu tputType(A wJ2kParame ters.AW_J2 K_FORMAT_J PG);                      
  786                    }
  787                    AwOu tputImageV alue value Obj = code c.AwJ2kGet OutputImag e();
  788                    // m ust copy o ut data fr om compres sor buffer  before le aving :-(
  789                    
  790                    Byte Buffer out put = Byte Buffer.all ocate(valu eObj.getIm ageLength( ));
  791                    outp ut.put(val ueObj.getI mage());
  792                    retu rn new Byt eBufferBac kedImageIn putStream( output, va lueObj.get ImageLengt h());
  793                }
  794                catch (A wJ2kExcept ion e) 
  795                {
  796                    LOGG ER.error(" compress -  Compressi on Excepti on: " + e. getMessage ());
  797                    thro w new Imag eConversio nCompressi onExceptio n("compres s - Compre ssion Exce ption: ",  e);
  798                }
  799                    catc h (AwJ2kCr iticalExce ption  ce)  
  800                    {
  801                    LOGG ER.error(" compress -  critical  exception  " + ce.get Message()) ;
  802                             throw  new ImageC onversionC ompression Exception( "compress  - critical  exception ", ce);
  803                    }
  804                    catc h (Excepti on e) 
  805                    {
  806                    LOGG ER.error(" compress -  generic e xception "  + e.getMe ssage());
  807                             throw  new ImageC onversionC ompression Exception( "compress  - generic  exception" , e);
  808                    }
  809                    fina lly 
  810                    {
  811                             try
  812                             {
  813                                      if (code c!=null)
  814                                               codec.AwJ2 kDestroy() ;
  815                             } 
  816                             catch  (AwJ2kExce ption ex) 
  817                             {
  818                             LOGGER .error("co mpress - A WJ2K Destr oy Excepti on: " + ex .getMessag e());
  819                             throw  new ImageC onversionC ompression Exception( "compress  - AWJ2K De stroy Exce ption: ",  ex);
  820                             }
  821                    }
  822           }
  823           /*  (non-Java doc)
  824            *  @see gov. va.med.ima ging.excha nge.conver sion.inter faces.IIma geConversi on#decompr essDicomDa ta(gov.va. med.imagin g.SizedInp utStream,  gov.va.med .imaging.e xchange.co nversion.I mageBuffer s)
  825            * /
  826           pr ivate Byte BufferBack edObject d ecompressD icomData(B yteBufferB ackedObjec t dicomIma geObject) 
  827           th rows Image Conversion IOExceptio n, ImageCo nversionDe compressio nException  
  828           {
  829                    // d ecompress  DCMJPG or  DCMJ2K dat a in buffe r1 to raw  DICOM form at (option al in futu re),
  830                    // o utput to b uffer2
  831           LO GGER.info( "Decompres s Dicom St ream");
  832                AwJ2k co dec = null ;
  833  
  834                    try 
  835                    {
  836                             codec  = new AwJ2 k();
  837                    AwJ2 k.AwJ2kEna bleErrorPr otectionMo de(true);              
  838  
  839                    code c.AwJ2kSet InputImage (dicomImag eObject.ge tBuffer(). array(), 
  840                                      dicomIma geObject.g etSize());
  841           
  842                    code c.AwJ2kSet OutputType (AwJ2kPara meters.AW_ J2K_FORMAT _DCM);
  843                    AwOu tputImageV alue value Obj = code c.AwJ2kGet OutputImag e();
  844                    
  845                    Byte Buffer out put = Byte Buffer.all ocate(valu eObj.getIm ageLength( ));
  846                    outp ut.put(val ueObj.getI mage());
  847                    retu rn new Byt eBufferBac kedObject( output, va lueObj.get ImageLengt h());
  848                }
  849                catch (A wJ2kExcept ion e) {
  850                    LOGG ER.error(" decompress DicomStrea m - Decomp ression ex ception "  + e.getMes sage());
  851                    thro w new Imag eConversio nDecompres sionExcept ion("decom pressDicom Stream - D ecompressi on Excepti on: ", e);
  852                }
  853                    catc h (AwJ2kCr iticalExce ption  ce)  {
  854                    LOGG ER.error(" decompress DicomStrea m - critic al excepti on " + ce. getMessage ());
  855                             throw  new ImageC onversionD ecompressi onExceptio n("decompr essDicomSt ream - cri tical exce ption", ce );
  856                    }
  857                    catc h (Excepti on e) {
  858                    LOGG ER.error(" decompress DicomStrea m - generi c exceptio n " + e.ge tMessage() );
  859                             throw  new ImageC onversionD ecompressi onExceptio n("decompr essDicomSt ream - gen eric excep tion", e);
  860                    }
  861                    fina lly 
  862                    {
  863                             try
  864                             {
  865                                      if (code c!=null)
  866                                               codec.AwJ2 kDestroy() ;
  867                             } 
  868                             catch  (AwJ2kExce ption ex) 
  869                             {
  870                             LOGGER .error("de compressDi comStream  - AWJ2K De stroy Exce ption: " +  ex.getMes sage());
  871                             throw  new ImageC onversionD ecompressi onExceptio n("decompr essDicomSt ream - AWJ 2K Destroy  Exception : ", ex);
  872                             }
  873                    }
  874           }
  875  
  876           /*  (non-Java doc)
  877            *  @see gov. va.med.ima ging.excha nge.conver sion.inter faces.IIma geConversi on#decompr essStream( gov.va.med .imaging.S izedInputS tream, gov .va.med.im aging.exch ange.conve rsion.Imag eBuffers)
  878            * /
  879           pr ivate Byte BufferBack edImageInp utStream d ecompressS tream(Imag eFormat ta rgetFormat
  880                             ByteBu fferBacked Object ima geObject) 
  881           th rows Image Conversion IOExceptio n, ImageCo nversionDe compressio nException  {
  882                    // d ecompress  J2K, JPEG  objects to  BMP, TIFF  or TGA an d DICOMJ2K  and DICOM JPEG
  883                    // o bjects to  plain DICO M
  884                    // u sing buffe r1 for inp ut and buf fer2 for o utput
  885           LO GGER.info( "Decompres sStream");
  886                AwJ2k co dec = null ;
  887  
  888                try 
  889                {
  890                             codec  = new AwJ2 k();
  891                    AwJ2 k.AwJ2kEna bleErrorPr otectionMo de(true);
  892  
  893                    code c.AwJ2kSet InputImage (imageObje ct.getBuff er().array (), imageO bject.getS ize());
  894  
  895                    if ( targetForm at==ImageF ormat.DICO M) 
  896                    {
  897                             codec. AwJ2kSetOu tputType(A wJ2kParame ters.AW_J2 K_FORMAT_D CM);
  898                    } 
  899                    else  if (targe tFormat==I mageFormat .BMP) 
  900                    {
  901                             codec. AwJ2kSetOu tputType(A wJ2kParame ters.AW_J2 K_FORMAT_B MP);
  902                    } 
  903                    else  if (targe tFormat==I mageFormat .TIFF) 
  904                    {
  905                             codec. AwJ2kSetOu tputType(A wJ2kParame ters.AW_J2 K_FORMAT_T IF);
  906                    } 
  907                    else  if (targe tFormat==I mageFormat .TGA) 
  908                    {
  909                             codec. AwJ2kSetOu tputType(A wJ2kParame ters.AW_J2 K_FORMAT_T GA);
  910                    } 
  911                    else  
  912                    {
  913                             codec. AwJ2kDestr oy();
  914                             LOGGER .error("de compressSt ream - inv alid targe t format:  " + target Format);
  915                             throw  new ImageC onversionI OException ("decompre ssStream -  invalid t arget form at: " + ta rgetFormat );
  916                    }
  917                    AwOu tputImageV alue value Obj = code c.AwJ2kGet OutputImag e();
  918                    
  919                    Byte Buffer out put = Byte Buffer.all ocate(valu eObj.getIm ageLength( ));
  920                    outp ut.put(val ueObj.getI mage(), 0,  valueObj. getImageLe ngth());
  921                    
  922                    retu rn new Byt eBufferBac kedImageIn putStream( output, va lueObj.get ImageLengt h());
  923                }
  924                catch (A wJ2kExcept ion e) 
  925                {
  926                    LOGG ER.error(" decompress Stream - D ecompressi on Excepti on: ", e);
  927                    thro w new Imag eConversio nDecompres sionExcept ion("decom pressStrea m - Decomp ression Ex ception: " , e);
  928                }
  929                    catc h (AwJ2kCr iticalExce ption  ce)  
  930                    {
  931                    LOGG ER.error(" decompress Stream - c ritical ex ception "  + ce.getMe ssage());
  932                             throw  new ImageC onversionD ecompressi onExceptio n("decompr essStream  - critical  exception ", ce);
  933                    }
  934                    catc h (Excepti on e) 
  935                    {
  936                    LOGG ER.error(" decompress Stream - g eneric exc eption " +  e.getMess age());
  937                             throw  new ImageC onversionD ecompressi onExceptio n("decompr essStream  - generic  exception" , e);
  938                    }
  939                    fina lly 
  940                    {
  941                             try
  942                             {
  943                                      if (code c!=null)
  944                                               codec.AwJ2 kDestroy() ;
  945                             } 
  946                             catch  (AwJ2kExce ption ex) 
  947                             {
  948                             LOGGER .error("de compressSt ream - AWJ 2K Destroy  Exception : " + ex.g etMessage( ));
  949                             throw  new ImageC onversionD ecompressi onExceptio n("decompr essStream  - AWJ2K De stroy Exce ption: ",  ex);
  950                             }
  951                    }
  952           }
  953  
  954           //  ========= ========== ========== ======== P rivate Uti lity metho ds ======= ========== ========== ========== ========== ===
  955           
  956           
  957           //  ========= ========== ========== = Private  DICOM oper ation rela ted method s ======== ========== ========== ========== ===
  958           
  959           pr ivate Byte BufferBack edObject s anitizeDic omData(Byt eBufferBac kedObject  imageObjec t)
  960           th rows Image Conversion IOExceptio
  961           {
  962                    // l ook for of fending el ements (ic on image,  etc.) in D ICOM data 
  963                    // a nd remove  them if ne cessary --  input fro m buffer2,  output to  tS
  964                    
  965                    // l et it thro ugh withou t sanity c heck
  966           LO GGER.info( "No DICOM  data sanit ization: w rite to ta rgetStream ");
  967           re turn image Object;
  968           }
  969  
  970           pr ivate Byte BufferBack edObject u pdateDicom Object(Byt eBufferBac kedObject  imageStrea m, 
  971                             ByteBu fferBacked Object tex tStream)
  972           th rows Image Conversion IOExceptio
  973           {
  974                    //       Reads  sourceStre am1, updat es Header  (direct ca ll to Imag ingDicomUt ilities),
  975                    //   finally fu nnels resu lt DataSet  to buffer 1
  976  
  977                    LOGG ER.info("U pdate Dico m Stream ( " + imageS tream.getS ize() + ")  with HIS/ TXT change s (" + tex tStream.ge tSize() +  ")");
  978                    byte [] data=nu ll;
  979  
  980                    try 
  981                    {
  982                             
  983                             SizedI nputStream  sizedDico mStream =  new SizedI nputStream (imageStre am.openInp utStreamTo Buffer(), 
  984                                               imageStrea m.getSize( ));
  985                             SizedI nputStream  sizedText Stream = n ew SizedIn putStream( textStream .openInput StreamToBu ffer(), 
  986                                               textStream .getSize() );
  987  
  988                             data =  dicomUtil ities.upda teDicomStr eam(sizedD icomStream , sizedTex tStream);
  989                             
  990                             ByteBu ffer outpu t = ByteBu ffer.alloc ate(data.l ength);
  991                             output .put(data) ;
  992                             
  993                             return  new ByteB ufferBacke dObject(ou tput, data .length);
  994                    }
  995                    catc h (Generic DicomRecon stitutionE xception g dre) 
  996                    {
  997                    LOGG ER.error(" updateDico mObject -  Error upda ting HIS d ata in DIC OM Stream:  " + gdre. getMessage ());
  998                             throw  new ImageC onversionI OException ("updateDi comObject  - Error up dating HIS  data in D ICOM Strea m", gdre);
  999                    }
  1000                    catc h (Excepti on e) 
  1001                    {
  1002                    LOGG ER.error(" updateDico mObject -  generic ex ception "  + e.getMes sage());
  1003                             throw  new ImageC onversionI OException ("updateDi comObject  - generic  exception" , e);
  1004                    }
  1005           }
  1006  
  1007           /*  (non-Java doc)
  1008            *  @see gov. va.med.ima ging.excha nge.conver sion.inter faces.IIma geConversi on#createD icomObject (gov.va.me d.imaging. SizedInput Stream, go v.va.med.i maging.Siz edInputStr eam, gov.v a.med.imag ing.exchan ge.convers ion.ImageB uffers)
  1009            * /
  1010           pr ivate Byte BufferBack edObject c reateDicom Object(Byt eBufferBac kedObject  tgaStream,  
  1011                             ByteBu fferBacked Object txt Stream)
  1012           th rows Image Conversion IOExceptio
  1013           {
  1014                    //       Reads  sourceStre am1&2 (TXT  and TGA d ata), crea tes Dicom  object (di rect call  to Imaging DicomUtili ties),
  1015                    //   finally fu nnels resu lt DataSet  to buffer 1
  1016  
  1017           LO GGER.info( "Assemble  Dicom Obje ct Stream  from Text  (" + tgaSt ream.getSi ze() + 
  1018                                      ") and T GA (" + tx tStream.ge tSize() +  ") streams ");
  1019                    byte [] data=nu ll;
  1020  
  1021                    try 
  1022                    {
  1023                             
  1024                             SizedI nputStream  sizedtgaS tream = ne w SizedInp utStream(t gaStream.o penInputSt reamToBuff er(), tgaS tream.getS ize());
  1025                             SizedI nputStream  sizedText Stream = n ew SizedIn putStream( txtStream. openInputS treamToBuf fer(), txt Stream.get Size());                        
  1026                             
  1027                             data =  dicomUtil ities.asse mbleDicomS tream(size dTextStrea m, sizedtg aStream);
  1028                             
  1029                             ByteBu ffer outpu t = ByteBu ffer.alloc ate(data.l ength);
  1030                             output .put(data) ;
  1031                             return  new ByteB ufferBacke dObject(ou tput, data .length);
  1032                    }
  1033                    catc h (Generic DicomRecon stitutionE xception g dre) 
  1034                    {
  1035                    LOGG ER.error(" createDico mObject -  Error crea ting DICOM  Output St ream: " +  gdre.getMe ssage());
  1036                             throw  new ImageC onversionI OException ("createDi comObject  - Error cr eating DIC OM Output  Stream: ",  gdre);
  1037                    }
  1038                    catc h (Excepti on e) 
  1039                    {
  1040                    LOGG ER.error(" createDico mObject -  generic ex ception "  + e.getMes sage());
  1041                             throw  new ImageC onversionI OException ("createDi comObject  - generic  exception" , e);
  1042                    }
  1043           }
  1044           //  ========= ========== ========== = compress ion suppor t methods  ========== ========== ========== =======
  1045           //  
  1046           /* *
  1047            *  This meth od parses  a DICOM fi le for the  2 byte DI COM Modali ty code.
  1048            *  @param im ageBuffer
  1049            *  @return r eturns the  2 byte st ring value  of the DI COM tag (0 008,0060)  if tag fou nd in firs t 1000 byt es of imag eBuffer
  1050            * /
  1051           pr ivate Stri ng getDico mModality( ByteBuffer  imageBuff er) 
  1052           {        
  1053           St ring mty=" xy";
  1054           im ageBuffer. rewind();
  1055           sh ort short1 =0, short2 ;
  1056                    for  (int i=0;  ((i < imag eBuffer.ca pacity()-6 ) && (i <  1000));) {
  1057                             short2 =imageBuff er.getShor t();
  1058                             i+=2;
  1059                             if ((s hort1==0x0 800) && (s hort2==0x6 000)) {
  1060                                      imageBuf fer.getInt (); // ski p 4 bytes
  1061                                      short1=i mageBuffer .getShort( );
  1062                                      mty=mty. replace('x ', (char)( ((short1 > > 8) & 0xF F)));
  1063                                      mty=mty. replace('y ', (char)( (0xFF & sh ort1)));
  1064                             imageB uffer.rewi nd();
  1065                                      return m ty;
  1066                             }
  1067                             short1 =short2;
  1068                    }
  1069           im ageBuffer. rewind();
  1070           re turn mty;      
  1071       }   
  1072   }