124. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 3/25/2019 8:58:08 AM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

124.1 Files compared

# Location File Last Modified
1 C:\AraxisMergeCompare\Pri_un\IMAG_Source\VISA\Java\VistaStorage\main\src\java\gov\va\med\imaging\vista\storage SmbStorageUtility.java Mon Mar 18 20:39:08 2019 UTC
2 C:\AraxisMergeCompare\Pri_re\IMAG_Source\VISA\Java\VistaStorage\main\src\java\gov\va\med\imaging\vista\storage SmbStorageUtility.java Tue Mar 19 15:16:46 2019 UTC

124.2 Comparison summary

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

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

124.4 Active regular expressions

No regular expressions were active.

124.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: Feb  6, 2008
  6     Site Nam e:  Washin gton OI Fi eld Office , Silver S pring, MD
  7       Developer:     DN S      WERFEJ
  8     Descript ion: 
  9  
  10           ;;  +-------- ---------- ---------- ---------- ---------- ---------- ---------- +
  11           ;;  Property  of the US  Government .
  12           ;;  No permis sion to co py or redi stribute t his softwa re is give n.
  13           ;;  Use of un released v ersions of  this soft ware requi res the us er
  14           ;;   to execu te a writt en test ag reement wi th the Vis tA Imaging
  15           ;;   Developm ent Office  of the De partment o f Veterans  Affairs,
  16           ;;   telephon e (301) 73 4-0100.
  17           ;;
  18           ;;  The Food  and Drug A dministrat ion classi fies this  software a s
  19           ;;  a Class I I medical  device.  A s such, it  may not b e changed
  20           ;;  in any wa y.  Modifi cations to  this soft ware may r esult in a n
  21           ;;  adulterat ed medical  device un der 21CFR8 20, the us e of which
  22           ;;  is consid ered to be  a violati on of US F ederal Sta tutes.
  23           ;;  +-------- ---------- ---------- ---------- ---------- ---------- ---------- +
  24  
  25    */
  26   package go v.va.med.i maging.vis ta.storage ;
  27  
  28   import jav a.io.File;
  29   import jav a.io.FileI nputStream ;
  30   import jav a.io.FileO utputStrea m;
  31   import jav a.io.IOExc eption;
  32   import jav a.io.Outpu tStream;
  33   import jav a.io.Outpu tStreamWri ter;
  34   import jav a.io.Write r;
  35   import jav a.net.Malf ormedURLEx ception;
  36   import jav a.net.Unkn ownHostExc eption;
  37   import jav a.util.Arr ayList;
  38   import jav a.util.Ite rator;
  39   import jav a.util.Lis t;
  40   import jav a.util.Pro perties;
  41   import jav a.util.Sca nner;
  42  
  43   import org .apache.lo gging.log4 j.LogManag er;
  44   import org .apache.lo gging.log4 j.Logger;
  45  
  46   import gov .va.med.im aging.core .interface s.ImageSto rageFacade ;
  47   import gov .va.med.im aging.core .interface s.StorageC redentials ;
  48   import gov .va.med.im aging.core .interface s.exceptio ns.Connect ionExcepti on;
  49   import gov .va.med.im aging.core .interface s.exceptio ns.ImageNe arLineExce ption;
  50   import gov .va.med.im aging.core .interface s.exceptio ns.ImageNo tFoundExce ption;
  51   import gov .va.med.im aging.core .interface s.exceptio ns.MethodE xception;
  52   import gov .va.med.im aging.exch ange.busin ess.ImageF ormatQuali tyList;
  53   import gov .va.med.im aging.exch ange.busin ess.ImageS treamRespo nse;
  54   import gov .va.med.im aging.exch ange.busin ess.storag e.NetworkL ocationInf o;
  55   import gov .va.med.im aging.exch ange.busin ess.storag e.Place;
  56   import gov .va.med.im aging.exch ange.enums .StoragePr oximity;
  57   import gov .va.med.im aging.exch ange.stora ge.Abstrac tBufferedI mageStorag eFacade;
  58   import gov .va.med.im aging.exch ange.stora ge.ByteBuf ferBackedI mageInputS tream;
  59   import gov .va.med.im aging.exch ange.stora ge.ByteBuf ferBackedI mageStream Response;
  60   import gov .va.med.im aging.exch ange.stora ge.ByteBuf ferBackedI nputStream ;
  61   import gov .va.med.im aging.exch ange.stora ge.DataSou rceImageIn putStream;
  62   import gov .va.med.im aging.tran sactioncon text.Trans actionCont ext;
  63   import gov .va.med.im aging.tran sactioncon text.Trans actionCont extFactory ;
  64   import gov .va.med.im aging.vist a.storage. configurat ion.VistaS torageConf iguration;
  65   import jci fs.CIFSCon text;
  66   import jci fs.CIFSExc eption;
  67   import jci fs.config. PropertyCo nfiguratio n;
  68   import jci fs.context .BaseConte xt;
  69   import jci fs.context .Singleton Context;
  70   import jci fs.smb.Ntl mPasswordA uthenticat ion;
  71   import jci fs.smb.Smb Exception;
  72   import jci fs.smb.Smb File;
  73   import jci fs.smb.Smb FileInputS tream;
  74   import jci fs.util.tr ansport.Tr ansportExc eption;
  75  
  76   /**
  77    * Utility  functions  to open i mage share s and retr ieve files
  78    * 
  79    * @author   DN S      WERFEJ
  80    *
  81    */
  82   public cla ss SmbStor ageUtility
  83   extends Ab stractBuff eredImageS torageFaca de
  84   implements  ImageStor ageFacade
  85   {
  86           pr ivate fina l static L ogger logg er = LogMa nager.getL ogger(SmbS torageUtil ity.class) ;
  87  
  88           pu blic final  static in t DEFAULT_ MAX_RETRIE S = 3;
  89           pu blic final  static lo ng DEFAULT _RETRY_DEL AY = 2000L ;
  90  
  91           //  parameter s that aff ect retry  logic for  off-line i mages.
  92           pr ivate int  maxNearLin eRetries =  DEFAULT_M AX_RETRIES ;
  93           pr ivate long  nearLineR etryDelay  = DEFAULT_ RETRY_DELA Y;  
  94           
  95           pr ivate int  getNearLin eRetries()
  96       {
  97                return m axNearLine Retries;
  98       }
  99  
  100           pu blic long  getNearLin eRetryDela y()
  101       {
  102           re turn nearL ineRetryDe lay;
  103       }
  104           
  105           st atic
  106           {
  107                    Prop erties pro ps = new P roperties( );
  108                    prop s.put("jci fs.netbios .cachePoli cy", "3600 "); 
  109                    prop s.put("jci fs.smb.cli ent.soTime out", "350 00");
  110                    prop s.put("jci fs.smb.cli ent.respon seTimeout" , "35000") ;
  111  
  112                    logg er.info("J CIFS Confi guration -  jcifs.net bios.cache Policy = "  + jcifs.C onfig.getI nt(props,  "jcifs.net bios.cache Policy") ) ;
  113                    logg er.info("J CIFS Confi guration -  jcifs.smb .client.so Timeout =  " + jcifs. Config.get Int(props,  "jcifs.sm b.client.s oTimeout")  );
  114                    logg er.info("J CIFS Confi guration -  jcifs.smb .client.re sponseTime out = " +  jcifs.Conf ig.getInt( props, "jc ifs.smb.cl ient.respo nseTimeout ") );
  115           }
  116  
  117   //      st atic {
  118   //               Prop erties pro ps = new P roperties( );
  119   //               prop s.put("jci fs.netbios .cachePoli cy", "3600 "); //  ca che the ne twork name s for 1 ho ur (value  in seconds , 0 is no  caching, - 1 is forev er)
  120   //               // J MW 1/3/200 8
  121   //               // S et the tim eout value s, these a re suppose d to be th e default  values but  for some  reason the y were not  set by de fault prop erly.
  122   //               // W e should d o some exp erimenting  with thes e values t o be sure  they are s ufficient  to access  images acr oss the WA N
  123   //               prop s.put("jci fs.smb.cli ent.soTime out", "350 00");
  124   //               prop s.put("jci fs.smb.cli ent.respon seTimeout" , "35000") ;
  125   //               jcif s.Config.s etProperti es(props);
  126   //      }
  127           
  128           /* *
  129            *  Change th e extensio n of a fil e
  130            *  @param fi lename The  filename  to change
  131            *  @param ne wExtension  The new e xtension f or the fil ename (do  not includ e the '.')
  132            *  @return
  133            * /
  134           pr ivate Stri ng changeF ileExtensi on(String  filename,  String new Extension)  {
  135                    Stri ng fname =  filename;
  136                    int  loc = file name.lastI ndexOf("." );
  137                    if(l oc >= 0) {
  138                             fname  = filename .substring (0, loc);
  139                             fname  += "." + n ewExtensio n;
  140                    }
  141                    retu rn fname;
  142           }
  143           
  144           pu blic Strin g getFileE xtension(S tring file name)
  145           {
  146                    int  loc = file name.lastI ndexOf("." );
  147                    if(l oc >= 0) 
  148                    {
  149                             return  filename. substring( loc + 1);
  150                    }
  151                    retu rn filenam e;
  152           }
  153  
  154           
  155           pr ivate Byte BufferBack edImageStr eamRespons e openFile Stream(Smb Credential s smbCrede ntials, 
  156                             NtlmPa sswordAuth entication  ntPassAut h, Storage Proximity  imageProxi mity)
  157           th rows Image NotFoundEx ception, I mageNearLi neExceptio n, SmbExce ption, IOE xception
  158           {
  159                    SmbS erverShare  smbServer Share = sm bCredentia ls.getSmbS erverShare ();
  160                    logg er.info("O pening ima ge with UR L '" + smb ServerShar e.getSmbPa th() + "'. ");
  161                    Byte BufferBack edImageStr eamRespons e response  = null;
  162                    CIFS Context co ntext = nu ll;
  163                    for( int nearli neRetry=0;  nearlineR etry < get NearLineRe tries(); + +nearlineR etry)
  164                    {                         
  165                             if(con text == nu ll){
  166                                      //contex t = Single tonContext .getInstan ce();
  167                                      context  = Singleto nContext.g etInstance ().withCre dentials(n tPassAuth) ;
  168                             }
  169                             logger .debug("Cr edentials  stored in  CIFS Conte xt: " + co ntext.getC redentials ().toStrin g());
  170                             SmbFil e imageFil e = new Sm bFile(smbS erverShare .getSmbPat h(), conte xt);
  171                             // log ger.info(" Image open ed");
  172                             if( im ageFile.ca nRead() ) 
  173                             {
  174                                      int file Length = ( int)imageF ile.length ();
  175                                      if(fileL ength > 0)
  176                                      {
  177                                               logger.inf o("File '"  + smbServ erShare.ge tSmbPath()  + "' has  fileLength =" + fileL ength + ",  reading i mage into  buffer.");
  178                                               response =  new ByteB ufferBacke dImageStre amResponse (
  179                                                                new  ByteBuffer BackedImag eInputStre am(imageFi le.getInpu tStream(),  
  180                                                                                  (int)ima geFile.len gth(), tru e));
  181                                               logger.inf o("File '"  + smbServ erShare.ge tSmbPath()  + "' read  into buff er.");
  182                                               imageFile. close();
  183                                               return res ponse;
  184                                      }
  185                                      else
  186                                      {
  187                                               imageFile. close();
  188                                               // was thr owing File NotFoundEx ception (e xtends IOE xception)  - changed  to ImageNo tFoundExce ption and  improved e rror messa ge
  189                                               throw new  ImageNotFo undExcepti on("File [ " + smbSer verShare.g etSmbPath( ) + "] has  length of  [" + file Length + " ], not gre ated than  0 therefor e no image  data");
  190                                      }
  191                             }
  192                             // if  we cannot  read the f ile and th e problem  is not tha t the imag e is
  193                             // pro bably near -line then  bug out
  194                             else i f( imagePr oximity ==  null || i mageProxim ity != Sto rageProxim ity.NEARLI NE )
  195                                      imageFil e.close();
  196                                      throw ne w ImageNot FoundExcep tion("Cann ot read im age file "  + smbServ erShare.ge tSmbPath()  + ", indi cates file  does not  exist on s torage sys tem.");
  197                    }
  198                    // i f we get t o here the n the all  nearline r etries hav e been exh austed
  199                    // t hrow a nea r-line exc eption
  200                    thro w new Imag eNearLineE xception(" Cannot rea d Near-Lin e image fi le '" + sm bServerSha re.getSmbP ath() + "'  yet, retr y later.") ;                                               
  201           }
  202           
  203           pr ivate List <Integer>  getSortedC onnectionP orts(SmbSe rverShare  smbServerS hare)
  204           {
  205                    List <Integer>  connection Ports = ne w ArrayLis t<Integer> ();
  206                    SmbC onnectionI nformation Manager sm bConnectio nInformati onManager  = getSmbCo nnectionIn formationM anager();
  207                    int  firstTryPo rt = 
  208                             smbCon nectionInf ormationMa nager.getS uccessfulP ort(smbSer verShare.g etServer()
  209                                               SmbServerS hare.defau ltServerSh arePort);
  210                    conn ectionPort s.add(firs tTryPort);
  211                    
  212                    for( int port :  SmbServer Share.poss ibleConnec tionPorts)
  213                    {
  214                             // don 't add the  initial p ort again
  215                             if(por t != first TryPort)
  216                                      connecti onPorts.ad d(port);
  217                    }                 
  218                    retu rn connect ionPorts;
  219           }
  220           
  221           pr ivate SmbC onnectionI nformation Manager ge tSmbConnec tionInform ationManag er()
  222           {
  223                    retu rn SmbConn ectionInfo rmationMan ager.getSm bConnectio nInformati onManager( );
  224           }
  225           
  226           pr ivate void  updateSuc cessfulPor t(SmbServe rShare smb ServerShar e)
  227           {
  228                    if(s mbServerSh are != nul l)
  229                    {
  230                             SmbCon nectionInf ormationMa nager smbC onnectionI nformation Manager = 
  231                                      getSmbCo nnectionIn formationM anager();
  232                             smbCon nectionInf ormationMa nager.upda teSuccessf ulPort(smb ServerShar e.getServe r(), 
  233                                               smbServerS hare.getPo rt());
  234                    }
  235           }
  236           
  237           /* *
  238            *  Open the  input stre am for the  file and  create a S izedInputS tream that  contains  the filesi ze
  239            *  @param fi lename The  filename  to open (f ull UNC pa th)
  240            *  @param st orageCrede ntials The  network l ocation th at stores  the file ( with crede ntials set )
  241            *  @param im ageProximi ty The cur rent locat ion of the  image (ma gnetic, wo rm, offlin e)
  242            *  @return T he SizedIn putStream  with the i nput strea m open and  set to th e desired  file and t he number  of bytes f rom the fi le set
  243            *  @throws I mageNearLi neExceptio n Occurs i f the imag e is on a  jukebox an d is not r eadable
  244            *  @throws I mageNotFou ndExceptio n Occurs i f the imag e does not  exist (ca nnot be re ad and is  on magneti c)
  245            * /
  246           pr ivate Byte BufferBack edImageStr eamRespons e openFile Stream(
  247                             String  filename,  
  248                             Storag eCredentia ls storage Credential s, 
  249                             Storag eProximity  imageProx imity)
  250           th rows Image NearLineEx ception, I mageNotFou ndExceptio n, MethodE xception
  251           {
  252           lo gger.debug ("StorageC redentials  Username( ) : " + st orageCrede ntials.get Username()  + "   Sys tem userna me: " + Sy stem.getPr operty("us er.name")) ;
  253                    
  254                    if ( storageCre dentials.g etUsername ().equalsI gnoreCase( System.get Property(" user.name" )))
  255                    {
  256                             return  openLocal FileStream (filename,  storageCr edentials,  imageProx imity);
  257                    }
  258                    
  259                    Stri ng storage CredUserna me = null;
  260                    Stri ng[] stora geCredUser  = storage Credential s.getUsern ame().spli t("\\\\");
  261                    if ( storageCre dUser.leng th > 1)
  262                    {
  263                             storag eCredUsern ame = stor ageCredUse r[1]; 
  264                    }
  265                    else
  266                    {
  267                             storag eCredUsern ame = stor ageCredUse r[0]; 
  268                    }
  269                    
  270                    Stri ng systemU sername =  null;
  271                    Stri ng[] syste mUser = Sy stem.getPr operty("us er.name"). split("\\\ \");
  272                    if ( systemUser .length >  1)
  273                    {
  274                             system Username =  systemUse r[1]; 
  275                    }
  276                    else
  277                    {
  278                             system Username =  systemUse r[0]; 
  279                    }
  280                    
  281           lo gger.debug ("StorageC redUsernam e: " + sto rageCredUs ername + "    System  username:  " + system Username);
  282  
  283                    if ( storageCre dUsername. equalsIgno reCase(sys temUsernam e))
  284                    {
  285                             return  openLocal FileStream (filename,  storageCr edentials,  imageProx imity);
  286                    }
  287                    else
  288                    {
  289                             return  openUncFi leStream(f ilename, s torageCred entials, i mageProxim ity);
  290                    }
  291           }
  292           
  293  
  294           pr ivate Byte BufferBack edImageStr eamRespons e openLoca lFileStrea m(
  295                String f ilename, S torageCred entials st orageCrede ntials, St orageProxi mity image Proximity)
  296       throws  ImageNear LineExcept ion, Image NotFoundEx ception, M ethodExcep tion
  297       {
  298           lo gger.info( "Opening l ocal image  with File  path '" +  filename  + "'.");
  299           By teBufferBa ckedImageS treamRespo nse respon se = openL ocalFileSt ream(filen ame, image Proximity) ;
  300           if  (response  == null)
  301           {
  302                    retu rn openUnc FileStream (filename,  storageCr edentials,  imageProx imity);
  303           }
  304           el se
  305           {
  306                    retu rn respons e;
  307           }
  308       }
  309  
  310           pr ivate Byte BufferBack edImageStr eamRespons e openLoca lFileStrea m(
  311                String f ilename, S torageProx imity imag eProximity )
  312       {
  313           lo gger.info( "Opening l ocal image  with File  path '" +  filename  + "'.");
  314           By teBufferBa ckedImageS treamRespo nse respon se = null;
  315           fo r(int near lineRetry= 0; nearlin eRetry < g etNearLine Retries();  ++nearlin eRetry)
  316           {            
  317                File ima geFile = n ew File(fi lename);
  318                if(!imag eFile.exis ts())
  319                    //th row new Im ageNotFoun dException ("Local fi le '" + fi lename + " ' does not  exist");
  320                    retu rn null;
  321                
  322                // logge r.info("Im age opened ");
  323                if( imag eFile.canR ead() ) 
  324                {
  325                    int  fileLength  = (int)im ageFile.le ngth();
  326                    if(f ileLength  > 0)
  327                    {
  328                         logger.inf o("Local f ile '" + f ilename  +  "' has fi leLength="  + fileLen gth + ", r eading ima ge into bu ffer.");
  329                         try
  330                         {
  331                             respon se = new B yteBufferB ackedImage StreamResp onse(
  332                                      new Byte BufferBack edImageInp utStream(n ew FileInp utStream(i mageFile),  
  333                                               (int)fileL ength, tru e));
  334                         }
  335                         catch(IOEx ception io X)
  336                         {
  337                             return  null;
  338                         }
  339                         logger.inf o("Local f ile '" + f ilename +  "' read in to buffer. ");
  340                         return res ponse;
  341                    }
  342                    else
  343                    {
  344                             return  null;
  345                    }
  346                }
  347                // if we  cannot re ad the fil e and the  problem is  not that  the image  is
  348                // proba bly near-l ine then b ug out
  349                else if(  imageProx imity == n ull || ima geProximit y != Stora geProximit y.NEARLINE  )
  350                    retu rn null;
  351           }
  352           
  353           //  if we get  to here t hen the al l nearline  retries h ave been e xhausted
  354           re turn null;
  355       }
  356           
  357           pr ivate Byte BufferBack edImageStr eamRespons e openUncF ileStream(
  358                             String  filename,  
  359                             Storag eCredentia ls storage Credential s, 
  360                             Storag eProximity  imageProx imity)
  361           th rows Image NearLineEx ception, I mageNotFou ndExceptio n, MethodE xception
  362           {
  363                    SmbS erverShare  smbServer Share = nu ll;
  364                    try
  365                    {
  366                             smbSer verShare =  new SmbSe rverShare( filename);
  367                    }
  368                    catc h(Malforme dURLExcept ion murlX)
  369                    {
  370                             String  msg = "Ma lformedURL Exception  creating s mb server  share, " +  murlX.get Message();
  371                             logger .error(msg , murlX);
  372                             throw  new Method Exception( murlX);                         
  373                    }
  374                    List <Integer>  connection Ports = ge tSortedCon nectionPor ts(smbServ erShare);
  375                    
  376                    Ntlm PasswordAu thenticati on ntPassA uth = null ;
  377                    CIFS Context co ntext = nu ll;
  378                    Iter ator<Integ er> portIt erator = c onnectionP orts.itera tor();
  379                    whil e(portIter ator.hasNe xt())
  380                    {
  381                             try
  382                             {
  383                                      int conn ectionPort  = portIte rator.next ();
  384                                      smbServe rShare.set Port(conne ctionPort) ;
  385                                      logger.d ebug("Tryi ng this po ssible Con nectionPor t: " + con nectionPor t +
  386                                                       "  smbServerS hare: " +  smbServerS hare.toStr ing());
  387                                      if(conte xt == null ){
  388                                               context =  SingletonC ontext.get Instance() ;
  389                                      }
  390                                      SmbCrede ntials smb Credential s = SmbCre dentials.c reate(smbS erverShare
  391                                                       st orageCrede ntials);
  392                                      // ntPas sAuth does n't change  based on  connection  port, so  only creat e it once
  393                                      if(ntPas sAuth == n ull)
  394                                      {
  395                                               logger.deb ug("SmbCre dential Do main: " +  smbCredent ials.getDo main() +
  396                                                                "    username:  " + smbCre dentials.g etUsername () +
  397                                                                "    password:  <protected >");
  398                                               ntPassAuth  = 
  399                                                       ne w NtlmPass wordAuthen tication(c ontext, sm bCredentia ls.getDoma in(), smbC redentials .getUserna me(), 
  400                                                                         smbCre dentials.g etPassword ());
  401                                      }
  402                                      context. withCreden tials(ntPa ssAuth);
  403                                      ByteBuff erBackedIm ageStreamR esponse re sponse = 
  404                                               openFileSt ream(smbCr edentials,  ntPassAut h, imagePr oximity);
  405                                      updateSu ccessfulPo rt(smbServ erShare);
  406                                      return r esponse;
  407                             }
  408                             catch( SmbExcepti on smbX)
  409                             {
  410                                      // if th e exceptio n is a Con nection Ti meout, the  root caus e will be  a Transpor tException
  411                                      logger.e rror(smbX) ;
  412                                      boolean  includesRo otCause =  false;
  413                                      String m sg = smbX. getMessage ();
  414                                      if((msg  == null) | | (msg.len gth() <= 0 ))
  415                                      {
  416                                               if(smbX.ge tRootCause () != null )
  417                                               {
  418                                                       ms g = smbX.g etRootCaus e().getMes sage();
  419                                                       in cludesRoot Cause = tr ue;
  420                                               }
  421                                      }
  422                                      boolean  throwExcep tion = tru e;
  423                                      if((smbX .getRootCa use() != n ull) && (s mbX.getRoo tCause() i nstanceof  TransportE xception))
  424                                      {
  425                                               logger.war n("SmbExce ption root Cause is T ransportEx ception, w ill attemp t to use n ext port t o connect.  Error='"  + smbX.get RootCause( ).getMessa ge() + "'. ");
  426                                               // if it i s a transp ort except ion then i t could be  a connect ion timeou t exceptio n which
  427                                               // indicat es the VIX  is not co nnecting o n the righ t port, wa nt to try  the next a vailable p ort
  428                                               if(portIte rator.hasN ext())
  429                                               {
  430                                                       
  431                                                       //  if there  is another  port to t ry, don't  throw the  exception  just yet
  432                                                       th rowExcepti on = false ;
  433                                               }
  434                                               else
  435                                               {
  436                                                       lo gger.warn( "No more a vailable p orts to co nnect to s hare with,  will thro w exceptio n");
  437                                               }
  438                                      }
  439                                      else if( (!includes RootCause)  && (smbX. getRootCau se() != nu ll) && (sm bX.getRoot Cause() in stanceof U nknownHost Exception) )
  440                                      {
  441                                               // if JCIF S has an U nknownHost Exception,  it is cau ght here
  442                                               // just wa nt to make  sure unkn ownhost ge ts into th e exceptio n message
  443                                               msg += ",  " + smbX.g etRootCaus e().toStri ng();
  444                                      }                                                   
  445                                      
  446                                      if(throw Exception)
  447                                      {
  448                                               throw new  ImageNotFo undExcepti on("SMBExc eption ope ning SMB f ile '" + f ilename +  "', NT sta tus [" + s mbX.getNtS tatus() +  "], " + ms g, smbX);                                         
  449                                      }
  450                             }
  451                             catch( UnknownHos tException  uhX)
  452                             {
  453                                      // this  doesn't ev er seem to  be trigge red, caugh t as SmbEx ception
  454                                      logger.e rror(uhX);
  455                                      //throw  new ImageN otFoundExc eption("Un knownHostE xception o pening SMB  file '" +  filename  + "', " +  uhX.getMes sage(), uh X);
  456                                      // if th ere is an  UnknownHos tException , throw th is as a Me thodExcept ion since  the VIX ca nnot resol ve the hos t name - t his is a p roblem whi ch should  be correct ed!
  457                                      throw ne w MethodEx ception("U nknownHost Exception  opening SM B file '"  + filename  + "', " +  uhX.getMe ssage(), u hX);
  458                             }
  459                             catch( IOExceptio n ioX)
  460                             {
  461                                      logger.e rror(ioX);
  462                                      throw ne w ImageNot FoundExcep tion("IOEx ception op ening SMB  file '" +  filename +  "', " + i oX.getMess age(), ioX );
  463                             }
  464                    }
  465                    // i f we've go tten here  then we've  run out o f possible  ports to  try to con nect to im age shares  on
  466                    
  467                    
  468                    retu rn null;
  469           }        
  470           
  471  
  472           /*  (non-Java doc)
  473            *  @see gov. va.med.ima ging.excha nge.storag e.Abstract ImageStora geFacade#o penImageSt reamIntern al(java.la ng.String,  gov.va.me d.imaging. core.inter faces.Stor ageCredent ials, gov. va.med.ima ging.excha nge.enums. StoragePro ximity, go v.va.med.i maging.exc hange.busi ness.Image FormatQual ityList)
  474            * /
  475           @O verride
  476           pr otected By teBufferBa ckedImageS treamRespo nse openIm ageStreamI nternal(St ring image Identifier ,
  477                    Stor ageCredent ials image Credential s,
  478                    Stor ageProximi ty imagePr oximity,
  479                    Imag eFormatQua lityList r equestForm atQualityL ist)
  480           th rows Image NearLineEx ception, I mageNotFou ndExceptio n,
  481                    Conn ectionExce ption, Met hodExcepti on
  482           {
  483                    Byte BufferBack edImageStr eamRespons e response  = 
  484                             openFi leStream(i mageIdenti fier, imag eCredentia ls, imageP roximity);
  485                    // s et the dat a source r esponse va lue, not n eeded in i mage conve rsion sinc e set by h ttp client
  486                    // p ut in here  so not ch anged by T XT file re quest
  487                    if(( response ! = null) &&  (response .getImageS tream() !=  null))
  488                    {                                           
  489                             Transa ctionConte xt context  = Transac tionContex tFactory.g et();
  490                             contex t.setDataS ourceBytes Received(n ew Long(re sponse.get ImageStrea m().getSiz e()));
  491                    }
  492                    retu rn respons e;
  493           }
  494  
  495           /*  (non-Java doc)
  496            *  @see gov. va.med.ima ging.excha nge.storag e.Abstract ImageStora geFacade#o penTXTStre amInternal (java.lang .String, g ov.va.med. imaging.co re.interfa ces.Storag eCredentia ls, gov.va .med.imagi ng.exchang e.enums.St orageProxi mity)
  497            * /
  498           @O verride
  499           pr otected By teBufferBa ckedInputS tream open TXTStreamI nternal(St ring image Identifier ,
  500                    Stor ageCredent ials image Credential s, Storage Proximity  imageProxi mity)
  501           th rows Image NearLineEx ception, I mageNotFou ndExceptio n,
  502                    Conn ectionExce ption, Met hodExcepti on 
  503           {
  504                    Stri ng txtFile name = cha ngeFileExt ension(ima geIdentifi er, "txt") ;
  505                    Byte BufferBack edImageStr eamRespons e response  = 
  506                             openFi leStream(t xtFilename , imageCre dentials,  imageProxi mity);
  507                    if(r esponse !=  null)
  508                             return  response. getImageSt ream();
  509                    retu rn null;
  510           }
  511  
  512           /*  (non-Java doc)
  513            *  @see gov. va.med.ima ging.core. interfaces .ImageStor ageFacade# openPhotoI d(java.lan g.String,  gov.va.med .imaging.c ore.interf aces.Stora geCredenti als)
  514            * /
  515           @O verride
  516           pu blic ByteB ufferBacke dInputStre am openPho toId(Strin g imageIde ntifier,
  517                             Storag eCredentia ls imageCr edentials)  
  518           th rows Image NotFoundEx ception, C onnectionE xception,  MethodExce ption 
  519           {
  520                    try
  521                    {
  522                             ByteBu fferBacked ImageStrea mResponse  response =  openFileS tream(imag eIdentifie r, 
  523                                               imageCrede ntials, St orageProxi mity.ONLIN E);
  524                             if(res ponse != n ull)
  525                             {                                  
  526                                      return r esponse.ge tImageStre am();
  527                             }
  528                             throw  new Connec tionExcept ion("Image  stream re sponse is  null");
  529                    }
  530                    catc h(ImageNea rLineExcep tion inlX)
  531                    {
  532                             logger .error("Ne arline exc eption get ting photo  id", inlX );
  533                             throw  new ImageN otFoundExc eption(inl X);
  534                    }
  535           }
  536           
  537           pu blic DataS ourceImage InputStrea m openFile InputStrea m(String u ncFilePath ,
  538                             Storag eCredentia ls imageCr edentials)  
  539           th rows Image NotFoundEx ception, C onnectionE xception,  MethodExce ption 
  540           {
  541                    try
  542                    {
  543                             ImageS treamRespo nse respon se = openF ileStream( uncFilePat h, 
  544                                               imageCrede ntials, St orageProxi mity.ONLIN E);
  545                             if(res ponse != n ull)
  546                             {                                  
  547                                      return r esponse.ge tImageStre am();
  548                             }
  549                             throw  new Connec tionExcept ion("Image  stream re sponse is  null");
  550                    }
  551                    catc h(ImageNea rLineExcep tion inlX)
  552                    {
  553                             logger .error("Ne arline exc eption get ting photo  id", inlX );
  554                             throw  new ImageN otFoundExc eption(inl X);
  555                    }
  556           }
  557           
  558           pr ivate Vist aStorageCo nfiguratio n getVista StorageCon figuration ()
  559           {
  560                    retu rn VistaSt orageConfi guration.g etVistaSto rageConfig uration();
  561           }
  562           
  563           pu blic Outpu tStream op enOutputSt ream(Strin g filename , StorageC redentials  storageCr edentials)  
  564           th rows  IOEx ception
  565           {
  566                    logg er.info("O pening out put stream  to file [ " + filena me + "]");
  567                    SmbF ile file =  getSmbFil e(filename , storageC redentials );
  568                    file .createNew File();
  569                    retu rn file.ge tOutputStr eam();  
  570                    
  571           }
  572  
  573           pu blic void  deleteFile (String fi lename, St orageCrede ntials sto rageCreden tials) 
  574           th rows  IOEx ception
  575           {
  576                    logg er.info("D eleting fi le [" + fi lename + " ]");
  577                    SmbF ile file =  getSmbFil e(filename , storageC redentials );
  578                    file .delete();
  579           }
  580  
  581           pu blic void  copyFile(S tring sour cePath, St ring desti nationPath , StorageC redentials  storageCr edentials)  
  582           th rows IOExc eption
  583           {
  584                    logg er.info("C opying fil e [" + sou rcePath +  "] to file  [" + dest inationPat h+ "]");
  585                    SmbF ile source File = get SmbFile(so urcePath,  storageCre dentials);
  586                    SmbF ile destin ationFile  = getSmbFi le(destina tionPath,  storageCre dentials);
  587                    sour ceFile.cop yTo(destin ationFile) ;
  588           }
  589  
  590           pu blic void  copyRemote FileToLoca lFile(Stri ng remoteP ath, Strin g localPat h, Storage Credential s storageC redentials
  591           th rows  IOEx ception
  592           {
  593                    logg er.info("C opying fil e [" + rem otePath +  "] to file  [" + loca lPath+ "]" );
  594                    SmbF ile remote File = get SmbFile(re motePath,  storageCre dentials);
  595                    SmbF ileInputSt ream in =  new SmbFil eInputStre am(remoteF ile); 
  596                    
  597                    
  598                    File  localFile  = new Fil e(localPat h);
  599                    if(! localFile. exists())  {
  600                             localF ile.getPar entFile(). mkdirs();
  601                             localF ile.create NewFile();
  602                    } 
  603                    File OutputStre am out = n ew FileOut putStream( localFile,  false); 
  604  
  605                    byte [] buffer  = new byte [16904]; 
  606                    int  read = 0; 
  607                    whil e ((read =  in.read(b uffer)) >  0) 
  608                         out.write( buffer, 0,  read); 
  609                    
  610                    in.c lose(); 
  611                    out. close(); 
  612           }
  613  
  614           pu blic void  renameFile (String fi lename, St ring newFi lename, St orageCrede ntials sto rageCreden tials) 
  615           th rows  IOEx ception
  616           {
  617                    logg er.info("r enaming fi le [" + fi lename + " ]");
  618                    SmbF ile oldFil e = getSmb File(filen ame, stora geCredenti als);
  619                    SmbF ile newFil e = getSmb File(newFi lename, st orageCrede ntials);
  620                    oldF ile.rename To(newFile );
  621           }
  622  
  623           pu blic boole an fileExi sts(String  filename,  StorageCr edentials  storageCre dentials) 
  624           th rows  IOEx ception
  625           {
  626                    logg er.info("C hecking to  see if fi le exists  [" + filen ame + "]") ;
  627                    SmbF ile file =  getSmbFil e(filename , storageC redentials );
  628                    retu rn file.ex ists();
  629           }
  630           
  631           pu blic Strin g readFile AsString ( String fil ename, Sto rageCreden tials stor ageCredent ials) 
  632           th rows  IOEx ception
  633           {
  634                    logg er.info("R eading fil e [" + fil ename + "]  as string ");
  635                    SmbF ile file =  getSmbFil e(filename , storageC redentials );
  636                    
  637                StringBu ilder text  = new Str ingBuilder ();
  638                String N L = System .getProper ty("line.s eparator") ;
  639                Scanner  scanner =  new Scanne r(new SmbF ileInputSt ream(file) );
  640                try {
  641                  while  (scanner.h asNextLine ()){
  642                    text .append(sc anner.next Line() + N L);
  643                  }
  644                }
  645                finally{
  646                  scanne r.close();
  647                }
  648                
  649                    retu rn text.to String();
  650           }
  651           
  652           pu blic void  writeStrin gToFile(St ring fileC ontents, S tring file name, Stor ageCredent ials stora geCredenti als) 
  653           th rows  IOEx ception
  654           {
  655                    logg er.info("W riting to  file [" +  filename +  "]");
  656                    
  657                Writer o ut = new O utputStrea mWriter(op enOutputSt ream(filen ame, stora geCredenti als));
  658                try {
  659                  out.wr ite(fileCo ntents);
  660                }
  661                finally  {
  662                  out.cl ose();
  663                }       
  664  
  665           }
  666           
  667   //      pr ivate SmbF ile getSmb File(Strin g filename , StorageC redentials  storageCr edentials)
  668   //      th rows Malfo rmedURLExc eption, Sm bException  
  669   //      {
  670   //               SmbC redentials  fileCrede ntials = S mbCredenti als.create (new SmbSe rverShare( filename),  
  671   //                                 storageC redentials );
  672   //               SmbC redentials  directory Credential s = SmbCre dentials.c reate(new  SmbServerS hare(this. getDirecto ry(filenam e)),
  673   //                                 storageC redentials );
  674   //               SmbF ile file =  null;
  675   //               SmbF ile direct ory = null ;
  676   //               
  677   //               CIFS Context co ntext = nu ll;
  678   //               if(c ontext ==  null){
  679   //                        contex t = Single tonContext .getInstan ce();
  680   //               }
  681   //               
  682   //               Ntlm PasswordAu thenticati on ntPassA uth = 
  683   //                        new Nt lmPassword Authentica tion(conte xt, fileCr edentials. getDomain( ),
  684   //                                          fileCreden tials.getU sername(),
  685   //                                          fileCreden tials.getP assword()) ;
  686   //
  687   //               
  688   //               dire ctory = ne w SmbFile( directoryC redentials .getSmbSer verShare() .getSmbPat h(), conte xt);
  689   //               
  690   //               if ( !directory .exists()) {
  691   //                        direct ory.mkdirs ();
  692   //               }
  693   //
  694   //               file  = new Smb File(fileC redentials .getSmbSer verShare() .getSmbPat h(), conte xt);
  695   //               
  696   //               dire ctory.clos e();
  697   //               retu rn file;
  698   //      }
  699           
  700           pr ivate SmbF ile getSmb File(Strin g filename , StorageC redentials  storageCr edentials)
  701           th rows Malfo rmedURLExc eption, Sm bException  
  702           {
  703                    SmbC redentials  fileCrede ntials = S mbCredenti als.create (new SmbSe rverShare( filename),  
  704                                      storageC redentials );
  705                    
  706                    SmbC redentials  directory Credential s = SmbCre dentials.c reate(new  SmbServerS hare(this. getDirecto ry(filenam e)),
  707                                      storageC redentials );
  708  
  709                    SmbF ile file =  null;
  710                    SmbF ile direct ory = null ;
  711                    
  712                    try  {
  713                             BaseCo ntext bc =  new BaseC ontext(new  PropertyC onfigurati on(System. getPropert ies()));
  714                             NtlmPa sswordAuth entication  ntPassAut h = 
  715                                               new NtlmPa sswordAuth entication (bc, 
  716                                                                file Credential s.getDomai n(),
  717                                                                file Credential s.getUsern ame(),
  718                                                                file Credential s.getPassw ord());
  719  
  720                             CIFSCo ntext cont ext = bc.w ithCredent ials(ntPas sAuth);
  721                             
  722                             direct ory = new  SmbFile(di rectoryCre dentials.g etSmbServe rShare().g etSmbPath( ), context );
  723                    
  724                             if (!d irectory.e xists()){
  725                                      director y.mkdirs() ;
  726                             }
  727                             
  728                             file =  new SmbFi le(fileCre dentials.g etSmbServe rShare().g etSmbPath( ), context );
  729                             
  730                    } ca tch (CIFSE xception e ) {
  731                             throw  new SmbExc eption(e.g etMessage( ));
  732                    }
  733                    
  734                    dire ctory.clos e();
  735                    retu rn file;
  736           }
  737  
  738           pr otected St ring getDi rectory(St ring fullF ileSpec){
  739                    int  endIndex =  fullFileS pec.lastIn dexOf("\\" );
  740                    retu rn fullFil eSpec.subs tring(0, e ndIndex);
  741           }
  742           
  743           pu blic stati c void mai n(String[]  args) 
  744           {
  745                    Stri ng sourceP ath = "\\\ \I873vstwi n-t\\d$\\t emp\\test_ url.txt";
  746                    Stri ng destina tionPath =  "\\\\I873 vstwin-t\\ d$\\temp_c opy\\copy_ test_url.t xt";
  747                    Stri ng destina tionPath2  = "\\\\I87 3vstwin-t\ \d$\\temp_ copy\\copy 2_test_url .txt";
  748                    Stri ng destina tionPath3  = "\\\\I87 3vstwin-t\ \d$\\temp_ copy\\new_ test.txt";
  749                    Stri ng localPa th = "c:\\ temp\\copy _test_url. txt";
  750                    
  751                    SmbS torageUtil ity util =  new SmbSt orageUtili ty();
  752                    Stor ageCredent ials stora geCredenti als = (Sto rageCreden tials) 
  753                                      new Netw orkLocatio nInfo("",  null, sour cePath,"I8 73vstwin-t \\administ rator", "V ista2014") ;
  754                    try  {
  755                             if (ut il.fileExi sts(destin ationPath,  storageCr edentials) )
  756                             {
  757                                      System.o ut.println ("remote d estination Path file  exist!");
  758                             
  759                                      util.del eteFile(de stinationP ath2, stor ageCredent ials);
  760                                      System.o ut.println ("remote d estination Path file  deleted!") ;
  761                             }
  762                             
  763                             if (ut il.fileExi sts(destin ationPath2 , storageC redentials ))
  764                             {
  765                                      System.o ut.println ("remote d estination Path2 file  exist!");
  766                             
  767                                      util.del eteFile(de stinationP ath2, stor ageCredent ials);
  768                                      System.o ut.println ("remote d estination Path2 file  deleted!" );
  769                             }
  770  
  771                             if (ut il.fileExi sts(destin ationPath3 , storageC redentials ))
  772                             {
  773                                      System.o ut.println ("remote d estination Path3 file  exist!");
  774                                      
  775                                      util.del eteFile(de stinationP ath3, stor ageCredent ials);
  776                                      System.o ut.println ("remote d estination Path3 file  deleted!" );
  777                             }
  778                             
  779                             util.c opyFile(so urcePath,  destinatio nPath, sto rageCreden tials);
  780                             System .out.print ln("remote  file copi ed!");
  781                             
  782                             util.r enameFile( destinatio nPath, des tinationPa th2, stora geCredenti als);
  783                             System .out.print ln("remote  file rena med!");
  784  
  785                             util.c opyRemoteF ileToLocal File(sourc ePath, loc alPath, st orageCrede ntials);
  786                             System .out.print ln("file c opied to l ocal locat ion!");
  787                             
  788                             util.d eleteFile( destinatio nPath2, st orageCrede ntials);
  789                             System .out.print ln("remote  file dele ted!");
  790                             
  791                             System .out.print ln(util.re adFileAsSt ring(sourc ePath, sto rageCreden tials));
  792                             
  793                             if (ut il.fileExi sts(destin ationPath3 , storageC redentials ))
  794                             {
  795                                      util.del eteFile(de stinationP ath3, stor ageCredent ials);
  796                                      System.o ut.println ("remote d estination Path3 file  deleted!" );
  797                             }
  798                             
  799                         Writer out  = new Out putStreamW riter(util .openOutpu tStream(de stinationP ath3, stor ageCredent ials));
  800                         try {
  801                           out.writ e("cccc");
  802                         }
  803                         finally {
  804                           out.clos e();
  805                         }       
  806                        
  807                        
  808                    } ca tch (IOExc eption e)  {
  809                             // TOD O Auto-gen erated cat ch block
  810                             e.prin tStackTrac e();
  811                    }
  812           }
  813  
  814  
  815   }