Coverage Report - org.owasp.dependencycheck.data.update.DatabaseUpdater
 
Classes in this File Line Coverage Branch Coverage Complexity
DatabaseUpdater
33%
90/267
30%
33/110
10
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 3  
  *
 4  
  * Dependency-check-core is free software: you can redistribute it and/or modify it
 5  
  * under the terms of the GNU General Public License as published by the Free
 6  
  * Software Foundation, either version 3 of the License, or (at your option) any
 7  
  * later version.
 8  
  *
 9  
  * Dependency-check-core is distributed in the hope that it will be useful, but
 10  
  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  
  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 12  
  * details.
 13  
  *
 14  
  * You should have received a copy of the GNU General Public License along with
 15  
  * dependency-check-core. If not, see http://www.gnu.org/licenses/.
 16  
  *
 17  
  * Copyright (c) 2012 Jeremy Long. All Rights Reserved.
 18  
  */
 19  
 package org.owasp.dependencycheck.data.update;
 20  
 
 21  
 import org.owasp.dependencycheck.data.nvdcve.NvdCve12Handler;
 22  
 import org.owasp.dependencycheck.data.nvdcve.NvdCve20Handler;
 23  
 import org.owasp.dependencycheck.data.nvdcve.InvalidDataException;
 24  
 import java.io.File;
 25  
 import java.io.FileNotFoundException;
 26  
 import java.io.IOException;
 27  
 import javax.xml.parsers.ParserConfigurationException;
 28  
 import org.xml.sax.SAXException;
 29  
 import org.owasp.dependencycheck.data.CachedWebDataSource;
 30  
 import java.net.MalformedURLException;
 31  
 import java.net.URISyntaxException;
 32  
 import java.net.URL;
 33  
 import java.sql.SQLException;
 34  
 import java.util.Calendar;
 35  
 import java.util.Date;
 36  
 import java.util.List;
 37  
 import java.util.Map;
 38  
 import java.util.TreeMap;
 39  
 import java.util.logging.Level;
 40  
 import java.util.logging.Logger;
 41  
 import javax.xml.parsers.SAXParser;
 42  
 import javax.xml.parsers.SAXParserFactory;
 43  
 import org.owasp.dependencycheck.data.UpdateException;
 44  
 import org.owasp.dependencycheck.data.cpe.CpeIndexWriter;
 45  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 46  
 import org.owasp.dependencycheck.dependency.VulnerableSoftware;
 47  
 import org.owasp.dependencycheck.utils.DownloadFailedException;
 48  
 import org.owasp.dependencycheck.utils.Downloader;
 49  
 import org.owasp.dependencycheck.utils.FileUtils;
 50  
 import org.owasp.dependencycheck.utils.Settings;
 51  
 import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
 52  
 import org.owasp.dependencycheck.utils.InvalidSettingException;
 53  
 import static org.owasp.dependencycheck.data.update.DataStoreMetaInfo.BATCH;
 54  
 import static org.owasp.dependencycheck.data.update.DataStoreMetaInfo.MODIFIED;
 55  
 
 56  
 /**
 57  
  * Class responsible for updating the CPE and NVDCVE data stores.
 58  
  *
 59  
  * @author Jeremy Long (jeremy.long@owasp.org)
 60  
  */
 61  2
 public class DatabaseUpdater implements CachedWebDataSource {
 62  
 
 63  
     /**
 64  
      * Utility to read and write meta-data about the data.
 65  
      */
 66  2
     private DataStoreMetaInfo properties = null;
 67  
     /**
 68  
      * Reference to the Cve Database.
 69  
      */
 70  2
     private CveDB cveDB = null;
 71  
     /**
 72  
      * Reference to the Cpe Index.
 73  
      */
 74  2
     private CpeIndexWriter cpeIndex = null;
 75  
     /**
 76  
      * A flag indicating whether or not the batch update should be performed.
 77  
      */
 78  
     private boolean doBatchUpdate;
 79  
 
 80  
     /**
 81  
      * Get the value of doBatchUpdate
 82  
      *
 83  
      * @return the value of doBatchUpdate
 84  
      */
 85  
     protected boolean isDoBatchUpdate() {
 86  2
         return doBatchUpdate;
 87  
     }
 88  
 
 89  
     /**
 90  
      * Set the value of doBatchUpdate
 91  
      *
 92  
      * @param doBatchUpdate new value of doBatchUpdate
 93  
      */
 94  
     protected void setDoBatchUpdate(boolean doBatchUpdate) {
 95  2
         this.doBatchUpdate = doBatchUpdate;
 96  2
     }
 97  
 
 98  
     /**
 99  
      * <p>Downloads the latest NVD CVE XML file from the web and imports it into
 100  
      * the current CVE Database.</p>
 101  
      *
 102  
      * @throws UpdateException is thrown if there is an error updating the
 103  
      * database
 104  
      */
 105  
     @Override
 106  
     public void update() throws UpdateException {
 107  2
         doBatchUpdate = false;
 108  2
         properties = new DataStoreMetaInfo();
 109  
         try {
 110  2
             final Map<String, NvdCveInfo> update = updateNeeded();
 111  2
             int maxUpdates = 0;
 112  2
             for (NvdCveInfo cve : update.values()) {
 113  2
                 if (cve.getNeedsUpdate()) {
 114  0
                     maxUpdates += 1;
 115  
                 }
 116  
             }
 117  2
             if (maxUpdates > 3 && !properties.isBatchUpdateMode()) {
 118  0
                 Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.INFO,
 119  
                         "NVD CVE requires several updates; this could take a couple of minutes.");
 120  
             }
 121  2
             if (maxUpdates > 0 && !isDoBatchUpdate()) {
 122  0
                 openDataStores();
 123  
             }
 124  
 
 125  2
             if (properties.isBatchUpdateMode() && isDoBatchUpdate()) {
 126  
                 try {
 127  2
                     performBatchUpdate();
 128  2
                     openDataStores();
 129  0
                 } catch (IOException ex) {
 130  0
                     throw new UpdateException("Unable to perform batch update", ex);
 131  2
                 }
 132  
             }
 133  
 
 134  2
             int count = 0;
 135  2
             for (NvdCveInfo cve : update.values()) {
 136  2
                 if (cve.getNeedsUpdate()) {
 137  0
                     count += 1;
 138  0
                     Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.INFO,
 139  
                             "Updating NVD CVE ({0} of {1})", new Object[]{count, maxUpdates});
 140  0
                     URL url = new URL(cve.getUrl());
 141  0
                     File outputPath = null;
 142  0
                     File outputPath12 = null;
 143  
                     try {
 144  0
                         Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.INFO,
 145  
                                 "Downloading {0}", cve.getUrl());
 146  0
                         outputPath = File.createTempFile("cve" + cve.getId() + "_", ".xml");
 147  0
                         Downloader.fetchFile(url, outputPath);
 148  
 
 149  0
                         url = new URL(cve.getOldSchemaVersionUrl());
 150  0
                         outputPath12 = File.createTempFile("cve_1_2_" + cve.getId() + "_", ".xml");
 151  0
                         Downloader.fetchFile(url, outputPath12);
 152  
 
 153  0
                         Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.INFO,
 154  
                                 "Processing {0}", cve.getUrl());
 155  
 
 156  0
                         importXML(outputPath, outputPath12);
 157  
 
 158  0
                         cveDB.commit();
 159  0
                         cpeIndex.commit();
 160  
 
 161  0
                         properties.save(cve);
 162  
 
 163  0
                         Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.INFO,
 164  
                                 "Completed update {0} of {1}", new Object[]{count, maxUpdates});
 165  0
                     } catch (FileNotFoundException ex) {
 166  0
                         throw new UpdateException(ex);
 167  0
                     } catch (ParserConfigurationException ex) {
 168  0
                         throw new UpdateException(ex);
 169  0
                     } catch (SAXException ex) {
 170  0
                         throw new UpdateException(ex);
 171  0
                     } catch (IOException ex) {
 172  0
                         throw new UpdateException(ex);
 173  0
                     } catch (SQLException ex) {
 174  0
                         throw new UpdateException(ex);
 175  0
                     } catch (DatabaseException ex) {
 176  0
                         throw new UpdateException(ex);
 177  0
                     } catch (ClassNotFoundException ex) {
 178  0
                         throw new UpdateException(ex);
 179  
                     } finally {
 180  0
                         boolean deleted = false;
 181  
                         try {
 182  0
                             if (outputPath != null && outputPath.exists()) {
 183  0
                                 deleted = outputPath.delete();
 184  
                             }
 185  
                         } finally {
 186  0
                             if (outputPath != null && (outputPath.exists() || !deleted)) {
 187  0
                                 outputPath.deleteOnExit();
 188  
                             }
 189  
                         }
 190  
                         try {
 191  0
                             deleted = false;
 192  0
                             if (outputPath12 != null && outputPath12.exists()) {
 193  0
                                 deleted = outputPath12.delete();
 194  
                             }
 195  
                         } finally {
 196  0
                             if (outputPath12 != null && (outputPath12.exists() || !deleted)) {
 197  0
                                 outputPath12.deleteOnExit();
 198  
                             }
 199  
                         }
 200  0
                     }
 201  2
                 }
 202  
             }
 203  2
             if (maxUpdates >= 1) { //ensure the modified file date gets written
 204  0
                 properties.save(update.get(MODIFIED));
 205  0
                 cveDB.cleanupDatabase();
 206  
             }
 207  2
             if (update.get(BATCH) != null) {
 208  1
                 properties.save(update.get(BATCH));
 209  
             }
 210  0
         } catch (MalformedURLException ex) {
 211  0
             throw new UpdateException(ex);
 212  0
         } catch (DownloadFailedException ex) {
 213  0
             throw new UpdateException(ex);
 214  
         } finally {
 215  2
             closeDataStores();
 216  2
         }
 217  2
     }
 218  
 
 219  
     /**
 220  
      * Imports the NVD CVE XML File into the Lucene Index.
 221  
      *
 222  
      * @param file the file containing the NVD CVE XML
 223  
      * @param oldVersion contains the file containing the NVD CVE XML 1.2
 224  
      * @throws ParserConfigurationException is thrown if there is a parser
 225  
      * configuration exception
 226  
      * @throws SAXException is thrown if there is a SAXException
 227  
      * @throws IOException is thrown if there is a IO Exception
 228  
      * @throws SQLException is thrown if there is a SQL exception
 229  
      * @throws DatabaseException is thrown if there is a database exception
 230  
      * @throws ClassNotFoundException thrown if the h2 database driver cannot be
 231  
      * loaded
 232  
      */
 233  
     private void importXML(File file, File oldVersion)
 234  
             throws ParserConfigurationException, SAXException, IOException, SQLException, DatabaseException, ClassNotFoundException {
 235  
 
 236  0
         final SAXParserFactory factory = SAXParserFactory.newInstance();
 237  0
         final SAXParser saxParser = factory.newSAXParser();
 238  
 
 239  0
         final NvdCve12Handler cve12Handler = new NvdCve12Handler();
 240  0
         saxParser.parse(oldVersion, cve12Handler);
 241  0
         final Map<String, List<VulnerableSoftware>> prevVersionVulnMap = cve12Handler.getVulnerabilities();
 242  
 
 243  0
         final NvdCve20Handler cve20Handler = new NvdCve20Handler();
 244  0
         cve20Handler.setCveDB(cveDB);
 245  0
         cve20Handler.setPrevVersionVulnMap(prevVersionVulnMap);
 246  0
         cve20Handler.setCpeIndex(cpeIndex);
 247  0
         saxParser.parse(file, cve20Handler);
 248  0
     }
 249  
 
 250  
     /**
 251  
      * Deletes the existing data directories.
 252  
      *
 253  
      * @throws IOException thrown if the directory cannot be deleted
 254  
      */
 255  
     protected void deleteExistingData() throws IOException {
 256  4
         File data = Settings.getFile(Settings.KEYS.CVE_DATA_DIRECTORY);
 257  4
         if (data.exists()) {
 258  2
             FileUtils.delete(data);
 259  
         }
 260  4
         data = Settings.getFile(Settings.KEYS.CPE_DATA_DIRECTORY);
 261  4
         if (data.exists()) {
 262  2
             FileUtils.delete(data);
 263  
         }
 264  4
         data = DataStoreMetaInfo.getPropertiesFile();
 265  4
         if (data.exists()) {
 266  2
             FileUtils.delete(data);
 267  
         }
 268  4
     }
 269  
 
 270  
     /**
 271  
      * Performs the batch update based on the configured batch update URL.
 272  
      *
 273  
      * @throws UpdateException thrown if there is an exception during the update
 274  
      * process
 275  
      */
 276  
     private void performBatchUpdate() throws UpdateException {
 277  2
         if (properties.isBatchUpdateMode() && doBatchUpdate) {
 278  2
             final String batchSrc = Settings.getString(Settings.KEYS.BATCH_UPDATE_URL);
 279  2
             File tmp = null;
 280  
             try {
 281  2
                 deleteExistingData();
 282  2
                 final File dataDirectory = CveDB.getDataDirectory().getParentFile();
 283  2
                 final URL batchUrl = new URL(batchSrc);
 284  2
                 if ("file".equals(batchUrl.getProtocol())) {
 285  
                     try {
 286  2
                         tmp = new File(batchUrl.toURI());
 287  0
                     } catch (URISyntaxException ex) {
 288  0
                         final String msg = String.format("Invalid batch update URI: %s", batchSrc);
 289  0
                         throw new UpdateException(msg, ex);
 290  2
                     }
 291  0
                 } else if ("http".equals(batchUrl.getProtocol())
 292  
                         || "https".equals(batchUrl.getProtocol())) {
 293  0
                     tmp = File.createTempFile("batch_", ".zip");
 294  0
                     Downloader.fetchFile(batchUrl, tmp);
 295  
                 }
 296  
                 //TODO add FTP?
 297  2
                 FileUtils.extractFiles(tmp, dataDirectory);
 298  
 
 299  0
             } catch (IOException ex) {
 300  0
                 final String msg = String.format("IO Exception Occured performing batch update using: %s", batchSrc);
 301  0
                 throw new UpdateException(msg, ex);
 302  
             } finally {
 303  2
                 if (tmp != null && !tmp.delete()) {
 304  0
                     tmp.deleteOnExit();
 305  
                 }
 306  
             }
 307  
         }
 308  2
     }
 309  
 
 310  
     /**
 311  
      * Closes the CVE and CPE data stores.
 312  
      */
 313  
     private void closeDataStores() {
 314  2
         if (cveDB != null) {
 315  
             try {
 316  2
                 cveDB.close();
 317  0
             } catch (Exception ignore) {
 318  0
                 Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINEST, "Error closing the cveDB", ignore);
 319  2
             }
 320  
         }
 321  2
         if (cpeIndex != null) {
 322  
             try {
 323  2
                 cpeIndex.close();
 324  0
             } catch (Exception ignore) {
 325  0
                 Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINEST, "Error closing the cpeIndex", ignore);
 326  2
             }
 327  
         }
 328  2
     }
 329  
 
 330  
     /**
 331  
      * Opens the CVE and CPE data stores.
 332  
      *
 333  
      * @throws UpdateException thrown if a data store cannot be opened
 334  
      */
 335  
     private void openDataStores() throws UpdateException {
 336  
         //open the cve and cpe data stores
 337  
         try {
 338  2
             cveDB = new CveDB();
 339  2
             cveDB.open();
 340  2
             cpeIndex = new CpeIndexWriter();
 341  2
             cpeIndex.open();
 342  0
         } catch (IOException ex) {
 343  0
             closeDataStores();
 344  0
             Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINE, "IO Error opening databases", ex);
 345  0
             throw new UpdateException("Error updating the CPE/CVE data, please see the log file for more details.");
 346  0
         } catch (SQLException ex) {
 347  0
             closeDataStores();
 348  0
             Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINE, "SQL Exception opening databases", ex);
 349  0
             throw new UpdateException("Error updating the CPE/CVE data, please see the log file for more details.");
 350  0
         } catch (DatabaseException ex) {
 351  0
             closeDataStores();
 352  0
             Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINE, "Database Exception opening databases", ex);
 353  0
             throw new UpdateException("Error updating the CPE/CVE data, please see the log file for more details.");
 354  0
         } catch (ClassNotFoundException ex) {
 355  0
             closeDataStores();
 356  0
             Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINE, "Class not found exception opening databases", ex);
 357  0
             throw new UpdateException("Error updating the CPE/CVE data, please see the log file for more details.");
 358  2
         }
 359  2
     }
 360  
 
 361  
     /**
 362  
      * Determines if the index needs to be updated. This is done by fetching the
 363  
      * NVD CVE meta data and checking the last update date. If the data needs to
 364  
      * be refreshed this method will return the NvdCveUrl for the files that
 365  
      * need to be updated.
 366  
      *
 367  
      * @return the NvdCveUrl of the files that need to be updated.
 368  
      * @throws MalformedURLException is thrown if the URL for the NVD CVE Meta
 369  
      * data is incorrect.
 370  
      * @throws DownloadFailedException is thrown if there is an error.
 371  
      * downloading the NVD CVE download data file.
 372  
      * @throws UpdateException Is thrown if there is an issue with the last
 373  
      * updated properties file.
 374  
      */
 375  
     private Map<String, NvdCveInfo> updateNeeded() throws MalformedURLException, DownloadFailedException, UpdateException {
 376  
 
 377  
         Map<String, NvdCveInfo> currentlyPublished;
 378  
         try {
 379  2
             currentlyPublished = retrieveCurrentTimestampsFromWeb();
 380  0
         } catch (InvalidDataException ex) {
 381  0
             final String msg = "Unable to retrieve valid timestamp from nvd cve downloads page";
 382  0
             Logger.getLogger(DataStoreMetaInfo.class.getName()).log(Level.FINE, msg, ex);
 383  0
             throw new DownloadFailedException(msg, ex);
 384  0
         } catch (InvalidSettingException ex) {
 385  0
             Logger.getLogger(DataStoreMetaInfo.class.getName()).log(Level.FINE, "Invalid setting found when retrieving timestamps", ex);
 386  0
             throw new DownloadFailedException("Invalid settings", ex);
 387  2
         }
 388  
 
 389  2
         if (currentlyPublished == null) {
 390  0
             throw new DownloadFailedException("Unable to retrieve the timestamps of the currently published NVD CVE data");
 391  
         }
 392  
 
 393  
 //        final File cpeDataDirectory;
 394  
 //        try {
 395  
 //            cpeDataDirectory = CveDB.getDataDirectory();
 396  
 //        } catch (IOException ex) {
 397  
 //            String msg;
 398  
 //            try {
 399  
 //                msg = String.format("Unable to create the CVE Data Directory '%s'",
 400  
 //                        Settings.getFile(Settings.KEYS.CVE_DATA_DIRECTORY).getCanonicalPath());
 401  
 //            } catch (IOException ex1) {
 402  
 //                msg = String.format("Unable to create the CVE Data Directory, this is likely a configuration issue: '%s%s%s'",
 403  
 //                        Settings.getString(Settings.KEYS.DATA_DIRECTORY, ""),
 404  
 //                        File.separator,
 405  
 //                        Settings.getString(Settings.KEYS.CVE_DATA_DIRECTORY, ""));
 406  
 //            }
 407  
 //            throw new UpdateException(msg, ex);
 408  
 //        }
 409  
 
 410  2
         if (!properties.isEmpty()) {
 411  
             try {
 412  0
                 boolean deleteAndRecreate = false;
 413  
                 float version;
 414  
 
 415  0
                 if (properties.getProperty("version") == null) {
 416  0
                     deleteAndRecreate = true;
 417  
                 } else {
 418  
                     try {
 419  0
                         version = Float.parseFloat(properties.getProperty("version"));
 420  0
                         final float currentVersion = Float.parseFloat(CveDB.DB_SCHEMA_VERSION);
 421  0
                         if (currentVersion > version) {
 422  0
                             deleteAndRecreate = true;
 423  
                         }
 424  0
                     } catch (NumberFormatException ex) {
 425  0
                         deleteAndRecreate = true;
 426  0
                     }
 427  
                 }
 428  
 
 429  0
                 final NvdCveInfo batchInfo = currentlyPublished.get(BATCH);
 430  0
                 if (properties.isBatchUpdateMode() && batchInfo != null) {
 431  0
                     final long lastUpdated = Long.parseLong(properties.getProperty(DataStoreMetaInfo.BATCH, "0"));
 432  0
                     if (lastUpdated != batchInfo.getTimestamp()) {
 433  0
                         deleteAndRecreate = true;
 434  
                     }
 435  
                 }
 436  
 
 437  0
                 if (deleteAndRecreate) {
 438  0
                     setDoBatchUpdate(properties.isBatchUpdateMode());
 439  
                     try {
 440  0
                         deleteExistingData();
 441  0
                     } catch (IOException ex) {
 442  0
                         final String msg = "Unable to delete existing data";
 443  0
                         Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.WARNING, msg);
 444  0
                         Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINE, null, ex);
 445  0
                     }
 446  0
                     return currentlyPublished;
 447  
                 }
 448  
 
 449  0
                 final long lastUpdated = Long.parseLong(properties.getProperty(DataStoreMetaInfo.LAST_UPDATED, "0"));
 450  0
                 final Date now = new Date();
 451  0
                 final int days = Settings.getInt(Settings.KEYS.CVE_MODIFIED_VALID_FOR_DAYS, 7);
 452  0
                 final int start = Settings.getInt(Settings.KEYS.CVE_START_YEAR, 2002);
 453  0
                 final int end = Calendar.getInstance().get(Calendar.YEAR);
 454  0
                 if (lastUpdated == currentlyPublished.get(MODIFIED).getTimestamp()) {
 455  0
                     currentlyPublished.clear(); //we don't need to update anything.
 456  0
                     setDoBatchUpdate(properties.isBatchUpdateMode());
 457  0
                 } else if (withinRange(lastUpdated, now.getTime(), days)) {
 458  0
                     currentlyPublished.get(MODIFIED).setNeedsUpdate(true);
 459  0
                     if (properties.isBatchUpdateMode()) {
 460  0
                         setDoBatchUpdate(false);
 461  
                     } else {
 462  0
                         for (int i = start; i <= end; i++) {
 463  0
                             currentlyPublished.get(String.valueOf(i)).setNeedsUpdate(false);
 464  
                         }
 465  
                     }
 466  0
                 } else if (properties.isBatchUpdateMode()) {
 467  0
                     currentlyPublished.get(MODIFIED).setNeedsUpdate(true);
 468  0
                     setDoBatchUpdate(true);
 469  
                 } else { //we figure out which of the several XML files need to be downloaded.
 470  0
                     currentlyPublished.get(MODIFIED).setNeedsUpdate(false);
 471  0
                     for (int i = start; i <= end; i++) {
 472  0
                         final NvdCveInfo cve = currentlyPublished.get(String.valueOf(i));
 473  0
                         long currentTimestamp = 0;
 474  
                         try {
 475  0
                             currentTimestamp = Long.parseLong(properties.getProperty(DataStoreMetaInfo.LAST_UPDATED_BASE + String.valueOf(i), "0"));
 476  0
                         } catch (NumberFormatException ex) {
 477  0
                             final String msg = String.format("Error parsing '%s' '%s' from nvdcve.lastupdated",
 478  
                                     DataStoreMetaInfo.LAST_UPDATED_BASE, String.valueOf(i));
 479  0
                             Logger.getLogger(DataStoreMetaInfo.class.getName()).log(Level.FINE, msg, ex);
 480  0
                         }
 481  0
                         if (currentTimestamp == cve.getTimestamp()) {
 482  0
                             cve.setNeedsUpdate(false); //they default to true.
 483  
                         }
 484  
                     }
 485  
                 }
 486  0
             } catch (NumberFormatException ex) {
 487  0
                 final String msg = "An invalid schema version or timestamp exists in the data.properties file.";
 488  0
                 Logger.getLogger(DataStoreMetaInfo.class.getName()).log(Level.WARNING, msg);
 489  0
                 Logger.getLogger(DataStoreMetaInfo.class.getName()).log(Level.FINE, null, ex);
 490  0
                 setDoBatchUpdate(properties.isBatchUpdateMode());
 491  0
             }
 492  
         } else {
 493  2
             setDoBatchUpdate(properties.isBatchUpdateMode());
 494  
         }
 495  2
         return currentlyPublished;
 496  
     }
 497  
 
 498  
     /**
 499  
      * Determines if the epoch date is within the range specified of the
 500  
      * compareTo epoch time. This takes the (compareTo-date)/1000/60/60/24 to
 501  
      * get the number of days. If the calculated days is less then the range the
 502  
      * date is considered valid.
 503  
      *
 504  
      * @param date the date to be checked.
 505  
      * @param compareTo the date to compare to.
 506  
      * @param range the range in days to be considered valid.
 507  
      * @return whether or not the date is within the range.
 508  
      */
 509  
     private boolean withinRange(long date, long compareTo, int range) {
 510  0
         final double differenceInDays = (compareTo - date) / 1000.0 / 60.0 / 60.0 / 24.0;
 511  0
         return differenceInDays < range;
 512  
     }
 513  
 
 514  
     /**
 515  
      * Retrieves the timestamps from the NVD CVE meta data file.
 516  
      *
 517  
      * @return the timestamp from the currently published nvdcve downloads page
 518  
      * @throws MalformedURLException thrown if the URL for the NVD CCE Meta data
 519  
      * is incorrect.
 520  
      * @throws DownloadFailedException thrown if there is an error downloading
 521  
      * the nvd cve meta data file
 522  
      * @throws InvalidDataException thrown if there is an exception parsing the
 523  
      * timestamps
 524  
      * @throws InvalidSettingException thrown if the settings are invalid
 525  
      */
 526  
     private Map<String, NvdCveInfo> retrieveCurrentTimestampsFromWeb()
 527  
             throws MalformedURLException, DownloadFailedException, InvalidDataException, InvalidSettingException {
 528  
 
 529  2
         final Map<String, NvdCveInfo> map = new TreeMap<String, NvdCveInfo>();
 530  2
         String retrieveUrl = Settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL);
 531  2
         if (retrieveUrl == null && properties.isBatchUpdateMode()) {
 532  1
             final NvdCveInfo item = new NvdCveInfo();
 533  1
             retrieveUrl = Settings.getString(Settings.KEYS.BATCH_UPDATE_URL);
 534  1
             if (retrieveUrl == null) {
 535  0
                 final String msg = "Invalid configuration - neither the modified or batch update URLs are specified in the configuration.";
 536  0
                 Logger.getLogger(DataStoreMetaInfo.class.getName()).log(Level.SEVERE, msg);
 537  0
                 throw new InvalidSettingException(msg);
 538  
             }
 539  1
             item.setTimestamp(Downloader.getLastModified(new URL(retrieveUrl)));
 540  1
             item.setId(BATCH);
 541  1
             item.setNeedsUpdate(false);
 542  1
             map.put(BATCH, item);
 543  1
         } else {
 544  1
             NvdCveInfo item = new NvdCveInfo();
 545  1
             item.setNeedsUpdate(false); //the others default to true, to make life easier later this should default to false.
 546  1
             item.setId(MODIFIED);
 547  1
             item.setUrl(retrieveUrl);
 548  1
             item.setOldSchemaVersionUrl(Settings.getString(Settings.KEYS.CVE_MODIFIED_12_URL));
 549  
 
 550  1
             item.setTimestamp(Downloader.getLastModified(new URL(retrieveUrl)));
 551  1
             map.put(MODIFIED, item);
 552  
 
 553  
             //only add these urls if we are not in batch mode
 554  1
             if (!properties.isBatchUpdateMode()) {
 555  0
                 final int start = Settings.getInt(Settings.KEYS.CVE_START_YEAR);
 556  0
                 final int end = Calendar.getInstance().get(Calendar.YEAR);
 557  0
                 final String baseUrl20 = Settings.getString(Settings.KEYS.CVE_SCHEMA_2_0);
 558  0
                 final String baseUrl12 = Settings.getString(Settings.KEYS.CVE_SCHEMA_1_2);
 559  0
                 for (int i = start; i <= end; i++) {
 560  0
                     retrieveUrl = String.format(baseUrl20, i);
 561  0
                     item = new NvdCveInfo();
 562  0
                     item.setId(Integer.toString(i));
 563  0
                     item.setUrl(retrieveUrl);
 564  0
                     item.setOldSchemaVersionUrl(String.format(baseUrl12, i));
 565  0
                     item.setTimestamp(Downloader.getLastModified(new URL(retrieveUrl)));
 566  0
                     map.put(item.getId(), item);
 567  
                 }
 568  
             }
 569  
         }
 570  2
         return map;
 571  
     }
 572  
 }