380. EPMO Open Source Coordination Office Redaction File Detail Report

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

380.1 Files compared

# Location File Last Modified
1 OSCIF_CTT_v4_build 1.zip\ISAAC-rest\src\main\java\gov\vha\isaac\rest ApplicationConfig.java Wed May 31 03:58:34 2017 UTC
2 OSCIF_CTT_v4_build 1.zip\ISAAC-rest\src\main\java\gov\vha\isaac\rest ApplicationConfig.java Mon Jul 3 22:01:23 2017 UTC

380.2 Comparison summary

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

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

380.4 Active regular expressions

No regular expressions were active.

380.5 Comparison detail

  1   package go v.vha.isaa c.rest;
  2  
  3   import sta tic gov.vh a.isaac.oc hre.api.co nstants.Co nstants.DA TA_STORE_R OOT_LOCATI ON_PROPERT Y;
  4  
  5   import jav a.io.File;
  6   import jav a.io.IOExc eption;
  7   import jav a.net.URL;
  8   import jav a.nio.file .Files;
  9   import jav a.nio.file .Paths;
  10   import jav a.security .SecureRan dom;
  11   import jav a.time.Loc alDateTime ;
  12   import jav a.time.for mat.DateTi meFormatte r;
  13   import jav a.util.Pro perties;
  14   import jav a.util.con current.at omic.Atomi cInteger;
  15   import jav a.util.str eam.Stream ;
  16  
  17   import jav ax.servlet .ServletCo ntext;
  18   import jav ax.ws.rs.A pplication Path;
  19   import jav ax.ws.rs.c ore.Contex t;
  20   import jav ax.xml.par sers.Docum entBuilder ;
  21   import jav ax.xml.par sers.Docum entBuilder Factory;
  22   import jav ax.xml.xpa th.XPath;
  23   import jav ax.xml.xpa th.XPathCo nstants;
  24   import jav ax.xml.xpa th.XPathFa ctory;
  25  
  26   import org .apache.co mmons.io.F ileUtils;
  27   import org .apache.co mmons.lang 3.StringUt ils;
  28   import org .apache.lo gging.log4 j.LogManag er;
  29   import org .apache.lo gging.log4 j.Logger;
  30   import org .glassfish .jersey.ja ckson.Jack sonFeature ;
  31   import org .glassfish .jersey.se rver.Resou rceConfig;
  32   import org .glassfish .jersey.se rver.spi.C ontainer;
  33   import org .glassfish .jersey.se rver.spi.C ontainerLi fecycleLis tener;
  34   import org .w3c.dom.D ocument;
  35   import org .w3c.dom.N ode;
  36  
  37   import gov .vha.isaac .MetaData;
  38   import gov .vha.isaac .ochre.api .Configura tionServic e;
  39   import gov .vha.isaac .ochre.api .Get;
  40   import gov .vha.isaac .ochre.api .LookupSer vice;
  41   import gov .vha.isaac .ochre.api .RemoteSer viceInfo;
  42   import gov .vha.isaac .ochre.api .component .sememe.Se memeChrono logy;
  43   import gov .vha.isaac .ochre.api .component .sememe.ve rsion.Desc riptionSem eme;
  44   import gov .vha.isaac .ochre.api .util.Arti factUtilit ies;
  45   import gov .vha.isaac .ochre.api .util.DBLo cator;
  46   import gov .vha.isaac .ochre.api .util.Down loadUnzipT ask;
  47   import gov .vha.isaac .ochre.api .util.Work Executors;
  48   import gov .vha.isaac .ochre.met adata.sour ce.IsaacMe tadataAuxi liary;
  49   import gov .vha.isaac .rest.api1 .RestPaths ;
  50   import gov .vha.isaac .rest.api1 .data.Rest SystemInfo ;
  51   import gov .vha.isaac .rest.sess ion.Prisme ServiceUti ls;
  52   import jav afx.beans. property.S impleStrin gProperty;
  53   import jav afx.beans. property.S tringPrope rty;
  54   import jav afx.concur rent.Task;
  55  
  56   @Applicati onPath(Res tPaths.app PathCompon ent)
  57   public cla ss Applica tionConfig  extends R esourceCon fig implem ents Conta inerLifecy cleListene r
  58   {
  59           pr ivate stat ic final A tomicInteg er startup  = new Ato micInteger (1);
  60           pr ivate Logg er log = L ogManager. getLogger( );
  61  
  62           pr ivate stat ic Applica tionConfig  instance_ ;
  63  
  64           pr ivate Stri ngProperty  status_ =  new Simpl eStringPro perty("Not  Started") ;
  65           pr ivate bool ean debugM ode = true ;
  66           pr ivate bool ean shutdo wn = false ;
  67  
  68           pr ivate stat ic String  databaseRo otLocation ;
  69  
  70           // Note - thi s injectio n works fi ne, when d eployed as  a war to  tomcat.  H owever, wh en launche d in the l ocalJettyR unner from  eclipse,
  71           // this remai ns null.
  72           @C ontext
  73           Se rvletConte xt context _;
  74  
  75           pr ivate Stri ng context Path;
  76  
  77           pr ivate stat ic byte[]  secret_;
  78  
  79           pr ivate Rest SystemInfo  systemInf o_;
  80           pr ivate Stri ng warFile Version_;   //read fr om prisme. properties
  81  
  82           pr ivate File  dbLocatio n;
  83           pr ivate stat ic final D ateTimeFor matter fil eDateTimeF ormatter =  DateTimeF ormatter.o fPattern(" yyyyMMddHH mmss");
  84  
  85           // TODO we ne ed to deal  with cont radictions  properly  whenever w e pull thi ngs from a  LatestVer sion objec t.  See co de in Rest ConceptCho nology
  86           // for extrac ting the l atest desc ription.
  87  
  88           pu blic Appli cationConf ig()
  89           {
  90                    //If  we leave  everything  to annota tions, is  picks up t he eclipse  moxy gson  writer, w hich doesn 't handle  abstract c lasses pro perly.
  91                    //Th e goal her e is to fo rce it to  use Jackso n, but it  seems that  registeri ng jackson  disables  scanning,  so also ha ve to re-e nable
  92                    //sc anning.  I t also see ms ot forg et to scan  this clas s... so re gister its elf..
  93                    supe r(new Reso urceConfig ().package s("gov.vha .isaac.res t").regist er(Jackson Feature.cl ass).regis ter(Applic ationConfi g.class));
  94           }
  95  
  96           pu blic stati c Applicat ionConfig  getInstanc e()
  97           {
  98                    retu rn instanc e_;
  99           }
  100  
  101           @O verride
  102           pu blic void  onReload(C ontainer a rg0)
  103           {
  104                    // n oop
  105           }
  106  
  107           @O verride
  108           pu blic void  onShutdown (Container  arg0)
  109           {
  110                    shut down = tru e;
  111                    log. info("Stop ping ISAAC ");
  112                    Look upService. shutdownIs aac();
  113                    log. info("ISAA C stopped" );
  114           }
  115  
  116           pr ivate void  configure Secret()
  117           {
  118                    //Th is hacking  is to pre vent forti fy from fl agging an  external d ata source  path
  119                    File  tempDirNa me = new F ile(string ForFortify (System.ge tProperty( "java.io.t mpdir")));
  120                    File  file = ne w File(tem pDirName,  contextPat h.replaceA ll("/", "_ ") + "-tok enSecret") ;
  121  
  122                    log. debug("Sec ret file f or token e ncoding "  + file.get AbsolutePa th() + " "  + (file.e xists() ?  "exists" :  "does not  exist"));
  123  
  124                    if ( file.exist s())
  125                    {
  126                             try
  127                             {
  128                                      byte[] t emp = File s.readAllB ytes(file. toPath());
  129                                      if (temp .length ==  20)
  130                                      {
  131                                               secret_ =  temp;
  132                                               log.info(" Restored t oken secre t");
  133                                      }
  134                                      else
  135                                      {
  136                                               log.warn(" Unexpected  data in t oken secre t file.  W ill calcul ate a new  token. " +  file.getC anonicalPa th());
  137                                      }
  138                             }
  139                             catch  (IOExcepti on e1)
  140                             {
  141                                      log.warn ("Failed o pening tok en secret  file.  Wil l calculat e a new to ken.", e1) ;
  142                             }
  143                    }
  144                    if ( secret_ ==  null)
  145                    {
  146                             byte[]  temp = ne w byte[20] ;
  147  
  148                             log.in fo("Calcul ating a ne w token");
  149                             //Don' t use Secu reRandom() .getInstan ceStrong()  here, it  hangs on l inux, and  we don't n eed that l evel of se curity.
  150                             //Is s upposed to  be fixed  in Java 9.
  151                             new Se cureRandom ().nextByt es(temp);
  152                             secret _ = temp;
  153                             try
  154                             {
  155                                      Files.wr ite(file.t oPath(), s ecret_);
  156                             }
  157                             catch  (IOExcepti on e)
  158                             {
  159                                      log.warn ("Unexpect ed error s toring tok en secret  file", e);
  160                             }
  161                    }
  162           }
  163  
  164           @O verride
  165           pu blic void  onStartup( Container  container)
  166           {
  167                    log. info("onSt artup call ed");
  168                    if ( instance_  != null)
  169                    {
  170                             throw  new Runtim eException ("Unexpect ed!");
  171                    }
  172                    inst ance_ = th is;
  173  
  174                    //co ntext is n ull when r un from ec lipse with  the local  jetty run ner.
  175                    if ( context_ = = null)
  176                    {
  177                             debugM ode = true ;
  178                             contex tPath = "r est";
  179                    }
  180                    else
  181                    {
  182                             contex tPath = co ntext_.get ContextPat h().replac e("/", "") ;
  183                             debugM ode = (con textPath.c ontains("S NAPSHOT")  ? true : f alse);
  184                    }
  185  
  186                    log. info("Cont ext path o f this dep loyment is  '" + cont extPath +  "' and deb ug mode is  " + debug Mode);
  187  
  188                    conf igureSecre t();
  189  
  190                    issa cInit();
  191           }
  192  
  193           pu blic boole an isIsaac Ready()
  194           {
  195                    retu rn LookupS ervice.isI saacStarte d();
  196           }
  197  
  198           pu blic Strin g getStatu sMessage()
  199           {
  200                    retu rn status_ .get();
  201           }
  202  
  203           pr ivate void  issacInit ()
  204           {
  205                    log. info("Isaa c Init cal led");
  206                    if ( startup.ge tAndDecrem ent() == 1 )
  207                    {
  208                             log.in fo("Execut ing initia l ISAAC In it in back ground thr ead");
  209                             //do s tartup in  this threa d
  210                             Lookup Service.ge t();
  211                             Lookup Service.st artupWorkE xecutors() ;
  212  
  213                             Runnab le r = new  Runnable( )
  214                             {
  215                                      @Overrid e
  216                                      public v oid run()
  217                                      {
  218                                               try
  219                                               {
  220                                                       lo g.info("IS AAC Init t hread begi ns");
  221                                                       
  222                                                       // Place git  config inf o into the  configura tion servi ce
  223                                                       Re moteServic eInfo gitC onfig = ne w RemoteSe rviceInfo( )
  224                                                       {
  225                                                                priv ate String  gitUserna me, url;
  226                                                                priv ate char[]  gitPw;
  227                                                                
  228                                                                {
  229                                                                         Proper ties props  = PrismeS erviceUtil s.getPrism ePropertie s();
  230                                                                         url =   props.get Property(" git_root",  "");
  231                                                                         gitUse rname = pr ops.getPro perty("git _user", "" );
  232                                                                         gitPw  = props.ge tProperty( "git_pwd",  "").toCha rArray();
  233                                                                }
  234                                                                
  235                                                                @Ove rride
  236                                                                publ ic String  getUsernam e()
  237                                                                {
  238                                                                         return  gitUserna me;
  239                                                                }
  240                                                                
  241                                                                @Ove rride
  242                                                                publ ic String  getURL()
  243                                                                {
  244                                                                         return  url;
  245                                                                }
  246                                                                
  247                                                                @Ove rride
  248                                                                publ ic char[]  getPasswor d()
  249                                                                {
  250                                                                         return  gitPw;
  251                                                                }
  252                                                       };
  253                                                       Ge t.configur ationServi ce().setGi tConfigura tion(gitCo nfig);
  254  
  255                                                       da tabaseRoot Location =  stringFor Fortify(Sy stem.getPr operty(DAT A_STORE_RO OT_LOCATIO N_PROPERTY ));
  256                                                       if  (StringUt ils.isBlan k(database RootLocati on) || !Fi les.isDire ctory(Path s.get(data baseRootLo cation)))
  257                                                       {
  258                                                                //if  there isn 't an offi cial syste m property  set, chec k this one  or if the  directory  does not  exist
  259                                                                Stri ng sysProp  = stringF orFortify( System.get Property(" isaacDatab aseLocatio n"));
  260                                                                if ( StringUtil s.isBlank( sysProp) | | !Files.i sDirectory (Paths.get (sysProp)) )
  261                                                                {
  262                                                                         databa seRootLoca tion = sys Prop;
  263                                                                         //No I SAAC defau lt propert y set, nor  the isaac DatabaseLo cation pro perty is s et.  Downl oad a DB.
  264                                                                         log.in fo("Downlo ading a da tabase for  use");
  265                                                                         status _.set("Dow nloading D B");
  266                                                                         try
  267                                                                         {
  268                                                                                  dbLocati on = downl oadDB();
  269                                                                         }
  270                                                                         catch  (Exception  e)
  271                                                                         {
  272                                                                                  status_. unbind();
  273                                                                                  status_. set("Downl oad Failed : " + e);
  274                                                                                  throw ne w RuntimeE xception(e );
  275                                                                         }
  276                                                                }
  277                                                                else
  278                                                                {
  279                                                                         dbLoca tion = new  File(sysP rop);
  280                                                                }
  281  
  282                                                                if ( shutdown)
  283                                                                {
  284                                                                         return ;
  285                                                                }
  286  
  287                                                                File  dataStore Location =  DBLocator .findDBFol der(dbLoca tion);
  288  
  289                                                                if ( !dataStore Location.e xists())
  290                                                                {
  291                                                                         throw  new Runtim eException ("Couldn't  find a da ta store f rom the in put of '"  + dataStor eLocation. getAbsolut eFile().ge tAbsoluteP ath() + "' ");
  292                                                                }
  293                                                                if ( !dataStore Location.i sDirectory ())
  294                                                                {
  295                                                                         throw  new Runtim eException ("The spec ified data  store: '"  + dataSto reLocation .getAbsolu tePath() +  "' is not  a folder" );
  296                                                                }
  297  
  298                                                                //us e the pass ed in JVM  parameter  location
  299                                                                Look upService. getService (Configura tionServic e.class).s etDataStor eFolderPat h(dataStor eLocation. toPath());
  300                                                                Syst em.out.pri ntln("  Se tup AppCon text, data  store loc ation = "  + dataStor eLocation. getAbsolut ePath());
  301                                                       }
  302  
  303                                                       if  (shutdown )
  304                                                       {
  305                                                                retu rn;
  306                                                       }
  307  
  308                                                       tr y {
  309                                                                stat us_.set("S tarting IS AAC");
  310                                                                Look upService. startupIsa ac();
  311                                                                                                                              
  312                                                                //lo g metadata  versions  of codebas e and data base
  313                                                                Stri ng auxilia ryMetadata Version =  getDatabas eIsaacMeta dataVersio n();
  314                                                                                                                              
  315                                                                log. info("Isaa c metadata  versions  - Codebase  {} - Data base {}.",
  316                                                                                  IsaacMet adataAuxil iary.AUXIL IARY_METAD ATA_VERSIO N,
  317                                                                                  auxiliar yMetadataV ersion);
  318                                                                
  319                                                                if ( !IsaacMeta dataAuxili ary.AUXILI ARY_METADA TA_VERSION .equals(au xiliaryMet adataVersi on)) {
  320                                                                         log.wa rn("Codeba se and dat abase are  not of the  same ISAA C Metadata  version!" );
  321                                                                }
  322                                                                         
  323                                                       }
  324                                                       ca tch(Except ion e){
  325                                                                log. error("Sta rtup faile d due to " , e);
  326                                                                //re name direc tory of ex isting dat abase and  restart st artup.
  327                                                                //if  database  exists, re name folde r
  328                                                                if ( dbLocation  != null & & dbLocati on.exists( ))
  329                                                                {
  330                                                                         log.in fo("Databa se deemed  corrupted.   Shutdown  database,  move it t o CORRUPT  directory,  download  new databa se, and re -startup s ystem.");
  331  
  332                                                                         // Shu tdown ISAA C
  333                                                                         log.in fo("Shutti ng down da tabase");
  334                                                                         Lookup Service.sh utdownIsaa c();
  335  
  336                                                                         // Mov e corrupte d database
  337                                                                         log.in fo("Moving  corrupted  database" );
  338                                                                         File c orruptDbLo cation = n ew File(st ringForFor tify(dbLoc ation.getP arent() +  File.separ ator + "CO RRUPT" + F ile.separa tor + Loca lDateTime. now().form at(fileDat eTimeForma tter)));
  339                                                                         log.in fo("DB Loc ation: " +  dbLocatio n.getAbsol utePath()  + " to " +  corruptDb Location.g etAbsolute Path());
  340                                                                         FileUt ils.moveDi rectoryToD irectory(d bLocation,  corruptDb Location,  true);
  341                                                                         FileUt ils.delete Directory( dbLocation );
  342  
  343                                                                         //down load a new  database
  344                                                                         log.in fo("Downlo ading new  database") ;
  345                                                                         dbLoca tion = dow nloadDB();
  346                                                                         File d ataStoreLo cation = D BLocator.f indDBFolde r(dbLocati on);
  347                                                                         Lookup Service.ge tService(C onfigurati onService. class).set DataStoreF olderPath( dataStoreL ocation.to Path());
  348                                                                         log.in fo("Setup  AppContext , data sto re locatio n = " + da taStoreLoc ation.getA bsolutePat h());
  349  
  350                                                                         // Re- start ISAA C
  351                                                                         log.in fo("Re-sta rting ISAA C");
  352                                                                         status _.set("Sta rting ISAA C");
  353                                                                         Lookup Service.st artupIsaac ();
  354  
  355                                                                         log.in fo("Direct ories cont aining the  corrupt d atabase we re renamed .  A new d atabase wa s download ed and ibd f file(s)  loaded");
  356                                                                }
  357                                                       }
  358  
  359                                                       sy stemInfo_  = new Rest SystemInfo ();
  360                                                       lo g.info(sys temInfo_.t oString()) ;
  361  
  362                                                       tr y
  363                                                       {
  364                                                                if ( StringUtil s.isNotBla nk(warFile Version_)  && !warFil eVersion_. equals(sys temInfo_.g etApiImple mentationV ersion()))
  365                                                                {
  366                                                                         log.wa rn("The WA R file ver sion found  in the pr isme.prope rties file  does not  match the  version fr om the pom .xml in th e war file !  Found "
  367                                                                                           + systemIn fo_.getApi Implementa tionVersio n() + " an d " + warF ileVersion _);
  368                                                                }
  369                                                       }
  370                                                       ca tch (Excep tion e)
  371                                                       {
  372                                                                log. error("Une xpected er ror valida ting war f ile versio ns!", e);
  373                                                       }
  374                                                       fi nally
  375                                                       {
  376                                                                warF ileVersion _ = null;   //No long er need th is
  377                                                       }
  378  
  379                                                       st atus_.set( "Ready");
  380                                                       Sy stem.out.p rintln("Do ne setting  up ISAAC" );
  381  
  382                                                       Sy stem.out.p rintln(Str ing.format ("Applicat ion starte d.\nTry ou t %s%s\nSt op the app lication b y pressing  enter.",
  383                                                                         "http: //localhos t:8180/",  RestPaths. conceptVer sionAppPat hComponent  + MetaDat a.CONCRETE _DOMAIN_OP ERATOR.get Nid()));
  384                                               }
  385                                               catch (Exc eption e)
  386                                               {
  387                                                       lo g.error("F ailure sta rting ISAA C", e);
  388                                                       st atus_.unbi nd();
  389                                                       st atus_.set( "FAILED!") ;
  390                                               }
  391                                      }
  392  
  393                             };
  394  
  395                             Lookup Service.ge t().getSer vice(WorkE xecutors.c lass).getE xecutor(). execute(r) ;
  396                    }
  397           }
  398  
  399           pr ivate bool ean valida teExisting Db(File ta rgetDBLoca tion, Stri ng groupId , String a rtifactId,  String ve rsion, Str ing classi fier) {
  400                    //We  need to r ead the po m.xml file  that we f ind inside  of target DBLocation  - and val idate that  each and  every
  401                    //pa rameter pe rfectly ma tches.  If  it doesn' t match, t hen the DB  must be d eleted, an d download ed.
  402                    //If  we don't  do this, w e won't ca tch the ca se where t he isaac-r est server  was undep loyed, the n redeploy ed with a  different  DB configu ration.
  403                    //Th e pom file  we need t o read wil l be at ta rgetDbLoca tion\*.dat a\META-INF \maven\{gr oupId}\{ar tifactId}\ pom.xml
  404                    //We  need to v alidate <g roupId>, < artifactId >, <versio n> and <re sultArtifa ctClassifi er> keepin g in mind  that class ifer
  405                    //is  optional
  406  
  407                    log. info("Chec king speci fied param eters agai nst existi ng db in f older: " +  targetDBL ocation.ge tAbsoluteP ath() + "  - expectin g to find  content fo r " 
  408                                      + "group  {}, artif act {}, ve rsion {} a nd classif ier {}", g roupId, ar tifactId,  version, c lassifier  );
  409  
  410                    stat us_.set("V alidating  existing D B director y");
  411  
  412                    if ( ! targetDB Location.i sDirectory ()) {
  413                             log.wa rn("Valida tion of ex isting DB  failed. In valid DB d irectory:  {}", targe tDBLocatio n.getAbsol uteFile()) ;
  414  
  415                             return  false;
  416                    }
  417  
  418                    File  pomFile =  null;
  419                    for  (File file  : targetD BLocation. listFiles( )) {
  420                             if (fi le.isDirec tory() &&  file.getNa me().endsW ith(".data ")) {
  421                                      pomFile  = new File (stringFor Fortify(fi le.getAbso lutePath()  + File.se paratorCha r + "META- INF" + Fil e.separato rChar + "m aven" + Fi le.separat orChar + g roupId + F ile.separa torChar +  artifactId   + File.s eparatorCh ar + "pom. xml"));
  422                                      if (pomF ile.exists () && pomF ile.isFile ()) {
  423                                               log.info(" Found the  expected e xisting po m file at:  {}" + pom File.getAb soluteFile ());
  424                                               break;
  425                                      }
  426                                      else
  427                                      {
  428                                               pomFile =  null;
  429                                      }
  430                             }
  431                    }
  432                    if ( pomFile ==  null || !  pomFile.i sFile()) {
  433                             log.wa rn("Valida tion of ex isting DB  failed.  "  + (pomFil e == null  ? "The exp ected pom  file was n ot found."  : "The ex pected pom  file loca tion is no t a file") ); 
  434                             return  false;
  435                    }
  436  
  437                    Docu mentBuilde rFactory d omFactory  = Document BuilderFac tory.newIn stance();
  438                    try  {
  439                             domFac tory.setFe ature("htt p://apache .org/xml/f eatures/di sallow-doc type-decl" , true);
  440                             Docume ntBuilder  builder =  domFactory .newDocume ntBuilder( );
  441                             Docume nt dDoc =  builder.pa rse(pomFil e);
  442                             XPath  xPath = XP athFactory .newInstan ce().newXP ath();
  443  
  444                             String  existingD bGroupId =  ((Node) x Path.evalu ate("/proj ect/groupI d", dDoc,  XPathConst ants.NODE) ).getTextC ontent();
  445                             String  existingD bArtifactI d = ((Node ) xPath.ev aluate("/p roject/art ifactId",  dDoc, XPat hConstants .NODE)).ge tTextConte nt();
  446                             String  existingD bVersion =  ((Node) x Path.evalu ate("/proj ect/versio n", dDoc,  XPathConst ants.NODE) ).getTextC ontent();
  447  
  448                             Node e xistingDbC lassifierN ode = (Nod e) xPath.e valuate("/ project/pr operties/r esultArtif actClassif ier", dDoc , XPathCon stants.NOD E);
  449                             String  existingD bClassifie r = existi ngDbClassi fierNode ! = null ? e xistingDbC lassifierN ode.getTex tContent()  : null;
  450  
  451                             if (!  existingDb GroupId.tr im().equal s(groupId. trim())) {
  452                                      log.warn ("Validati on of exis ting DB po m file fai led. Exist ing groupI d {} != {} ", existin gDbGroupId , groupId) ;
  453  
  454                                      return f alse;
  455                             }
  456                             if (!  existingDb ArtifactId .trim().eq uals(artif actId.trim ())) {
  457                                      log.warn ("Validati on of exis ting DB po m file fai led. Exist ing artifa ctId {} !=  {}", exis tingDbArti factId, ar tifactId);
  458                                      return f alse;
  459                             }
  460                             if (!  existingDb Version.tr im().equal s(version. trim())) {
  461                                      log.warn ("Validati on of exis ting DB po m file fai led. Exist ing versio n {} != {} ", existin gDbVersion , version) ;
  462                                      return f alse;
  463                             }
  464  
  465                             if (St ringUtils. isBlank(cl assifier)  && StringU tils.isBla nk(existin gDbClassif ier)) {
  466                                      return t rue;
  467                             } else  if (class ifier == n ull || exi stingDbCla ssifier ==  null) {
  468                                      log.warn ("Validati on of exis ting DB po m file fai led. Exist ing classi fier {} !=  {}", exis tingDbClas sifier, cl assifier);
  469  
  470                                      return f alse;
  471                             } else  if (class ifier.trim ().equals( existingDb Classifier .trim()))  {
  472                                      return t rue;
  473                             } else  {
  474                                      log.warn ("Validati on of exis ting DB po m file fai led. Exist ing classi fier {} !=  {}", exis tingDbClas sifier, cl assifier);
  475                                      return f alse;
  476                             }
  477                    } ca tch (Excep tion e) {
  478                             log.wa rn("Valida tion of ex isting DB  pom file f ailed", e) ;
  479                    }
  480  
  481                    retu rn false;
  482           }
  483  
  484           pr ivate File  downloadD B() throws  Exception
  485           {
  486                    File  tempDbFol der = null ;
  487                    try
  488                    {
  489                             String  baseMaven URL = null ;
  490                             String  mavenUser name = nul l;
  491                             String  mavenPwd  = null;
  492                             String  groupId =  null;
  493                             String  artifactI d = null;
  494                             String  version =  null;
  495                             String  classifie r = null;
  496  
  497                             //Firs t, see if  there is a  propertie s file emb edded in t he war (PR ISME place s this dur ing deploy ment)
  498                             Proper ties props  = PrismeS erviceUtil s.getPrism ePropertie s();
  499                             try 
  500                             {
  501                                      if (prop s.size() = = 0)
  502                                      {
  503                                               log.info(" No prisme. properties  file was  found on t he classpa th");
  504                                      }
  505                                      else
  506                                      {
  507                                               log.info(" Reading da tabase con figuration  from pris me.propert ies file") ;
  508                                               baseMavenU RL = props .getProper ty("nexus_ repository _url");
  509                                               mavenUsern ame = prop s.getPrope rty("nexus _user");
  510                                               mavenPwd =  props.get Property(" nexus_pwd" );
  511                                               groupId =  props.getP roperty("d b_group_id ");
  512                                               artifactId  = props.g etProperty ("db_artif act_id");
  513                                               version =  props.getP roperty("d b_version" );
  514                                               classifier  = props.g etProperty ("db_class ifier");
  515                                               warFileVer sion_ = pr ops.getPro perty("war _version") ;
  516                                      }
  517                             }
  518                             catch  (Exception  e1)
  519                             {
  520                                      log.erro r("Unexpec ted error  trying to  read prope rties from  the prism e.properti es file",  e1);
  521                                      throw ne w RuntimeE xception(e 1);
  522                             }
  523  
  524                             if (St ringUtils. isBlank(ve rsion))
  525                             {
  526                                      log.warn ("Unable t o determin e specifie d DB - usi ng develop er default  options!" );
  527                                      baseMave nURL = "ht tps://DNS                :PORT";
  528                                      mavenUse rname = "s ystem";
  529                                      mavenPwd  = "system ";
  530                                      groupId  = "gov.vha .isaac.db" ;
  531                                      artifact Id = "vhat ";
  532                                      version  = "2016.08 .18-1.11";
  533                                      classifi er = "all" ;
  534                             }
  535  
  536                             log.in fo("Checki ng for exi sting DB") ;
  537  
  538                             File t argetDBLoc ation = ne w File(str ingForFort ify(System .getProper ty("java.i o.tmpdir") ), "ISAAC. " + contex tPath + ". db");
  539  
  540                             if (ta rgetDBLoca tion.isDir ectory())
  541                             {
  542                                      if (vali dateExisti ngDb(targe tDBLocatio n, groupId , artifact Id, versio n, classif ier)) {
  543                                               log.info(" Using exis ting db fo lder: " +  targetDBLo cation.get AbsolutePa th());
  544  
  545                                               return tar getDBLocat ion;
  546                                      } else {
  547                                               log.warn(" Removing e xisting db  because c onsistency  validatio n failed") ;
  548  
  549                                               FileUtils. deleteDire ctory(targ etDBLocati on);
  550                                      }
  551                             }
  552  
  553                             tempDb Folder = F ile.create TempFile(" ISAAC-DATA ", "");
  554                             tempDb Folder.del ete();
  555                             tempDb Folder.mkd irs();
  556                             log.in fo("Downlo ading DB t o " + temp DbFolder.g etAbsolute Path());
  557                             URL cr adle = Art ifactUtili ties.makeF ullURL(bas eMavenURL,  mavenUser name, mave nPwd, grou pId, artif actId, ver sion, clas sifier, "c radle.zip" );
  558                             Task<F ile> task  = new Down loadUnzipT ask(mavenU sername, m avenPwd, c radle, tru e, true, t empDbFolde r);
  559                             status _.bind(tas k.messageP roperty()) ;
  560                             Get.wo rkExecutor s().getExe cutor().su bmit(task) ;
  561                             try
  562                             {
  563                                      task.get ();
  564                             }
  565                             catch  (Interrupt edExceptio n e)
  566                             {
  567                                      task.can cel(true);
  568                                      throw e;
  569                             }
  570                             status _.unbind() ;
  571  
  572                             URL lu cene = Art ifactUtili ties.makeF ullURL(bas eMavenURL,  mavenUser name, mave nPwd, grou pId, artif actId, ver sion, clas sifier, "l ucene.zip" );
  573                             task =  new Downl oadUnzipTa sk(mavenUs ername, ma venPwd, lu cene, true , true, te mpDbFolder );
  574                             status _.bind(tas k.messageP roperty()) ;
  575                             Get.wo rkExecutor s().getExe cutor().su bmit(task) ;
  576                             try
  577                             {
  578                                      task.get ();
  579                             }
  580                             catch  (Interrupt edExceptio n e)
  581                             {
  582                                      task.can cel(true);
  583                                      throw e;
  584                             }
  585                             status _.unbind() ;
  586                             status _.set("Dow nload comp lete");
  587  
  588                             log.de bug("Renam ing " + te mpDbFolder .getCanoni calPath()  + " to " +  targetDBL ocation.ge tCanonical Path());
  589                             if (te mpDbFolder .renameTo( targetDBLo cation))
  590                             {
  591                                      if (vali dateExisti ngDb(targe tDBLocatio n, groupId , artifact Id, versio n, classif ier)) {
  592                                               log.info(" Using exis ting db fo lder: " +  targetDBLo cation.get AbsolutePa th());
  593  
  594                                               return tar getDBLocat ion;
  595                                      } else {
  596                                               log.error( "Failed to  validate  the new da tabase");
  597                                               throw new  RuntimeExc eption("Fa iled to va lidate the  new DB");
  598                                      }
  599                             }
  600                             else
  601                             {
  602                                      log.erro r("Failed  to rename  the databa se");
  603                                      throw ne w RuntimeE xception(" Failed to  rename the  DB folder ");
  604                             }
  605                    }
  606                    catc h (Excepti on e)
  607                    {
  608                             log.er ror("exist ing downlo adDB metho d with err or: " + e) ;
  609                             //clea nup
  610                             try
  611                             {
  612                                      if (temp DbFolder ! = null)
  613                                      {
  614                                               FileUtils. deleteDire ctory(temp DbFolder);
  615                                      }
  616                             }
  617                             catch  (Exception  e1)
  618                             {
  619                                      log.erro r("Unexpec ted error  during cle anup", e1) ;
  620                             }
  621                             throw  e;
  622                    }
  623           }
  624  
  625           /* *
  626            *  @return t rue if thi s is a deb ug deploym ent (in ec lipse, or  context co ntains SNA PSHOT)
  627            * /
  628           pu blic boole an isDebug Deploy()
  629           {
  630                    retu rn debugMo de;
  631           }
  632  
  633           /* *
  634            *  @return S tring cont ext path,  which is a  hard-code d value if  in eclips e Jetty
  635            * /
  636           pu blic Strin g getConte xtPath() {
  637                    retu rn context Path;
  638           }
  639  
  640           /* *
  641            *  @return
  642            * /
  643           pu blic stati c byte[] g etSecret()
  644           {
  645                    retu rn secret_ ;
  646           }
  647  
  648           pu blic RestS ystemInfo  getSystemI nfo()
  649           {
  650                    retu rn systemI nfo_;
  651           }
  652  
  653           pu blic Servl etContext  getServlet Context()
  654           {
  655                    retu rn context _;
  656           }
  657  
  658           pr ivate Stri ng stringF orFortify( String con vertString )
  659           {
  660                    Stri ngBuilder  temp = new  StringBui lder();
  661                    if ( convertStr ing != nul l) {
  662                             conver tString.ch ars().forE ach(c -> t emp.append ((char)c)) ;
  663                    }
  664                    retu rn temp.to String();
  665           }
  666           
  667           pr ivate Stri ng getData baseIsaacM etadataVer sion() {
  668                    Stri ng version  = "";
  669                    Stre am<SememeC hronology< ? extends  Descriptio nSememe<?> >> ds = Ge t.sememeSe rvice()
  670                                      .getDesc riptionsFo rComponent (MetaData. ISAAC_META DATA.getNi d());
  671                    for  (Object o  : ds.toArr ay()) {
  672                             Sememe Chronology <? extends  Descripti onSememe<? >> x = (Se memeChrono logy<? ext ends Descr iptionSeme me<?>>)o;
  673                             for(De scriptionS ememe d :  x.getVersi onList())  {
  674                                      if (d.ge tText() !=  null && " version".e qualsIgnor eCase(d.ge tText()) & & StringUt ils.isNotE mpty(versi on));
  675                                      {
  676                                               version =  d.getText( ).substrin g(d.getTex t().lastIn dexOf(":") +1);
  677                                      }
  678                             }
  679                             if (St ringUtils. isNotEmpty (version))  break;
  680                    };
  681                    retu rn version ;
  682           }
  683   }