List of usage examples for org.apache.commons.dbcp BasicDataSource getConnection
public Connection getConnection() throws SQLException
From source file:org.jumpmind.symmetric.AbstractCommandLauncher.java
protected void testConnection() { try {//from ww w .j ava 2 s . c om BasicDataSource ds = ClientSymmetricEngine.createBasicDataSource(propertiesFile); Connection conn = ds.getConnection(); conn.close(); ds.close(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.mzd.shap.sql.FunctionalTable.java
/** * @param args/*from w ww .j a v a2 s. com*/ */ public static void main(String[] args) throws Exception { if (args.length != 2) { throw new Exception("Usage: [func_cat.txt] [cog-to-cat.txt]"); } BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUrl("jdbc:mysql://localhost/Dummy"); ds.setUsername("test"); ds.setPassword("xeno12"); Connection conn = ds.getConnection(); // Get the Sequence ID list. PreparedStatement insert = null; LineNumberReader reader = null; try { reader = new LineNumberReader(new FileReader(args[0])); insert = conn.prepareStatement("INSERT INTO CogCategories (code,function,class) values (?,?,?)"); while (true) { String line = reader.readLine(); if (line == null) { break; } String[] fields = line.split("\t"); if (fields.length != 3) { throw new Exception("Bad number of fields [" + fields.length + "] for line [" + line + "]"); } insert.setString(1, fields[0]); insert.setString(2, fields[1]); insert.setString(3, fields[2]); insert.executeUpdate(); } insert.close(); reader.close(); reader = new LineNumberReader(new FileReader(args[1])); insert = conn.prepareStatement("INSERT INTO CogFunctions (accession,code) values (?,?)"); while (true) { String line = reader.readLine(); if (line == null) { break; } String[] fields = line.split("\\s+"); if (fields.length != 2) { throw new Exception("Bad number of fields [" + fields.length + "] for line [" + line + "]"); } for (char code : fields[1].toCharArray()) { insert.setString(1, fields[0]); insert.setString(2, String.valueOf(code)); insert.executeUpdate(); } } insert.close(); } finally { if (reader != null) { reader.close(); } conn.close(); ds.close(); } }
From source file:org.mzd.shap.sql.UpdateFeatureTable.java
/** * @param args// ww w.j ava 2 s . c o m */ public static void main(String[] args) throws SQLException { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUrl("jdbc:mysql://localhost/BBay01a"); ds.setUsername("test"); ds.setPassword("xeno12"); Connection conn = ds.getConnection(); // Get the Sequence ID list. PreparedStatement select = null; PreparedStatement update = null; ResultSet result = null; select = conn.prepareStatement("SELECT DISTINCT SEQUENCE_ID FROM Features"); result = select.executeQuery(); List<Integer> sequenceIds = new ArrayList<Integer>(); result.beforeFirst(); while (result.next()) { sequenceIds.add(result.getInt(1)); } result.close(); select.close(); // Get the list of Feature IDs for this Sequence ID select = conn.prepareStatement("SELECT FEATURE_ID FROM Features WHERE SEQUENCE_ID=? ORDER BY start"); // Update the idx column for this feature id update = conn.prepareStatement("UPDATE Features SET featureOrder=? where FEATURE_ID=?"); for (Integer seqId : sequenceIds) { select.setInt(1, seqId); result = select.executeQuery(); int n = 0; result.beforeFirst(); while (result.next()) { int featId = result.getInt(1); update.setInt(1, n++); update.setInt(2, featId); if (update.executeUpdate() != 1) { System.out.println("Failed update [" + update.toString() + "]"); throw new SQLException(); } } result.close(); } update.close(); select.close(); conn.close(); ds.close(); }
From source file:org.olap4j.test.TestContext.java
/** * Factory method for the {@link Tester} * object which determines which driver to test. * * @param testContext Test context/*from w w w . ja va 2 s . c o m*/ * @param testProperties Properties that define the properties of the tester * @return a new Tester */ private static Tester createTester(TestContext testContext, Properties testProperties) { String helperClassName = testProperties.getProperty(Property.HELPER_CLASS_NAME.path); if (helperClassName == null) { helperClassName = "org.olap4j.XmlaTester"; if (!testProperties.containsKey(TestContext.Property.XMLA_CATALOG_URL.path)) { testProperties.setProperty(TestContext.Property.XMLA_CATALOG_URL.path, "dummy_xmla_catalog_url"); } } Tester tester; try { Class<?> clazz = Class.forName(helperClassName); final Constructor<?> constructor = clazz.getConstructor(TestContext.class); tester = (Tester) constructor.newInstance(testContext); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } // Apply a wrapper, if the "org.olap4j.test.wrapper" property is // specified. String wrapperName = testProperties.getProperty(Property.WRAPPER.path); Wrapper wrapper; if (wrapperName == null || wrapperName.equals("")) { wrapper = Wrapper.NONE; } else { try { wrapper = Enum.valueOf(Wrapper.class, wrapperName); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Unknown wrapper value '" + wrapperName + "'"); } } switch (wrapper) { case NONE: break; case DBCP: final BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(tester.getDriverClassName()); dataSource.setUrl(tester.getURL()); // need access to underlying connection so that we can call // olap4j-specific methods dataSource.setAccessToUnderlyingConnectionAllowed(true); tester = new DelegatingTester(tester) { public Connection createConnection() throws SQLException { return dataSource.getConnection(); } public Wrapper getWrapper() { return Wrapper.DBCP; } }; break; } return tester; }
From source file:org.openbravo.erpCommon.modules.ImportModule.java
/** * Inserts in database the Vector<DynaBean> with its dependencies * /*from ww w .ja v a2s . c o m*/ * @param dModulesToInstall * @param dependencies1 * @param newModule * @throws Exception */ private void insertDynaModulesInDB(Vector<DynaBean> dModulesToInstall, Vector<DynaBean> dependencies1, Vector<DynaBean> dbPrefix, boolean newModule) throws Exception { final Properties obProperties = new Properties(); obProperties.load(new FileInputStream(obDir + "/config/Openbravo.properties")); final String url = obProperties.getProperty("bbdd.url") + (obProperties.getProperty("bbdd.rdbms").equals("POSTGRE") ? "/" + obProperties.getProperty("bbdd.sid") : ""); final BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(obProperties.getProperty("bbdd.driver")); ds.setUrl(url); ds.setUsername(obProperties.getProperty("bbdd.user")); ds.setPassword(obProperties.getProperty("bbdd.password")); final Connection conn = ds.getConnection(); Integer seqNo = new Integer(ImportModuleData.selectSeqNo(pool)); for (final DynaBean module : dModulesToInstall) { seqNo += 10; module.set("ISDEFAULT", "N"); module.set("STATUS", "I"); module.set("SEQNO", seqNo); module.set("UPDATE_AVAILABLE", null); module.set("UPGRADE_AVAILABLE", null); log4j.info("Inserting in DB info for module: " + module.get("NAME")); String moduleId = (String) module.get("AD_MODULE_ID"); // Clean temporary tables ImportModuleData.cleanModuleInstall(pool, moduleId); ImportModuleData.cleanModuleDBPrefixInstall(pool, moduleId); ImportModuleData.cleanModuleDependencyInstall(pool, moduleId); String type = (String) module.get("TYPE"); String applyConfigScript = "Y"; if ("T".equals(type)) { if (newModule && V3_TEMPLATE_ID.equals(moduleId)) { // When installing V3 template do not apply its config script applyConfigScript = "N"; } else { org.openbravo.model.ad.module.Module template = OBDal.getInstance() .get(org.openbravo.model.ad.module.Module.class, moduleId); applyConfigScript = template == null ? "Y" : template.isApplyConfigurationScript() ? "Y" : "N"; } } // Insert data in temporary tables ImportModuleData.insertModuleInstall(pool, moduleId, (String) module.get("NAME"), (String) module.get("VERSION"), (String) module.get("DESCRIPTION"), (String) module.get("HELP"), (String) module.get("URL"), type, (String) module.get("LICENSE"), (String) module.get("ISINDEVELOPMENT"), (String) module.get("ISDEFAULT"), seqNo.toString(), (String) module.get("JAVAPACKAGE"), (String) module.get("LICENSETYPE"), (String) module.get("AUTHOR"), (String) module.get("STATUS"), (String) module.get("UPDATE_AVAILABLE"), (String) module.get("ISTRANSLATIONREQUIRED"), (String) module.get("AD_LANGUAGE"), (String) module.get("HASCHARTOFACCOUNTS"), (String) module.get("ISTRANSLATIONMODULE"), (String) module.get("HASREFERENCEDATA"), (String) module.get("ISREGISTERED"), (String) module.get("UPDATEINFO"), (String) module.get("UPDATE_VER_ID"), (String) module.get("REFERENCEDATAINFO"), applyConfigScript); // Set installed for modules being updated ImportModuleData.setModuleUpdated(pool, (String) module.get("AD_MODULE_ID")); addLog("@ModuleInstalled@ " + module.get("NAME") + " - " + module.get("VERSION"), MSG_SUCCESS); } for (final DynaBean module : dependencies1) { ImportModuleData.insertModuleDependencyInstall(pool, (String) module.get("AD_MODULE_DEPENDENCY_ID"), (String) module.get("AD_MODULE_ID"), (String) module.get("AD_DEPENDENT_MODULE_ID"), (String) module.get("STARTVERSION"), (String) module.get("ENDVERSION"), (String) module.get("ISINCLUDED"), (String) module.get("DEPENDANT_MODULE_NAME")); } for (final DynaBean module : dbPrefix) { ImportModuleData.insertModuleDBPrefixInstall(pool, (String) module.get("AD_MODULE_DBPREFIX_ID"), (String) module.get("AD_MODULE_ID"), (String) module.get("NAME")); } conn.close(); }
From source file:org.openlogics.gears.jdbc.TransactionInterceptorTest.java
@Before public void setup() { final BasicDataSource basicDataSource = new BasicDataSource(); try {/*from w w w.j av a 2s . c o m*/ basicDataSource.setUrl("jdbc:h2:mem:parametrostest"); basicDataSource.setDriverClassName("org.h2.Driver"); Connection connection = basicDataSource.getConnection(); URL sql = getResource(TestStub.class, "students.sql"); try { connection.createStatement().execute(Resources.toString(sql, US_ASCII)); connection.close(); URL resource = getResource(TestStub.class, "students.xml"); FlatXmlDataSet build = new FlatXmlDataSetBuilder().build(resource); DataSourceDatabaseTester databaseTester = new DataSourceDatabaseTester(basicDataSource); databaseTester.setDataSet(build); databaseTester.onSetup(); } catch (SQLException x) { } } catch (Exception x) { x.printStackTrace(); } Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { TransactionInterceptor tob = new TransactionInterceptor(); //requestInjection(tob); bindInterceptor(Matchers.any(), Matchers.annotatedWith(TransactionObservable.class), tob); //inject datastore bind(DataStore.class).toInstance(new JdbcDataStore(basicDataSource)); } }); injector.injectMembers(this); injector.injectMembers(fooDao); }
From source file:org.orbisgis.geoserver.h2gis.datastore.H2GISDataStoreFactory.java
@Override protected DataSource createDataSource(Map params, SQLDialect dialect) throws IOException { String database = (String) DATABASE.lookUp(params); String host = (String) HOST.lookUp(params); Boolean mvcc = (Boolean) MVCC.lookUp(params); Boolean mvstore = (Boolean) MVSTORE.lookUp(params); BasicDataSource dataSource = new BasicDataSource(); if (host != null && !host.equals("")) { Integer port = (Integer) PORT.lookUp(params); if (port != null) { dataSource.setUrl("jdbc:h2:tcp://" + host + ":" + port + "/" + database); } else {//w ww . j a v a2 s. c om dataSource.setUrl("jdbc:h2:tcp://" + host + "/" + database); } } else if (baseDirectory == null) { //use current working directory dataSource.setUrl("jdbc:h2:" + database + ";AUTO_SERVER=TRUE" + (mvcc != null ? (";MVCC=" + mvcc) : "") + (mvstore != null ? (";MVSTORE=" + mvstore) : "")); } else { //use directory specified if the patch is relative String location; if (!new File(database).isAbsolute()) { location = new File(baseDirectory, database).getAbsolutePath(); } else { location = database; } dataSource.setUrl("jdbc:h2:file:" + location + ";AUTO_SERVER=TRUE" + (mvcc != null ? (";MVCC=" + mvcc) : "") + (mvstore != null ? (";MVSTORE=" + mvstore) : "")); } String username = (String) USER.lookUp(params); if (username != null) { dataSource.setUsername(username); } String password = (String) PASSWD.lookUp(params); if (password != null) { dataSource.setPassword(password); } dataSource.setDriverClassName("org.h2.Driver"); dataSource.setPoolPreparedStatements(false); // if we got here the database has been created, now verify it has the H2GIS extension // and eventually try to create them JDBCDataStore closer = new JDBCDataStore(); Connection cx = null; try { cx = dataSource.getConnection(); //Add the spatial function if (!JDBCUtilities.tableExists(cx, "PUBLIC.GEOMETRY_COLUMNS")) { CreateSpatialExtension.initSpatialExtension(cx); } } catch (SQLException e) { throw new IOException("Failed to create the target database", e); } finally { closer.closeSafe(cx); } return new DBCPDataSource(dataSource); }
From source file:org.overlord.dtgov.devsvr.bpm.DTGovBpmDevServer.java
/** * Creates an in-memory datasource./*from w w w. j av a2 s. c om*/ * @throws SQLException */ private static DataSource createInMemoryDatasource() throws SQLException { System.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(Driver.class.getName()); ds.setUsername("sa"); ds.setPassword(""); ds.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"); Connection connection = ds.getConnection(); connection.close(); return ds; }
From source file:org.sonar.core.persistence.profiling.PersistenceProfilingTest.java
@Test public void should_enable_profiling_when_profiling_is_full() throws Exception { final Logger sqlLogger = (Logger) LoggerFactory.getLogger("sql"); ListAppender<ILoggingEvent> appender = new ListAppender<ILoggingEvent>(); appender.setContext(new ContextBase()); appender.start();//w w w . j a va 2 s. co m sqlLogger.addAppender(appender); BasicDataSource originDataSource = mock(BasicDataSource.class); Connection connection = mock(Connection.class); when(originDataSource.getConnection()).thenReturn(connection); String sql = "select 'polop' from dual;"; String sqlWithParams = "insert into polop (col1, col2, col3, col4) values (?, ?, ?, ?, ?);"; int param1 = 42; String param2 = "plouf"; Date param3 = new Date(System.currentTimeMillis()); Timestamp param4 = new Timestamp(System.currentTimeMillis()); byte[] param5 = "blob".getBytes("UTF-8"); PreparedStatement preparedStatement = mock(PreparedStatement.class); when(connection.prepareStatement(sqlWithParams)).thenReturn(preparedStatement); when(preparedStatement.execute()).thenReturn(true); Statement statement = mock(Statement.class); when(connection.createStatement()).thenReturn(statement); when(statement.execute(sql)).thenReturn(true); Settings settings = new Settings(); settings.setProperty(Profiling.CONFIG_PROFILING_LEVEL, Profiling.Level.FULL.toString()); BasicDataSource resultDataSource = PersistenceProfiling.addProfilingIfNeeded(originDataSource, settings); assertThat(resultDataSource).isInstanceOf(ProfilingDataSource.class); assertThat(resultDataSource.getUrl()).isNull(); assertThat(resultDataSource.getConnection().getClientInfo()).isNull(); PreparedStatement preparedStatementProxy = resultDataSource.getConnection().prepareStatement(sqlWithParams); preparedStatementProxy.setInt(1, param1); preparedStatementProxy.setString(2, param2); preparedStatementProxy.setDate(3, param3); preparedStatementProxy.setTimestamp(4, param4); preparedStatementProxy.setBlob(5, new ByteArrayInputStream(param5)); assertThat(preparedStatementProxy.getConnection()).isNull(); assertThat(preparedStatementProxy.execute()).isTrue(); final Statement statementProxy = resultDataSource.getConnection().createStatement(); assertThat(statementProxy.getConnection()).isNull(); assertThat(statementProxy.execute(sql)).isTrue(); assertThat(appender.list).hasSize(2); assertThat(appender.list.get(0).getLevel()).isEqualTo(Level.INFO); assertThat(appender.list.get(0).getFormattedMessage()).contains(sqlWithParams) .contains(" - parameters are: ").contains(Integer.toString(param1)).contains(param2); assertThat(appender.list.get(1).getLevel()).isEqualTo(Level.INFO); assertThat(appender.list.get(1).getFormattedMessage()).contains(sql); }
From source file:org.sonar.core.persistence.profiling.ProfiledDataSourceTest.java
@Test public void log_sql_requests() throws Exception { BasicDataSource originDataSource = mock(BasicDataSource.class); Connection connection = mock(Connection.class); when(originDataSource.getConnection()).thenReturn(connection); String sql = "select 'polop' from dual;"; String sqlWithParams = "insert into polop (col1, col2, col3, col4) values (?, ?, ?, ?, ?);"; int param1 = 42; String param2 = "plouf"; Date param3 = new Date(System.currentTimeMillis()); Timestamp param4 = new Timestamp(System.currentTimeMillis()); byte[] param5 = "blob".getBytes("UTF-8"); PreparedStatement preparedStatement = mock(PreparedStatement.class); when(connection.prepareStatement(sqlWithParams)).thenReturn(preparedStatement); when(preparedStatement.execute()).thenReturn(true); Statement statement = mock(Statement.class); when(connection.createStatement()).thenReturn(statement); when(statement.execute(sql)).thenReturn(true); ProfiledDataSource ds = new ProfiledDataSource(originDataSource); assertThat(ds.getUrl()).isNull();/*from w ww .j a v a2s . c o m*/ assertThat(ds.getConnection().getClientInfo()).isNull(); PreparedStatement preparedStatementProxy = ds.getConnection().prepareStatement(sqlWithParams); preparedStatementProxy.setInt(1, param1); preparedStatementProxy.setString(2, param2); preparedStatementProxy.setDate(3, param3); preparedStatementProxy.setTimestamp(4, param4); preparedStatementProxy.setBlob(5, new ByteArrayInputStream(param5)); assertThat(preparedStatementProxy.getConnection()).isNull(); assertThat(preparedStatementProxy.execute()).isTrue(); final Statement statementProxy = ds.getConnection().createStatement(); assertThat(statementProxy.getConnection()).isNull(); assertThat(statementProxy.execute(sql)).isTrue(); assertThat(logTester.logs()).hasSize(2); assertThat(logTester.logs().get(1)).contains(sql); }