7300. EPMO Open Source Coordination Office Redaction File Detail Report

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

7300.1 Files compared

# Location File Last Modified
1 PRE_PPS-N_v3.0.1.zip\PS_PPS_srv\src\main\java\gov\va\med\pharmacy\peps\service\common\capability\impl NdfUpdateCapabilityImpl.java Fri Jan 12 15:43:30 2018 UTC
2 PRE_PPS-N_v3.0.1.zip\PS_PPS_srv\src\main\java\gov\va\med\pharmacy\peps\service\common\capability\impl NdfUpdateCapabilityImpl.java Wed Mar 7 18:49:32 2018 UTC

7300.2 Comparison summary

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

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

7300.4 Active regular expressions

No regular expressions were active.

7300.5 Comparison detail

  1   /*
  2    * 
  3    */
  4   package go v.va.med.p harmacy.pe ps.service .common.ca pability.i mpl;
  5  
  6   import gov .va.med.ph armacy.pep s.common.e mail.Email ;
  7   import gov .va.med.ph armacy.pep s.common.e mail.Email Service;
  8   import gov .va.med.ph armacy.pep s.common.e xception.V alidationE xception;
  9   import gov .va.med.ph armacy.pep s.common.e xception.V alueObject Validation Exception;
  10   import gov .va.med.ph armacy.pep s.common.e xception.W rappedIOEx ception;
  11   import gov .va.med.ph armacy.pep s.common.u tility.sec urity.Untr ustedLogPa ram;
  12   import gov .va.med.ph armacy.pep s.common.v o.FieldKey ;
  13   import gov .va.med.ph armacy.pep s.common.v o.NdfUpdat eFileVo;
  14   import gov .va.med.ph armacy.pep s.common.v o.Paginate dList;
  15   import gov .va.med.ph armacy.pep s.common.v o.StatusVo ;
  16   import gov .va.med.ph armacy.pep s.common.v o.UpdateSe archCriter ia;
  17   import gov .va.med.ph armacy.pep s.common.v o.UserVo;
  18   import gov .va.med.ph armacy.pep s.common.v o.validato r.ErrorKey ;
  19   import gov .va.med.ph armacy.pep s.common.v o.validato r.Errors;
  20   import gov .va.med.ph armacy.pep s.domain.c ommon.capa bility.Ndf UpdateFile MgtDomainC apability;
  21   import gov .va.med.ph armacy.pep s.domain.c ommon.capa bility.Ndf UpdateFile StatusDoma inCapabili ty;
  22   import gov .va.med.ph armacy.pep s.service. common.cap ability.Nd fUpdateCap ability;
  23   import gov .va.med.ph armacy.pep s.service. common.cap ability.Nd fUpdatePro cessCapabi lity;
  24   import gov .va.med.ph armacy.pep s.service. common.uti lity.NdfUp dateProces sFile;
  25  
  26   import jav a.io.IOExc eption;
  27   import jav a.nio.file .Path;
  28   import jav a.util.Cal endar;
  29   import jav a.util.Gre gorianCale ndar;
  30   import jav a.util.Lis t;
  31   import jav a.util.Opt ional;
  32  
  33   import jav ax.annotat ion.Resour ce;
  34  
  35   import org .apache.co mmons.lang 3.StringUt ils;
  36   import org .apache.lo gging.log4 j.LogManag er;
  37   import org .apache.lo gging.log4 j.Logger;
  38   import org .springfra mework.con text.annot ation.Conf iguration;
  39   import org .springfra mework.con text.annot ation.Prop ertySource ;
  40   import org .springfra mework.cor e.env.Envi ronment;
  41   import org .springfra mework.tra nsaction.P latformTra nsactionMa nager;
  42   import org .springfra mework.tra nsaction.T ransaction Status;
  43   import org .springfra mework.tra nsaction.s upport.Tra nsactionCa llback;
  44   import org .springfra mework.tra nsaction.s upport.Tra nsactionCa llbackWith outResult;
  45   import org .springfra mework.tra nsaction.s upport.Tra nsactionTe mplate;
  46  
  47   /**
  48    * Contain s the main  logic to  create the  NDF Updat e File and  send emai l notifica tions. Thi s class is  not compl etely
  49    * thread- safe but s ee the {@l ink NdfUpd ateCapabil ity} class  documenta tion for w hat is thr ead-safe.
  50    */
  51   @Configura tion
  52   @PropertyS ource("cla sspath:gov .va.med.ph armacy.pep s.emailser vice.prope rties")
  53   public cla ss NdfUpda teCapabili tyImpl imp lements Nd fUpdateCap ability {
  54     
  55     private  static fin al String  THREAD_NAM E = "On-de mand Updat e File Thr ead";
  56  
  57     /**
  58      * The p roperty na me of the  email addr ess list t o send fil e rejected  emails to .
  59      */
  60     static f inal Strin g FILE_REJ ECTED_TO_E MAIL_PROPE RTY = "upd ate_file_r ejected_to _email";
  61  
  62     /**
  63      * The p roperty na me of the  email addr ess list t o send fil e approved  emails to .
  64      */
  65     static f inal Strin g FILE_APP ROVED_TO_E MAIL_PROPE RTY = "upd ate_file_a pproved_to _email";
  66  
  67     /**
  68      * The p roperty na me of the  email addr ess list t o send fil e ready fo r testing  emails to.
  69      */
  70     static f inal Strin g FILE_REA DY_FOR_TES TING_TO_EM AIL_PROPER TY = "upda te_file_on _test_site _to_email" ;
  71  
  72       /** Th e Logger.  */
  73       privat e static f inal Logge r LOG = Lo gManager
  74                .getLogg er(NdfUpda teCapabili tyImpl.cla ss);
  75       
  76       /** Th e NdfUpdat eProcessCa pability.  */
  77       privat e NdfUpdat eProcessCa pability n dfUpdatePr ocessCapab ility;
  78       
  79       /** Th e NdfUpdat eFileMgtDo mainCapabi lity. */
  80       privat e NdfUpdat eFileMgtDo mainCapabi lity ndfUp dateFileMg tDomainCap ability;
  81       
  82       /** Th e NdfUpdat eFileStatu sDomainCap ability. * /
  83       privat e NdfUpdat eFileStatu sDomainCap ability nd fUpdateFil eStatusDom ainCapabil ity;
  84       
  85       /** Th e NdfUpdat eProcessFi le. */
  86       privat e NdfUpdat eProcessFi le ndfUpda teProcessF ile;
  87  
  88       /** Th e transact ion manage r. */
  89       privat e Platform Transactio nManager t ransaction Manager;
  90  
  91       /** Th e email se rvice. */
  92       privat e EmailSer vice email Service;
  93  
  94       /** Th e environm ent. */
  95       privat e Environm ent enviro nment;
  96       
  97     // This  method is  synchroniz ed because  this proc ess should  only be e xecuted by  one threa d at a tim e. This cl ass
  98     // shoul d also be  a singleto n.
  99     @Overrid e
  100     public s ynchronize d NdfUpdat eFileVo cr eateOnDema ndFileAsyn c(UserVo u ser) throw s Validati onExceptio n {
  101  
  102       final  Optional<N dfUpdateFi leVo> opti onalFileTo Generate =  getFileRe cordForGen eration(us er);
  103       // If  a file was  already i n process,  throw the  exception  per the m ethod cont ract.
  104       if (!o ptionalFil eToGenerat e.isPresen t()) {
  105         thro w new Vali dationExce ption(Vali dationExce ption.NON_ FINAL_STAT E_FILE_IN_ PROCESS);
  106       }
  107       
  108       final  NdfUpdateF ileVo file ToGenerate  = optiona lFileToGen erate.get( );
  109  
  110       // It  would be b etter to u se a pre-e xisting th read for p erformance  here, but  we don't  have a com mon
  111       // Exe cutorServi ce availab le and per formance i s not a ma jor concer n for this  operation .
  112       new Th read(new R unnable()  {
  113         @Ove rride
  114         publ ic void ru n() {
  115           tr y {
  116              LOG.info(" Executing  on-demand  file gener ation.");
  117              // generat eAndTransm itFile() i s also syn chronized  so this ne w thread w ill not ex ecute it u ntil the
  118              // kicking -off metho d returns.
  119              generateAn dTransmitF ile(fileTo Generate,  user);
  120           }  catch (fin al Excepti on e) {
  121              handleExce ptionDurin gCreateAnd SendToTest Process(us er, fileTo Generate,  e);
  122              cleanupFro mException DuringCrea teAndSendT oTestProce ss(fileToG enerate);
  123             
  124              // Don't r e-throw an  exception  because w e're on a  separate t hread. We  have alrea dy updated  the file  metadata
  125              // to repo rt the err or.
  126           }
  127         }
  128       }, THR EAD_NAME). start();
  129  
  130       return  fileToGen erate;
  131     }
  132  
  133       @Overr ide
  134       // Thi s method i s synchron ized becau se this pr ocess shou ld only be  executed  by one thr ead at a t ime. This  class
  135       // sho uld also b e a single ton.
  136       public  synchroni zed void c reateSched uledFile(U serVo user ) throws I OException  {
  137  
  138         // G et the fil e record i n a separa te transac tion becau se we want  to commit  it before  we start  the transa ction for
  139         // g enerateAnd TransmitFi le().
  140         fina l Transact ionTemplat e txTempla te = new T ransaction Template(t ransaction Manager);
  141         txTe mplate.set Propagatio nBehavior( Transactio nTemplate. PROPAGATIO N_REQUIRES _NEW);
  142         fina l Optional <NdfUpdate FileVo> op tionalNewF ile = txTe mplate.exe cute(
  143              new Transa ctionCallb ack<Option al<NdfUpda teFileVo>> () {
  144                @Overrid e
  145                public O ptional<Nd fUpdateFil eVo> doInT ransaction (Transacti onStatus s tatus) {
  146                  return  getFileRe cordForGen eration(us er);
  147                }
  148              });
  149  
  150         if ( optionalNe wFile.isPr esent()) {
  151           fi nal NdfUpd ateFileVo  newFileVo  = optional NewFile.ge t(); // Ne ver return s null.
  152  
  153           tr y {
  154              // This me thod execu tes in its  own trans action.
  155              generateAn dTransmitF ile(newFil eVo, user) ;
  156           }  catch (Exc eption e)  {
  157              handleExce ptionDurin gCreateAnd SendToTest Process(us er, newFil eVo, e);
  158              cleanupFro mException DuringCrea teAndSendT oTestProce ss(newFile Vo);
  159  
  160              // Still t hrow the e xception p er the met hod contra ct.
  161              throw e;
  162           }
  163  
  164         }
  165       }
  166  
  167       /**
  168        * Ret urns the { @link NdfU pdateFileV o} to use  for genera ting a new  update fi le. Create s one or r esets an e xisting
  169        * one  as approp riate.
  170        * 
  171        * @re turn an "e mpty" opti onal if no  appropria te record  could be r eturned an d the file  should no t be gener ated now.
  172        * Oth erwise, a  "present"  optional c ontaining  the record  to use. N ever null.
  173        */
  174       privat e synchron ized Optio nal<NdfUpd ateFileVo>  getFileRe cordForGen eration(Us erVo user)  {
  175         fina l NdfUpdat eFileVo la testFileVo  = ndfUpda teFileMgtD omainCapab ility.retr ieveCurren tStatus();
  176         if ( latestFile Vo == null ) {
  177           //  very firs t time cre ating a fi le
  178           re turn Optio nal.of(cre ateInitiat edFile(use r));
  179  
  180         } el se if (Sta tusVo.NON_ FINAL_STAT E_STATUSES .contains( latestFile Vo.getStat us().getSt atusId()))  {
  181           LO G.info("Ca nnot creat e new file , as the p revious fi le is not  in a final  state.");
  182           re turn Optio nal.empty( );
  183  
  184         } el se if (Sta tusVo.PPSN _ERROR ==  latestFile Vo.getStat us().getSt atusId())  {
  185           //  reuse the  NdfUpdate FileVo
  186           la testFileVo .setCommen ts(null);
  187           la testFileVo .setDirect oryPath(nu ll);
  188           la testFileVo .setFileNa me(null);
  189           la testFileVo .getStatus ().setStat usId(Statu sVo.INITIA TED);
  190           //  Go ahead  and update  the recor d in the d atabase to  prevent a nyone from  trying to  kick off  another pr ocess.
  191           up dateNdfUpd ateFile(la testFileVo , user);
  192           re turn Optio nal.of(lat estFileVo) ;
  193  
  194         } el se {
  195           re turn Optio nal.of(cre ateInitiat edFile(use r));
  196         }
  197       }
  198  
  199       /**
  200        * Gen erates an  update fil e, transmi ts it to t he test fo lder, and  updates it s metadata  in the da tabase, al l in its
  201        * own  transacti on.
  202        * 
  203        * @pa ram newFil eVo the as sociated { @link NdfU pdateFileV o}. Must b e in {@lin k StatusVo #INITIATED } status.
  204        * @pa ram user t he user ge nerating t he file
  205        * @th rows IOExc eption if  there is a n error ge nerating o r transfer ring the u pdate file .
  206        */
  207       // Thi s method i s mainly p rotected j ust to all ow automat ed testing , but theo retically  a subclass  could use  it.
  208       protec ted synchr onized voi d generate AndTransmi tFile(NdfU pdateFileV o newFileV o, UserVo  user) thro ws IOExcep tion {
  209         
  210         // P reconditio n check.
  211         if ( StatusVo.I NITIATED ! = newFileV o.getStatu s().getSta tusId()) {
  212           th row new Il legalArgum entExcepti on("The gi ven update  file is n ot ready t o generate .");
  213         }
  214  
  215         // U se Transac tionTempla te because  @Transact ional does  not work  when calli ng methods  on 'this' .
  216         fina l Transact ionTemplat e txTempla te = new T ransaction Template(t ransaction Manager);
  217         txTe mplate.set Propagatio nBehavior( Transactio nTemplate. PROPAGATIO N_REQUIRES _NEW);
  218         try  {
  219           tx Template.e xecute(new  Transacti onCallback WithoutRes ult() {
  220              @Override
  221              protected  void doInT ransaction WithoutRes ult(Transa ctionStatu s status)  {
  222                try {
  223                  create AndAttachP hysicalFil e(user, ne wFileVo);
  224           
  225                  ndfUpd ateProcess Capability .addDataTo File(newFi leVo, ndfU pdateProce ssFile);
  226             
  227                  transm itUpdateFi leToTest(n ewFileVo,  user);
  228                } catch  (IOExcepti on ex) {
  229                  throw  new Wrappe dIOExcepti on(ex);
  230                }
  231  
  232                updateNd fUpdateFil e(newFileV o, user);
  233         
  234                LOG.info ("Generate d and tran smitted up date file  {}.", newF ileVo.getF ileName()) ;
  235              }
  236           }) ;
  237         } ca tch (final  WrappedIO Exception  ex) {
  238           LO G.debug("C aught Wrap pedIOExcep tion. Tran slating ba ck to a no rmal IOExc eption.",  ex);
  239           th row new IO Exception( "Failed to  generate  update fil e.", ex.ge tWrappedEx ception()) ;
  240         }
  241       }
  242  
  243       /**
  244        * Cre ate the lo cal physic al file an d attach i t to speci fied NdfUp dateFileVo .
  245        * @pa ram user U ser
  246        * @pa ram newFil eVo NdfUpd ateFileVo  to associa te to the  new physic al file
  247        * @th rows IOExc eption Thr own if err ors encoun tered duri ng physica l file cre ation
  248        */ 
  249       privat e void cre ateAndAtta chPhysical File(UserV o user, Nd fUpdateFil eVo newFil eVo) throw s IOExcept ion {
  250  
  251           Pa th filePat h = ndfUpd ateProcess File.creat eFile(newF ileVo.getF ileId());
  252      
  253           ne wFileVo.se tFileName( filePath.g etFileName ().toStrin g());
  254           ne wFileVo.se tDirectory Path(ndfUp dateProces sFile.getP ath().toSt ring());
  255           ne wFileVo.se tStatus(ne w StatusVo (StatusVo. CREATED));
  256           up dateNdfUpd ateFile(ne wFileVo, u ser);
  257       }
  258  
  259       /**
  260        * Han dles an ex ception du ring the f ile creati on process .
  261        * @pa ram user U ser who in voked the  file creat ion
  262        * @pa ram newFil eVo the Nd fUpdateFil eVo being  processed.  Must not  be null.
  263        * @pa ram e the  exception  encountere d
  264        */
  265       privat e void han dleExcepti onDuringCr eateAndSen dToTestPro cess(UserV o user, Nd fUpdateFil eVo newFil eVo, Excep tion e) {
  266           tr y{
  267                LOG.erro r(
  268                    "Exc eption in  NdfUpdateC apabilityI mpl.proces s() - " +  new Untrus tedLogPara m(e.getMes sage()), e );
  269                newFileV o.setStatu s(new Stat usVo(Statu sVo.PPSN_E RROR));
  270                newFileV o.setComme nts("PPS-N /NDF Updat e Test Fil e Creation  Failed. L og a CA ti cket");
  271                updateNd fUpdateFil eInSeparat eTxn(newFi leVo, user );
  272           }
  273           ca tch (Excep tion e1){
  274                LOG.erro r("Seconda ry excepti on encount ered durin g cleanup  after a pr imary exce ption.", e 1);
  275           }
  276       }
  277       
  278       /**
  279        * Cre ates an Nd fUpdateFil eVo with i nitiated s tatus. 
  280        * @pa ram user U ser initia ting the f ile
  281        * @re turn NdfUp dateFileVo  with init iated stat us
  282        */
  283       privat e NdfUpdat eFileVo cr eateInitia tedFile(Us erVo user)  {
  284           Nd fUpdateFil eVo initia tedFile =  new NdfUpd ateFileVo( );
  285           in itiatedFil e.setStatu s(new Stat usVo(Statu sVo.INITIA TED));
  286           in itiatedFil e.setFileN ame("");
  287           Nd fUpdateFil eVo update File = ins ertNdfUpda teFile(ini tiatedFile , user);
  288           re turn updat eFile;
  289       }
  290  
  291       @Overr ide
  292       public  synchroni zed void a pprove(Ndf UpdateFile Vo toUpdat e, UserVo  user) thro ws Validat ionExcepti on {
  293           tr y {
  294                transmit UpdateFile ToProd(toU pdate, use r);
  295           }  catch (Exc eption e)  {
  296                LOG.erro r("Error w hile trans mitting fi le to prod uction.",  e);
  297                throw ne w Validati onExceptio n(Validati onExceptio n.FILE_APP ROVAL_FAIL ED);
  298           }
  299       }
  300       
  301       @Overr ide
  302       public  synchroni zed void r eject(NdfU pdateFileV o toUpdate , UserVo u ser)
  303                throws V alidationE xception {
  304           
  305         if ( StringUtil s.isBlank( toUpdate.g etComments ())) {
  306           Er rors error s = new Er rors();
  307           er rors.addEr ror(FieldK ey.UPDATE_ FILE, Erro rKey.FILE_ REJECTION_ COMMENTS_R EQUIRED);
  308           th row new Va lueObjectV alidationE xception(e rrors);
  309         }
  310  
  311         try  {
  312           tr ansmitUpda teFileToRe ject(toUpd ate, user) ;
  313           nd fUpdatePro cessCapabi lity.proce ssRejected File(toUpd ate);                  
  314         } ca tch (Excep tion e) {
  315           LO G.error("E rror while  transmitt ing file t o reject." , e);
  316           th row new Va lidationEx ception(Va lidationEx ception.FI LE_REJECTI ON_FAILED) ;
  317         }
  318       }        
  319       
  320       /**
  321        * Tra nsmit upda te file to  productio n - Moves  the file t o the prod uction fol der, sends  an email  notificati on, and st ores 
  322        * the  NdfUpdate FileVo wit h an updat ed status.   
  323        *
  324        * @pa ram update File the u pdate file
  325        * @pa ram user t he user
  326        * @th rows IOExc eption if  the file c ould not b e moved
  327        */
  328       privat e void tra nsmitUpdat eFileToPro d(NdfUpdat eFileVo up dateFile,  UserVo use r) throws  IOExceptio n {
  329         LOG. info("Prep aring to t ransmit "  + updateFi le.getFile Name() + "  file to P rod.");
  330  
  331         ndfU pdateProce ssFile.tra nsmitFileT oProd(upda teFile.get FileName() );
  332  
  333         Cale ndar gc =  GregorianC alendar.ge tInstance( );
  334         upda teFile.set ProdTransm issionDtm( gc.getTime ());
  335         upda teFile.set Status(new  StatusVo( StatusVo.T RANSMITTED _TO_PRODUC TION));
  336  
  337         try  {
  338           se ndEmailNot ification( updateFile .getStatus (), update File.getFi leName(),
  339                ndfUpdat eProcessFi le.getProd uctionFile Size(updat eFile.getF ileName()) );
  340         } ca tch (final  Exception  ex) {
  341           //  The file  was sent,  but the em ail failed . We don't  want to f ail the wh ole proces s for this .
  342           up dateFile.s etComments (
  343                "PPS-N/N DF Update  Production  File Tran smission S uccessful,  but subse quent erro rs encount ered sendi ng "
  344                    + "e mail. Log  a CA ticke t.");
  345           LO G.error("F ile was se nt, but su bsequent e rror occur red sendin g email.",  ex);
  346         }
  347  
  348         upda teNdfUpdat eFile(upda teFile, us er);
  349       }
  350       
  351       /**
  352        * Tra nsmit upda te file to  test - Mo ves the fi le to the  test folde r and send s an email  notificat ion. If th e transmit
  353        * is  successful , this met hod will u pdate the  status of  the passed  {@link Nd fUpdateFil eVo} but w ill not pe rsist the
  354        * upd ate to the  database.
  355        *
  356        * @pa ram update File the u pdate file
  357        * @pa ram user t he user
  358        * @th rows IOExc eption if  file trans mission fa iled
  359        */     
  360       protec ted void t ransmitUpd ateFileToT est(NdfUpd ateFileVo  updateFile , UserVo u ser) throw s IOExcept ion {
  361           LO G.info("Pr eparing to  transmit  " + update File.getFi leName() +  " file to  Test.");
  362  
  363           tr y {
  364                ndfUpdat eProcessFi le.transmi tFileToTes t(updateFi le.getFile Name());
  365                Calendar  gc = Greg orianCalen dar.getIns tance();
  366                updateFi le.setTest Transmissi onDtm(gc.g etTime());
  367                updateFi le.setStat us(new Sta tusVo(Stat usVo.READY _FOR_TESTI NG));
  368                try {
  369                    send EmailNotif ication(up dateFile.g etStatus() , updateFi le.getFile Name(), 
  370                             ndfUpd ateProcess File.getPe ndingFileS ize(update File.getFi leName())) ;
  371                }
  372                catch (E xception e ) {
  373                    //th e file was  sent, but  the email  or status  updates f ailed.
  374                    LOG. error("Fil e was sent , but subs equent err or occurre d sending  email.", e );
  375                    upda teFile.set Comments(
  376                             "PPS-N /NDF Updat e Test Fil e Transmis sion Succe ssful, but  subsequen t errors e ncountered  sending e mail. "
  377                                      + "Log a  CA ticket .");                 
  378                }
  379           } 
  380           ca tch (final  IOExcepti on e) {
  381              // Don't u pdate the  file statu s or anyth ing, just  re-wrap in  a new IOE xception w ith an err or message  at the
  382              // appropr iate level  of detail . We'll re ly on the  calling me thod to up date the f ile status .
  383              throw new  IOExceptio n("Failed  to transmi t file to  test folde r.", e);
  384           } 
  385       }    
  386       
  387       /**
  388        * Tra nsmit upda te file to  reject -  Renames an d moves th e file to  the reject  folder, s ends an em ail notifi cation, 
  389        * and  stores th e NdfUpdat eFileVo wi th an upda ted status .  
  390        *
  391        * @pa ram update File the u pdate file
  392        * @pa ram user t he user
  393        * @th rows IOExc eption if  the file c ould not b e moved
  394        */
  395       privat e void tra nsmitUpdat eFileToRej ect(NdfUpd ateFileVo  updateFile , UserVo u ser) throw s IOExcept ion {
  396           LO G.info("Pr eparing to  rename an d transmit  " + updat eFile.getF ileName()  + " file t o the Reje cted folde r.");
  397           
  398           St ring rejec tedFileNam e = ndfUpd ateProcess File.getRe jectedFile Name(updat eFile.getF ileName()) ;
  399           nd fUpdatePro cessFile.t ransmitFil eToReject( updateFile .getFileNa me(), reje ctedFileNa me);
  400           
  401           // If the cal ler specif ied VISTA_ ERROR, sto re VISTA_E RROR, othe rwise, set  the statu s to REJEC TED_BY_QA 
  402           if  (updateFi le.getStat us().getSt atusId() ! = StatusVo .VISTA_ERR OR)
  403           {
  404                updateFi le.setStat us(new Sta tusVo(Stat usVo.REJEC TED_BY_QA) );
  405           }
  406           
  407           //  we rename  the file  name in th e database  also
  408           up dateFile.s etFileName (rejectedF ileName);
  409           
  410           tr y {
  411              sendEmailN otificatio n(updateFi le.getStat us(), upda teFile.get FileName()
  412                      nd fUpdatePro cessFile.g etRejected FileSize(u pdateFile. getFileNam e()));
  413           }  catch (fin al Excepti on ex) {
  414              // The fil e was sent , but the  email fail ed. We don 't want to  fail the  whole proc ess for th is.
  415              updateFile .setCommen ts(
  416                  "PPS-N /NDF Updat e Reject F ile Rename /Move Succ essful, bu t subseque nt errors  encountere d sending  email. "
  417                      +  "Log a CA  ticket.");
  418              LOG.error( "File was  sent, but  subsequent  error occ urred send ing email. ", ex);
  419           }
  420  
  421           up dateNdfUpd ateFile(up dateFile,  user);       
  422       }        
  423       
  424       /**
  425        * Upd ate the gi ven NdfUpd ateFileVo  in the dat abase.
  426        * 
  427        * @pa ram update dFile
  428        *             Ma nagedItemV o to updat e
  429        * @pa ram user
  430        *             Us erVo updat ing item
  431        */
  432       protec ted void u pdateNdfUp dateFile(N dfUpdateFi leVo updat edFile, Us erVo user)  {
  433           LO G.debug("U pdating ND FUpdateFil e Info.");
  434           Ca lendar gc  = Gregoria nCalendar. getInstanc e();
  435  
  436           up datedFile. setModifie dDate(gc.g etTime());
  437           up datedFile. setStatusM odifiedDtm (gc.getTim e());
  438           up datedFile. setModifie dBy(user.g etUsername ());
  439  
  440           nd fUpdateFil eMgtDomain Capability .update(up datedFile,  user);
  441       }
  442  
  443       /**
  444        * Upd ate the gi ven NdfUpd ateFileVo  in the dat abase, in  a separate  transacti on.  Usefu l for upda ting statu s and comm ents 
  445        * dur ing error  scenarios.
  446        * 
  447        * @pa ram update dFile
  448        *             Ma nagedItemV o to updat e
  449        * @pa ram user
  450        *             Us erVo updat ing item
  451        */   
  452       protec ted void u pdateNdfUp dateFileIn SeparateTx n(final Nd fUpdateFil eVo update dFile, fin al UserVo  user)
  453       {
  454         // U se Transac tionTempla te because  @Transact ional does  not work  when calli ng methods  on 'this' .
  455         fina l Transact ionTemplat e txTempla te = new T ransaction Template(t ransaction Manager);
  456         txTe mplate.set Propagatio nBehavior( Transactio nTemplate. PROPAGATIO N_REQUIRES _NEW);
  457         txTe mplate.exe cute(new T ransaction CallbackWi thoutResul t() {
  458  
  459           @O verride
  460           pr otected vo id doInTra nsactionWi thoutResul t(final Tr ansactionS tatus txSt atus) {
  461              updateNdfU pdateFile( updatedFil e, user);        
  462           }
  463         });
  464       }
  465  
  466       /**
  467        * Ins ert the gi ven NdfUpd ateFileVo  in the dat abase.
  468        *
  469        * @pa ram insert File the i nsert file
  470        * @pa ram user              UserVo upd ating item
  471        * @re turn the n df update  file vo
  472        */
  473       privat e NdfUpdat eFileVo in sertNdfUpd ateFile(Nd fUpdateFil eVo insert File, User Vo user) {
  474           Nd fUpdateFil eVo insert edFile = n ull;
  475           Ca lendar gc  = Gregoria nCalendar. getInstanc e();
  476  
  477           in sertFile.s etModified By(user.ge tUsername( ));
  478           in sertFile.s etModified Date(gc.ge tTime());
  479           in sertFile.s etStatusMo difiedDtm( gc.getTime ());
  480  
  481           in sertedFile  = ndfUpda teFileMgtD omainCapab ility.inse rt(insertF ile,
  482                    user );
  483           re turn inser tedFile;
  484       }
  485  
  486       /**
  487        * Ret rieve all  NdfUpdateF ileVo.
  488        * @re turn List< FileUpdate Vo> update Files
  489        */
  490       @Overr ide
  491       public  List<NdfU pdateFileV o> retriev eFileUpdat es() {
  492           re turn ndfUp dateFileMg tDomainCap ability.re trieveAll( );
  493       }
  494  
  495       /**
  496        * Ret rieve page d NdfUpdat eFileVo.
  497        *
  498        * @pa ram search Criteria
  499        *             th e search c riteria
  500        * @re turn List< FileUpdate Vo> update Files
  501        */
  502       @Overr ide
  503       public  Paginated List<NdfUp dateFileVo > retrieve PagedFileU pdates(
  504                UpdateSe archCriter ia searchC riteria) {
  505           re turn ndfUp dateFileMg tDomainCap ability.re trievePage d(searchCr iteria);
  506       }
  507  
  508       /**
  509        * Ret rieve all  the status  values (E PL_STATUS) .
  510        * @re turn List< StatusVo>  all update  file stat uses
  511        */
  512       @Overr ide
  513       public  List<Stat usVo> retr ieveAllFil eStatuses( ) {
  514           re turn ndfUp dateFileSt atusDomain Capability .retrieveA ll();
  515       }
  516  
  517       /**
  518        * Ret rieve NdfU pdateFileV o ready fo r approval /rejection .
  519        * @re turn List< NdfUpdateF ileVo> pen dingUpdate Files
  520        */
  521       @Overr ide
  522       public  List<NdfU pdateFileV o> retriev ePendingUp date() {
  523           re turn ndfUp dateFileMg tDomainCap ability.re trievePend ing();
  524       }
  525  
  526       @Overr ide
  527       public  NdfUpdate FileVo ret rieveById( Long id) {
  528           re turn ndfUp dateFileMg tDomainCap ability.re trieveById (id);
  529       }
  530  
  531       /**
  532        * Ret rieve a li st of File UpdateVo w ith initia ted status .  Realist ically, th ere should  only ever  be one.
  533        *
  534        * @re turn List< FileUpdate Vo> initia tedUpdateF iles
  535        */
  536       @Overr ide
  537       public  List<NdfU pdateFileV o> retriev eInitiated Update() {
  538           re turn ndfUp dateFileMg tDomainCap ability.re trieveInit iated();
  539       }
  540  
  541       /**
  542        * get s the Tran sactionMan ager for N dfUpdateCa pabilityIm pl.
  543        * 
  544        * @re turn the t ransaction Manager
  545        */
  546       public  PlatformT ransaction Manager ge tTransacti onManager( ) {
  547           re turn trans actionMana ger;
  548       }
  549  
  550       /**
  551        * set s the Tran sactionMan ager for N dfUpdateCa pabilityIm pl.
  552        * 
  553        * @pa ram transa ctionManag er
  554        *             th e transact ionManager  to set
  555        */
  556       @Resou rce
  557       public  void setT ransaction Manager(
  558                Platform Transactio nManager t ransaction Manager) {
  559           th is.transac tionManage r = transa ctionManag er;
  560       }
  561  
  562       /**
  563        * set NdfUpdateP rocessCapa bility in  NdfUpdateP rocessCapa bilityImpl .
  564        *
  565        * @pa ram ndfUpd ateProcess Capability  the new N dfUpdatePr ocessCapab ility
  566        */
  567       public  void setN dfUpdatePr ocessCapab ility(NdfU pdateProce ssCapabili ty ndfUpda teProcessC apability)  {
  568           th is.ndfUpda teProcessC apability  = ndfUpdat eProcessCa pability;
  569       }
  570  
  571       /**
  572        * Get s the NdfU pdateFileM gtDomainCa pability.
  573        *
  574        * @re turn the N dfUpdateFi leMgtDomai nCapabilit y
  575        */
  576       public  NdfUpdate FileMgtDom ainCapabil ity getNdf UpdateFile MgtDomainC apability( ) {
  577           re turn ndfUp dateFileMg tDomainCap ability;
  578       }
  579  
  580       /**
  581        * Set s the NdfU pdateFileM gtDomainCa pability.
  582        *
  583        * @pa ram ndfUpd ateFileMgt DomainCapa bility the  new NdfUp dateFileMg tDomainCap ability
  584        */
  585       public  void setN dfUpdateFi leMgtDomai nCapabilit y(
  586                NdfUpdat eFileMgtDo mainCapabi lity ndfUp dateFileMg tDomainCap ability) {
  587           th is.ndfUpda teFileMgtD omainCapab ility = nd fUpdateFil eMgtDomain Capability ;
  588       }
  589  
  590       /**
  591        * Get  the refer ence to th e NdfUpdat eProcessFi le, which  represents  a physica l file and  its actio ns.
  592        *
  593        * @re turn the N dfUpdatePr ocessFile
  594        */
  595       public  NdfUpdate ProcessFil e getNdfUp dateProces sFile() {
  596           re turn ndfUp dateProces sFile;
  597       }
  598  
  599       /**
  600        * Set  the refer ence to th e NdfUpdat eProcessFi le, which  represents  a physica l file and  its actio ns.
  601        *
  602        * @pa ram ndfUpd ateProcess File the n ew NdfUpda teProcessF ile
  603        */
  604       public  void setN dfUpdatePr ocessFile( NdfUpdateP rocessFile  ndfUpdate ProcessFil e) {
  605           th is.ndfUpda teProcessF ile = ndfU pdateProce ssFile;
  606       }
  607  
  608       /**
  609        * Get s the emai l service.
  610        *
  611        * @re turn the e mailServic e
  612        */
  613       public  EmailServ ice getEma ilService( ) {
  614           re turn email Service;
  615       }
  616  
  617       /**
  618        * Set s the emai l service.
  619        *
  620        * @pa ram emailS ervice the  emailServ ice to set
  621        */
  622       @Resou rce
  623       public  void setE mailServic e(EmailSer vice email Service) {
  624           th is.emailSe rvice = em ailService ;
  625       }
  626  
  627       /**
  628        * Sen ds text em ail notifi cation.
  629        *
  630        * @pa ram status  the statu s
  631        * @pa ram filena me the fil ename
  632        * @pa ram fileSi ze the fil e size
  633        */
  634       privat e void sen dEmailNoti fication(S tatusVo st atus, Stri ng filenam e, String  fileSize)
  635       {
  636           St ring toEma ilIds = nu ll;  
  637           St ring email Subject =  null;
  638           St ring email Message =  null;
  639           
  640                    
  641           if (status.is ReadyForTe sting()){                         
  642                // File  ready for  SQA             
  643                emailSub ject="PPS- N/NDF File  ["+ filen ame +"] CR EATED FOR  QA";
  644                emailMes sage="\n\n The PPS-N/ NDF File "  + filenam e + " (Siz e " + file Size  + "  bytes) "
  645                         + "has bee n CREATED  and TRANSM ITTED to t he test sF TP.  It is  now ready  to "
  646                         + "be DOWN LOADED and  INSTALLED .";
  647                toEmailI ds = envir onment.get RequiredPr operty(FIL E_READY_FO R_TESTING_ TO_EMAIL_P ROPERTY);
  648            }   // File  has been A pproved/Re leased       
  649           el se if(stat us.isTrans mittedToPr oduction() ){
  650                emailSub ject="PPS- N/NDF File  " + filen ame + " RE LEASED NAT IONALLY";
  651                emailMes sage="\n\n The PPS-N/ NDF Update  File " +  filename +  " (Size "  + fileSiz e  + " byt es) "
  652                         + "has bee n National ly Release d to the P roduct sFT P and is a vailable t o be "
  653                         + "DOWNLOA DED and IN STALLED at  the local  sites.";
  654                toEmailI ds = envir onment.get RequiredPr operty(FIL E_APPROVED _TO_EMAIL_ PROPERTY);
  655           }   // File h as been Re jected
  656           el se if (sta tus.isReje ctedByQA() ){
  657                emailSub ject="PPS- N/NDF File  " + filen ame + " RE JECTED";
  658                emailMes sage="\n\n The PPS-N/ NDF Update  Test File  " + filen ame + " (S ize " + fi leSize  +  " bytes) "
  659                         + "has bee n REJECTED  by the PP S-N Manage r.";
  660                toEmailI ds = envir onment.get RequiredPr operty(FIL E_REJECTED _TO_EMAIL_ PROPERTY);
  661           }  else if (  status.isV istaError( )) {
  662                emailSub ject="PPS- N/NDF File  " + filen ame + " AU TO REJECTE D";
  663                emailMes sage="\n\n The PPS-N/ NDF File "  + filenam e + " (Siz e " + file Size + " b ytes) has  been "
  664                         + "AUTO RE JECTED by  QA.";
  665               toEmailId s = enviro nment.getR equiredPro perty(FILE _REJECTED_ TO_EMAIL_P ROPERTY);
  666           }
  667  
  668           Em ail emailB ean = new  Email();
  669  
  670           /*
  671            *  Need to s et to in a nother way  by conver ting to an  array as
  672              * setting  addresses  like  PII                 PII                  Gives
  673            *  error by  javax mail  Address P arser.
  674            * /
  675           St ring[] toE mailId = n ew String[ ] { "" };
  676  
  677           //  if toEmai lIdStr str ing is a c omma separ ated strin g then spl it it.
  678           if  (null !=  toEmailIds  && toEmai lIds.lengt h() > 0) {
  679                toEmailI d = toEmai lIds.split (",");
  680           }
  681  
  682           em ailBean.se tTo(toEmai lId);
  683           em ailBean.se tSubject(e mailSubjec t);
  684           em ailBean.se tEmailMess age(emailM essage);
  685  
  686           em ailService .sendEmail MutlipleTi mes(emailB ean);
  687       }  
  688       
  689       /**
  690        * Cle anup from  a PPSN err or during  file creat ion or sen ding to te st.
  691        *
  692        * @pa ram ndfUpd ateFileVo  the NdfUpd ateFileVo  with {@cod e StatusVo .PPSN_ERRO R} status.  Must not  be null.
  693        * @re turn true,  if succes sful
  694        */   
  695       privat e boolean  cleanupFro mException DuringCrea teAndSendT oTestProce ss(NdfUpda teFileVo n dfUpdateFi leVo) {
  696           tr y{             
  697                //cleanu p the phys ical file  on the loc al drive,  if it exis ts.
  698                NdfUpdat eProcessFi le.deleteF ile(ndfUpd ateFileVo) ;
  699           }
  700           ca tch (Excep tion e1){
  701                LOG.erro r("Seconda ry excepti on encount ered durin g cleanup  after a pr imary exce ption.", e 1);
  702           }         
  703           re turn true;
  704       }  
  705       
  706       /**
  707        * Get s the ndf  update fil e status d omain capa bility.
  708        *
  709        * @re turn the n df update  file statu s domain c apability
  710        */
  711       public  NdfUpdate FileStatus DomainCapa bility get NdfUpdateF ileStatusD omainCapab ility() {
  712           re turn ndfUp dateFileSt atusDomain Capability ;
  713       }
  714  
  715       /**
  716        * Set s the ndf  update fil e status d omain capa bility.
  717        *
  718        * @pa ram ndfUpd ateFileSta tusDomainC apability  the new nd f update f ile status  domain ca pability
  719        */
  720       public  void setN dfUpdateFi leStatusDo mainCapabi lity(
  721                NdfUpdat eFileStatu sDomainCap ability nd fUpdateFil eStatusDom ainCapabil ity) {
  722           th is.ndfUpda teFileStat usDomainCa pability =  ndfUpdate FileStatus DomainCapa bility;
  723       }
  724  
  725  
  726       /**
  727        * Set s the {@li nk Environ ment} inst ance to us e.
  728        * @pa ram enviro nment inst ance to us e
  729        */
  730       @Resou rce
  731       public  void setE nvironment (Environme nt environ ment) {
  732         this .environme nt = envir onment;
  733       }
  734   }