Search in sources :

Example 11 with PreparedStatementSetter

use of org.springframework.jdbc.core.PreparedStatementSetter in project uPortal by Jasig.

the class HibernateStyleCounterStore method getNextIdInternal.

private int getNextIdInternal(final Optimizer optimizer, final String counterName) {
    return (Integer) optimizer.generate(new AccessCallback() {

        @Override
        public IntegralDataTypeHolder getNextValue() {
            IntegralDataTypeHolder rslt = null;
            for (int i = 0; rslt == null && i < MAX_ATTEMPTS; i++) {
                rslt = transactionOperations.execute(new TransactionCallback<IntegralDataTypeHolder>() {

                    @Override
                    public IntegralDataTypeHolder doInTransaction(TransactionStatus status) {
                        final IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder(identifierType.getReturnedClass());
                        // Try and load the current value,
                        // returns true if the expected row
                        // exists, null otherwise
                        final boolean selected = jdbcOperations.query(SELECT_QUERY, new ResultSetExtractor<Boolean>() {

                            @Override
                            public Boolean extractData(ResultSet rs) throws SQLException, DataAccessException {
                                if (rs.next()) {
                                    value.initialize(rs, 1);
                                    return true;
                                }
                                return false;
                            }
                        }, counterName);
                        // it
                        if (!selected) {
                            value.initialize(initialValue);
                            jdbcOperations.update(INSERT_QUERY, new PreparedStatementSetter() {

                                @Override
                                public void setValues(PreparedStatement ps) throws SQLException {
                                    ps.setString(1, counterName);
                                    value.bind(ps, 2);
                                }
                            });
                        }
                        // Increment the counter row value
                        final IntegralDataTypeHolder updateValue = value.copy();
                        if (optimizer.applyIncrementSizeToSourceValues()) {
                            updateValue.add(incrementSize);
                        } else {
                            updateValue.increment();
                        }
                        // Update the counter row, if rows
                        // returns 0 the update failed due to a
                        // race condition, it will be retried
                        int rowsAltered = jdbcOperations.update(UPDATE_QUERY, new PreparedStatementSetter() {

                            @Override
                            public void setValues(PreparedStatement ps) throws SQLException {
                                updateValue.bind(ps, 1);
                                ps.setString(2, counterName);
                                value.bind(ps, 3);
                            }
                        });
                        return rowsAltered > 0 ? // Success
                        value : // Failed;  try again...
                        null;
                    }
                });
            }
            if (rslt == null) {
                throw new RuntimeException("Failed to fetch a new batch of sequence values after " + MAX_ATTEMPTS + " tries");
            }
            return rslt;
        }
    });
}
Also used : SQLException(java.sql.SQLException) TransactionStatus(org.springframework.transaction.TransactionStatus) PreparedStatementSetter(org.springframework.jdbc.core.PreparedStatementSetter) PreparedStatement(java.sql.PreparedStatement) AccessCallback(org.hibernate.id.enhanced.AccessCallback) TransactionCallback(org.springframework.transaction.support.TransactionCallback) ResultSet(java.sql.ResultSet) IntegralDataTypeHolder(org.hibernate.id.IntegralDataTypeHolder) DataAccessException(org.springframework.dao.DataAccessException)

Example 12 with PreparedStatementSetter

use of org.springframework.jdbc.core.PreparedStatementSetter in project spring-security-oauth by spring-projects.

the class JdbcApprovalStore method purgeExpiredApprovals.

public boolean purgeExpiredApprovals() {
    logger.debug("Purging expired approvals from database");
    try {
        int deleted = jdbcTemplate.update(deleteApprovalStatment + " where expiresAt <= ?", new PreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setTimestamp(1, new Timestamp(new Date().getTime()));
            }
        });
        logger.debug(deleted + " expired approvals deleted");
    } catch (DataAccessException ex) {
        logger.error("Error purging expired approvals", ex);
        return false;
    }
    return true;
}
Also used : SQLException(java.sql.SQLException) PreparedStatementSetter(org.springframework.jdbc.core.PreparedStatementSetter) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) Date(java.util.Date) DataAccessException(org.springframework.dao.DataAccessException)

Example 13 with PreparedStatementSetter

