package com.sample.rmcustom.common.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.User;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.security.userdetails.jdbc.JdbcDaoImpl;
/**
*
* This class represents Customized UserDetailsService implementation
* <li>Wired in applicationContext-security.xml with bean name ‘userDetailsService’</li>
*/
public class CustomJdbcDaoImpl extends JdbcDaoImpl {
public static final String USER_BY_USERNAME_QRY = “SELECT username,password,enabled,exp_date ”
+ “FROM schema.users ” + “WHERE username = ?”;
public static final String USER_AUTHORITIES_BY_USERNAME_QUERY =
“SELECT username,authority ” +
“FROM schema.authorities ” +
“WHERE username = ?”;
private String rolePrefix = “”;
private MappingSqlQuery usersByUsernameMappingQry;
private MappingSqlQuery authoritiesByUsernameMapping;
private String schema = “sample”;
/**
* This method is used to load user details
*/
@SuppressWarnings(“unchecked”)
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
String schemaName = “pcivok”;
setSchema(schemaName);
List users = loadUsersByUsername(username);
if (users.size() == 0) {
throw new UsernameNotFoundException(messages.getMessage(
“JdbcDaoImpl.notFound”, new Object[] { username },
“Username {0} not found”), username);
}
UserDetails user = (UserDetails) users.get(0); // contains no GrantedAuthority[]
Set dbAuthsSet = new HashSet();
if (getEnableAuthorities()) {
dbAuthsSet.addAll(loadUserAuthorities(user.getUsername()));
}
if (getEnableGroups()) {
dbAuthsSet.addAll(loadGroupAuthorities(user.getUsername()));
}
List dbAuths = new ArrayList(dbAuthsSet);
addCustomAuthorities(user.getUsername(), dbAuths);
if (dbAuths.size() == 0) {
throw new UsernameNotFoundException(messages.getMessage(
“JdbcDaoImpl.noAuthority”, new Object[] { username },
“User {0} has no GrantedAuthority”), username);
}
GrantedAuthority[] arrayAuths = (GrantedAuthority[]) dbAuths
.toArray(new GrantedAuthority[dbAuths.size()]);
return createUserDetails(username, user, arrayAuths);
}
/**
* Executes the <tt>usersByUsernameMappingQry</tt> and returns a list of UserDetails objects (there should normally
* only be one matching user).
*/
protected List loadUsersByUsername(String username) {
this.usersByUsernameMappingQry = new CustomQryUsersByUsernameMapping(
getDataSource());
return usersByUsernameMappingQry.execute(username);
}
protected List loadUserAuthorities(String username) {
this.authoritiesByUsernameMapping = new CustomAuthoritiesByUsernameMapping(getDataSource());
return authoritiesByUsernameMapping.execute(username);
}
public static String getQuery( String qry, String schema) {
qry = qry.replace(“schema”, schema);
return qry;
}
/**
* Query object to look up a user.
*/
private class CustomQryUsersByUsernameMapping extends MappingSqlQuery {
protected CustomQryUsersByUsernameMapping(DataSource ds) {
super(ds, getQuery(USER_BY_USERNAME_QRY, schema));
declareParameter(new SqlParameter(Types.VARCHAR));
compile();
}
protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
String username = rs.getString(1);
String password = rs.getString(2);
String enabledStr = rs.getString(3);
java.sql.Date expDate = rs.getDate(4);
boolean enabled = false;
boolean nonExpired = false;
if (enabledStr.equals(“1″)) {
enabled = true;
}
Calendar today = Calendar.getInstance();
if (expDate.after(today.getTime()))
nonExpired = true;
UserDetails user = new User(
username,
password,
enabled,
nonExpired,
true,
true,
new GrantedAuthority[] { new GrantedAuthorityImpl(“HOLDER”) });
return user;
}
}
/**
* Query object to look up a user’s authorities.
*/
private class CustomAuthoritiesByUsernameMapping extends MappingSqlQuery {
protected CustomAuthoritiesByUsernameMapping(DataSource ds) {
super(ds, getQuery(USER_AUTHORITIES_BY_USERNAME_QUERY, schema));
declareParameter(new SqlParameter(Types.VARCHAR));
compile();
}
protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
String roleName = rolePrefix + rs.getString(2);
GrantedAuthorityImpl authority = new GrantedAuthorityImpl(roleName);
return authority;
}
}
/**
* @return the schema
*/
public String getSchema() {
return schema;
}
/**
* @param schema the schema to set
*/
public void setSchema(String schema) {
this.schema = schema;
}
}
———————————————————————————————-
package com.sample.custom.common.services;
import java.math.BigDecimal;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.TransactionException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import com.sample.custom.bo.User;
public class UserDaoService extends HibernateDaoSupport {
PlatformTransactionManager transactionManager;
/**
* @return transactionManager
*/
public PlatformTransactionManager getTransactionManager() {
return transactionManager;
}
/**
* This method allows spring framework to inject transaction manager. Used
* by hibernate applicationContext-security.xml file currently sets this to
* org.springframework.orm.hibernate3.HibernateTransactionManager
*
* @param PlatformTransactionManager
* txManager
*/
public void setTransactionManager(PlatformTransactionManager txManager) {
this.transactionManager = txManager;
}
public Integer getnextUserId() {
BigDecimal userId = (BigDecimal) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
SQLQuery q = session.createSQLQuery(“select max(USER_ID) from pcivok.USERS”);
return q.uniqueResult();
}
});
if(userId == null){
return 0;
}else{
return userId.intValue();
}
}
public void updateUser(final User user) {
TransactionTemplate txTemplate = new TransactionTemplate(
getTransactionManager());
try {
txTemplate.execute(new TransactionCallbackWithoutResult() {
public void doInTransactionWithoutResult(
TransactionStatus status) {
getHibernateTemplate().saveOrUpdate(user);
}
});
} catch (TransactionException e) {
throw e;
}
}
}