List of usage examples for org.springframework.jdbc.datasource DataSourceUtils releaseConnection
public static void releaseConnection(@Nullable Connection con, @Nullable DataSource dataSource)
From source file:cc.tooyoung.common.db.JdbcTemplate.java
/** * try 3 times to get connection//from w ww . ja v a 2 s . co m * @param ds * @return * @throws CannotGetJdbcConnectionException */ private Connection safeGetConnection(DataSource ds, boolean isWrite) throws CannotGetJdbcConnectionException { Connection con = null; int retryCount, count; retryCount = count = (isWrite ? writeTryGetConCount : readTryGetConCount); while (count-- > 0) { try { con = DataSourceUtils.getConnection(ds); return con; } catch (CannotGetJdbcConnectionException e) { ApiLogger.info(new StringBuilder(64).append("get connection try count:") .append((retryCount - count)).append(", ds=") .append(((com.mchange.v2.c3p0.ComboPooledDataSource) ds).getJdbcUrl())); DataSourceUtils.releaseConnection(con, ds); } } ApiLogger.fire(new StringBuffer().append("DB ") .append(((com.mchange.v2.c3p0.ComboPooledDataSource) ds).getJdbcUrl()).append(" Error:") .append("Could not get JDBC Connection: ")); throw new CannotGetJdbcConnectionException("Could not get JDBC Connection: " + ", ds=" + ((com.mchange.v2.c3p0.ComboPooledDataSource) ds).getJdbcUrl(), new SQLException()); }
From source file:lib.JdbcTemplate.java
@Override public <T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action) throws DataAccessException { Assert.notNull(psc, "PreparedStatementCreator must not be null"); Assert.notNull(action, "Callback object must not be null"); if (logger.isDebugEnabled()) { String sql = getSql(psc); logger.debug("Executing prepared SQL statement" + (sql != null ? " [" + sql + "]" : "")); }/*from w ww. ja v a 2 s .co m*/ Connection con = DataSourceUtils.getConnection(getDataSource()); PreparedStatement ps = null; try { Connection conToUse = con; if (this.nativeJdbcExtractor != null && this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativePreparedStatements()) { conToUse = this.nativeJdbcExtractor.getNativeConnection(con); } ps = psc.createPreparedStatement(conToUse); applyStatementSettings(ps); PreparedStatement psToUse = ps; if (this.nativeJdbcExtractor != null) { psToUse = this.nativeJdbcExtractor.getNativePreparedStatement(ps); } T result = action.doInPreparedStatement(psToUse); handleWarnings(ps); return result; } catch (SQLException ex) { // Release Connection early, to avoid potential connection pool deadlock // in the case when the exception translator hasn't been initialized yet. if (psc instanceof ParameterDisposer) { ((ParameterDisposer) psc).cleanupParameters(); } String sql = getSql(psc); psc = null; JdbcUtils.closeStatement(ps); ps = null; DataSourceUtils.releaseConnection(con, getDataSource()); con = null; throw getExceptionTranslator().translate("PreparedStatementCallback", sql, ex); } finally { if (psc instanceof ParameterDisposer) { ((ParameterDisposer) psc).cleanupParameters(); } JdbcUtils.closeStatement(ps); DataSourceUtils.releaseConnection(con, getDataSource()); } }
From source file:cc.tooyoung.common.db.JdbcTemplate.java
public Object execute(PreparedStatementCreator psc, PreparedStatementCallback action, boolean isWrite) throws DataAccessException { Assert.notNull(psc, "PreparedStatementCreator must not be null"); Assert.notNull(action, "Callback object must not be null"); if (ApiLogger.isTraceEnabled()) { String sql = getSql(psc); ApiLogger.trace(new StringBuilder(128).append("Executing prepared SQL statement") .append((sql != null ? " [" + sql + "]" : ""))); }/* w ww .j ava 2 s . co m*/ long start = System.currentTimeMillis(); DataSource ds = getDataSource(isWrite); Connection con = safeGetConnection(ds, isWrite); PreparedStatement ps = null; try { Connection conToUse = con; if (this.nativeJdbcExtractor != null && this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativePreparedStatements()) { conToUse = this.nativeJdbcExtractor.getNativeConnection(con); } ps = psc.createPreparedStatement(conToUse); applyStatementSettings(ds, ps); PreparedStatement psToUse = ps; if (this.nativeJdbcExtractor != null) { psToUse = this.nativeJdbcExtractor.getNativePreparedStatement(ps); } Object result = action.doInPreparedStatement(psToUse); handleWarnings(ps); return result; } catch (Exception ex) { // Release Connection early, to avoid potential connection pool deadlock // in the case when the exception translator hasn't been initialized yet. if (psc instanceof ParameterDisposer) { ((ParameterDisposer) psc).cleanupParameters(); } String sql = getSql(psc); psc = null; JdbcUtils.closeStatement(ps); ps = null; DataSourceUtils.releaseConnection(con, ds); con = null; if (ex instanceof SQLException) { throw getExceptionTranslator(ds).translate("PreparedStatementCallback", sql, (SQLException) ex); } else { throw new RuntimeException("PreparedStatementCallback " + getSql(psc), ex); } } finally { //add slow log long useTime = System.currentTimeMillis() - start; if (useTime > ApiLogger.DB_FIRE_TIME) { ApiLogger.fire(new StringBuffer().append("DB ") .append(((com.mchange.v2.c3p0.ComboPooledDataSource) ds).getJdbcUrl()).append(" too slow :") .append(useTime).append(" isWrite:").append(isWrite)); } if (psc instanceof ParameterDisposer) { ((ParameterDisposer) psc).cleanupParameters(); } JdbcUtils.closeStatement(ps); DataSourceUtils.releaseConnection(con, ds); TimeStatUtil.addElapseTimeStat(resource, isWrite, start, useTime); } }
From source file:annis.administration.DefaultAdministrationDao.java
private void bulkloadTableFromResource(String table, Resource resource) { log.debug("bulk-loading data from '" + resource.getFilename() + "' into table '" + table + "'"); String sql = "COPY " + table + " FROM STDIN WITH DELIMITER E'\t' NULL AS 'NULL'"; try {// ww w . jav a 2 s . c o m // retrieve the currently open connection if running inside a transaction Connection con = DataSourceUtils.getConnection(dataSource); // Postgres JDBC4 8.4 driver now supports the copy API PGConnection pgCon = (PGConnection) con; pgCon.getCopyAPI().copyIn(sql, resource.getInputStream()); DataSourceUtils.releaseConnection(con, dataSource); } catch (SQLException e) { throw new DatabaseAccessException(e); } catch (IOException e) { throw new FileAccessException(e); } }
From source file:cc.tooyoung.common.db.JdbcTemplate.java
public Object execute(CallableStatementCreator csc, CallableStatementCallback action, boolean isWrite) throws DataAccessException { Assert.notNull(csc, "CallableStatementCreator must not be null"); Assert.notNull(action, "Callback object must not be null"); if (ApiLogger.isTraceEnabled()) { String sql = getSql(csc); ApiLogger.trace("Calling stored procedure" + (sql != null ? " [" + sql + "]" : "")); }//from www .j a v a 2s. co m long start = System.currentTimeMillis(); DataSource ds = getDataSource(isWrite); Connection con = safeGetConnection(ds, isWrite); CallableStatement cs = null; try { Connection conToUse = con; if (this.nativeJdbcExtractor != null) { conToUse = this.nativeJdbcExtractor.getNativeConnection(con); } cs = csc.createCallableStatement(conToUse); applyStatementSettings(ds, cs); CallableStatement csToUse = cs; if (this.nativeJdbcExtractor != null) { csToUse = this.nativeJdbcExtractor.getNativeCallableStatement(cs); } Object result = action.doInCallableStatement(csToUse); handleWarnings(cs); return result; } catch (Exception ex) { // Release Connection early, to avoid potential connection pool deadlock // in the case when the exception translator hasn't been initialized yet. if (csc instanceof ParameterDisposer) { ((ParameterDisposer) csc).cleanupParameters(); } String sql = getSql(csc); csc = null; JdbcUtils.closeStatement(cs); cs = null; DataSourceUtils.releaseConnection(con, ds); con = null; if (ex instanceof SQLException) { throw getExceptionTranslator(ds).translate("CallableStatementCallback", sql, (SQLException) ex); } else { throw new RuntimeException("CallableStatementCallback " + getSql(csc), ex); } } finally { //add slow log long useTime = System.currentTimeMillis() - start; if (useTime > ApiLogger.DB_FIRE_TIME) { ApiLogger.fire(new StringBuffer().append("DB ") .append(((com.mchange.v2.c3p0.ComboPooledDataSource) ds).getJdbcUrl()).append(" too slow :") .append(useTime).append(" isWrite:").append(isWrite)); } if (csc instanceof ParameterDisposer) { ((ParameterDisposer) csc).cleanupParameters(); } JdbcUtils.closeStatement(cs); DataSourceUtils.releaseConnection(con, ds); TimeStatUtil.addElapseTimeStat(resource, isWrite, start, useTime); } }
From source file:lib.JdbcTemplate.java
@Override public <T> T execute(CallableStatementCreator csc, CallableStatementCallback<T> action) throws DataAccessException { Assert.notNull(csc, "CallableStatementCreator must not be null"); Assert.notNull(action, "Callback object must not be null"); if (logger.isDebugEnabled()) { String sql = getSql(csc); logger.debug("Calling stored procedure" + (sql != null ? " [" + sql + "]" : "")); }// w w w.j a va2 s . co m Connection con = DataSourceUtils.getConnection(getDataSource()); CallableStatement cs = null; try { Connection conToUse = con; if (this.nativeJdbcExtractor != null) { conToUse = this.nativeJdbcExtractor.getNativeConnection(con); } cs = csc.createCallableStatement(conToUse); applyStatementSettings(cs); CallableStatement csToUse = cs; if (this.nativeJdbcExtractor != null) { csToUse = this.nativeJdbcExtractor.getNativeCallableStatement(cs); } T result = action.doInCallableStatement(csToUse); handleWarnings(cs); return result; } catch (SQLException ex) { // Release Connection early, to avoid potential connection pool deadlock // in the case when the exception translator hasn't been initialized yet. if (csc instanceof ParameterDisposer) { ((ParameterDisposer) csc).cleanupParameters(); } String sql = getSql(csc); csc = null; JdbcUtils.closeStatement(cs); cs = null; DataSourceUtils.releaseConnection(con, getDataSource()); con = null; throw getExceptionTranslator().translate("CallableStatementCallback", sql, ex); } finally { if (csc instanceof ParameterDisposer) { ((ParameterDisposer) csc).cleanupParameters(); } JdbcUtils.closeStatement(cs); DataSourceUtils.releaseConnection(con, getDataSource()); } }
From source file:annis.administration.AdministrationDao.java
private void bulkloadTableFromResource(String table, Resource resource) { log.debug("bulk-loading data from '" + resource.getFilename() + "' into table '" + table + "'"); String sql = "COPY " + table + " FROM STDIN WITH DELIMITER E'\t' NULL AS 'NULL'"; try {// w w w . j a v a 2s. c o m // retrieve the currently open connection if running inside a transaction Connection originalCon = DataSourceUtils.getConnection(getDataSource()); Connection con = originalCon; if (con instanceof DelegatingConnection) { DelegatingConnection<?> delCon = (DelegatingConnection<?>) con; con = delCon.getInnermostDelegate(); } Preconditions.checkState(con instanceof PGConnection, "bulk-loading only works with a PostgreSQL JDBC connection"); // Postgres JDBC4 8.4 driver now supports the copy API PGConnection pgCon = (PGConnection) con; pgCon.getCopyAPI().copyIn(sql, resource.getInputStream()); DataSourceUtils.releaseConnection(originalCon, getDataSource()); } catch (SQLException e) { throw new DatabaseAccessException(e); } catch (IOException e) { throw new FileAccessException(e); } }
From source file:org.agnitas.beans.impl.MailingImpl.java
@Override public boolean triggerMailing(int maildropStatusID, Hashtable<String, Object> opts, ApplicationContext con) { Mailgun aMailgun = null;//ww w . j av a2 s . c o m DataSource ds = (DataSource) con.getBean("dataSource"); Connection dbCon = DataSourceUtils.getConnection(ds); boolean exitValue = true; try { if (maildropStatusID == 0) { throw new Exception("maildropStatusID is 0"); } aMailgun = (Mailgun) con.getBean("Mailgun"); aMailgun.initializeMailgun(Integer.toString(maildropStatusID)); aMailgun.prepareMailgun(new Hashtable<String, Object>()); aMailgun.executeMailgun(opts); } catch (Exception e) { logger.error("triggerMailing", e); exitValue = false; } DataSourceUtils.releaseConnection(dbCon, ds); return exitValue; }
From source file:org.agnitas.dao.impl.ImportRecipientsDaoImpl.java
@Override public LinkedHashMap<String, Map<String, Object>> getColumnInfoByColumnName(int companyId, String column) { DataSource ds = (DataSource) applicationContext.getBean("dataSource"); LinkedHashMap<String, Map<String, Object>> list = new LinkedHashMap<String, Map<String, Object>>(); ResultSet resultSet = null;/*from ww w. j a va2 s . c om*/ Connection con = DataSourceUtils.getConnection(ds); try { if (AgnUtils.isOracleDB()) { resultSet = con.getMetaData().getColumns(null, AgnUtils.getDefaultValue("jdbc.username").toUpperCase(), "CUSTOMER_" + companyId + "_TBL", column.toUpperCase()); } else { resultSet = con.getMetaData().getColumns(null, null, "customer_" + companyId + "_tbl", column); } if (resultSet != null) { while (resultSet.next()) { String type; String col = resultSet.getString(4).toLowerCase(); Map<String, Object> mapping = new HashMap<String, Object>(); mapping.put("column", col); mapping.put("shortname", col); type = ImportUtils.dbtype2string(resultSet.getInt(5)); mapping.put("type", type); mapping.put("length", resultSet.getInt(7)); if (resultSet.getInt(11) == DatabaseMetaData.columnNullable) { mapping.put("nullable", 1); } else { mapping.put("nullable", 0); } list.put((String) mapping.get("shortname"), mapping); } } resultSet.close(); } catch (Exception e) { logger.error(MessageFormat.format("Failed to get column ({0}) info for admin ({1})", column, companyId), e); // TODO: Check this: is "admin" in combination with companyId correct here??? } finally { DataSourceUtils.releaseConnection(con, ds); } return list; }
From source file:org.agnitas.dao.impl.RecipientDaoImpl.java
/** * Load complete Subscriber-Data from DB. customerID must be set first for this method. * * @return Map with Key/Value-Pairs of customer data *///from w w w . ja v a 2 s. c o m @Override public CaseInsensitiveMap<Object> getCustomerDataFromDb(int companyID, int customerID) { String aName = null; String aValue = null; int a; java.sql.Timestamp aTime = null; Recipient cust = (Recipient) applicationContext.getBean("Recipient"); if (cust.getCustParameters() == null) { cust.setCustParameters(new CaseInsensitiveMap<Object>()); } String getCust = "SELECT * FROM customer_" + companyID + "_tbl WHERE customer_id=" + customerID; if (cust.getCustDBStructure() == null) { cust.loadCustDBStructure(); } DataSource ds = (DataSource) this.applicationContext.getBean("dataSource"); Connection con = DataSourceUtils.getConnection(ds); try { Statement stmt = con.createStatement(); ResultSet rset = stmt.executeQuery(getCust); if (logger.isInfoEnabled()) { logger.info("getCustomerDataFromDb: " + getCust); } if (rset.next()) { ResultSetMetaData aMeta = rset.getMetaData(); for (a = 1; a <= aMeta.getColumnCount(); a++) { aValue = null; aName = aMeta.getColumnName(a).toLowerCase(); switch (aMeta.getColumnType(a)) { case java.sql.Types.TIMESTAMP: case java.sql.Types.TIME: case java.sql.Types.DATE: try { aTime = rset.getTimestamp(a); } catch (Exception e) { aTime = null; } if (aTime == null) { cust.getCustParameters().put(aName + "_DAY_DATE", ""); cust.getCustParameters().put(aName + "_MONTH_DATE", ""); cust.getCustParameters().put(aName + "_YEAR_DATE", ""); cust.getCustParameters().put(aName + "_HOUR_DATE", ""); cust.getCustParameters().put(aName + "_MINUTE_DATE", ""); cust.getCustParameters().put(aName + "_SECOND_DATE", ""); cust.getCustParameters().put(aName, ""); } else { GregorianCalendar aCal = new GregorianCalendar(); aCal.setTime(aTime); cust.getCustParameters().put(aName + "_DAY_DATE", Integer.toString(aCal.get(GregorianCalendar.DAY_OF_MONTH))); cust.getCustParameters().put(aName + "_MONTH_DATE", Integer.toString(aCal.get(GregorianCalendar.MONTH) + 1)); cust.getCustParameters().put(aName + "_YEAR_DATE", Integer.toString(aCal.get(GregorianCalendar.YEAR))); cust.getCustParameters().put(aName + "_HOUR_DATE", Integer.toString(aCal.get(GregorianCalendar.HOUR_OF_DAY))); cust.getCustParameters().put(aName + "_MINUTE_DATE", Integer.toString(aCal.get(GregorianCalendar.MINUTE))); cust.getCustParameters().put(aName + "_SECOND_DATE", Integer.toString(aCal.get(GregorianCalendar.SECOND))); SimpleDateFormat bdfmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); cust.getCustParameters().put(aName, bdfmt.format(aCal.getTime())); } break; default: aValue = rset.getString(a); if (aValue == null) { aValue = ""; } cust.getCustParameters().put(aName, aValue); break; } } } rset.close(); stmt.close(); } catch (Exception e) { logger.error("getCustomerDataFromDb: " + getCust, e); AgnUtils.sendExceptionMail("sql:" + getCust, e); } DataSourceUtils.releaseConnection(con, ds); cust.setChangeFlag(false); Map<String, Object> result = cust.getCustParameters(); if (result instanceof CaseInsensitiveMap) { return (CaseInsensitiveMap<Object>) result; } else { return new CaseInsensitiveMap<Object>(result); } }