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:com.alibaba.druid.benckmark.pool.CaseKylin_mysql.java
private void p0(final DataSource dataSource, String name, int threadCount) throws Exception { final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; ++i) { Thread thread = new Thread() { public void run() { try { startLatch.await();/*from w ww . j a v a2 s . c om*/ for (int i = 0; i < LOOP_COUNT; ++i) { Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT 1 FROM DUAL"); ResultSet rs = stmt.executeQuery(); rs.next(); rs.getInt(1); rs.close(); stmt.close(); conn.close(); } } catch (Exception ex) { ex.printStackTrace(); } endLatch.countDown(); } }; thread.start(); } long startMillis = System.currentTimeMillis(); long startYGC = TestUtil.getYoungGC(); long startFullGC = TestUtil.getFullGC(); startLatch.countDown(); endLatch.await(); long millis = System.currentTimeMillis() - startMillis; long ygc = TestUtil.getYoungGC() - startYGC; long fullGC = TestUtil.getFullGC() - startFullGC; System.out.println("thread " + threadCount + " " + name + " millis : " + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC); }
From source file:org.accada.epcis.repository.query.QuerySubscription.java
/** * Updates the subscription in the database. This is required in order to * correctly re-initialize the subscriptions, especially the * lastTimeExecuted field, after a context restart. * <p>/* w ww.ja v a2 s. c o m*/ * TODO: This is a back-end method: move this method to the * QueryOperationsBackend and delegate to it (thus we would need a reference * to the QueryOperationsBackend in this class). * * @param lastTimeExecuted * The new lastTimeExecuted. */ private void updateSubscription(final GregorianCalendar lastTimeExecuted) { String jndiName = getProperties().getProperty("jndi.datasource.name", "java:comp/env/jdbc/EPCISDB"); try { // open a database connection Context ctx = new InitialContext(); DataSource db = (DataSource) ctx.lookup(jndiName); Connection dbconnection = db.getConnection(); // update the subscription in the database String update = "UPDATE subscription SET lastexecuted=(?), params=(?)" + " WHERE subscriptionid=(?);"; PreparedStatement stmt = dbconnection.prepareStatement(update); LOG.debug("SQL: " + update); Timestamp ts = new Timestamp(lastTimeExecuted.getTimeInMillis()); String time = ts.toString(); stmt.setString(1, time); LOG.debug(" query param 1: " + time); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(outStream); out.writeObject(queryParams); ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray()); stmt.setBinaryStream(2, inStream, inStream.available()); LOG.debug(" query param 2: [" + inStream.available() + " bytes]"); stmt.setString(3, subscriptionID); LOG.debug(" query param 3: " + subscriptionID); stmt.executeUpdate(); // close the database connection dbconnection.close(); } catch (SQLException e) { String msg = "An SQL error occurred while updating the subscriptions in the database."; LOG.error(msg, e); } catch (IOException e) { String msg = "Unable to update the subscription in the database: " + e.getMessage(); LOG.error(msg, e); } catch (NamingException e) { String msg = "Unable to find JNDI data source with name " + jndiName; LOG.error(msg, e); } }
From source file:com.alfaariss.oa.engine.requestor.jdbc.JDBCRequestorPool.java
private void addProperties(DataSource oDataSource, String sPoolPropertiesTable) throws RequestorException { Connection oConnection = null; PreparedStatement oPreparedStatement = null; ResultSet rsProperties = null; try {// ww w. j a va2s .c o m oConnection = oDataSource.getConnection(); StringBuffer sbSelectProperties = new StringBuffer("SELECT "); sbSelectProperties.append(sPoolPropertiesTable).append(".*"); sbSelectProperties.append(" FROM "); sbSelectProperties.append(sPoolPropertiesTable); sbSelectProperties.append(" WHERE "); sbSelectProperties.append(sPoolPropertiesTable); sbSelectProperties.append("."); sbSelectProperties.append(JDBCRequestorPool.COLUMN_PROPERTY_POOL_ID); sbSelectProperties.append("=?"); oPreparedStatement = oConnection.prepareStatement(sbSelectProperties.toString()); oPreparedStatement.setString(1, _sID); rsProperties = oPreparedStatement.executeQuery(); _properties = new Properties(); while (rsProperties.next()) { String sName = rsProperties.getString(JDBCRequestorPool.COLUMN_PROPERTY_NAME); Object value = rsProperties.getString(JDBCRequestorPool.COLUMN_PROPERTY_VALUE); _properties.put(sName, value); } _logger.debug("Retrieved requestorpool-properties: " + _properties); } catch (SQLException e) { _logger.error("Can not read from database", e); throw new RequestorException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (Exception e) { _logger.fatal("Internal error during create of a requestorpool", e); throw new RequestorException(SystemErrors.ERROR_INTERNAL); } finally { try { if (rsProperties != null) rsProperties.close(); } catch (Exception e) { _logger.error("Could not close resultset", e); } try { if (oPreparedStatement != null) oPreparedStatement.close(); } catch (Exception e) { _logger.error("Could not close statement", e); } try { if (oConnection != null) oConnection.close(); } catch (Exception e) { _logger.error("Could not close connection", e); } } }
From source file:org.craftercms.cstudio.alfresco.objectstate.ObjectStateDAOServiceImpl.java
@Override public void initIndexes() { DataSource dataSource = _sqlMapClient.getDataSource(); Connection connection = null; int oldval = -1; try {/* w ww. ja v a 2 s .c om*/ connection = dataSource.getConnection(); oldval = connection.getTransactionIsolation(); if (oldval != Connection.TRANSACTION_READ_COMMITTED) { connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); } List<HashMap> checkTable = _sqlMapClient.queryForList(STATEMENT_CHECK_TABLE_EXISTS); if (checkTable == null || checkTable.size() < 1) { ScriptRunner scriptRunner = new ScriptRunner(connection, false, true); scriptRunner.runScript(Resources.getResourceAsReader(initializeScriptPath)); } else { Integer checkColumnCTEUsername = (Integer) _sqlMapClient.queryForObject(STATEMENT_CHECK_PATH_SIZE); if (checkColumnCTEUsername < 2000) { ScriptRunner scriptRunner = new ScriptRunner(connection, false, true); scriptRunner.runScript(Resources.getResourceAsReader( initializeScriptPath.replace("initialize.sql", "alter_path_column_size.sql"))); } } List<HashMap> indexCheckResult = _sqlMapClient.queryForList(STATEMENT_CHECK_OBJECT_IDX); if (indexCheckResult == null || indexCheckResult.size() < 1) { _sqlMapClient.insert(STATEMENT_ADD_OBJECT_IDX); } connection.commit(); if (oldval != -1) { connection.setTransactionIsolation(oldval); } } catch (SQLException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error while initializing Object State table DB indexes.", e); } } catch (IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error while initializing Sequence table DB indexes.", e); } } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { } connection = null; } } }
From source file:com.alfaariss.oa.engine.requestor.jdbc.JDBCRequestorPool.java
private void addAuthenticationProfiles(DataSource oDataSource, String sAuthenticationTable) throws RequestorException { Connection oConnection = null; PreparedStatement oPreparedStatement = null; ResultSet oResultSet = null;/*from w ww .j av a 2 s. c o m*/ try { oConnection = oDataSource.getConnection(); StringBuffer sbSelect = new StringBuffer("SELECT "); sbSelect.append(COLUMN_AUTHENTICATION_ID); sbSelect.append(" FROM "); sbSelect.append(sAuthenticationTable); sbSelect.append(" WHERE "); sbSelect.append(COLUMN_AUTHENTICATION_POOLID); sbSelect.append("=? ORDER BY "); sbSelect.append(COLUMN_ORDER_ID); sbSelect.append(" ASC"); oPreparedStatement = oConnection.prepareStatement(sbSelect.toString()); oPreparedStatement.setString(1, _sID); oResultSet = oPreparedStatement.executeQuery(); while (oResultSet.next()) { String sAuthenticationProfileID = oResultSet.getString(COLUMN_AUTHENTICATION_ID); super.addAuthenticationProfileID(sAuthenticationProfileID); } } catch (SQLException e) { _logger.error("Can not read from database", e); throw new RequestorException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (Exception e) { _logger.fatal("Internal error during retrieval of requestors", e); throw new RequestorException(SystemErrors.ERROR_INTERNAL); } finally { try { if (oResultSet != null) oResultSet.close(); } catch (Exception e) { _logger.error("Could not close resultset", e); } try { if (oPreparedStatement != null) oPreparedStatement.close(); } catch (Exception e) { _logger.error("Could not close statement", e); } try { if (oConnection != null) oConnection.close(); } catch (Exception e) { _logger.error("Could not close connection", e); } } }
From source file:de.griffel.confluence.plugins.plantuml.AbstractDatabaseStructureMacroImpl.java
/** * Returns database meta data./*from w ww . j av a 2 s .co m*/ * * Returned object must be closed using "closeDatabaseMetaData" * * @param jdbcName Database which is configured at "java:comp/env/jdbc/<jdbcName>" * @return Connection or null if none could be made. _errorMessage contains reason in the latter case. */ private DatabaseMetaData openDatabaseMetaData() { Context jndiContext = null; DatabaseMetaData dbmd = null; try { jndiContext = new InitialContext(); javax.sql.DataSource ds = (javax.sql.DataSource) jndiContext .lookup("java:comp/env/jdbc/" + _macroParams.getDatasource()); try { _con = ds.getConnection(); dbmd = _con.getMetaData(); } catch (SQLException e) { sqlException(_macroParams.getDatasource(), e); } } catch (NamingException e) { _errorMessage = e.getMessage(); log.error("NamingException " + _macroParams.getDatasource() + _errorMessage, e); } finally { if (jndiContext != null) { try { jndiContext.close(); } catch (NamingException e2) { log.debug("Exception closing JNDI context", e2); } } } return dbmd; }
From source file:org.apache.cayenne.tools.dbimport.DefaultDbImportAction.java
@Override public void execute(DbImportConfiguration config) throws Exception { if (logger.isDebugEnabled()) { logger.debug("DB connection: " + config.getDataSourceInfo()); logger.debug(config);/*from w w w .ja v a 2 s. co m*/ } boolean hasChanges = false; DataNodeDescriptor dataNodeDescriptor = config.createDataNodeDescriptor(); DataSource dataSource = dataSourceFactory.getDataSource(dataNodeDescriptor); DbAdapter adapter = adapterFactory.createAdapter(dataNodeDescriptor, dataSource); ObjectNameGenerator objectNameGenerator = config.createNameGenerator(); DataMap sourceDataMap; try (Connection connection = dataSource.getConnection()) { sourceDataMap = load(config, adapter, connection); } DataMap targetDataMap = existingTargetMap(config); if (targetDataMap == null) { String path = config.getTargetDataMap() == null ? "null" : config.getTargetDataMap().getAbsolutePath() + "'"; logger.info(""); logger.info("Map file does not exist. Loaded db model will be saved into '" + path); hasChanges = true; targetDataMap = newTargetDataMap(config); } // transform source DataMap before merging transformSourceBeforeMerge(sourceDataMap, targetDataMap, config); MergerTokenFactory mergerTokenFactory = mergerTokenFactoryProvider.get(adapter); DbLoaderConfiguration loaderConfig = config.getDbLoaderConfig(); List<MergerToken> tokens = DataMapMerger.builder(mergerTokenFactory) .filters(loaderConfig.getFiltersConfig()).skipPKTokens(loaderConfig.isSkipPrimaryKeyLoading()) .skipRelationshipsTokens(loaderConfig.isSkipRelationshipsLoading()).build() .createMergeTokens(targetDataMap, sourceDataMap); hasChanges |= syncDataMapProperties(targetDataMap, config); hasChanges |= applyTokens(config.createMergeDelegate(), targetDataMap, log(sort(reverse(mergerTokenFactory, tokens))), objectNameGenerator, config.createMeaningfulPKFilter(), config.isUsePrimitives()); hasChanges |= syncProcedures(targetDataMap, sourceDataMap, loaderConfig.getFiltersConfig()); if (hasChanges) { saveLoaded(targetDataMap); } }
From source file:com.alibaba.druid.benckmark.pool.Oracle_Case4.java
private void p0(final DataSource dataSource, String name, int threadCount) throws Exception { final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; ++i) { Thread thread = new Thread() { public void run() { try { startLatch.await();//from w ww.ja va 2 s. c o m for (int i = 0; i < LOOP_COUNT; ++i) { Connection conn = dataSource.getConnection(); int mod = i % 500; String sql = SQL; // + " AND ROWNUM <= " + (mod + 1); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, 61); ResultSet rs = stmt.executeQuery(); int rowCount = 0; while (rs.next()) { rowCount++; } // Assert.isTrue(!rs.isClosed()); rs.close(); // Assert.isTrue(!stmt.isClosed()); stmt.close(); Assert.isTrue(stmt.isClosed()); conn.close(); Assert.isTrue(conn.isClosed()); } } catch (Exception ex) { ex.printStackTrace(); } endLatch.countDown(); } }; thread.start(); } long startMillis = System.currentTimeMillis(); long startYGC = TestUtil.getYoungGC(); long startFullGC = TestUtil.getFullGC(); startLatch.countDown(); endLatch.await(); long millis = System.currentTimeMillis() - startMillis; long ygc = TestUtil.getYoungGC() - startYGC; long fullGC = TestUtil.getFullGC() - startFullGC; System.out.println("thread " + threadCount + " " + name + " millis : " + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC); }
From source file:kenh.xscript.database.elements.Connection.java
public void process(@Attribute(ATTRIBUTE_VARIABLE) String var, @Attribute(ATTRIBUTE_SOURCE) DataSource source, @Attribute(ATTRIBUTE_AUTO_COMMIT) boolean autoCommit) throws UnsupportedScriptException { var = StringUtils.trimToEmpty(var); if (StringUtils.isBlank(var)) { UnsupportedScriptException ex = new UnsupportedScriptException(this, "Variable name is empty."); throw ex; }/* w w w. j a va 2s . c o m*/ if (source == null) { UnsupportedScriptException ex = new UnsupportedScriptException(this, "Data source is empty."); throw ex; } try { kenh.xscript.database.wrap.Connection conn = new kenh.xscript.database.wrap.Connection( source.getConnection()); conn.setAutoCommit(autoCommit); this.saveVariable(var, conn, null); } catch (SQLException e) { throw new UnsupportedScriptException(this, e); } }
From source file:org.intalio.deploy.deployment.impl.ClusteredDeployServiceDeployTest.java
public void setUp() throws Exception { PropertyConfigurator.configure(new File(TestUtils.getTestBase(), "log4j.properties").getAbsolutePath()); Utils.deleteRecursively(_deployDir); XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("clustered-test.xml")); cluster = (ClusterProxy) factory.getBean("cluster"); cluster.startUpProcesses();/*w ww. ja va 2s . c om*/ Thread.sleep(6000); cluster.setNodes((List<ClusteredNode>) factory.getBean("nodes")); // setup database DataSource ds = cluster.getDataSource(); ClassPathResource script = new ClassPathResource("deploy.derby.sql"); if (script == null) throw new IOException("Unable to find file: deploy.derby.sql"); SQLScript sql = new SQLScript(script.getInputStream(), ds); sql.setIgnoreErrors(true); sql.setInteractive(false); sql.executeScript(); Connection c = ds.getConnection(); EasyStatement.execute(c, "DELETE FROM DEPLOY_RESOURCES"); EasyStatement.execute(c, "DELETE FROM DEPLOY_COMPONENTS"); EasyStatement.execute(c, "DELETE FROM DEPLOY_ASSEMBLIES"); c.close(); }