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