Coverage Report - org.owasp.dependencycheck.data.nvdcve.ConnectionFactory
 
Classes in this File Line Coverage Branch Coverage Complexity
ConnectionFactory
47%
48/101
38%
10/26
5.571
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 3  
  *
 4  
  * Licensed under the Apache License, Version 2.0 (the "License");
 5  
  * you may not use this file except in compliance with the License.
 6  
  * You may obtain a copy of the License at
 7  
  *
 8  
  *     http://www.apache.org/licenses/LICENSE-2.0
 9  
  *
 10  
  * Unless required by applicable law or agreed to in writing, software
 11  
  * distributed under the License is distributed on an "AS IS" BASIS,
 12  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  
  * See the License for the specific language governing permissions and
 14  
  * limitations under the License.
 15  
  *
 16  
  * Copyright (c) 2014 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.data.nvdcve;
 19  
 
 20  
 import java.io.BufferedReader;
 21  
 import java.io.File;
 22  
 import java.io.IOException;
 23  
 import java.io.InputStream;
 24  
 import java.io.InputStreamReader;
 25  
 import java.sql.CallableStatement;
 26  
 import java.sql.Connection;
 27  
 import java.sql.DriverManager;
 28  
 import java.sql.ResultSet;
 29  
 import java.sql.SQLException;
 30  
 import java.sql.Statement;
 31  
 import java.util.logging.Level;
 32  
 import java.util.logging.Logger;
 33  
 import org.owasp.dependencycheck.utils.DBUtils;
 34  
 import org.owasp.dependencycheck.utils.Settings;
 35  
 
 36  
 /**
 37  
  * Loads the configured database driver and returns the database connection. If the embedded H2 database is used
 38  
  * obtaining a connection will ensure the database file exists and that the appropriate table structure has been
 39  
  * created.
 40  
  *
 41  
  * @author Jeremy Long <jeremy.long@owasp.org>
 42  
  */
 43  
 public final class ConnectionFactory {
 44  
 
 45  
     /**
 46  
      * The version of the current DB Schema.
 47  
      */
 48  
     public static final String DB_SCHEMA_VERSION = "2.9";
 49  
     /**
 50  
      * Resource location for SQL file used to create the database schema.
 51  
      */
 52  
     public static final String DB_STRUCTURE_RESOURCE = "data/initialize.sql";
 53  
 
 54  
     /**
 55  
      * Private constructor for this factory class; no instance is ever needed.
 56  
      */
 57  0
     private ConnectionFactory() {
 58  0
     }
 59  
 
 60  
     /**
 61  
      * Constructs a new database connection object per the database configuration. This will load the appropriate
 62  
      * database driver, via the DriverManager, if configured.
 63  
      *
 64  
      * @return a database connection object
 65  
      * @throws DatabaseException thrown if there is an exception loading the database connection
 66  
      */
 67  
     public static Connection getConnection() throws DatabaseException {
 68  54
         Connection conn = null;
 69  
         try {
 70  54
             Logger.getLogger(CveDB.class.getName()).log(Level.FINE, "Loading database connection");
 71  
 
 72  54
             final String connStr = getConnectionString();
 73  54
             final String user = Settings.getString(Settings.KEYS.DB_USER, "dcuser");
 74  
             //yes, yes - hard-coded password - only if there isn't one in the properties file.
 75  54
             final String pass = Settings.getString(Settings.KEYS.DB_PASSWORD, "DC-Pass1337!");
 76  54
             Logger.getLogger(CveDB.class.getName()).log(Level.FINE, "Connection String: {0}", connStr);
 77  54
             Logger.getLogger(CveDB.class.getName()).log(Level.FINE, "Database User: {0}", user);
 78  54
             boolean createTables = false;
 79  54
             if (connStr.startsWith("jdbc:h2:file:")) { //H2
 80  54
                 createTables = needToCreateDatabaseStructure();
 81  54
                 Logger.getLogger(CveDB.class.getName()).log(Level.FINE, "Need to create DB Structure: {0}", createTables);
 82  
             }
 83  54
             final String driverName = Settings.getString(Settings.KEYS.DB_DRIVER_NAME, "");
 84  54
             if (!driverName.isEmpty()) { //likely need to load the correct driver
 85  54
                 Logger.getLogger(CveDB.class.getName()).log(Level.FINE, "Loading driver: {0}", driverName);
 86  54
                 final String driverPath = Settings.getString(Settings.KEYS.DB_DRIVER_PATH, "");
 87  54
                 if (!driverPath.isEmpty()) { //ugh, driver is not on classpath?
 88  0
                     Logger.getLogger(CveDB.class.getName()).log(Level.FINE, "Loading driver from: {0}", driverPath);
 89  0
                     DriverLoader.load(driverName, driverPath);
 90  
                 } else {
 91  54
                     DriverLoader.load(driverName);
 92  
                 }
 93  
             }
 94  
 
 95  
             //JDBC4 drivers don't need this call.
 96  
             //Class.forName("org.h2.Driver");
 97  54
             conn = DriverManager.getConnection(connStr, user, pass);
 98  54
             if (createTables) {
 99  
                 try {
 100  0
                     createTables(conn);
 101  0
                 } catch (DatabaseException ex) {
 102  0
                     Logger.getLogger(ConnectionFactory.class.getName()).log(Level.FINE, null, ex);
 103  0
                     throw new DatabaseException("Unable to create the database structure");
 104  0
                 }
 105  
             } else {
 106  
                 try {
 107  54
                     ensureSchemaVersion(conn);
 108  0
                 } catch (DatabaseException ex) {
 109  0
                     Logger.getLogger(ConnectionFactory.class.getName()).log(Level.FINE, null, ex);
 110  0
                     throw new DatabaseException("Database schema does not match this version of dependency-check");
 111  54
                 }
 112  
             }
 113  0
         } catch (IOException ex) {
 114  0
             Logger.getLogger(ConnectionFactory.class.getName()).log(Level.FINE, null, ex);
 115  0
             throw new DatabaseException("Unable to load database");
 116  0
         } catch (DriverLoadException ex) {
 117  0
             Logger.getLogger(ConnectionFactory.class.getName()).log(Level.FINE, null, ex);
 118  0
             throw new DatabaseException("Unable to load database driver");
 119  0
         } catch (SQLException ex) {
 120  0
             Logger.getLogger(ConnectionFactory.class.getName()).log(Level.FINE, null, ex);
 121  0
             throw new DatabaseException("Unable to connect to the database");
 122  54
         }
 123  54
         return conn;
 124  
     }
 125  
 
 126  
     /**
 127  
      * Returns the configured connection string. If using the embedded H2 database this function will also ensure the
 128  
      * data directory exists and if not create it.
 129  
      *
 130  
      * @return the connection string
 131  
      * @throws IOException thrown the data directory cannot be created
 132  
      */
 133  
     private static String getConnectionString() throws IOException {
 134  54
         final String connStr = Settings.getString(Settings.KEYS.DB_CONNECTION_STRING, "jdbc:h2:file:%s;AUTO_SERVER=TRUE");
 135  54
         if (connStr.contains("%s")) {
 136  54
             final String directory = getDataDirectory().getCanonicalPath();
 137  54
             final File dataFile = new File(directory, "cve." + DB_SCHEMA_VERSION);
 138  54
             Logger.getLogger(ConnectionFactory.class.getName()).log(Level.FINE, String.format("File path for H2 file: '%s'", dataFile.toString()));
 139  54
             return String.format(connStr, dataFile.getAbsolutePath());
 140  
         }
 141  0
         return connStr;
 142  
     }
 143  
 
 144  
     /**
 145  
      * Retrieves the directory that the JAR file exists in so that we can ensure we always use a common data directory
 146  
      * for the embedded H2 database. This is public solely for some unit tests; otherwise this should be private.
 147  
      *
 148  
      * @return the data directory to store data files
 149  
      * @throws IOException is thrown if an IOException occurs of course...
 150  
      */
 151  
     public static File getDataDirectory() throws IOException {
 152  108
         final File path = Settings.getDataFile(Settings.KEYS.DATA_DIRECTORY);
 153  108
         if (!path.exists()) {
 154  0
             if (!path.mkdirs()) {
 155  0
                 throw new IOException("Unable to create NVD CVE Data directory");
 156  
             }
 157  
         }
 158  108
         return path;
 159  
     }
 160  
 
 161  
     /**
 162  
      * Determines if the H2 database file exists. If it does not exist then the data structure will need to be created.
 163  
      *
 164  
      * @return true if the H2 database file does not exist; otherwise false
 165  
      * @throws IOException thrown if the data directory does not exist and cannot be created
 166  
      */
 167  
     private static boolean needToCreateDatabaseStructure() throws IOException {
 168  54
         final File dir = getDataDirectory();
 169  54
         final String name = String.format("cve.%s.h2.db", DB_SCHEMA_VERSION);
 170  54
         final File file = new File(dir, name);
 171  54
         return !file.exists();
 172  
     }
 173  
 
 174  
     /**
 175  
      * Creates the database structure (tables and indexes) to store the CVE data.
 176  
      *
 177  
      * @param conn the database connection
 178  
      * @throws DatabaseException thrown if there is a Database Exception
 179  
      */
 180  
     private static void createTables(Connection conn) throws DatabaseException {
 181  0
         Logger.getLogger(ConnectionFactory.class.getName()).log(Level.FINE, "Creating database structure");
 182  
         InputStream is;
 183  
         InputStreamReader reader;
 184  0
         BufferedReader in = null;
 185  
         try {
 186  0
             is = ConnectionFactory.class.getClassLoader().getResourceAsStream(DB_STRUCTURE_RESOURCE);
 187  0
             reader = new InputStreamReader(is, "UTF-8");
 188  0
             in = new BufferedReader(reader);
 189  0
             final StringBuilder sb = new StringBuilder(2110);
 190  
             String tmp;
 191  0
             while ((tmp = in.readLine()) != null) {
 192  0
                 sb.append(tmp);
 193  
             }
 194  0
             Statement statement = null;
 195  
             try {
 196  0
                 statement = conn.createStatement();
 197  0
                 statement.execute(sb.toString());
 198  0
             } catch (SQLException ex) {
 199  0
                 Logger.getLogger(ConnectionFactory.class.getName()).log(Level.FINE, null, ex);
 200  0
                 throw new DatabaseException("Unable to create database statement", ex);
 201  
             } finally {
 202  0
                 DBUtils.closeStatement(statement);
 203  0
             }
 204  0
         } catch (IOException ex) {
 205  0
             throw new DatabaseException("Unable to create database schema", ex);
 206  
         } finally {
 207  0
             if (in != null) {
 208  
                 try {
 209  0
                     in.close();
 210  0
                 } catch (IOException ex) {
 211  0
                     Logger.getLogger(ConnectionFactory.class.getName()).log(Level.FINEST, null, ex);
 212  0
                 }
 213  
             }
 214  
         }
 215  0
     }
 216  
 
 217  
     /**
 218  
      * Uses the provided connection to check the specified schema version within the database.
 219  
      *
 220  
      * @param conn the database connection object
 221  
      * @throws DatabaseException thrown if the schema version is not compatible with this version of dependency-check
 222  
      */
 223  
     private static void ensureSchemaVersion(Connection conn) throws DatabaseException {
 224  54
         ResultSet rs = null;
 225  54
         CallableStatement cs = null;
 226  
         try {
 227  54
             cs = conn.prepareCall("SELECT value FROM properties WHERE id = 'version'");
 228  54
             rs = cs.executeQuery();
 229  54
             if (rs.next()) {
 230  54
                 final boolean isWrongSchema = !DB_SCHEMA_VERSION.equals(rs.getString(1));
 231  54
                 if (isWrongSchema) {
 232  0
                     throw new DatabaseException("Incorrect database schema; unable to continue");
 233  
                 }
 234  54
             } else {
 235  0
                 throw new DatabaseException("Database schema is missing");
 236  
             }
 237  0
         } catch (SQLException ex) {
 238  0
             Logger.getLogger(ConnectionFactory.class.getName()).log(Level.FINE, null, ex);
 239  0
             throw new DatabaseException("Unable to check the database schema version");
 240  
         } finally {
 241  54
             DBUtils.closeResultSet(rs);
 242  54
             DBUtils.closeStatement(cs);
 243  54
         }
 244  54
     }
 245  
 }