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