74. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 7/10/2017 1:01:44 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.

74.1 Files compared

# Location File Last Modified
1 C:\AraxisMergeCompare\Pri_un\IV-ehmp_cif\ImagingExchangeBaseWebProxy\main\src\java\gov\va\med\imaging\proxy ImagingProxy.java Thu Jun 29 17:22:05 2017 UTC
2 C:\AraxisMergeCompare\Pri_re\IV-ehmp_cif\ImagingExchangeBaseWebProxy\main\src\java\gov\va\med\imaging\proxy ImagingProxy.java Thu Jul 6 15:03:18 2017 UTC

74.2 Comparison summary

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

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

74.4 Active regular expressions

No regular expressions were active.

74.5 Comparison detail

  1   package go v.va.med.i maging.pro xy;
  2  
  3  
  4   import gov .va.med.im aging.Size dInputStre am;
  5   import gov .va.med.im aging.chan nels.Check sumValue;
  6   import gov .va.med.im aging.chan nels.excep tions.Chec ksumFormat Exception;
  7   import gov .va.med.im aging.core .interface s.exceptio ns.Connect ionExcepti on;
  8   import gov .va.med.im aging.core .interface s.exceptio ns.ImageCo nversionEx ception;
  9   import gov .va.med.im aging.core .interface s.exceptio ns.ImageNe arLineExce ption;
  10   import gov .va.med.im aging.core .interface s.exceptio ns.ImageNo tFoundExce ption;
  11   import gov .va.med.im aging.core .interface s.exceptio ns.MethodE xception;
  12   import gov .va.med.im aging.core .interface s.exceptio ns.Securit yCredentia lsExpiredE xception;
  13   import gov .va.med.im aging.exch ange.busin ess.ImageF ormatQuali tyList;
  14   import gov .va.med.im aging.exch ange.busin ess.Reques tor;
  15   import gov .va.med.im aging.exch ange.enums .ImageForm at;
  16   import gov .va.med.im aging.exch ange.enums .ImageQual ity;
  17   import gov .va.med.im aging.prox y.exceptio ns.ProxySe rviceNotFo undExcepti on;
  18   import gov .va.med.im aging.prox y.services .ProxyServ ice;
  19   import gov .va.med.im aging.prox y.services .ProxyServ iceType;
  20   import gov .va.med.im aging.prox y.services .ProxyServ ices;
  21   import gov .va.med.im aging.tran sactioncon text.Trans actionCont ext;
  22   import gov .va.med.im aging.tran sactioncon text.Trans actionCont extFactory ;
  23   import gov .va.med.im aging.tran sactioncon text.Trans actionCont extHttpHea ders;
  24  
  25   import jav a.io.IOExc eption;
  26   import jav a.io.Input Stream;
  27   import jav a.text.Dat eFormat;
  28   import jav a.text.Sim pleDateFor mat;
  29   import jav a.util.zip .CheckedIn putStream;
  30   import jav a.util.zip .Checksum;
  31   import jav a.util.zip .GZIPInput Stream;
  32  
  33   import org .apache.ax is.transpo rt.http.HT TPConstant s;
  34   import org .apache.co mmons.http client.Hea der;
  35   import org .apache.co mmons.http client.Htt pClient;
  36   import org .apache.co mmons.http client.Htt pException ;
  37   import org .apache.co mmons.http client.Htt pStatus;
  38   import org .apache.co mmons.http client.URI ;
  39   import org .apache.co mmons.http client.Use rnamePassw ordCredent ials;
  40   import org .apache.co mmons.http client.aut h.AuthScop e;
  41   import org .apache.co mmons.http client.met hods.GetMe thod;
  42   import org .apache.lo g4j.Logger ;
  43  
  44   /**
  45    * This cl ass is a s imple prox y for the  web access  to images .
  46    * The fun ctionality  in here i s shared b y the thre e webservi ce proxies  (exchange , federati on and cli nicaldispl ay).
  47    * This cl ass may be  used as a  concrete  class, tho ugh there  is current ly nowhere  that it i s used as  such
  48    * @author         
BECKEC
  49    *
  50    */
  51   public abs tract clas s ImagingP roxy
  52   {
  53           //  the list  of HTTP he aders fiel ds set by  the proxy  and unders tood by
  54           //  the serve r
  55           /*
  56           //  JMW 8/19/ 2010
  57           //  these hea der values  no longer  used, usi ng values  from Trans actionCont extHttpHea ders class  
  58           //  (identica l to these  here) 
  59           pu blic final  static St ring httpH eaderDuz =  "xxx-duz" ;
  60           pu blic final  static St ring httpH eaderFullN ame = "xxx -fullname" ;
  61           pu blic final  static St ring httpH eaderSiteN ame = "xxx -sitename" ;
  62           pu blic final  static St ring httpH eaderSiteN umber = "x xx-sitenum ber";
  63           pu blic final  static St ring httpH eaderSSN =  "xxx-ssn" ;
  64           pu blic final  static St ring httpH eaderPurpo seOfUse =  "xxx-purpo se-of-use" ;
  65           pu blic final  static St ring httpH eaderCheck sum = "xxx -checksum" ;
  66           pu blic final  static St ring httpH eaderTrans actionId =  "xxx-tran saction-id ";
  67           pu blic final  static St ring httpH eaderBroke rSecurityT okenId = " xxx-securi tyToken";
  68           pu blic final  static St ring httpH eaderCache LocationId  = "xxx-ca cheLocatio nId";
  69           pu blic final  static St ring httpH eaderUserD ivision =  "xxx-userD ivision";
  70           
  71           pu blic final  static St ring httpH eaderImage Checksum =  "xxx-imag e-checksum ";
  72           pu blic final  static St ring httpH eaderTXTCh ecksum = " xxx-txt-ch ecksum";
  73           pu blic final  static St ring httpH eaderImage Quality =  "xxx-image -quality";
  74           pu blic final  static St ring httpH eaderImage Size = "xx x-image-le ngth";
  75           pu blic final  static St ring httpH eaderTxtSi ze = "xxx- txt-length ";
  76           */
  77           
  78           pr otected Lo gger logge r = Logger .getLogger (ImagingPr oxy.class) ;
  79           
  80           
  81           //  YYYYMMDDH HMMSS.FFFF FF+ZZZZ
  82           //  The compo nents of t his string , from lef t to right , are 
  83           //  YYYY = Ye ar, 
  84           //  MM = Mont h, 
  85           //  DD = Day,  
  86           //  HH = Hour
  87           //  MM = Minu te, 
  88           //  SS = Seco nd,
  89           //  FFFFFF =  millisecon ds
  90           //  ZZZZ - ti mezone off set
  91           pr ivate fina l static S tring dico mDateForma t = "yyyyM MddHHmmss. SSSSzzzzz" ;
  92           //  do not re -use a sim ple date f ormat inst ance, they  are not t hread safe
  93           pu blic final  static Da teFormat g etDicomDat eFormat()
  94           {
  95                    retu rn new Sim pleDateFor mat(dicomD ateFormat) ;
  96           }
  97           
  98           pr ivate fina l static S tring requ estDateFor mat = "MM/ dd/yyyy";
  99           pu blic final  static Da teFormat g etRequestD ateFormat( )
  100           {
  101                    retu rn new Sim pleDateFor mat(reques tDateForma t);
  102           }
  103           
  104           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== =======
  105           //
  106           //  ========= ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== =======
  107           pr otected St ring respo nseContent Type="";
  108           pr otected St ring respo nseEncodin g="";
  109           pr otected St ring respo nseMessage ="";
  110           pr otected St ring respo nseChecksu m=null;
  111           pr otected St ring image Checksum=n ull;
  112           pr otected St ring txtCh ecksum = n ull;
  113           pr otected Im ageQuality  requested Quality =  null;
  114           pr otected bo olean requ estGzip =  false;
  115           pr otected in t fileLeng th = 0;
  116           pr otected in t txtLengt h = 0;
  117           
  118           pr otected fi nal ProxyS ervices pr oxyService s;
  119           pr ivate fina l boolean  instanceUr lEscaped;
  120           
  121           pr otected Im agingProxy (ProxyServ ices proxy Service, b oolean ins tanceUrlEs caped)
  122           {
  123                    asse rt proxySe rvice != n ull;
  124                    this .proxyServ ices = pro xyService;
  125                    this .instanceU rlEscaped  = instance UrlEscaped ;
  126           }
  127           
  128           /* *
  129            *  Returns t he ProxySe rvice for  the ProxyS erviceType .image, if  none is f ound
  130            *  then the  exception  is caught  and null i s returned .
  131            * /
  132           pu blic Proxy Service ge tImageProx yService()
  133           {
  134                    try
  135                    {
  136                             return  proxyServ ices.getPr oxyService (ProxyServ iceType.im age);
  137                    }
  138                    catc h(ProxySer viceNotFou ndExceptio n psnfX)
  139                    {
  140                             return  null;
  141                    }
  142           }
  143           
  144           /* *
  145            *  Returns t he ProxySe rvice for  the ProxyS erviceType .metadata,  if none i s found
  146            *  then the  exception  is caught  and null i s returned .
  147            * /
  148           pu blic Proxy Service ge tMetadataP roxyServic e()
  149           {
  150                    try
  151                    {
  152                             return  proxyServ ices.getPr oxyService (ProxyServ iceType.me tadata);
  153                    }
  154                    catc h(ProxySer viceNotFou ndExceptio n psnfX)
  155                    {
  156                             return  null;
  157                    }
  158           }
  159  
  160           pu blic Strin g getRespo nseContent Type()
  161           {
  162                    retu rn this.re sponseCont entType;
  163           }
  164  
  165           pu blic Strin g getRespo nseMessage ()
  166           {
  167                    retu rn this.re sponseMess age;
  168           }
  169  
  170           pu blic Strin g getRespo nseChecksu m()
  171           {
  172                    retu rn this.re sponseChec ksum;
  173           }
  174           
  175           pu blic Image Quality ge tRequested Quality()  {
  176                    retu rn request edQuality;
  177           }
  178  
  179           pu blic Check sumValue g etResponse ChecksumVa lue()
  180           {
  181                    try
  182                    {
  183                             return  getRespon seChecksum () == null  ?
  184                                               null : new  ChecksumV alue(getRe sponseChec ksum());
  185                    } 
  186                    catc h (Checksu mFormatExc eption x)
  187                    {
  188                             logger .warn("Err or parsing  checksum  '" + getRe sponseChec ksum() + " '.", x);
  189                             return  null;
  190                    }
  191           }
  192  
  193           pu blic Strin g getImage Checksum()  {
  194                    retu rn imageCh ecksum;
  195           }
  196  
  197           pu blic Strin g getTxtCh ecksum() {
  198                    retu rn txtChec ksum;
  199           }
  200  
  201           /* *
  202            *  @return t he fileLen gth
  203            * /
  204           pu blic int g etFileLeng th() {
  205                    retu rn fileLen gth;
  206           }
  207  
  208           /* *
  209            *  @return t he txtLeng th
  210            * /
  211           pu blic int g etTxtLengt h() {
  212                    retu rn txtLeng th;
  213           }
  214  
  215           /* *
  216            *  Set or ge t whether  the reques t should s et the acc ept-conten t to 
  217            *  include g zip or not .
  218            *  
  219            *  @return
  220            * /
  221           pu blic boole an isReque stGzip()
  222       {
  223           re turn reque stGzip;
  224       }
  225  
  226           pu blic void  setRequest Gzip(boole an request Gzip)
  227       {
  228           th is.request Gzip = req uestGzip;
  229       }
  230  
  231           /* *
  232            *  Create a  URL string  for an im age specif ic to this  proxy. 
  233            *   
  234            *  @param im ageUrn
  235            *  @return
  236            * /
  237           pu blic Strin g createIm ageUrl(Str ing imageU rn, ImageF ormatQuali tyList req uestFormat QualityLis t)
  238           th rows Proxy ServiceNot FoundExcep tion
  239           {
  240                    retu rn Utiliti es.createI mageUrl(th is.proxySe rvices, im ageUrn, 
  241                                      requestF ormatQuali tyList, ge tInstanceR equestProx yServiceTy pe());
  242           }
  243           
  244           pu blic Strin g createTx tUrl(Strin g imageUrn , String a ccept)
  245           th rows Proxy ServiceNot FoundExcep tion
  246           {
  247                    retu rn Utiliti es.createT xtUrl(this .proxyServ ices, imag eUrn, acce pt,
  248                                      getTextF ileRequest ProxyServi ceType());
  249           }
  250           
  251           /* *
  252            *  
  253            *  @param im ageUrn
  254            *  @param im ageQuality
  255            *  @param ac cept
  256            *  @return
  257            *  @throws P roxyExcept ion 
  258            * /
  259           pu blic Sized InputStrea m getInsta nce(String  imageUrn,  ImageForm atQualityL ist reques tFormatQua lityList,  boolean in cludeVista SecurityCo ntext) 
  260           th rows Image NearLineEx ception, I mageNotFou ndExceptio n, 
  261           Se curityCred entialsExp iredExcept ion, Image Conversion Exception,  MethodExc eption, Co nnectionEx ception
  262           {
  263                    retu rn getInst ance(image Urn, reque stFormatQu alityList,  null, inc ludeVistaS ecurityCon text);
  264           }
  265  
  266           /* *
  267            *  Make an H TTP reques t to get t he image n amed by th e given UR N.
  268            *  The check sum will c ontain the  calculate d checksum  only afte r
  269            *  the entir e stream c ontents ha ve been re ad.
  270            *  
  271            *  @param im ageUrn
  272            *  @param im ageQuality
  273            *  @param im ageFormat
  274            *  @param ch ecksum
  275            *  @return a n InputStr eam contai ning the c ontents of  the image .
  276            *  If the ch ecksum par ameter is  not null t hen the In putStream  will be of  type 
  277            *  java.util .zip.Check edInputStr eam.
  278            * /
  279           pu blic Sized InputStrea m getInsta nce(String  imageUrn,  ImageForm atQualityL ist reques tFormatQua lityList, 
  280                             Checks um checksu m, boolean  includeVi staSecurit yContext) 
  281           th rows Image NearLineEx ception, I mageNotFou ndExceptio n, 
  282           Se curityCred entialsExp iredExcept ion, Image Conversion Exception,  MethodExc eption, Co nnectionEx ception
  283           {                 
  284                    Stri ng imageUr lString =  null;
  285                    Imag eFormat fi rstImageFo rmat = req uestFormat QualityLis t.get(0).g etImageFor mat();
  286                    this .requested Quality =  requestFor matQuality List.get(0 ).getImage Quality();       
  287                    try
  288                    {
  289                             if(fir stImageFor mat == Ima geFormat.T EXT_DICOM)
  290                             {
  291                                      imageUrl String = c reateTxtUr l(imageUrn , firstIma geFormat.g etMime());
  292                             }
  293                             else 
  294                             {
  295                                      imageUrl String = c reateImage Url(imageU rn, reques tFormatQua lityList);
  296                             }
  297                    }
  298                    catc h(ProxySer viceNotFou ndExceptio n psnfX)
  299                    {
  300                             logger .error("Er ror findin g proxy se rvice", ps nfX);
  301                             throw  new Connec tionExcept ion(psnfX. getMessage ());
  302                    }
  303                    Tran sactionCon text trans actionCont ext = Tran sactionCon textFactor y.get();
  304                    Stri ng transac tionIdenti fier = tra nsactionCo ntext.getT ransaction Id();
  305                    logg er.info("T ransaction  [" + tran sactionIde ntifier +  "] initiat ed, retrei ving [" +  imageUrlSt ring + "]" );
  306                    tran sactionCon text.addDe bugInforma tion("getI nstance to  URL '" +  imageUrlSt ring + "'. ");
  307  
  308                    int  result = 0 ;
  309                    Http Client cli ent = null ;
  310                    GetM ethod getM ethod = nu ll;
  311                    
  312                    try
  313                    {
  314                             client  = new Htt pClient();
  315                             client .getHttpCo nnectionMa nager().ge tParams(). setConnect ionTimeout (30000); / / DKB - 30  sec to ge t a connec tion
  316                client.g etHttpConn ectionMana ger().getP arams().se tSoTimeout (120000);  // 120 sec  to wait f or data
  317                             client .getParams ().setAuth entication Preemptive (true);
  318                             //getM ethod = ne w GetMetho d(imageUrl String);
  319                             getMet hod = new  GetMethod( );
  320                             getMet hod.setURI (new URI(i mageUrlStr ing, insta nceUrlEsca ped));
  321                             
  322                             Header  acceptHea der = new  Header("Ac cept", req uestFormat QualityLis t.getAccep tString(fa lse));
  323                             getMet hod.setReq uestHeader (acceptHea der);
  324                             
  325                             Header  acceptLan guageHeade r = new He ader("Acce pt-Languag e", "en-us ,en");
  326                             getMet hod.setReq uestHeader (acceptLan guageHeade r);
  327                             
  328                             Header  acceptCha rsetHeader  = new Hea der("Accep t-Charset" , "ISO-885 9-1,utf-8" );
  329                             getMet hod.setReq uestHeader (acceptCha rsetHeader );
  330  
  331                             // ++  CTB 14MAy2 008
  332                             if(isR equestGzip ())
  333                             {
  334                                      Header e ncodingHea der = new  Header("Ac cept-Encod ing", "gzi p");
  335                                      getMetho d.setReque stHeader(e ncodingHea der);
  336                             }
  337                             
  338                             getMet hod.setFol lowRedirec ts(true);
  339  
  340                             getMet hod.setReq uestHeader ( HTTPCons tants.HEAD ER_CACHE_C ONTROL, "n o-cache,no -store,no- transform" );
  341                             getMet hod.setReq uestHeader ( HTTPCons tants.HEAD ER_PRAGMA,  "no-cache ");
  342                             
  343                             // add  the secur ity inform ation to t he http he aders
  344                             addSec urityConte xtToHeader (client, g etMethod,  includeVis taSecurity Context);
  345                             
  346                             addOpt ionalGetIn stanceHead ers(getMet hod);
  347                             
  348                             result  = client. executeMet hod(getMet hod);
  349  
  350                // How m any bytes  received?
  351                transact ionContext .setDataSo urceBytesR eceived (g etMethod.g etBytesRec eived ());
  352                
  353                             // How  long did  it take to  get a res ponse comi ng back?
  354                             Long t imeSent =  getMethod. getTimeReq uestSent ( );
  355                             Long t imeReceive d = getMet hod.getTim eFirstByte Received ( );
  356                             if (ti meSent !=  null && ti meReceived  != null)
  357                             {
  358                                lon g timeTook  = timeRec eived.long Value () -  timeSent. longValue  ();
  359                                tra nsactionCo ntext.setT imeToFirst Byte (new  Long (time Took));
  360                             }
  361                             
  362                             Header  contentTy peHeader=g etMethod.g etResponse Header("Co ntent-Type ");
  363                             if (co ntentTypeH eader != n ull)
  364                                      response ContentTyp e = conten tTypeHeade r.getValue (); // def ault is em pty string
  365                             
  366                             // ++  CTB 14MAy2 008
  367                             Header  encodingT ypeHeader= getMethod. getRespons eHeader("C ontent-Enc oding");
  368                             if (en codingType Header !=  null)
  369                                      response Encoding =  encodingT ypeHeader. getValue() ; // defau lt is empt y string
  370                             
  371                             Header  checksumH eader=getM ethod.getR esponseHea der(Transa ctionConte xtHttpHead ers.httpHe aderChecks um);
  372                             if (ch ecksumHead er != null )
  373                                      response Checksum =  checksumH eader.getV alue(); //  default i s empty st ring
  374                             else
  375                                      response Checksum =  null;
  376                             
  377                             // get  the check sums for a  zip file  (only used  in Federa tion)
  378                             Header  imageChec ksumHeader  = getMeth od.getResp onseHeader (Transacti onContextH ttpHeaders .httpHeade rImageChec ksum);
  379                             if(ima geChecksum Header !=  null)
  380                                      imageChe cksum = im ageChecksu mHeader.ge tValue();
  381                             else
  382                                      imageChe cksum = nu ll;
  383                             
  384                             Header  txtChecks umHeader =  getMethod .getRespon seHeader(T ransaction ContextHtt pHeaders.h ttpHeaderT XTChecksum );
  385                             if(txt ChecksumHe ader != nu ll)
  386                                      txtCheck sum = txtC hecksumHea der.getVal ue();
  387                             else
  388                                      txtCheck sum = null ;
  389                             
  390                             Header  imgFileLe ngthHeader  = getMeth od.getResp onseHeader (Transacti onContextH ttpHeaders .httpHeade rImageSize );
  391                             if(img FileLength Header !=  null)
  392                             {
  393                                      try
  394                                      {
  395                                               fileLength  = Integer .parseInt( imgFileLen gthHeader. getValue() );
  396                                      }
  397                                      catch(Nu mberFormat Exception  nfX)
  398                                      {
  399                                               logger.deb ug("Error  parsing im age length  header va lue [" + i mgFileLeng thHeader.g etValue()  + "].", nf X);
  400                                      }
  401                             }
  402                             else
  403                                      fileLeng th = 0;
  404                             
  405                             Header  txtFileLe ngthHeader  = getMeth od.getResp onseHeader (Transacti onContextH ttpHeaders .httpHeade rTxtSize);
  406                             if(txt FileLength Header !=  null)
  407                             {
  408                                      try
  409                                      {
  410                                               txtLength  = Integer. parseInt(t xtFileLeng thHeader.g etValue()) ;
  411                                      }
  412                                      catch(Nu mberFormat Exception  nfX)
  413                                      {
  414                                               logger.deb ug("Error  parsing TX T file len gth header  value ["  + imgFileL engthHeade r.getValue () + "].",  nfX);
  415                                      }
  416                             }
  417                             else
  418                                      txtLengt h = 0;
  419                             
  420                             Header  responseQ ualityHead er = getMe thod.getRe sponseHead er(Transac tionContex tHttpHeade rs.httpHea derImageQu ality);
  421                             if(res ponseQuali tyHeader ! = null)
  422                             {
  423                                      try
  424                                      {
  425                                               requestedQ uality = I mageQualit y.getImage Quality(re sponseQual ityHeader. getValue() );
  426                                      }
  427                                      catch(Nu mberFormat Exception  nfX) 
  428                                      {
  429                                               logger.deb ug("Error  parsing qu ality head er value [ " + respon seQualityH eader.getV alue() + " ].", nfX);
  430                                      }
  431                             }                         
  432                             Header  responseM achineName Header = 
  433                                      getMetho d.getRespo nseHeader( Transactio nContextHt tpHeaders. httpHeader MachineNam e);
  434                             if(res ponseMachi neNameHead er != null )
  435                             {
  436                                      String m achineName  = respons eMachineNa meHeader.g etValue();
  437                                      logger.i nfo("Recei ved respon se from ma chine name  '" + mach ineName +  "'.");
  438                                      transact ionContext .setDataSo urceRespon seServer(m achineName );
  439                             }
  440                    } 
  441                    catc h (HttpExc eption e)
  442                    {
  443                             e.prin tStackTrac e();
  444                             respon seMessage  = "HTTPExc eption on  execute GE T method,  got respon se code '"  + result  + "', " +  e.getMessa ge();
  445                             throw  new Connec tionExcept ion(respon seMessage,  e);
  446                    } 
  447                    catc h (IOExcep tion e)
  448                    {
  449                             e.prin tStackTrac e();
  450                             respon seMessage  = "IOExcep tion on ex ecute GET  method, go t response  code '" +  result +  "', " + e. getMessage ();
  451                             throw  new Connec tionExcept ion(respon seMessage,  e);
  452                    }
  453                    
  454                    // 1 00 series  codes shou ld have be en dealt w ith by the  underlyin g HTTP pro xy.
  455                    // I f not then  we have n o choice b ut to pass  the error  message o n up and l et the cli ent
  456                    // d ecide if t hey can re -try.
  457                    if ( result >=  HttpStatus .SC_CONTIN UE && resu lt < HttpS tatus.SC_O K)
  458                    {
  459                             String  message =  readRespo nseMessage Body(respo nseContent Type, getM ethod);
  460                             if(mes sage == nu ll)
  461                                      message  = "Server  response w as '" + re sult + "',  responses  other tha n 200 (OK)  are consi dered erro rs.";
  462                             
  463                             logger .warn("Tra nsaction [ " + transa ctionIdent ifier + "]  response  code = '"  + result +  "' messag e is '" +  message +  "'");
  464                             throw  new Connec tionExcept ion(messag e);
  465                    }
  466                    
  467                    else  if(result  == HttpSt atus.SC_OK )
  468                    {
  469                             try
  470                             {
  471                                      int byte sRead = 0;
  472                                      InputStr eam input  = null;
  473                                      
  474                                      try
  475                                      {
  476                                               Header con tentLength Header = g etMethod.g etResponse Header("co ntent-leng th");
  477                                               if (conten tLengthHea der!=null)  
  478                                               {
  479                                                       St ring heade rLengthVal ue = conte ntLengthHe ader.getVa lue();
  480                                                       by tesRead =  Integer.pa rseInt(hea derLengthV alue);
  481                                               }
  482                                      } 
  483                                      catch (E xception e )
  484                                      {
  485                                               responseMe ssage = "E xception o n get resp onse heade r/value";
  486                                               logger.err or(e);
  487                                      }
  488                                      
  489                                      logger.i nfo("Trans action ["  + transact ionIdentif ier + "] r eturned SU CCESS. Con tent Lengt h [" + byt esRead + " ]");
  490                                      InputStr eam inStre am = getMe thod.getRe sponseBody AsStream() ;
  491                                      
  492                                      // ++ CT B 14MAy200 8
  493                                      // if th e response  body is g zip encode d then cre ate a GZIP  decoding  input stre am and
  494                                      // retur n that
  495                                      if(respo nseEncodin g.indexOf( "gzip") >=  0)
  496                                      {
  497                                               GZIPInputS tream zipI n = new GZ IPInputStr eam(inStre am);
  498                                               inStream =  zipIn;
  499                                      }
  500                                      
  501                                      // if a  checksum i nstance wa s provided , attach i t to a Che ckedInputS tream inst ance
  502                                      // and r eturn it,  else retur n the raw  stream
  503                                      if(check sum != nul l)
  504                                      {
  505                                               input = ne w CheckedI nputStream (inStream,  checksum) ;
  506                                      }
  507                                      else
  508                                               input = in Stream;
  509                                               //return i nStream;
  510                                      return n ew SizedIn putStream( input, byt esRead);
  511                             } 
  512                             catch  (IOExcepti on e)
  513                             {
  514                                      logger.e rror(e);
  515                             }
  516                    }
  517                    // 2 00 series  error code s that are  not expli citly an O K
  518                    // s ome of the se can be  lived with , some not .  For now  we call t hem all er rors.
  519                    else  if (resul t > HttpSt atus.SC_OK   && resul t < HttpSt atus.SC_MU LTIPLE_CHO ICES)
  520                    {
  521                             String  message =  readRespo nseMessage Body(respo nseContent Type, getM ethod);
  522                             if(mes sage == nu ll)
  523                                      message  = "Server  response w as '" + re sult + "',  responses  other tha n 200 (OK)  are consi dered erro rs.";
  524                             
  525                             logger .warn("Tra nsaction [ " + transa ctionIdent ifier + "]  response  code = '"  + result +  "' messag e is '" +  message +  "'");
  526                             throw  new Connec tionExcept ion(messag e);
  527                    }
  528                    
  529                    // 3 00 series  error code s
  530                    // r esult is p robably a  client err or, report  it, the u ser may be  able to m odify the  request an d re-submi t
  531                    else  if (resul t >= HttpS tatus.SC_M ULTIPLE_CH OICES  &&  result < H ttpStatus. SC_BAD_REQ UEST)
  532                    {
  533                             String  message =  readRespo nseMessage Body(respo nseContent Type, getM ethod);
  534                             if(mes sage == nu ll)
  535                                      message  = "Server  response w as '" + re sult + "',  responses  other tha n 200 (OK)  are consi dered erro rs.";
  536                             
  537                             logger .warn("Tra nsaction [ " + transa ctionIdent ifier + "]  response  code = '"  + result +  "' messag e is '" +  message +  "'");
  538                             throw  new Connec tionExcept ion(messag e);
  539                    }
  540                    
  541                    // 4 00 series  error code s
  542                    // r esult is a  client er ror, repor t it, the  user may b e able to  modify the  request a nd re-subm it
  543                    else  if (resul t >= HttpS tatus.SC_B AD_REQUEST   && resul t < HttpSt atus.SC_IN TERNAL_SER VER_ERROR)
  544                    {
  545                             String  message =  "Server r esponse wa s '" + res ult + "',  responses  other than  200 (OK)  are consid ered error s.";
  546                             if("te xt/html".e quals(resp onseConten tType))
  547                                      message  = readHTTP Message(cl ient, getM ethod);
  548                             else i f (("appli cation/dic om".equals (responseC ontentType )) || 
  549                                               ("image/jp eg/dicom". equals(res ponseConte ntType)))
  550                                      message  += readHTT PMessage(c lient, get Method);
  551                             logger .warn("Tra nsaction [ " + transa ctionIdent ifier + "]  response  code = '"  + result +  "' messag e is '" +  message +  "'");
  552                             
  553                             // 409  result
  554                             if(res ult == Htt pStatus.SC _CONFLICT)
  555                             {
  556                                      throw ne w ImageNea rLineExcep tion(image Urn);
  557                             }                
  558                             // The  Exchange  interface  does not r espond wit h a 404 fo r file not  founds bu t Federati on does
  559                             else i f(result = = HttpStat us.SC_NOT_ FOUND)
  560                             {
  561                                      throw ne w ImageNot FoundExcep tion(messa ge);
  562                             }
  563                             else i f(result = = HttpStat us.SC_PREC ONDITION_F AILED)
  564                             {
  565                                      throw ne w Security Credential sExpiredEx ception(me ssage);
  566                             }
  567                             else i f(result = = HttpStat us.SC_UNSU PPORTED_ME DIA_TYPE)
  568                             {
  569                                      throw ne w ImageCon versionExc eption(mes sage);
  570                             }
  571  
  572                             
  573                             throw  new Connec tionExcept ion(messag e);
  574                    }
  575                    
  576                    // 5 00 series  error code s
  577                    // r esult is a  server er ror, repor t it but n ot much we  can do to  correct i t
  578                    else  if (resul t >= HttpS tatus.SC_I NTERNAL_SE RVER_ERROR )
  579                    {
  580                             String  message =  "Server r esponse wa s '" + res ult + "',  responses  other than  200 (OK)  are consid ered error s.";
  581                             if("te xt/html".e quals(resp onseConten tType))
  582                                      message  += readHTT PMessage(c lient, get Method);
  583                             
  584                             if(res ult == Htt pStatus.SC _BAD_GATEW AY)
  585                             {
  586                                      logger.e rror("Conn ectionExce ption tran saction ["  + transac tionIdenti fier + "],  response  code = '"  + result +  "' messag e is '" +  message +  "'"); 
  587                                      throw ne w Connecti onExceptio n(message) ;
  588                             }
  589                             else
  590                             {                         
  591                                      logger.e rror("Meth odExceptio n transact ion [" + t ransaction Identifier  + "], res ponse code  = '" + re sult + "'  message is  '" + mess age + "'") ;                       
  592                                      throw ne w MethodEx ception(me ssage);
  593                             }
  594                    }
  595                    
  596                    retu rn null;
  597           }
  598           
  599           /* *
  600            *  Function  adds optio nal header s to the r equest. Th is functio n should b e overridd en by othe r classes  to add the se
  601            *  optional  headers
  602            *  @param ge tMethod
  603            * /
  604           pr otected ab stract voi d addOptio nalGetInst anceHeader s(GetMetho d getMetho d);     
  605           
  606           /* *
  607            *  Returns t he ProxySe rviceType  to use whe n doing a  getInstanc e request
  608            *  @return
  609            * /
  610           pr otected ab stract Pro xyServiceT ype getIns tanceReque stProxySer viceType() ;
  611           
  612           /* *
  613            *  Returns t he ProxySe rviceType  used when  doing a ge tInstance  for a text  file requ est.
  614            *  @return
  615            * /
  616           pr otected ab stract Pro xyServiceT ype getTex tFileReque stProxySer viceType() ;
  617  
  618           /* *
  619            *  @param cl ient
  620            *  @param ge tMethod 
  621            *  @return
  622            * /
  623           pr otected St ring readR esponseMes sageBody(S tring cont entType, G etMethod g etMethod)
  624           {
  625                    if(c ontentType  != null & & contentT ype.toLowe rCase().st artsWith(" text"))
  626                    {
  627                             try
  628                             {
  629                                      return g etMethod.g etResponse BodyAsStri ng();
  630                             } 
  631                             catch  (IOExcepti on x)
  632                             {
  633                                      logger.e rror(x);
  634                             }
  635                    }
  636                    
  637                    retu rn null;
  638           }
  639  
  640           /* *
  641            *  @param cl ient
  642            *  @param ge tMethod 
  643            *  @return
  644            * /
  645           pr otected St ring readH TTPMessage (HttpClien t client,  GetMethod  getMethod)
  646           {
  647                             String  response  = " " + ge tMethod.ge tStatusTex t();
  648                             return  response;
  649           }
  650  
  651           /* *
  652            *  Adds the  user ID an d password  to the HT TP headers  using BAS IC securit y.
  653            *  Adds the  parameter  of the thr ead local  security c ontext to  the HTTP h eader.
  654            *  
  655            *  @param ge tMethod
  656            * /
  657           pr otected vo id addSecu rityContex tToHeader( HttpClient  client, G etMethod g etMethod, 
  658                             boolea n includeV istaSecuri tyContext)
  659           {
  660                    // B TW, don't  import the  Credentia ls class b ecause the re is an a pp specifi c Credenti als
  661                    // t hat derive s from the  java Prin cipal clas s, which i s where th e thread l ocal
  662                    // s ecutity co ntext is s tored
  663                    org. apache.com mons.httpc lient.Cred entials im ageXChange Credential s = null;
  664                    
  665                    try
  666                    {
  667                             ProxyS ervice ima geService  = proxySer vices.getP roxyServic e(ProxySer viceType.i mage);
  668                    
  669                             if(ima geService. getCredent ials() ins tanceof St ring)
  670                                      imageXCh angeCreden tials = 
  671                                               new Userna mePassword Credential s(imageSer vice.getUi d(), (Stri ng)(imageS ervice.get Credential s()) );
  672                             
  673                             AuthSc ope imageX ChangeAuth Scope = ne w AuthScop e(imageSer vice.getHo st(), imag eService.g etPort(),  AuthScope. ANY_REALM) ;
  674                             client .getState( ).setCrede ntials(ima geXChangeA uthScope,  imageXChan geCredenti als);
  675                    }
  676                    catc h(ProxySer viceNotFou ndExceptio n psnfX)
  677                    {
  678                             logger .warn("Can not find i mage proxy  service t o set cred entials, c ontinuing  without",  psnfX);
  679                    }
  680                    //He ader autho rizationHe ader = new  Header("A uthorizati on", "Basi c ");
  681                    //ge tMethod.se tRequestHe ader(autho rizationHe ader);
  682                    
  683                    // t he thread  local secu rity crede ntials (th e VistA sp ecific stu ff) is wri tten into
  684                    // a pp specifi c HTTP hea ders
  685                    Tran sactionCon text trans actionCont ext = Tran sactionCon textFactor y.get();
  686                    
  687                    // 3 -11-2008 D KB - modif ied to sen d all head ers except  the DUZ i f includeV istaSecuri tyContext  is false
  688                    // t he silver  BIA was th rowing an  error beca use we wer e not send ing httpHe aderFullNa me, httpHe aderSiteNa me,
  689                    // h ttpHeaderS iteNumber  and httpHe aderSSN
  690                    if(i ncludeVist aSecurityC ontext)
  691                    {
  692                             if(tra nsactionCo ntext.getD uz() != nu ll)
  693                                      getMetho d.setReque stHeader(n ew Header( Transactio nContextHt tpHeaders. httpHeader Duz, 
  694                                                       tr ansactionC ontext.get Duz()));
  695                             logger .debug("Se tting DUZ  in Request  Header: " +transacti onContext. getDuz());
  696                             String  securityT oken = tra nsactionCo ntext.getB rokerSecur ityToken() ;
  697                    if(s ecurityTok en != null  && securi tyToken.le ngth() > 0 )
  698                             getMet hod.setReq uestHeader (new Heade r(Transact ionContext HttpHeader s.httpHead erBrokerSe curityToke nId, 
  699                                               securityTo ken));
  700                    logg er.debug(" Setting Se curity Tok en in Requ est Header : "+securi tyToken);
  701                    Stri ng cacheLo cationId =  transacti onContext. getCacheLo cationId() ;
  702                    if(c acheLocati onId != nu ll && cach eLocationI d.length()  > 0)
  703                             getMet hod.setReq uestHeader (new Heade r(Transact ionContext HttpHeader s.httpHead erCacheLoc ationId, 
  704                                               cacheLocat ionId));
  705                    
  706                    Stri ng userDiv ision = tr ansactionC ontext.get UserDivisi on();
  707                    if(u serDivisio n != null  && userDiv ision.leng th() > 0)
  708                             getMet hod.setReq uestHeader (new Heade r(Transact ionContext HttpHeader s.httpHead erUserDivi sion, 
  709                                               userDivisi on));
  710  
  711                    }
  712                    if(t ransaction Context.ge tFullName( ) != null)
  713                             getMet hod.setReq uestHeader (new Heade r(Transact ionContext HttpHeader s.httpHead erFullName
  714                                               transactio nContext.g etFullName ()));
  715                    if(t ransaction Context.ge tSiteName( ) != null)
  716                             getMet hod.setReq uestHeader (new Heade r(Transact ionContext HttpHeader s.httpHead erSiteName
  717                                               transactio nContext.g etSiteName ()));
  718                    if(t ransaction Context.ge tSiteNumbe r() != nul l)
  719                             getMet hod.setReq uestHeader (new Heade r(Transact ionContext HttpHeader s.httpHead erSiteNumb er, 
  720                                               transactio nContext.g etSiteNumb er()));
  721           lo gger.debug ("Setting  Site Numbe r in Reque st Header:  "+transac tionContex t.getSiteN umber());
  722                    if(t ransaction Context.ge tSsn() !=  null)
  723                             getMet hod.setReq uestHeader (new Heade r(Transact ionContext HttpHeader s.httpHead erSSN, 
  724                                               transactio nContext.g etSsn()));
  725                    logg er.debug(" Setting SS N in Reque st Header. ");
  726                    
  727                    if(t ransaction Context.ge tTransacti onId() !=  null)
  728                             getMet hod.setReq uestHeader (new Heade r(Transact ionContext HttpHeader s.httpHead erTransact ionId, 
  729                                               transactio nContext.g etTransact ionId()));
  730                    // 1 /8/07 JMW  - Add the  purpose of  use to th e request  for images
  731                    getM ethod.setR equestHead er(new Hea der(Transa ctionConte xtHttpHead ers.httpHe aderPurpos eOfUse, 
  732                                      Requesto r.PurposeO fUse.routi neMedicalC are.getDes cription() ));            
  733           }        
  734   }