List of usage examples for org.apache.commons.dbcp BasicDataSource getConnection
public Connection getConnection() throws SQLException
From source file:org.apache.lens.server.user.TestUserConfigLoader.java
/** * Setup hsql db.// w w w . ja v a2s .c om * * @param dbName the db name * @param path the path * @param changeLogPath the change log path * @throws SQLException the SQL exception * @throws LiquibaseException the liquibase exception */ private void setupHsqlDb(String dbName, String path, String changeLogPath) throws SQLException, LiquibaseException { Server server = new Server(); server.setLogWriter(new PrintWriter(System.out)); server.setErrWriter(new PrintWriter(System.out)); server.setSilent(true); server.setDatabaseName(0, dbName); server.setDatabasePath(0, "file:" + path); server.start(); BasicDataSource ds = UtilityMethods.getDataSourceFromConf(conf); Liquibase liquibase = new Liquibase(UserConfigLoader.class.getResource(changeLogPath).getFile(), new FileSystemResourceAccessor(), new HsqlConnection(ds.getConnection())); liquibase.update(""); }
From source file:org.apache.stratos.tenant.mgt.util.TenantMgtUtil.java
public static void deleteTenantUMData(int tenantId) throws Exception { RealmConfiguration realmConfig = TenantMgtServiceComponent.getRealmService() .getBootstrapRealmConfiguration(); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(realmConfig.getRealmProperty(JDBCRealmConstants.DRIVER_NAME)); dataSource.setUrl(realmConfig.getRealmProperty(JDBCRealmConstants.URL)); dataSource.setUsername(realmConfig.getRealmProperty(JDBCRealmConstants.USER_NAME)); dataSource.setPassword(realmConfig.getRealmProperty(JDBCRealmConstants.PASSWORD)); dataSource.setMaxActive(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_ACTIVE))); dataSource.setMinIdle(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MIN_IDLE))); dataSource.setMaxWait(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_WAIT))); TenantUMDataDeletionUtil.deleteTenantUMData(tenantId, dataSource.getConnection()); }
From source file:org.fao.geonet.arcgis.ArcSDEJdbcConnection.java
/** * * * @param connectionString An example of server string in case of Oracle * is: "jdbc:oracle:thin:@84.123.79.19:1521:orcl". * @param username the username to connect to the database. * @param password the password to connect to the database. *///from w ww .j a v a2s. c om public ArcSDEJdbcConnection(String driverName, String connectionString, String username, String password) { try { Log.debug(ARCSDE_LOG_MODULE_NAME, "Getting ArcSDE connection (via JDBC)"); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(driverName); dataSource.setUrl(connectionString); dataSource.setUsername(username); dataSource.setPassword(password); // Test the connection config getting a connection and closing it. dataSource.getConnection().close(); jdbcTemplate = new NamedParameterJdbcTemplate(dataSource); } catch (SQLException x) { Log.error(ARCSDE_LOG_MODULE_NAME, "Error getting ArcSDE connection (via JDBC)", x); throw new ExceptionInInitializerError(new ArcSDEConnectionException( "Exception in ArcSDEConnection using JDBC: can not connect to the database", x)); } }
From source file:org.geosde.core.jdbc.data.datasource.DataSourceUtil.java
/** * Builds up a default DBCP DataSource that easy to use connection factories * can use to setup a connection pool./*from ww w . ja v a 2 s.c o m*/ * * @param url * the jdbc url * @param driverName * the jdbc driver full qualified class name * @param username * @param password * @param maxActive maximum number of concurrent connections in the pool * @param minIdle minimum number of concurrent connections in the pool * @param validationQuery * the validation query to be used for connection liveliness on * borrow, or null, if no check is to be performed * @param cachePreparedStatements * wheter to cache prepared statements or not * @return * @throws DataSourceException */ public static ManageableDataSource buildDefaultDataSource(String url, String driverName, String username, String password, int maxActive, int minIdle, String validationQuery, boolean cachePreparedStatements, int removeAbandonedTimeout) throws DataSourceException { // basics BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(driverName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setAccessToUnderlyingConnectionAllowed(true); // pool size dataSource.setMaxActive(maxActive); dataSource.setMinIdle(minIdle); // pool eviction settings dataSource.setMinEvictableIdleTimeMillis(1000 * 20); dataSource.setTimeBetweenEvictionRunsMillis(1000 * 10); // connection validation if (validationQuery != null) { dataSource.setTestOnBorrow(true); dataSource.setValidationQuery(validationQuery); } // prepared statement cache if (cachePreparedStatements) { dataSource.setPoolPreparedStatements(true); dataSource.setMaxOpenPreparedStatements(10); } // remove abandoned connections (I know it's deprecated, but we do want // something shaving off lost connections. Let's give them 5 minutes of // continuous usage if (removeAbandonedTimeout > 0) { dataSource.setRemoveAbandoned(true); dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout); dataSource.setLogAbandoned(true); } Connection conn = null; try { conn = dataSource.getConnection(); } catch (Exception e) { throw new DataSourceException("Connection test failed ", e); } finally { if (conn != null) try { conn.close(); } catch (SQLException e) { } } return new DBCPDataSource(dataSource); }
From source file:org.geosde.core.jdbc.data.datasource.DBCPDataSourceFactory.java
public DataSource createNewDataSource(Map params) throws IOException { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName((String) DRIVERCLASS.lookUp(params)); dataSource.setUrl((String) JDBC_URL.lookUp(params)); dataSource.setUsername((String) USERNAME.lookUp(params)); dataSource.setPassword((String) PASSWORD.lookUp(params)); dataSource.setAccessToUnderlyingConnectionAllowed(true); dataSource.setMaxActive(((Integer) MAXACTIVE.lookUp(params)).intValue()); dataSource.setMaxIdle(((Integer) MAXIDLE.lookUp(params)).intValue()); // check the data source is properly setup by trying to gather a connection out of it Connection conn = null;//from ww w .j av a 2 s . co m try { conn = dataSource.getConnection(); } catch (SQLException e) { throw new DataSourceException("Connection pool improperly set up: " + e.getMessage(), e); } finally { // close the connection at once if (conn != null) try { conn.close(); } catch (SQLException e) { } } return dataSource; }
From source file:org.geoserver.spatialite.SpatiaLiteDataStoreFactory.java
static void initializeDataSource(BasicDataSource dataSource) throws IOException { //because of the way spatialite is loaded we need to instantiate and close // a connection, and the spatialite functions will be registered for all future // connections try {/*from ww w . j av a 2 s.c o m*/ Connection cx = dataSource.getConnection(); cx.close(); } catch (SQLException e) { throw (IOException) new IOException().initCause(e); } }
From source file:org.geotools.data.jdbc.ds.UnWrapperTest.java
public void testDBCPUnwrapper() throws SQLException, IOException { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName("org.h2.Driver"); ds.setUrl("jdbc:h2:mem:test_mem"); ds.setAccessToUnderlyingConnectionAllowed(true); Connection conn = ds.getConnection(); UnWrapper uw = DataSourceFinder.getUnWrapper(conn); assertNotNull(uw);/*from w w w . j a v a 2 s .co m*/ assertTrue(uw.canUnwrap(conn)); Connection unwrapped = uw.unwrap(conn); assertNotNull(unwrapped); assertTrue(unwrapped instanceof org.h2.jdbc.JdbcConnection); Statement st = conn.createStatement(); uw = DataSourceFinder.getUnWrapper(st); assertNotNull(uw); assertTrue(uw.canUnwrap(st)); Statement uwst = uw.unwrap(st); assertNotNull(uwst); assertTrue(uwst instanceof org.h2.jdbc.JdbcStatement); st.close(); PreparedStatement ps = conn.prepareStatement("select curtime()"); uw = DataSourceFinder.getUnWrapper(ps); assertNotNull(uw); assertTrue(uw.canUnwrap(ps)); PreparedStatement uwps = (PreparedStatement) uw.unwrap(ps); assertNotNull(uwps); assertTrue(uwps instanceof org.h2.jdbc.JdbcPreparedStatement); ps.close(); conn.close(); ds.close(); }
From source file:org.globus.workspace.testing.NimbusTestBase.java
private void quickResetDB() throws Exception, WorkspaceException, ReturnException { final BasicDataSource ds = (BasicDataSource) applicationContext.getBean(DATA_SOURCE_BEAN_NAME); final Connection conn = ds.getConnection(); try {/*from w w w .j a va2s . co m*/ conn.setAutoCommit(false); final DatabaseMetaData dmd = conn.getMetaData(); final ResultSet trs = dmd.getTables(null, "NIMBUS", null, null); while (trs.next()) { final String tableName = trs.getString("TABLE_NAME"); logger.debug("Deleting all rows from " + tableName); final Statement stmt = conn.createStatement(); stmt.executeUpdate("DELETE FROM " + tableName); } } finally { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } }
From source file:org.globus.workspace.testing.NimbusTestBase.java
private void shutdownDB() throws Exception { logger.info("Shutting down DB.."); BasicDataSource ds = (BasicDataSource) applicationContext.getBean(DATA_SOURCE_BEAN_NAME); ds.addConnectionProperty("shutdown", "true"); for (int i = 0; i < 1000; i++) { try {//ww w . j ava 2 s . c o m ds.getConnection(); Thread.sleep(10); } catch (SQLException e) { if (e.getSQLState().equals("08006") || e.getSQLState().equals("XJ004")) { logger.info("DB succesfully shutdown. ('" + e.getSQLState() + "')"); return; } else { logger.info("DB not shutdown yet ('" + e.getSQLState() + "')"); } } } throw new Exception("Could not shutdown DB!"); }
From source file:org.glowroot.plugin.jdbc.Connections.java
private static Connection createCommonsDbcpWrappedConnection() throws SQLException { // set up database BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName("org.hsqldb.jdbc.JDBCDriver"); ds.setUrl("jdbc:hsqldb:mem:test"); Connection connection = ds.getConnection(); insertRecords(connection);//from w ww . j a v a 2 s.c o m return connection; }