Coverage Report - org.owasp.dependencycheck.data.nvdcve.ConnectionFactory
 
Classes in this File Line Coverage Branch Coverage Complexity
ConnectionFactory
45%
66/146
32%
13/40
6.222
 
 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.Driver;
 28  
 import java.sql.DriverManager;
 29  
 import java.sql.ResultSet;
 30  
 import java.sql.SQLException;
 31  
 import java.sql.Statement;
 32  
 import java.util.logging.Level;
 33  
 import java.util.logging.Logger;
 34  
 import org.owasp.dependencycheck.utils.DBUtils;
 35  
 import org.owasp.dependencycheck.utils.Settings;
 36  
 
 37  
 /**
 38  
  * Loads the configured database driver and returns the database connection. If the embedded H2 database is used
 39  
  * obtaining a connection will ensure the database file exists and that the appropriate table structure has been
 40  
  * created.
 41  
  *
 42  
  * @author Jeremy Long <jeremy.long@owasp.org>
 43  
  */
 44  
 public final class ConnectionFactory {
 45  
     /**
 46  
      * The Logger.
 47  
      */
 48  1
     private static final Logger LOGGER = Logger.getLogger(ConnectionFactory.class.getName());
 49  
     /**
 50  
      * The version of the current DB Schema.
 51  
      */
 52  
     public static final String DB_SCHEMA_VERSION = "2.9";
 53  
     /**
 54  
      * Resource location for SQL file used to create the database schema.
 55  
      */
 56  
     public static final String DB_STRUCTURE_RESOURCE = "data/initialize.sql";
 57  
     /**
 58  
      * The database driver used to connect to the database.
 59  
      */
 60  1
     private static Driver driver = null;
 61  
     /**
 62  
      * The database connection string.
 63  
      */
 64  1
     private static String connectionString = null;
 65  
     /**
 66  
      * The username to connect to the database.
 67  
      */
 68  1
     private static String userName = null;
 69  
     /**
 70  
      * The password for the database.
 71  
      */
 72  1
     private static String password = null;
 73  
 
 74  
     /**
 75  
      * Private constructor for this factory class; no instance is ever needed.
 76  
      */
 77  
     private ConnectionFactory() {
 78  
     }
 79  
 
 80  
     /**
 81  
      * Initializes the connection factory. Ensuring that the appropriate drivers are loaded and that a connection can be
 82  
      * made successfully.
 83  
      *
 84  
      * @throws DatabaseException thrown if we are unable to connect to the database
 85  
      */
 86  
     public static synchronized void initialize() throws DatabaseException {
 87  
         //this only needs to be called once.
 88  7
         if (connectionString != null) {
 89  6
             return;
 90  
         }
 91  1
         Connection conn = null;
 92  
         try {
 93  
             //load the driver if necessary
 94  1
             final String driverName = Settings.getString(Settings.KEYS.DB_DRIVER_NAME, "");
 95  1
             if (!driverName.isEmpty()) { //likely need to load the correct driver
 96  1
                 LOGGER.log(Level.FINE, "Loading driver: {0}", driverName);
 97  1
                 final String driverPath = Settings.getString(Settings.KEYS.DB_DRIVER_PATH, "");
 98  
                 try {
 99  1
                     if (!driverPath.isEmpty()) {
 100  0
                         LOGGER.log(Level.FINE, "Loading driver from: {0}", driverPath);
 101  0
                         driver = DriverLoader.load(driverName, driverPath);
 102  
                     } else {
 103  1
                         driver = DriverLoader.load(driverName);
 104  
                     }
 105  0
                 } catch (DriverLoadException ex) {
 106  0
                     LOGGER.log(Level.FINE, "Unable to load database driver", ex);
 107  0
                     throw new DatabaseException("Unable to load database driver");
 108  1
                 }
 109  
             }
 110  1
             userName = Settings.getString(Settings.KEYS.DB_USER, "dcuser");
 111  
             //yes, yes - hard-coded password - only if there isn't one in the properties file.
 112  1
             password = Settings.getString(Settings.KEYS.DB_PASSWORD, "DC-Pass1337!");
 113  
             try {
 114  1
                 connectionString = getConnectionString();
 115  0
             } catch (IOException ex) {
 116  0
                 LOGGER.log(Level.FINE,
 117  
                         "Unable to retrieve the database connection string", ex);
 118  0
                 throw new DatabaseException("Unable to retrieve the database connection string");
 119  1
             }
 120  1
             boolean shouldCreateSchema = false;
 121  
             try {
 122  1
                 if (connectionString.startsWith("jdbc:h2:file:")) { //H2
 123  1
                     shouldCreateSchema = !dbSchemaExists();
 124  1
                     LOGGER.log(Level.FINE, "Need to create DB Structure: {0}", shouldCreateSchema);
 125  
                 }
 126  0
             } catch (IOException ioex) {
 127  0
                 LOGGER.log(Level.FINE, "Unable to verify database exists", ioex);
 128  0
                 throw new DatabaseException("Unable to verify database exists");
 129  1
             }
 130  1
             LOGGER.log(Level.FINE, "Loading database connection");
 131  1
             LOGGER.log(Level.FINE, "Connection String: {0}", connectionString);
 132  1
             LOGGER.log(Level.FINE, "Database User: {0}", userName);
 133  
 
 134  
             try {
 135  1
                 conn = DriverManager.getConnection(connectionString, userName, password);
 136  0
             } catch (SQLException ex) {
 137  0
                 if (ex.getMessage().contains("java.net.UnknownHostException") && connectionString.contains("AUTO_SERVER=TRUE;")) {
 138  0
                     connectionString = connectionString.replace("AUTO_SERVER=TRUE;", "");
 139  
                     try {
 140  0
                         conn = DriverManager.getConnection(connectionString, userName, password);
 141  0
                         Settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
 142  0
                         LOGGER.log(Level.FINE,
 143  
                                 "Unable to start the database in server mode; reverting to single user mode");
 144  0
                     } catch (SQLException sqlex) {
 145  0
                         LOGGER.log(Level.FINE, "Unable to connect to the database", ex);
 146  0
                         throw new DatabaseException("Unable to connect to the database");
 147  0
                     }
 148  
                 } else {
 149  0
                     LOGGER.log(Level.FINE, "Unable to connect to the database", ex);
 150  0
                     throw new DatabaseException("Unable to connect to the database");
 151  
                 }
 152  1
             }
 153  
 
 154  1
             if (shouldCreateSchema) {
 155  
                 try {
 156  0
                     createTables(conn);
 157  0
                 } catch (DatabaseException dex) {
 158  0
                     LOGGER.log(Level.FINE, null, dex);
 159  0
                     throw new DatabaseException("Unable to create the database structure");
 160  0
                 }
 161  
             } else {
 162  
                 try {
 163  1
                     ensureSchemaVersion(conn);
 164  0
                 } catch (DatabaseException dex) {
 165  0
                     LOGGER.log(Level.FINE, null, dex);
 166  0
                     throw new DatabaseException("Database schema does not match this version of dependency-check");
 167  1
                 }
 168  
             }
 169  
         } finally {
 170  1
             if (conn != null) {
 171  
                 try {
 172  1
                     conn.close();
 173  0
                 } catch (SQLException ex) {
 174  0
                     LOGGER.log(Level.FINE, "An error occurred closing the connection", ex);
 175  1
                 }
 176  
             }
 177  
         }
 178  1
     }
 179  
 
 180  
     /**
 181  
      * Cleans up resources and unloads any registered database drivers. This needs to be called to ensure the driver is
 182  
      * unregistered prior to the finalize method being called as during shutdown the class loader used to load the
 183  
      * driver may be unloaded prior to the driver being de-registered.
 184  
      */
 185  
     public static synchronized void cleanup() {
 186  0
         if (driver != null) {
 187  
             try {
 188  0
                 DriverManager.deregisterDriver(driver);
 189  0
             } catch (SQLException ex) {
 190  0
                 LOGGER.log(Level.FINE, "An error occurred unloading the database driver", ex);
 191  0
             } catch (Throwable unexpected) {
 192  0
                 LOGGER.log(Level.FINE,
 193  
                         "An unexpected throwable occurred unloading the database driver", unexpected);
 194  0
             }
 195  0
             driver = null;
 196  
         }
 197  0
         connectionString = null;
 198  0
         userName = null;
 199  0
         password = null;
 200  0
     }
 201  
 
 202  
     /**
 203  
      * Constructs a new database connection object per the database configuration.
 204  
      *
 205  
      * @return a database connection object
 206  
      * @throws DatabaseException thrown if there is an exception loading the database connection
 207  
      */
 208  
     public static Connection getConnection() throws DatabaseException {
 209  6
         initialize();
 210  6
         Connection conn = null;
 211  
         try {
 212  6
             conn = DriverManager.getConnection(connectionString, userName, password);
 213  0
         } catch (SQLException ex) {
 214  0
             LOGGER.log(Level.FINE, null, ex);
 215  0
             throw new DatabaseException("Unable to connect to the database");
 216  6
         }
 217  6
         return conn;
 218  
     }
 219  
 
 220  
     /**
 221  
      * Returns the configured connection string. If using the embedded H2 database this function will also ensure the
 222  
      * data directory exists and if not create it.
 223  
      *
 224  
      * @return the connection string
 225  
      * @throws IOException thrown the data directory cannot be created
 226  
      */
 227  
     private static String getConnectionString() throws IOException {
 228  1
         final String connStr = Settings.getString(Settings.KEYS.DB_CONNECTION_STRING, "jdbc:h2:file:%s;AUTO_SERVER=TRUE");
 229  1
         if (connStr.contains("%s")) {
 230  1
             final String directory = getDataDirectory().getCanonicalPath();
 231  1
             final File dataFile = new File(directory, "cve." + DB_SCHEMA_VERSION);
 232  1
             LOGGER.log(Level.FINE, String.format("File path for H2 file: '%s'", dataFile.toString()));
 233  1
             return String.format(connStr, dataFile.getAbsolutePath());
 234  
         }
 235  0
         return connStr;
 236  
     }
 237  
 
 238  
     /**
 239  
      * Retrieves the directory that the JAR file exists in so that we can ensure we always use a common data directory
 240  
      * for the embedded H2 database. This is public solely for some unit tests; otherwise this should be private.
 241  
      *
 242  
      * @return the data directory to store data files
 243  
      * @throws IOException is thrown if an IOException occurs of course...
 244  
      */
 245  
     public static File getDataDirectory() throws IOException {
 246  2
         final File path = Settings.getDataFile(Settings.KEYS.DATA_DIRECTORY);
 247  2
         if (!path.exists()) {
 248  0
             if (!path.mkdirs()) {
 249  0
                 throw new IOException("Unable to create NVD CVE Data directory");
 250  
             }
 251  
         }
 252  2
         return path;
 253  
     }
 254  
 
 255  
     /**
 256  
      * Determines if the H2 database file exists. If it does not exist then the data structure will need to be created.
 257  
      *
 258  
      * @return true if the H2 database file does not exist; otherwise false
 259  
      * @throws IOException thrown if the data directory does not exist and cannot be created
 260  
      */
 261  
     private static boolean dbSchemaExists() throws IOException {
 262  1
         final File dir = getDataDirectory();
 263  1
         final String name = String.format("cve.%s.h2.db", DB_SCHEMA_VERSION);
 264  1
         final File file = new File(dir, name);
 265  1
         return file.exists();
 266  
     }
 267  
 
 268  
     /**
 269  
      * Creates the database structure (tables and indexes) to store the CVE data.
 270  
      *
 271  
      * @param conn the database connection
 272  
      * @throws DatabaseException thrown if there is a Database Exception
 273  
      */
 274  
     private static void createTables(Connection conn) throws DatabaseException {
 275  0
         LOGGER.log(Level.FINE, "Creating database structure");
 276  
         InputStream is;
 277  
         InputStreamReader reader;
 278  0
         BufferedReader in = null;
 279  
         try {
 280  0
             is = ConnectionFactory.class.getClassLoader().getResourceAsStream(DB_STRUCTURE_RESOURCE);
 281  0
             reader = new InputStreamReader(is, "UTF-8");
 282  0
             in = new BufferedReader(reader);
 283  0
             final StringBuilder sb = new StringBuilder(2110);
 284  
             String tmp;
 285  0
             while ((tmp = in.readLine()) != null) {
 286  0
                 sb.append(tmp);
 287  
             }
 288  0
             Statement statement = null;
 289  
             try {
 290  0
                 statement = conn.createStatement();
 291  0
                 statement.execute(sb.toString());
 292  0
             } catch (SQLException ex) {
 293  0
                 LOGGER.log(Level.FINE, null, ex);
 294  0
                 throw new DatabaseException("Unable to create database statement", ex);
 295  
             } finally {
 296  0
                 DBUtils.closeStatement(statement);
 297  0
             }
 298  0
         } catch (IOException ex) {
 299  0
             throw new DatabaseException("Unable to create database schema", ex);
 300  
         } finally {
 301  0
             if (in != null) {
 302  
                 try {
 303  0
                     in.close();
 304  0
                 } catch (IOException ex) {
 305  0
                     LOGGER.log(Level.FINEST, null, ex);
 306  0
                 }
 307  
             }
 308  
         }
 309  0
     }
 310  
 
 311  
     /**
 312  
      * Uses the provided connection to check the specified schema version within the database.
 313  
      *
 314  
      * @param conn the database connection object
 315  
      * @throws DatabaseException thrown if the schema version is not compatible with this version of dependency-check
 316  
      */
 317  
     private static void ensureSchemaVersion(Connection conn) throws DatabaseException {
 318  1
         ResultSet rs = null;
 319  1
         CallableStatement cs = null;
 320  
         try {
 321  1
             cs = conn.prepareCall("SELECT value FROM properties WHERE id = 'version'");
 322  1
             rs = cs.executeQuery();
 323  1
             if (rs.next()) {
 324  1
                 final boolean isWrongSchema = !DB_SCHEMA_VERSION.equals(rs.getString(1));
 325  1
                 if (isWrongSchema) {
 326  0
                     throw new DatabaseException("Incorrect database schema; unable to continue");
 327  
                 }
 328  1
             } else {
 329  0
                 throw new DatabaseException("Database schema is missing");
 330  
             }
 331  0
         } catch (SQLException ex) {
 332  0
             LOGGER.log(Level.FINE, null, ex);
 333  0
             throw new DatabaseException("Unable to check the database schema version");
 334  
         } finally {
 335  1
             DBUtils.closeResultSet(rs);
 336  1
             DBUtils.closeStatement(cs);
 337  1
         }
 338  1
     }
 339  
 }