Coverage Report - org.owasp.dependencycheck.data.nvdcve.ConnectionFactory
 
Classes in this File Line Coverage Branch Coverage Complexity
ConnectionFactory
42%
59/138
36%
11/30
7
 
 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 Logger.
 48  
      */
 49  1
     private static final Logger LOGGER = Logger.getLogger(ConnectionFactory.class.getName());
 50  
     /**
 51  
      * The version of the current DB Schema.
 52  
      */
 53  1
     public static final String DB_SCHEMA_VERSION = Settings.getString(Settings.KEYS.DB_VERSION);
 54  
     /**
 55  
      * Resource location for SQL file used to create the database schema.
 56  
      */
 57  
     public static final String DB_STRUCTURE_RESOURCE = "data/initialize.sql";
 58  
     /**
 59  
      * The database driver used to connect to the database.
 60  
      */
 61  1
     private static Driver driver = null;
 62  
     /**
 63  
      * The database connection string.
 64  
      */
 65  1
     private static String connectionString = null;
 66  
     /**
 67  
      * The username to connect to the database.
 68  
      */
 69  1
     private static String userName = null;
 70  
     /**
 71  
      * The password for the database.
 72  
      */
 73  1
     private static String password = null;
 74  
 
 75  
     /**
 76  
      * Private constructor for this factory class; no instance is ever needed.
 77  
      */
 78  0
     private ConnectionFactory() {
 79  0
     }
 80  
 
 81  
     /**
 82  
      * Initializes the connection factory. Ensuring that the appropriate drivers are loaded and that a connection can be
 83  
      * made successfully.
 84  
      *
 85  
      * @throws DatabaseException thrown if we are unable to connect to the database
 86  
      */
 87  
     public static synchronized void initialize() throws DatabaseException {
 88  
         //this only needs to be called once.
 89  4
         if (connectionString != null) {
 90  3
             return;
 91  
         }
 92  1
         Connection conn = null;
 93  
         try {
 94  
             //load the driver if necessary
 95  1
             final String driverName = Settings.getString(Settings.KEYS.DB_DRIVER_NAME, "");
 96  1
             if (!driverName.isEmpty()) { //likely need to load the correct driver
 97  1
                 LOGGER.log(Level.FINE, "Loading driver: {0}", driverName);
 98  1
                 final String driverPath = Settings.getString(Settings.KEYS.DB_DRIVER_PATH, "");
 99  
                 try {
 100  1
                     if (!driverPath.isEmpty()) {
 101  0
                         LOGGER.log(Level.FINE, "Loading driver from: {0}", driverPath);
 102  0
                         driver = DriverLoader.load(driverName, driverPath);
 103  
                     } else {
 104  1
                         driver = DriverLoader.load(driverName);
 105  
                     }
 106  0
                 } catch (DriverLoadException ex) {
 107  0
                     LOGGER.log(Level.FINE, "Unable to load database driver", ex);
 108  0
                     throw new DatabaseException("Unable to load database driver");
 109  1
                 }
 110  
             }
 111  1
             userName = Settings.getString(Settings.KEYS.DB_USER, "dcuser");
 112  
             //yes, yes - hard-coded password - only if there isn't one in the properties file.
 113  1
             password = Settings.getString(Settings.KEYS.DB_PASSWORD, "DC-Pass1337!");
 114  
             try {
 115  1
                 connectionString = Settings.getConnectionString(
 116  
                         Settings.KEYS.DB_CONNECTION_STRING,
 117  
                         Settings.KEYS.DB_FILE_NAME,
 118  
                         Settings.KEYS.DB_VERSION);
 119  0
             } catch (IOException ex) {
 120  0
                 LOGGER.log(Level.FINE,
 121  
                         "Unable to retrieve the database connection string", ex);
 122  0
                 throw new DatabaseException("Unable to retrieve the database connection string");
 123  1
             }
 124  1
             boolean shouldCreateSchema = false;
 125  
             try {
 126  1
                 if (connectionString.startsWith("jdbc:h2:file:")) { //H2
 127  1
                     shouldCreateSchema = !h2DataFileExists();
 128  1
                     LOGGER.log(Level.FINE, "Need to create DB Structure: {0}", shouldCreateSchema);
 129  
                 }
 130  0
             } catch (IOException ioex) {
 131  0
                 LOGGER.log(Level.FINE, "Unable to verify database exists", ioex);
 132  0
                 throw new DatabaseException("Unable to verify database exists");
 133  1
             }
 134  1
             LOGGER.log(Level.FINE, "Loading database connection");
 135  1
             LOGGER.log(Level.FINE, "Connection String: {0}", connectionString);
 136  1
             LOGGER.log(Level.FINE, "Database User: {0}", userName);
 137  
 
 138  
             try {
 139  1
                 conn = DriverManager.getConnection(connectionString, userName, password);
 140  0
             } catch (SQLException ex) {
 141  0
                 if (ex.getMessage().contains("java.net.UnknownHostException") && connectionString.contains("AUTO_SERVER=TRUE;")) {
 142  0
                     connectionString = connectionString.replace("AUTO_SERVER=TRUE;", "");
 143  
                     try {
 144  0
                         conn = DriverManager.getConnection(connectionString, userName, password);
 145  0
                         Settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
 146  0
                         LOGGER.log(Level.FINE,
 147  
                                 "Unable to start the database in server mode; reverting to single user mode");
 148  0
                     } catch (SQLException sqlex) {
 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  0
                     }
 152  
                 } else {
 153  0
                     LOGGER.log(Level.FINE, "Unable to connect to the database", ex);
 154  0
                     throw new DatabaseException("Unable to connect to the database");
 155  
                 }
 156  1
             }
 157  
 
 158  1
             if (shouldCreateSchema) {
 159  
                 try {
 160  0
                     createTables(conn);
 161  0
                 } catch (DatabaseException dex) {
 162  0
                     LOGGER.log(Level.FINE, null, dex);
 163  0
                     throw new DatabaseException("Unable to create the database structure");
 164  0
                 }
 165  
             } else {
 166  
                 try {
 167  1
                     ensureSchemaVersion(conn);
 168  0
                 } catch (DatabaseException dex) {
 169  0
                     LOGGER.log(Level.FINE, null, dex);
 170  0
                     throw new DatabaseException("Database schema does not match this version of dependency-check");
 171  1
                 }
 172  
             }
 173  
         } finally {
 174  1
             if (conn != null) {
 175  
                 try {
 176  1
                     conn.close();
 177  0
                 } catch (SQLException ex) {
 178  0
                     LOGGER.log(Level.FINE, "An error occurred closing the connection", ex);
 179  1
                 }
 180  
             }
 181  
         }
 182  1
     }
 183  
 
 184  
     /**
 185  
      * Cleans up resources and unloads any registered database drivers. This needs to be called to ensure the driver is
 186  
      * unregistered prior to the finalize method being called as during shutdown the class loader used to load the
 187  
      * driver may be unloaded prior to the driver being de-registered.
 188  
      */
 189  
     public static synchronized void cleanup() {
 190  0
         if (driver != null) {
 191  
             try {
 192  0
                 DriverManager.deregisterDriver(driver);
 193  0
             } catch (SQLException ex) {
 194  0
                 LOGGER.log(Level.FINE, "An error occurred unloading the database driver", ex);
 195  0
             } catch (Throwable unexpected) {
 196  0
                 LOGGER.log(Level.FINE,
 197  
                         "An unexpected throwable occurred unloading the database driver", unexpected);
 198  0
             }
 199  0
             driver = null;
 200  
         }
 201  0
         connectionString = null;
 202  0
         userName = null;
 203  0
         password = null;
 204  0
     }
 205  
 
 206  
     /**
 207  
      * Constructs a new database connection object per the database configuration.
 208  
      *
 209  
      * @return a database connection object
 210  
      * @throws DatabaseException thrown if there is an exception loading the database connection
 211  
      */
 212  
     public static Connection getConnection() throws DatabaseException {
 213  3
         initialize();
 214  3
         Connection conn = null;
 215  
         try {
 216  3
             conn = DriverManager.getConnection(connectionString, userName, password);
 217  0
         } catch (SQLException ex) {
 218  0
             LOGGER.log(Level.FINE, null, ex);
 219  0
             throw new DatabaseException("Unable to connect to the database");
 220  3
         }
 221  3
         return conn;
 222  
     }
 223  
 
 224  
     /**
 225  
      * Determines if the H2 database file exists. If it does not exist then the data structure will need to be created.
 226  
      *
 227  
      * @return true if the H2 database file does not exist; otherwise false
 228  
      * @throws IOException thrown if the data directory does not exist and cannot be created
 229  
      */
 230  
     private static boolean h2DataFileExists() throws IOException {
 231  1
         final File dir = Settings.getDataDirectory();
 232  1
         final String name = Settings.getString(Settings.KEYS.DB_FILE_NAME);
 233  1
         final String fileName = String.format(name, DB_SCHEMA_VERSION);
 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.log(Level.FINE, "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.log(Level.FINE, null, 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.log(Level.FINEST, null, ex);
 276  0
                 }
 277  
             }
 278  
         }
 279  0
     }
 280  
 
 281  
     /**
 282  
      * Uses the provided connection to check the specified schema version within the database.
 283  
      *
 284  
      * @param conn the database connection object
 285  
      * @throws DatabaseException thrown if the schema version is not compatible with this version of dependency-check
 286  
      */
 287  
     private static void ensureSchemaVersion(Connection conn) throws DatabaseException {
 288  1
         ResultSet rs = null;
 289  1
         CallableStatement cs = null;
 290  
         try {
 291  1
             cs = conn.prepareCall("SELECT value FROM properties WHERE id = 'version'");
 292  1
             rs = cs.executeQuery();
 293  1
             if (rs.next()) {
 294  1
                 final boolean isWrongSchema = !DB_SCHEMA_VERSION.equals(rs.getString(1));
 295  1
                 if (isWrongSchema) {
 296  0
                     throw new DatabaseException("Incorrect database schema; unable to continue");
 297  
                 }
 298  1
             } else {
 299  0
                 throw new DatabaseException("Database schema is missing");
 300  
             }
 301  0
         } catch (SQLException ex) {
 302  0
             LOGGER.log(Level.FINE, null, ex);
 303  0
             throw new DatabaseException("Unable to check the database schema version");
 304  
         } finally {
 305  1
             DBUtils.closeResultSet(rs);
 306  1
             DBUtils.closeStatement(cs);
 307  1
         }
 308  1
     }
 309  
 }