294. EPMO Open Source Coordination Office Redaction File Detail Report

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

294.1 Files compared

# Location File Last Modified
1 IV-eHMP_CIF.zip\IMAG_Source\VISA\Java\ImagingExchangeImageConversion\main\src\java\gov\va\med\imaging\exchange\conversion ImageConversion.java Mon Dec 4 21:34:58 2017 UTC
2 IV-eHMP_CIF.zip\IMAG_Source\VISA\Java\ImagingExchangeImageConversion\main\src\java\gov\va\med\imaging\exchange\conversion ImageConversion.java Mon Dec 4 22:03:23 2017 UTC

294.2 Comparison summary

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

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

294.4 Active regular expressions

No regular expressions were active.

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