List of usage examples for java.sql PreparedStatement setQueryTimeout
void setQueryTimeout(int seconds) throws SQLException;
Statement
object to execute to the given number of seconds. From source file:org.seasar.dbflute.s2dao.jdbc.TnStatementFactoryImpl.java
protected void doReflectStatementOptions(PreparedStatement ps, StatementConfig actualConfig) { if (actualConfig == null || !actualConfig.hasStatementOptions()) { return;//from w w w. j av a2 s .com } try { if (actualConfig.hasQueryTimeout()) { final Integer queryTimeout = actualConfig.getQueryTimeout(); if (isInternalDebugEnabled()) { _log.debug("...Setting queryTimeout of statement: " + queryTimeout); } ps.setQueryTimeout(queryTimeout); } if (actualConfig.hasFetchSize()) { final Integer fetchSize = actualConfig.getFetchSize(); if (isInternalDebugEnabled()) { _log.debug("...Setting fetchSize of statement: " + fetchSize); } ps.setFetchSize(fetchSize); } if (actualConfig.hasMaxRows()) { final Integer maxRows = actualConfig.getMaxRows(); if (isInternalDebugEnabled()) { _log.debug("...Setting maxRows of statement: " + maxRows); } ps.setMaxRows(maxRows); } } catch (SQLException e) { handleSQLException(e, ps); } }
From source file:org.springframework.batch.item.database.AbstractCursorItemReader.java
/** * Prepare the given JDBC Statement (or PreparedStatement or * CallableStatement), applying statement settings such as fetch size, max * rows, and query timeout. @param stmt the JDBC Statement to prepare * * @param stmt {@link java.sql.PreparedStatement} to be configured * * @throws SQLException if interactions with provided stmt fail * * @see #setFetchSize//from w w w. ja v a2 s .com * @see #setMaxRows * @see #setQueryTimeout */ protected void applyStatementSettings(PreparedStatement stmt) throws SQLException { if (fetchSize != VALUE_NOT_SET) { stmt.setFetchSize(fetchSize); stmt.setFetchDirection(ResultSet.FETCH_FORWARD); } if (maxRows != VALUE_NOT_SET) { stmt.setMaxRows(maxRows); } if (queryTimeout != VALUE_NOT_SET) { stmt.setQueryTimeout(queryTimeout); } }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
private void doTestStrings(JdbcTemplateCallback jdbcTemplateCallback, boolean usePreparedStatement, Integer fetchSize, Integer maxRows, Integer queryTimeout, Object argument) throws Exception { String sql = "SELECT FORENAME FROM CUSTMR"; String[] results = { "rod", "gary", " portia" }; class StringHandler implements RowCallbackHandler { private List list = new LinkedList(); public void processRow(ResultSet rs) throws SQLException { list.add(rs.getString(1));// w ww . j a v a2 s . c o m } public String[] getStrings() { return (String[]) list.toArray(new String[list.size()]); } } MockControl ctrlResultSet = MockControl.createControl(ResultSet.class); ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock(); mockResultSet.next(); ctrlResultSet.setReturnValue(true); mockResultSet.getString(1); ctrlResultSet.setReturnValue(results[0]); mockResultSet.next(); ctrlResultSet.setReturnValue(true); mockResultSet.getString(1); ctrlResultSet.setReturnValue(results[1]); mockResultSet.next(); ctrlResultSet.setReturnValue(true); mockResultSet.getString(1); ctrlResultSet.setReturnValue(results[2]); mockResultSet.next(); ctrlResultSet.setReturnValue(false); mockResultSet.close(); ctrlResultSet.setVoidCallable(); MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class); PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock(); if (fetchSize != null) { mockStatement.setFetchSize(fetchSize.intValue()); } if (maxRows != null) { mockStatement.setMaxRows(maxRows.intValue()); } if (queryTimeout != null) { mockStatement.setQueryTimeout(queryTimeout.intValue()); } if (argument != null) { mockStatement.setObject(1, argument); } if (usePreparedStatement) { mockStatement.executeQuery(); } else { mockStatement.executeQuery(sql); } ctrlStatement.setReturnValue(mockResultSet); if (debugEnabled) { mockStatement.getWarnings(); ctrlStatement.setReturnValue(null); } mockStatement.close(); ctrlStatement.setVoidCallable(); if (usePreparedStatement) { mockConnection.prepareStatement(sql); } else { mockConnection.createStatement(); } ctrlConnection.setReturnValue(mockStatement); ctrlResultSet.replay(); ctrlStatement.replay(); replay(); StringHandler sh = new StringHandler(); JdbcTemplate template = new JdbcTemplate(); template.setDataSource(mockDataSource); if (fetchSize != null) { template.setFetchSize(fetchSize.intValue()); } if (maxRows != null) { template.setMaxRows(maxRows.intValue()); } if (queryTimeout != null) { template.setQueryTimeout(queryTimeout.intValue()); } jdbcTemplateCallback.doInJdbcTemplate(template, sql, sh); // Match String[] forenames = sh.getStrings(); assertTrue("same length", forenames.length == results.length); for (int i = 0; i < forenames.length; i++) { assertTrue("Row " + i + " matches", forenames[i].equals(results[i])); } ctrlResultSet.verify(); ctrlStatement.verify(); }
From source file:org.wso2.carbon.dataservices.core.description.query.SQLQuery.java
private PreparedStatement createProcessedPreparedStatement(int queryType, InternalParamCollection params, Connection conn) throws DataServiceFault { try {//from w w w . j a va 2 s . c o m /* * lets see first if there's already a batch prepared statement * created */ boolean inTheMiddleOfABatch = false; PreparedStatement stmt = this.getBatchPreparedStatement(); int currentParamCount = this.getParamCount(); /* create a new prepared statement */ if (stmt == null) { /* batch mode is not supported for dynamic queries */ Object[] result = this.processDynamicQuery(this.getQuery(), params); String dynamicSQL = (String) result[0]; currentParamCount = (Integer) result[1]; String processedSQL = this.createProcessedQuery(dynamicSQL, params, currentParamCount); if (queryType == SQLQuery.DS_QUERY_TYPE_NORMAL) { if (this.isReturnGeneratedKeys()) { if (this.getKeyColumns() != null) { stmt = conn.prepareStatement(processedSQL, this.getKeyColumns()); } else { stmt = conn.prepareStatement(processedSQL, Statement.RETURN_GENERATED_KEYS); } } else { stmt = conn.prepareStatement(processedSQL); } } else if (queryType == SQLQuery.DS_QUERY_TYPE_STORED_PROC) { stmt = conn.prepareCall(processedSQL); } else { throw new DataServiceFault("Unsupported query type: " + queryType); } } else { inTheMiddleOfABatch = true; } if (!inTheMiddleOfABatch) { /* set query timeout */ if (this.isHasQueryTimeout()) { stmt.setQueryTimeout(this.getQueryTimeout()); } /* adding the try catch to avoid setting this for jdbc drivers that do not implement this method. */ try { /* set fetch direction */ if (this.isHasFetchDirection()) { stmt.setFetchDirection(this.getFetchDirection()); } /* set fetch size - user's setting */ if (this.isHasFetchSize()) { stmt.setFetchSize(this.getFetchSize()); } else { /* * stream data by sections - avoid the full result set * to be loaded to memory, and only stream if there * aren't any OUT parameters, MySQL fails in the * scenario of streaming and OUT parameters, so the * possibility is there for other DBMSs */ if (!this.hasOutParams() && this.getFetchSizeProperty().isChangeFetchSize()) { stmt.setFetchSize(this.getFetchSizeProperty().getFetchSize()); } } } catch (Throwable e) { log.debug("Exception while setting fetch size: " + e.getMessage(), e); } /* set max field size */ if (this.isHasMaxFieldSize()) { stmt.setMaxFieldSize(this.getMaxFieldSize()); } /* set max rows */ if (this.isHasMaxRows()) { stmt.setMaxRows(this.getMaxRows()); } } int currentOrdinal = 0; InternalParam param; ParamValue value; for (int i = 1; i <= currentParamCount; i++) { param = params.getParam(i); value = param.getValue(); /* * handle array values, if value is null, this param has to be * an OUT param */ if (value != null && value.getValueType() == ParamValue.PARAM_VALUE_ARRAY) { for (ParamValue arrayElement : value.getArrayValue()) { this.setParamInPreparedStatement(stmt, param, arrayElement == null ? null : arrayElement.toString(), queryType, currentOrdinal); currentOrdinal++; } } else { /* scalar value */ this.setParamInPreparedStatement(stmt, param, value != null ? value.getScalarValue() : null, queryType, currentOrdinal); currentOrdinal++; } } /* if we are in JDBC batch processing mode, batch it! */ if (this.isJDBCBatchRequest()) { stmt.addBatch(); } return stmt; } catch (SQLException e) { throw new DataServiceFault(e, "Error in 'createProcessedPreparedStatement'"); } }
From source file:org.wso2.carbon.identity.user.store.count.jdbc.internal.InternalCountRetriever.java
public Long countRoles(String filter) throws UserStoreCounterException { Connection dbConnection = null; String sqlStmt = null;//from w w w .j a v a2 s.co m PreparedStatement prepStmt = null; ResultSet resultSet = null; try { dbConnection = getDBConnection(); if (filter.startsWith(UserCoreConstants.INTERNAL_DOMAIN)) { sqlStmt = InternalStoreCountConstants.COUNT_INTERNAL_ONLY_ROLES_SQL; filter = filter.replace(UserCoreConstants.INTERNAL_DOMAIN, ""); } else { sqlStmt = InternalStoreCountConstants.COUNT_INTERNAL_ROLES_SQL; } prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setString(1, filter); prepStmt.setInt(2, tenantId); prepStmt.setQueryTimeout(searchTime); resultSet = prepStmt.executeQuery(); if (resultSet.next()) { return resultSet.getLong("RESULT"); } else { log.error("No role count is retrieved for Internal domain filter:" + filter); return Long.valueOf(-1); } } catch (SQLException e) { if (log.isDebugEnabled()) { log.debug("Using sql : " + sqlStmt); } throw new UserStoreCounterException(e.getMessage(), e); } catch (Exception e) { throw new UserStoreCounterException(e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, resultSet, prepStmt); } }
From source file:org.wso2.carbon.identity.user.store.count.jdbc.internal.InternalCountRetriever.java
public Long countInternalRoles(String filter) throws UserStoreCounterException { Connection dbConnection = null; String sqlStmt = null;//from w ww .j ava 2s. c om PreparedStatement prepStmt = null; ResultSet resultSet = null; try { dbConnection = getDBConnection(); sqlStmt = InternalStoreCountConstants.COUNT_INTERNAL_ROLES_SQL; prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setString(1, filter); prepStmt.setInt(2, tenantId); prepStmt.setQueryTimeout(searchTime); resultSet = prepStmt.executeQuery(); if (resultSet.next()) { return resultSet.getLong("RESULT"); } else { log.error("No role count is retrieved for Internal domain filter:" + filter); return Long.valueOf(-1); } } catch (SQLException e) { if (log.isDebugEnabled()) { log.debug("Using sql : " + sqlStmt); } throw new UserStoreCounterException(e.getMessage(), e); } catch (Exception e) { throw new UserStoreCounterException(e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, resultSet, prepStmt); } }
From source file:org.wso2.carbon.identity.user.store.count.jdbc.JDBCUserStoreCountRetriever.java
@Override public Long countUsers(String filter) throws UserStoreCounterException { Connection dbConnection = null; String sqlStmt = null;/* ww w. java2s.co m*/ PreparedStatement prepStmt = null; ResultSet resultSet = null; try { dbConnection = getDBConnection(realmConfiguration); sqlStmt = JDBCUserStoreMetricsConstants.COUNT_USERS_SQL; prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setString(1, "%" + filter + "%"); prepStmt.setInt(2, tenantId); prepStmt.setQueryTimeout(searchTime); resultSet = prepStmt.executeQuery(); if (resultSet.next()) { return resultSet.getLong("RESULT"); } else { log.error("No user count is retrieved from the user store"); return Long.valueOf(-1); } } catch (SQLException e) { if (log.isDebugEnabled()) { log.debug("Using sql : " + sqlStmt); } throw new UserStoreCounterException(e.getMessage(), e); } catch (Exception e) { throw new UserStoreCounterException(e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, resultSet, prepStmt); } }
From source file:org.wso2.carbon.identity.user.store.count.jdbc.JDBCUserStoreCountRetriever.java
@Override public Long countRoles(String filter) throws UserStoreCounterException { Connection dbConnection = null; String sqlStmt = null;// ww w.j a v a 2 s . c o m PreparedStatement prepStmt = null; ResultSet resultSet = null; try { dbConnection = getDBConnection(realmConfiguration); sqlStmt = JDBCUserStoreMetricsConstants.COUNT_ROLES_SQL; prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setString(1, "%" + filter + "%"); prepStmt.setInt(2, tenantId); prepStmt.setQueryTimeout(searchTime); resultSet = prepStmt.executeQuery(); if (resultSet.next()) { return resultSet.getLong("RESULT"); } else { log.error("No role count is retrieved from the user store."); return Long.valueOf(-1); } } catch (SQLException e) { if (log.isDebugEnabled()) { log.debug("Using sql : " + sqlStmt); } throw new UserStoreCounterException(e.getMessage(), e); } catch (Exception e) { throw new UserStoreCounterException(e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, resultSet, prepStmt); } }
From source file:org.wso2.carbon.identity.user.store.count.jdbc.JDBCUserStoreCountRetriever.java
@Override public Long countClaim(String claimURI, String valueFilter) throws UserStoreCounterException { Connection dbConnection = null; String sqlStmt = null;/*from ww w . j a va 2 s .co m*/ PreparedStatement prepStmt = null; ResultSet resultSet = null; String mappedAttribute = null; try { String domainName = realmConfiguration .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); if (StringUtils.isEmpty(domainName)) { domainName = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME; } UserRealm userRealm = UserStoreCountDSComponent.getRealmService().getTenantUserRealm(tenantId); if (StringUtils.isNotEmpty(claimURI)) { mappedAttribute = userRealm.getClaimManager().getAttributeName(domainName, claimURI); } dbConnection = getDBConnection(realmConfiguration); sqlStmt = JDBCUserStoreMetricsConstants.COUNT_CLAIM_SQL; prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setString(1, mappedAttribute); prepStmt.setInt(2, tenantId); prepStmt.setString(3, "%" + valueFilter + "%"); prepStmt.setString(4, UserCoreConstants.DEFAULT_PROFILE); prepStmt.setQueryTimeout(searchTime); resultSet = prepStmt.executeQuery(); if (resultSet.next()) { return resultSet.getLong("RESULT"); } else { log.error("No claim count is retrieved from the user store."); return Long.valueOf(-1); } } catch (SQLException e) { if (log.isDebugEnabled()) { log.debug("Using sql : " + sqlStmt); } throw new UserStoreCounterException(e.getMessage(), e); } catch (Exception e) { throw new UserStoreCounterException(e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, resultSet, prepStmt); } }
From source file:org.wso2.carbon.user.core.hybrid.HybridRoleManager.java
/** * @param filter/*from ww w . jav a 2 s . c o m*/ * @return * @throws UserStoreException */ public String[] getHybridRoles(String filter) throws UserStoreException { Connection dbConnection = null; PreparedStatement prepStmt = null; ResultSet rs = null; String sqlStmt = HybridJDBCConstants.GET_ROLES; int maxItemLimit = UserCoreConstants.MAX_USER_ROLE_LIST; int searchTime = UserCoreConstants.MAX_SEARCH_TIME; try { maxItemLimit = Integer.parseInt( realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_ROLE_LIST)); } catch (Exception e) { maxItemLimit = DEFAULT_MAX_ROLE_LIST_SIZE; } try { searchTime = Integer.parseInt( realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_SEARCH_TIME)); } catch (Exception e) { searchTime = DEFAULT_MAX_SEARCH_TIME; } try { if (filter != null && filter.trim().length() != 0) { filter = filter.trim(); filter = filter.replace("*", "%"); filter = filter.replace("?", "_"); } else { filter = "%"; } dbConnection = DatabaseUtil.getDBConnection(dataSource); if (dbConnection == null) { throw new UserStoreException("null connection"); } dbConnection.setAutoCommit(false); dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setString(1, filter); if (sqlStmt.contains(UserCoreConstants.UM_TENANT_COLUMN)) { prepStmt.setInt(2, tenantId); } prepStmt.setMaxRows(maxItemLimit); try { prepStmt.setQueryTimeout(searchTime); } catch (Exception e) { // this can be ignored since timeout method is not implemented log.debug(e); } List<String> filteredRoles = new ArrayList<String>(); try { rs = prepStmt.executeQuery(); } catch (SQLException e) { log.error("Error while retrieving roles from Internal JDBC role store", e); // May be due time out, therefore ignore this exception } if (rs != null) { while (rs.next()) { String name = rs.getString(1); // Append the domain if (!name.contains(UserCoreConstants.DOMAIN_SEPARATOR)) { name = UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR + name; } filteredRoles.add(name); } } return filteredRoles.toArray(new String[filteredRoles.size()]); } catch (SQLException e) { String errorMessage = "Error occurred while getting hybrid roles from filter : " + filter; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt); } }