List of usage examples for java.sql DriverManager registerDriver
public static void registerDriver(java.sql.Driver driver) throws SQLException
From source file:org.pentaho.di.core.database.Database.java
/** * Connect using the correct classname/*from www . j a va 2 s .c om*/ * * @param classname * for example "org.gjt.mm.mysql.Driver" * @return true if the connect was successful, false if something went wrong. */ private void connectUsingClass(String classname, String partitionId) throws KettleDatabaseException { // first see if this is a JNDI connection if (databaseMeta.getAccessType() == DatabaseMeta.TYPE_ACCESS_JNDI) { initWithNamedDataSource(environmentSubstitute(databaseMeta.getDatabaseName())); return; } // Install and load the jdbc Driver PluginInterface plugin = PluginRegistry.getInstance().getPlugin(DatabasePluginType.class, databaseMeta.getDatabaseInterface()); try { synchronized (java.sql.DriverManager.class) { ClassLoader classLoader = PluginRegistry.getInstance().getClassLoader(plugin); Class<?> driverClass = classLoader.loadClass(classname); // Only need DelegatingDriver for drivers not from our classloader if (driverClass.getClassLoader() != this.getClass().getClassLoader()) { String pluginId = PluginRegistry.getInstance().getPluginId(DatabasePluginType.class, databaseMeta.getDatabaseInterface()); Set<String> registeredDriversFromPlugin = registeredDrivers.get(pluginId); if (registeredDriversFromPlugin == null) { registeredDriversFromPlugin = new HashSet<String>(); registeredDrivers.put(pluginId, registeredDriversFromPlugin); } // Prevent registering multiple delegating drivers for same class, plugin if (!registeredDriversFromPlugin.contains(driverClass.getCanonicalName())) { DriverManager.registerDriver(new DelegatingDriver((Driver) driverClass.newInstance())); registeredDriversFromPlugin.add(driverClass.getCanonicalName()); } } else { // Trigger static register block in driver class Class.forName(classname); } } } catch (NoClassDefFoundError e) { throw new KettleDatabaseException( BaseMessages.getString(PKG, "Database.Exception.UnableToFindClassMissingDriver", databaseMeta.getDriverClass(), plugin.getName()), e); } catch (ClassNotFoundException e) { throw new KettleDatabaseException( BaseMessages.getString(PKG, "Database.Exception.UnableToFindClassMissingDriver", databaseMeta.getDriverClass(), plugin.getName()), e); } catch (Exception e) { throw new KettleDatabaseException("Exception while loading class", e); } try { String url; if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId)) { url = environmentSubstitute(databaseMeta.getURL(partitionId)); } else { url = environmentSubstitute(databaseMeta.getURL()); } String clusterUsername = null; String clusterPassword = null; if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId)) { // Get the cluster information... PartitionDatabaseMeta partition = databaseMeta.getPartitionMeta(partitionId); if (partition != null) { clusterUsername = partition.getUsername(); clusterPassword = Encr.decryptPasswordOptionallyEncrypted(partition.getPassword()); } } String username; String password; if (!Const.isEmpty(clusterUsername)) { username = clusterUsername; password = clusterPassword; } else { username = environmentSubstitute(databaseMeta.getUsername()); password = Encr .decryptPasswordOptionallyEncrypted(environmentSubstitute(databaseMeta.getPassword())); } if (databaseMeta.supportsOptionsInURL()) { if (!Const.isEmpty(username) || !Const.isEmpty(password)) { if (databaseMeta.getDatabaseInterface() instanceof MSSQLServerNativeDatabaseMeta) { // Needs user & password in the URL // String instance = environmentSubstitute(databaseMeta.getSQLServerInstance()); if (Const.isEmpty(instance)) { connection = DriverManager .getConnection(url + ";user=" + username + ";password=" + password); } else { connection = DriverManager.getConnection(url + ";user=" + username + ";password=" + password + ";instanceName=" + instance); } } else { // also allow for empty username with given password, in this case // username must be given with one space connection = DriverManager.getConnection(url, Const.NVL(username, " "), Const.NVL(password, "")); } } else { // Perhaps the username is in the URL or no username is required... connection = DriverManager.getConnection(url); } } else { Properties properties = databaseMeta.getConnectionProperties(); if (!Const.isEmpty(username)) { properties.put("user", username); } if (!Const.isEmpty(password)) { properties.put("password", password); } connection = DriverManager.getConnection(url, properties); } } catch (SQLException e) { throw new KettleDatabaseException("Error connecting to database: (using class " + classname + ")", e); } catch (Throwable e) { throw new KettleDatabaseException("Error connecting to database: (using class " + classname + ")", e); } }
From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccOracle.CFAccOracleSchema.java
public boolean connect(String username, String password) { final String S_ProcName = "connect-userpw"; if (cnx != null) { return (false); }/*from ww w. java 2s .c o m*/ if ((username == null) || (username.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1, "username"); } if (password == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1, "password"); } if (configuration != null) { try { DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); } catch (SQLException e) { throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e); } String dbServer = configuration.getDbServer(); int dbPort = configuration.getDbPort(); String dbDatabase = configuration.getDbDatabase(); String dbUserName = username; String dbPassword = password; String url = "jdbc:oracle:thin:@" + dbServer; Properties props = new Properties(); props.setProperty("user", dbUserName); props.setProperty("password", dbPassword); try { cnx = DriverManager.getConnection(url, props); cnx.setAutoCommit(false); cnx.rollback(); setSchemaDbName(dbDatabase); } catch (SQLException e) { throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e); } return (true); } throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName, "configurationFile not found, do not know how to connect to database"); }
From source file:io.github.divinespear.maven.plugin.JpaSchemaGeneratorMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { if (this.skip) { log.info("schema generation is skipped."); return;/* ww w.j ava2s . c om*/ } if (this.outputDirectory != null && !this.outputDirectory.exists()) { this.outputDirectory.mkdirs(); } final ClassLoader classLoader = this.getProjectClassLoader(); // driver load hack // http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location if (StringUtils.isNotBlank(this.jdbcDriver)) { try { Driver driver = (Driver) classLoader.loadClass(this.jdbcDriver).newInstance(); DriverManager.registerDriver(driver); } catch (Exception e) { throw new MojoExecutionException("Dependency for driver-class " + this.jdbcDriver + " is missing!", e); } } // generate schema Thread thread = Thread.currentThread(); ClassLoader currentClassLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(classLoader); this.generate(); } catch (Exception e) { throw new MojoExecutionException("Error while running", e); } finally { thread.setContextClassLoader(currentClassLoader); } // post-process try { this.postProcess(); } catch (IOException e) { throw new MojoExecutionException("Error while post-processing script file", e); } }
From source file:org.pentaho.pac.server.PacServiceImpl.java
/** * NOTE: caller is responsible for closing connection * /*from ww w . j av a 2 s.c o m*/ * @param ds * @return * @throws DataSourceManagementException */ private static Connection getDataSourceConnection(PentahoDataSource ds) throws DataSourceManagementException { Connection conn = null; String driverClass = ds.getDriverClass(); if (StringUtils.isEmpty(driverClass)) { throw new DataSourceManagementException( Messages.getErrorString("PacService.ERROR_0024_CONNECTION_ATTEMPT_FAILED", driverClass)); //$NON-NLS-1$ } Class<?> driverC = null; try { driverC = Class.forName(driverClass); } catch (ClassNotFoundException e) { throw new DataSourceManagementException( Messages.getErrorString("PacService.ERROR_0026_DRIVER_NOT_FOUND_IN_CLASSPATH", driverClass), e); //$NON-NLS-1$ } if (!Driver.class.isAssignableFrom(driverC)) { throw new DataSourceManagementException( Messages.getErrorString("PacService.ERROR_0026_DRIVER_NOT_FOUND_IN_CLASSPATH", driverClass)); //$NON-NLS-1$ } } Driver driver = null; try { driver = driverC.asSubclass(Driver.class).newInstance(); } catch (InstantiationException e) { throw new DataSourceManagementException( Messages.getErrorString("PacService.ERROR_0027_UNABLE_TO_INSTANCE_DRIVER", driverClass), e); //$NON-NLS-1$ } catch (IllegalAccessException e) { throw new DataSourceManagementException( Messages.getErrorString("PacService.ERROR_0027_UNABLE_TO_INSTANCE_DRIVER", driverClass), e); //$NON-NLS-1$ } } try { DriverManager.registerDriver(driver); conn = DriverManager.getConnection(ds.getUrl(), ds.getUserName(), ds.getPassword()); return conn; } catch (SQLException e) { throw new DataSourceManagementException( Messages.getErrorString("PacService.ERROR_0025_UNABLE_TO_CONNECT", e.getMessage()), e); //$NON-NLS-1$ } }
From source file:org.miloss.fgsms.common.Utility.java
@Deprecated private static Connection getPerformanceDB_NONPOOLED_Connection_FAILOVER() { try {/*w ww. ja va2 s. co m*/ Properties prop = PropertyLoader.loadProperties(PropertyFilePath); Driver d = (Driver) Class.forName(prop.getProperty(DBdriver)).newInstance(); DriverManager.registerDriver(d); Connection con = DriverManager.getConnection(prop.getProperty(PerformanceDBURL_FAILOVER), prop.getProperty(PerformanceUsername_FAILOVER), DE(prop.getProperty(PerformancePassword_FAILOVER))); PreparedStatement com = con.prepareStatement("select 1;"); try { com.execute(); DBUtils.safeClose(com); return con; } catch (Exception e) { log.log(Level.FATAL, "Error obtaining secondary perf database connection, msg:" + e.getLocalizedMessage(), e); return null; } finally { DBUtils.safeClose(com); } } catch (Exception ex) { log.log(Level.FATAL, "No connection to the secondary database could be made, msg:" + ex.getLocalizedMessage(), ex); return null; } }
From source file:gov.nih.nci.cadsr.sentinel.database.DBAlertOracle.java
/** * Required prior to using any other methods within this class. This method * checks for the existence of the pool attached to the Servlet Context. * Once the pool is successfully created subsequent invocations perform no * action. The method is static and synchronized to allow for possible * multiple invocations of the Sentinel Tool simultaneously. Although the * data referenced is not static we don't want to take the chance that the * ServletContext.getAttribute() is called, we loose the time slice and upon * return from the VM one invocation thinks the pool is missing when another * invocation has just successfully created it. This is only called from the * Logon Action currently so the overhead inherit with synchronized * functions is minimized.//from w ww . ja v a 2s. co m * <p> * To use this from a browser servlet, use the method which requires an * HttpServletRequest as the first argument to the method. * * @param dsurl_ * The URL entry for the desired database. * @param username_ * The default database user logon id. * @param password_ * The password to match the user. * @return 0 if successful, otherwise the Oracle error code. */ private static synchronized OracleConnectionPoolDataSource setupPool(String dsurl_, String username_, String password_) { // First register the database driver. OracleConnectionPoolDataSource ocpds = null; int rc = 0; String rcTxt = null; try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); } catch (SQLException ex) { rc = ex.getErrorCode(); rcTxt = rc + ": " + ex.toString(); } try { // Create an the connection pool data source and set the parameters. ocpds = new OracleConnectionPoolDataSource(); if (dsurl_.indexOf(':') > 0) { String parts[] = dsurl_.split("[:]"); ocpds.setDriverType("thin"); ocpds.setServerName(parts[0]); ocpds.setPortNumber(Integer.parseInt(parts[1])); ocpds.setServiceName(parts[2]); } else { ocpds.setDriverType("oci8"); ocpds.setTNSEntryName(dsurl_); } ocpds.setUser(username_); ocpds.setPassword(password_); } catch (SQLException ex) { // We have a problem. rc = ex.getErrorCode(); rcTxt = rc + ": " + ex.toString(); ocpds = null; } if (rc != 0) { // Send a user friendly message to the Logon window and the more // detailed // message to the console. _logger.error(rcTxt); } return ocpds; }
From source file:org.miloss.fgsms.common.Utility.java
/** * returns a NON pooled database connection by using the data in the * database.properties if the primary cannot be reached, the secondary is * used or null is returned./*ww w . j av a2s .com*/ * * configuration is loaded from the database.properties embedded within * fgsms.common.jar * * @return */ @Deprecated public static Connection getPerformanceDB_NONPOOLED_Connection() { try { Properties prop = PropertyLoader.loadProperties(PropertyFilePath); Driver d = (Driver) Class.forName(prop.getProperty(DBdriver)).newInstance(); DriverManager.registerDriver(d); Connection con = DriverManager.getConnection(prop.getProperty(PerformanceDBURL), prop.getProperty(PerformanceUsername), DE(prop.getProperty(PerformancePassword))); PreparedStatement com = con.prepareStatement("select 1;"); try { com.execute(); DBUtils.safeClose(com); return con; } catch (Exception e) { log.log(Level.ERROR, "Error obtaining primary perf database connection, attempting alternate. msg:" + e.getLocalizedMessage(), e); return getPerformanceDB_NONPOOLED_Connection_FAILOVER(); } finally { DBUtils.safeClose(com); } } catch (Exception ex) { log.log(Level.ERROR, "No connection to the performance database could be made, msg:" + ex.getLocalizedMessage(), ex); return null; } }
From source file:org.apache.phoenix.query.BaseTest.java
protected static void setUpRealDriver(ReadOnlyProps serverProps, ReadOnlyProps clientProps) throws Exception { if (!clusterInitialized) { setUpConfigForMiniCluster(config, serverProps); utility = new HBaseTestingUtility(config); try {/* w w w. j av a 2 s.com*/ utility.startMiniCluster(NUM_SLAVES_BASE); utility.startMiniMapReduceCluster(); url = QueryUtil.getConnectionUrl(new Properties(), utility.getConfiguration()); } catch (Throwable t) { throw new RuntimeException(t); } clusterInitialized = true; } Class.forName(PhoenixDriver.class.getName()); realDriver = PhoenixDriver.INSTANCE; DriverManager.registerDriver(realDriver); if (clientProps.getBoolean(QueryServices.TRANSACTIONS_ENABLED, QueryServicesOptions.DEFAULT_TRANSACTIONS_ENABLED)) { setupTxManager(); } }
From source file:com.jaspersoft.jasperserver.api.common.service.impl.JdbcDriverServiceImpl.java
protected void registerDriverInJVM(Driver driver) throws SQLException { DriverManager.registerDriver(driver); }
From source file:org.miloss.fgsms.common.Utility.java
/** * returns a NON pooled database connection by using the data in the * database.properties if the primary cannot be reached, the secondary is * used or null is returned./*from w w w .ja v a 2 s . c o m*/ * * configuration is loaded from the database.properties embedded within * fgsms.common.jar * * @return */ @Deprecated public static Connection getConfigurationDB_NONPOOLED_Connection() { try { Properties prop = PropertyLoader.loadProperties(PropertyFilePath); Driver d = (Driver) Class.forName(prop.getProperty(DBdriver)).newInstance(); DriverManager.registerDriver(d); Connection con = DriverManager.getConnection(prop.getProperty(ConfigDBURL), prop.getProperty(ConfigUsername), DE(prop.getProperty(ConfigPassword))); PreparedStatement com = con.prepareStatement("select 1;"); try { com.execute(); DBUtils.safeClose(com); return con; } catch (Exception e) { log.log(Level.ERROR, "Error obtaining primary config database connection, attempting alternate. msg:" + e.getLocalizedMessage(), e); return getConfigurationDB_NONPOOLED_Connection_FAILOVER(); } finally { DBUtils.safeClose(com); } } catch (Exception ex) { log.log(Level.ERROR, "Error obtaining primary conf database connection:" + ex.getLocalizedMessage(), ex); return getConfigurationDB_NONPOOLED_Connection_FAILOVER(); } }