use of org.springframework.jdbc.core.PreparedStatementSetter in project spring-security-oauth by spring-projects.

the class JdbcApprovalStore method revokeApprovals.

@Override
public boolean revokeApprovals(Collection<Approval> approvals) {
    logger.debug(String.format("Revoking approvals: [%s]", approvals));
    boolean success = true;
    for (final Approval approval : approvals) {
        if (handleRevocationsAsExpiry) {
            int refreshed = jdbcTemplate.update(expireApprovalStatement, new PreparedStatementSetter() {

                @Override
                public void setValues(PreparedStatement ps) throws SQLException {
                    ps.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
                    ps.setString(2, approval.getUserId());
                    ps.setString(3, approval.getClientId());
                    ps.setString(4, approval.getScope());
                }
            });
            if (refreshed != 1) {
                success = false;
            }
        } else {
            int refreshed = jdbcTemplate.update(deleteApprovalStatment, new PreparedStatementSetter() {

                @Override
                public void setValues(PreparedStatement ps) throws SQLException {
                    ps.setString(1, approval.getUserId());
                    ps.setString(2, approval.getClientId());
                    ps.setString(3, approval.getScope());
                }
            });
            if (refreshed != 1) {
                success = false;
            }
        }
    }
    return success;
}
Also used : SQLException(java.sql.SQLException) PreparedStatementSetter(org.springframework.jdbc.core.PreparedStatementSetter) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp)

Example 14 with PreparedStatementSetter

use of org.springframework.jdbc.core.PreparedStatementSetter in project spring-security by spring-projects.

the class JdbcUserDetailsManager method createUser.

// ~ UserDetailsManager implementation
// ==============================================================================
public void createUser(final UserDetails user) {
    validateUserDetails(user);
    getJdbcTemplate().update(createUserSql, new PreparedStatementSetter() {

        public void setValues(PreparedStatement ps) throws SQLException {
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setBoolean(3, user.isEnabled());
        }
    });
    if (getEnableAuthorities()) {
        insertUserAuthorities(user);
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatementSetter(org.springframework.jdbc.core.PreparedStatementSetter) PreparedStatement(java.sql.PreparedStatement)

Example 15 with PreparedStatementSetter

use of org.springframework.jdbc.core.PreparedStatementSetter in project spring-security by spring-projects.

the class JdbcUserDetailsManager method removeUserFromGroup.

public void removeUserFromGroup(final String username, final String groupName) {
    logger.debug("Removing user '" + username + "' to group '" + groupName + "'");
    Assert.hasText(username, "username should have text");
    ;
    Assert.hasText(groupName, "groupName should have text");
    ;
    final int id = findGroupId(groupName);
    getJdbcTemplate().update(deleteGroupMemberSql, new PreparedStatementSetter() {

        public void setValues(PreparedStatement ps) throws SQLException {
            ps.setInt(1, id);
            ps.setString(2, username);
        }
    });
    userCache.removeUserFromCache(username);
}
Also used : SQLException(java.sql.SQLException) PreparedStatementSetter(org.springframework.jdbc.core.PreparedStatementSetter) PreparedStatement(java.sql.PreparedStatement)

Aggregations

PreparedStatementSetter (org.springframework.jdbc.core.PreparedStatementSetter)22 SQLException (java.sql.SQLException)13 PreparedStatement (java.sql.PreparedStatement)12 List (java.util.List)5 Timestamp (java.sql.Timestamp)4 Date (java.util.Date)4 ArgumentPreparedStatementSetter (org.springframework.jdbc.core.ArgumentPreparedStatementSetter)4 JdbcTemplate (org.springframework.jdbc.core.JdbcTemplate)4 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)3 Map (java.util.Map)3 SqlParameterValue (org.springframework.jdbc.core.SqlParameterValue)3 Lists (com.google.common.collect.Lists)2 ResultSet (java.sql.ResultSet)2 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 DataSource (javax.sql.DataSource)2 SessionFactory (org.hibernate.SessionFactory)2 SortOrder (org.hisp.dhis.analytics.SortOrder)2 DataStatisticsEvent (org.hisp.dhis.datastatistics.DataStatisticsEvent)2