List of usage examples for javax.sql DataSource getConnection
Connection getConnection() throws SQLException;
Attempts to establish a connection with the data source that this DataSource object represents.
From source file:csiro.pidsvc.mappingstore.Manager.java
/************************************************************************** * Construction/destruction./*from w ww. j av a 2 s. com*/ */ public Manager() throws NamingException, SQLException, IOException { InitialContext initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource) envCtx.lookup(Settings.getInstance().getProperty("jndiReferenceName")); _connection = ds.getConnection(); refreshCaseSensitivity(); }
From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java
/** Function to extract users from JDBCs. */ private List<String> getUserList(JdbcRealm obj) { List<String> userlist = new ArrayList<>(); Connection con = null;//from ww w . j av a2s. c o m PreparedStatement ps = null; ResultSet rs = null; DataSource dataSource = null; String authQuery = ""; String retval[]; String tablename = ""; String username = ""; String userquery; try { dataSource = (DataSource) FieldUtils.readField(obj, "dataSource", true); authQuery = (String) FieldUtils.readField(obj, "authenticationQuery", true); LOGGER.info(authQuery); String authQueryLowerCase = authQuery.toLowerCase(); retval = authQueryLowerCase.split("from", 2); if (retval.length >= 2) { retval = retval[1].split("with|where", 2); tablename = retval[0]; retval = retval[1].split("where", 2); if (retval.length >= 2) { retval = retval[1].split("=", 2); } else { retval = retval[0].split("=", 2); } username = retval[0]; } if (StringUtils.isBlank(username) || StringUtils.isBlank(tablename)) { return userlist; } userquery = String.format("SELECT %s FROM %s", username, tablename); } catch (IllegalAccessException e) { LOGGER.error("Error while accessing dataSource for JDBC Realm", e); return Lists.newArrayList(); } try { con = dataSource.getConnection(); ps = con.prepareStatement(userquery); rs = ps.executeQuery(); while (rs.next()) { userlist.add(rs.getString(1).trim()); } } catch (Exception e) { LOGGER.error("Error retrieving User list from JDBC Realm", e); } finally { JdbcUtils.closeResultSet(rs); JdbcUtils.closeStatement(ps); JdbcUtils.closeConnection(con); } return userlist; }
From source file:net.certifi.audittablegen.GenericDMRTest.java
/** * Test of executeChanges method, of class GenericDMR. */// w w w .j a v a2 s . c o m @Test public void testExecuteChanges() throws SQLException { System.out.println("executeChanges"); DataSource realDs = HsqldbDMR.getRunTimeDataSource(); GenericDMR instance = new GenericDMR(realDs); List<DBChangeUnit> op = new ArrayList<>(); String tableName = "TESTTABLE1"; String column1Name = "data"; DBChangeUnit unit; unit = new DBChangeUnit(DBChangeType.begin); op.add(unit); unit = new DBChangeUnit(DBChangeType.createTable); unit.setTableName(tableName); op.add(unit); unit = new DBChangeUnit(DBChangeType.addColumn); unit.setTableName(tableName); unit.setColumnName(column1Name); unit.setTypeName("varchar"); unit.setSize(255); op.add(unit); op.add(new DBChangeUnit(DBChangeType.end)); instance.operations.add(op); instance.executeChanges(); //test if the table got created Connection conn = realDs.getConnection(); Statement stmt = conn.createStatement(); String verify = "select table_name from information_schema.system_tables" + " where table_name = '" + tableName + "'"; ResultSet rs = stmt.executeQuery(verify); String result = ""; while (rs.next()) { result = rs.getString(1); } assertEquals(tableName, result); }
From source file:org.apache.ddlutils.TestSummaryCreatorTask.java
/** * Adds the data from the test jdbc propertis file to the document. * //from w w w . ja v a2 s.c o m * @param element The element to add the relevant database properties to * @param jdbcPropertiesFile The path of the properties file */ protected void addTargetDatabaseInfo(Element element, String jdbcPropertiesFile) throws IOException, BuildException { if (jdbcPropertiesFile == null) { return; } Properties props = readProperties(jdbcPropertiesFile); Connection conn = null; DatabaseMetaData metaData = null; try { String dataSourceClass = props.getProperty( TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX + "class", BasicDataSource.class.getName()); DataSource dataSource = (DataSource) Class.forName(dataSourceClass).newInstance(); for (Iterator it = props.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); String propName = (String) entry.getKey(); if (propName.startsWith(TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX) && !propName.equals(TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX + "class")) { BeanUtils.setProperty(dataSource, propName.substring(TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX.length()), entry.getValue()); } } String platformName = props.getProperty(TestAgainstLiveDatabaseBase.DDLUTILS_PLATFORM_PROPERTY); if (platformName == null) { platformName = new PlatformUtils().determineDatabaseType(dataSource); if (platformName == null) { throw new BuildException( "Could not determine platform from datasource, please specify it in the jdbc.properties via the ddlutils.platform property"); } } element.addAttribute("platform", platformName); element.addAttribute("dataSourceClass", dataSourceClass); conn = dataSource.getConnection(); metaData = conn.getMetaData(); try { element.addAttribute("dbProductName", metaData.getDatabaseProductName()); } catch (Throwable ex) { // we ignore it } try { element.addAttribute("dbProductVersion", metaData.getDatabaseProductVersion()); } catch (Throwable ex) { // we ignore it } try { int databaseMajorVersion = metaData.getDatabaseMajorVersion(); int databaseMinorVersion = metaData.getDatabaseMinorVersion(); element.addAttribute("dbVersion", databaseMajorVersion + "." + databaseMinorVersion); } catch (Throwable ex) { // we ignore it } try { element.addAttribute("driverName", metaData.getDriverName()); } catch (Throwable ex) { // we ignore it } try { element.addAttribute("driverVersion", metaData.getDriverVersion()); } catch (Throwable ex) { // we ignore it } try { int jdbcMajorVersion = metaData.getJDBCMajorVersion(); int jdbcMinorVersion = metaData.getJDBCMinorVersion(); element.addAttribute("jdbcVersion", jdbcMajorVersion + "." + jdbcMinorVersion); } catch (Throwable ex) { // we ignore it } } catch (Exception ex) { throw new BuildException(ex); } finally { if (conn != null) { try { conn.close(); } catch (SQLException ex) { // we ignore it } } } }
From source file:it.cnr.icar.eric.server.repository.hibernate.RepositoryHibernateUtil.java
@SuppressWarnings("unused") protected Configuration getConfiguration() { if (configuration == null) { synchronized (RepositoryHibernateUtil.class) { if (configuration == null) { try { String cfgResource; DataSource ds = null; boolean useConnectionPool = Boolean .valueOf(RegistryProperties.getInstance() .getProperty("eric.persistence.rdb.useConnectionPooling", "true")) .booleanValue(); boolean debugConnectionPool = Boolean.valueOf(RegistryProperties.getInstance() .getProperty("eric.persistence.rdb.pool.debug", "false")).booleanValue(); // Try DataSource first, if configured if (useConnectionPool && !debugConnectionPool) { cfgResource = "/repository.datasource.cfg.xml"; configuration = new Configuration().configure(cfgResource); String dataSourceName = configuration.getProperty("connection.datasource"); if (dataSourceName != null && !"".equals(dataSourceName)) { try { Context ctx = new InitialContext(); if (ctx != null) { ds = (DataSource) ctx.lookup(dataSourceName); if (ds != null) { // create a test connection to // make sure all is well with // DataSource Connection connection = null; try { connection = ds.getConnection(); } catch (Exception e) { ds = null; log.info(ServerResourceBundle.getInstance().getString( "message.UnableToCreateTestConnectionForDataSource", new Object[] { dataSourceName }), e); } finally { if (connection != null) { try { connection.close(); } catch (Exception e1) { //Do nothing. connection = null; } } } }/*www .java2 s. c o m*/ } else { log.info(ServerResourceBundle.getInstance() .getString("message.UnableToGetInitialContext")); } } catch (NamingException e) { log.info(ServerResourceBundle.getInstance().getString( "message.UnableToGetJNDIContextForDataSource", new Object[] { dataSourceName })); } } } if (ds == null) { // fall back to jdbc cfgResource = "/repository.jdbc.cfg.xml"; configuration = new Configuration().configure(cfgResource); } // support $user.home and $eric.home in eric repository cfg String connUrl = configuration.getProperty("hibernate.connection.url"); if (connUrl != null && !"".equals(connUrl)) { connUrl = substituteVariable(connUrl, "$user.home", System.getProperty("user.home")); connUrl = substituteVariable(connUrl, "$eric.home", RegistryProperties.getInstance().getProperty("eric.home")); configuration.setProperty("hibernate.connection.url", connUrl); } sessionFactory = configuration.buildSessionFactory(); } catch (HibernateException ex) { throw new RuntimeException(ServerResourceBundle.getInstance() .getString("message.buildingSessionFactory", new Object[] { ex.getMessage() }), ex); } } } } return configuration; }
From source file:org.apache.gobblin.metastore.MysqlStateStore.java
/** * Manages the persistence and retrieval of {@link State} in a MySQL database * @param dataSource the {@link DataSource} object for connecting to MySQL * @param stateStoreTableName the table for storing the state in rows keyed by two levels (store_name, table_name) * @param compressedValues should values be compressed for storage? * @param stateClass class of the {@link State}s stored in this state store * @throws IOException//from w w w .j av a 2 s.co m */ public MysqlStateStore(DataSource dataSource, String stateStoreTableName, boolean compressedValues, Class<T> stateClass) throws IOException { this.dataSource = dataSource; this.stateClass = stateClass; this.compressedValues = compressedValues; UPSERT_JOB_STATE_SQL = UPSERT_JOB_STATE_TEMPLATE.replace("$TABLE$", stateStoreTableName); SELECT_JOB_STATE_SQL = SELECT_JOB_STATE_TEMPLATE.replace("$TABLE$", stateStoreTableName); SELECT_JOB_STATE_WITH_LIKE_SQL = SELECT_JOB_STATE_WITH_LIKE_TEMPLATE.replace("$TABLE$", stateStoreTableName); SELECT_JOB_STATE_EXISTS_SQL = SELECT_JOB_STATE_EXISTS_TEMPLATE.replace("$TABLE$", stateStoreTableName); SELECT_JOB_STATE_NAMES_SQL = SELECT_JOB_STATE_NAMES_TEMPLATE.replace("$TABLE$", stateStoreTableName); DELETE_JOB_STORE_SQL = DELETE_JOB_STORE_TEMPLATE.replace("$TABLE$", stateStoreTableName); DELETE_JOB_STATE_SQL = DELETE_JOB_STATE_TEMPLATE.replace("$TABLE$", stateStoreTableName); CLONE_JOB_STATE_SQL = CLONE_JOB_STATE_TEMPLATE.replace("$TABLE$", stateStoreTableName); SELECT_STORE_NAMES_SQL = SELECT_STORE_NAMES_TEMPLATE.replace("$TABLE$", stateStoreTableName); SELECT_METADATA_SQL = SELECT_METADATA_TEMPLATE.replace("$TABLE$", stateStoreTableName); // create table if it does not exist String createJobTable = CREATE_JOB_STATE_TABLE_TEMPLATE.replace("$TABLE$", stateStoreTableName); try (Connection connection = dataSource.getConnection(); PreparedStatement createStatement = connection.prepareStatement(createJobTable)) { createStatement.executeUpdate(); } catch (SQLException e) { throw new IOException("Failure creation table " + stateStoreTableName, e); } }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_1.CFAstPgSql.CFAstPgSqlSchema.java
public boolean connect() { final String S_ProcName = "connect"; if (cnx != null) { return (false); }/*from w ww . j a v a2 s. c om*/ if (configuration != null) { String dbServer = configuration.getDbServer(); int dbPort = configuration.getDbPort(); String dbDatabase = configuration.getDbDatabase(); String dbUserName = configuration.getDbUserName(); String dbPassword = configuration.getDbPassword(); String url = "jdbc:postgresql://" + dbServer + ":" + Integer.toString(dbPort) + "/" + dbDatabase; Properties props = new Properties(); props.setProperty("user", dbUserName); props.setProperty("password", dbPassword); try { cnx = DriverManager.getConnection(url, props); cnx.setAutoCommit(false); cnx.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); cnx.rollback(); setDbSchemaName(dbDatabase); } catch (SQLException e) { throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e); } return (true); } if (jndiName != null) { try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(jndiName); if (ds == null) { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Could not get resolve DataSource \"" + jndiName + "\""); } cnx = ds.getConnection(); if (cnx == null) { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Could not get Connection from PooledConnection for ConnectionPoolDataSource \"" + jndiName + "\""); } cnx.setAutoCommit(false); cnx.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); cnx.rollback(); } catch (NamingException e) { cnx = null; throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "NamingException " + e.getMessage(), e); } catch (SQLException e) { cnx = null; inTransaction = false; throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e); } return (true); } throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName, "Neither configurationFile nor jndiName found, do not know how to connect to database"); }
From source file:jdbc.pool.JDBCPoolMySQLTest.java
public synchronized void testGetDataSource() { testGetInstanceNull();/*from w w w. j a v a 2 s. c o m*/ logger.debug("testGetDataSource Start."); CConnectionPoolManager manager = null; try { manager = create(); CPoolStatisticsBean bean = manager.getPoolStatistics("MYSQL"); assertEquals("Pool Name", "MYSQL", bean.getPoolName()); assertEquals("Bad Connections Count", 0, bean.getBadConnectionCount()); assertEquals("Connections High Count", 0, bean.getConnectionsHighCount()); assertEquals("Current Free Connections", 3, bean.getCurrentFreeConnectionCount()); assertEquals("Current Used Connection count", 0, bean.getCurrentUsedConnectionCount()); assertEquals("Leaked Connection Count", 0, bean.getLeakedConnectionCount()); assertEquals("Leaked Statement Count", 0, bean.getLeakedStatementCount()); assertEquals("Leaked ResultSet Count", 0, bean.getLeakedResultSetCount()); DataSource dataSource = manager.getDataSource("MYSQL"); Connection con = dataSource.getConnection(); bean = manager.getPoolStatistics("MYSQL"); assertEquals("Pool Name", "MYSQL", bean.getPoolName()); assertEquals("Bad Connections Count", 0, bean.getBadConnectionCount()); assertEquals("Connections High Count", 1, bean.getConnectionsHighCount()); assertEquals("Current Free Connections", 2, bean.getCurrentFreeConnectionCount()); assertEquals("Current Used Connection count", 1, bean.getCurrentUsedConnectionCount()); assertEquals("Leaked Connection Count", 0, bean.getLeakedConnectionCount()); assertEquals("Leaked Statement Count", 0, bean.getLeakedStatementCount()); assertEquals("Leaked ResultSet Count", 0, bean.getLeakedResultSetCount()); con.close(); bean = manager.getPoolStatistics("MYSQL"); assertEquals("Pool Name", "MYSQL", bean.getPoolName()); assertEquals("Bad Connections Count", 0, bean.getBadConnectionCount()); assertEquals("Connections High Count", 1, bean.getConnectionsHighCount()); assertEquals("Current Free Connections", 3, bean.getCurrentFreeConnectionCount()); assertEquals("Current Used Connection count", 0, bean.getCurrentUsedConnectionCount()); assertEquals("Leaked Connection Count", 0, bean.getLeakedConnectionCount()); assertEquals("Leaked Statement Count", 0, bean.getLeakedStatementCount()); assertEquals("Leaked ResultSet Count", 0, bean.getLeakedResultSetCount()); Connection con1 = dataSource.getConnection(); Connection con2 = dataSource.getConnection(); bean = manager.getPoolStatistics("MYSQL"); assertEquals("Pool Name", "MYSQL", bean.getPoolName()); assertEquals("Bad Connections Count", 0, bean.getBadConnectionCount()); assertEquals("Connections High Count", 2, bean.getConnectionsHighCount()); assertEquals("Current Free Connections", 1, bean.getCurrentFreeConnectionCount()); assertEquals("Current Used Connection count", 2, bean.getCurrentUsedConnectionCount()); assertEquals("Leaked Connection Count", 0, bean.getLeakedConnectionCount()); assertEquals("Leaked Statement Count", 0, bean.getLeakedStatementCount()); assertEquals("Leaked ResultSet Count", 0, bean.getLeakedResultSetCount()); con1.close(); con2.close(); bean = manager.getPoolStatistics("MYSQL"); assertEquals("Pool Name", "MYSQL", bean.getPoolName()); assertEquals("Bad Connections Count", 0, bean.getBadConnectionCount()); assertEquals("Connections High Count", 2, bean.getConnectionsHighCount()); assertEquals("Current Free Connections", 3, bean.getCurrentFreeConnectionCount()); assertEquals("Current Used Connection count", 0, bean.getCurrentUsedConnectionCount()); assertEquals("Leaked Connection Count", 0, bean.getLeakedConnectionCount()); assertEquals("Leaked Statement Count", 0, bean.getLeakedStatementCount()); assertEquals("Leaked ResultSet Count", 0, bean.getLeakedResultSetCount()); manager.destroy(true); testGetInstanceNull(); } catch (ConfigurationException e) { e.printStackTrace(); fail("Caught ConfigurationException"); } catch (ParseException e) { e.printStackTrace(); fail("Caught ParseException"); } catch (IOException e) { e.printStackTrace(); fail("Caught IOException"); } catch (SQLException e) { e.printStackTrace(); fail("Caught SQLException"); } catch (ClassNotFoundException e) { e.printStackTrace(); fail("Caught ClassNotFoundException"); } catch (Throwable t) { t.printStackTrace(); } finally { if (manager != null) manager.destroy(true); testGetInstanceNull(); } logger.debug("testGetDataSource end."); }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_1.CFAstDb2LUW.CFAstDb2LUWSchema.java
public boolean connect() { final String S_ProcName = "connect"; if (cnx != null) { return (false); }/*from w ww.j a v a 2 s.co m*/ if (configuration != null) { try { Class.forName("com.ibm.db2.jcc.DB2Driver"); } catch (ClassNotFoundException e) { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), "connect", "Could not load IBM DB/2 LUW 10.5 driver", e); } String dbServer = configuration.getDbServer(); int dbPort = configuration.getDbPort(); String dbDatabase = configuration.getDbDatabase(); String dbUserName = configuration.getDbUserName(); String dbPassword = configuration.getDbPassword(); String url = "jdbc:db2://" + dbServer + ":" + Integer.toString(dbPort) + "/" + dbDatabase; Properties props = new Properties(); props.setProperty("user", dbUserName); props.setProperty("password", dbPassword); try { cnx = DriverManager.getConnection(url, props); cnx.setAutoCommit(false); cnx.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); cnx.rollback(); setDbSchemaName(dbDatabase); } catch (SQLException e) { throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e); } return (true); } if (jndiName != null) { try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(jndiName); if (ds == null) { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Could not get resolve DataSource \"" + jndiName + "\""); } cnx = ds.getConnection(); if (cnx == null) { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Could not get Connection from PooledConnection for ConnectionPoolDataSource \"" + jndiName + "\""); } cnx.setAutoCommit(false); cnx.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); cnx.rollback(); } catch (NamingException e) { cnx = null; throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "NamingException " + e.getMessage(), e); } catch (SQLException e) { cnx = null; inTransaction = false; throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e); } return (true); } throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName, "Neither configurationFile nor jndiName found, do not know how to connect to database"); }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_1.CFAstOracle.CFAstOracleSchema.java
public boolean connect() { final String S_ProcName = "connect"; if (cnx != null) { return (false); }/*from w w w . ja va 2s .com*/ 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 = configuration.getDbUserName(); String dbPassword = configuration.getDbPassword(); 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(); setDbSchemaName(dbDatabase); } catch (SQLException e) { throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e); } return (true); } if (jndiName != null) { try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(jndiName); if (ds == null) { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Could not get resolve DataSource \"" + jndiName + "\""); } cnx = ds.getConnection(); if (cnx == null) { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Could not get Connection from PooledConnection for ConnectionPoolDataSource \"" + jndiName + "\""); } cnx.setAutoCommit(false); cnx.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); cnx.rollback(); } catch (NamingException e) { cnx = null; throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "NamingException " + e.getMessage(), e); } catch (SQLException e) { cnx = null; inTransaction = false; throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e); } return (true); } throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName, "Neither configurationFile nor jndiName found, do not know how to connect to database"); }