daoserv

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;
}
}

}

util2

package com.sample.custom.util;

import java.io.File;
import java.io.FileInputStream;

import javax.servlet.ServletContextEvent;

import org.apache.log4j.Logger;

public class RMProperties{

private static ConfigProperties props_ = null;
private static RMProperties    this_ = null;

private static Logger log = Logger.getLogger(RMProperties.class);

static {
try {
loadProperties();
}
catch(Exception e) {
throw new ExceptionInInitializerError(e);
}
}

public void release(ServletContextEvent event)
{
log.info(“releasing Properties”);
props_ = null;
this_ = null;
}

public static ConfigProperties loadProperties()
throws RuntimeException
{
if(props_ != null) {
return(props_);
}
try {

File pfile = new File(System.getProperty(“catalina.base”),
“conf/rmcustom/RMCustom.properties”);

log.info(“loading config from [" + pfile.getAbsolutePath() + "]“);

ConfigProperties props = new ConfigProperties();
this_ = new RMProperties();

FileInputStream fis = new FileInputStream(pfile);
props.load(fis);
fis.close();

/* expand propetries from self defined variables */
props.expandAllProperties();
/* substitute variables from system properties like ${catalina.home} etc */
props.expandAllProperties(System.getProperties());

props_ = props;

} catch (Exception e) {

props_ = null;
this_ = null;
log.error(“can’t initialize config “, e);
throw new RuntimeException(e);
}
return(props_);
}
public static RMProperties getConfiguration() {
return(this_);
}

public static String getProperty(String pKey) {
return props_.getProperty(pKey);
}
public static int getIntProperty(String pKey) {
return(props_.getIntProperty(pKey));
}
public static Object setProperty(String pKey,String pValue) {
return props_.setProperty(pKey,pValue);
}

}

util1

package com.sample.rmcustom.util;

import java.io.StringReader;
import java.io.IOException;
import java.util.Properties;
import java.util.Enumeration;

public class ConfigProperties
extends Properties
{
private static final long serialVersionUID = 1L;
protected int expansionLevel_ = 0;

/** The maximum depth for recursive substitution
* of constants within property values
* (e.g., A=${B} .. B=${C} .. C=${D} .. etc.)
*/
private static final int MaxSubstitutionDepth = 5;

public ConfigProperties()
{
super();
}
public ConfigProperties(Properties defaults)
{
super(defaults);
}
/**
* @param level if <= 0 expansion is turned off
* otherwise the maximum recursion depth to go
*/
void setExpansionDepth(int level)
{
if(level <= 0) {
level = 0;
} else {
if(level > MaxSubstitutionDepth) {
level = MaxSubstitutionDepth;
}
}
expansionLevel_ = level;
}

public void loadArgv(String[] argv)
throws IOException
{
// parse arguments
for(int i = 0; i < argv.length; ++i) {
StringReader r = new StringReader(argv[i]);
load(r);
}
}
public String getProperty(String pKey, String defaultVal)
{
Object o = get(pKey);
if(o != null) {
if(o instanceof String) {
return((String)o);
}
return(null);
} else {
setProperty(pKey,defaultVal);
}
return(defaultVal);
}
public Integer getIntProperty(String pKey)
{
Object o = get(pKey);
if(o instanceof Integer) {
return((Integer)o);
}
String prop = (String)o;
if(expansionLevel_ > 0) {
prop = expandProperty(this,prop,expansionLevel_);
if(prop != prop) {
put(pKey,prop);
}
}
Integer i = Integer.parseInt(prop);
put(pKey,i);
return(i);
}
public Integer getIntProperty(String pKey, int defaultVal)
{
Object o = get(pKey);
if(o instanceof Integer) {
return((Integer)o);
}
Integer i;

if(o == null) {
i = defaultVal;
} else {
String prop = (String)o;
if(expansionLevel_ > 0) {
prop = expandProperty(this,prop,expansionLevel_);
if(prop != prop) {
put(pKey,prop);
}
}
i = Integer.parseInt(prop);
}
return(i);
}
public Long getLongProperty(String pKey, long defaultVal)
{
Object o = get(pKey);
if(o instanceof Long) {
return((Long)o);
}
Long i;

if(o == null) {
i = defaultVal;
} else {
String prop = (String)o;
if(expansionLevel_ > 0) {
prop = expandProperty(this,prop,expansionLevel_);
if(prop != prop) {
put(pKey,prop);
}
}
i = Long.parseLong(prop);
}
return(i);
}

/** code for properties expansion of “${xxx} from previously set
* properties.
*/

/** The prefix and suffix for constant names
* within property values */
private static final String VariableStart = “${“;
private static final int    VariableStartLength = 2;
private static final String VariableEnd = “}”;
private static final int    VariableEndLength = 1;

/**
* expand all properties in dest from source
* @param dest
* @param source
*/
public static void expandAllProperties(Properties dest, Properties source)
{
Enumeration<Object> keys = dest.keys();

while(keys.hasMoreElements()) {
Object o = keys.nextElement();
String key = (String)o;

o = dest.getProperty(key);
if(o instanceof String) {
String val = (String)o;
String result = expandProperty(source, val, 1);
if(result != val) {
dest.setProperty(key, result);
}
}
}
}
/**
* Expand all properties in this from source
* @param source
*/
public void expandAllProperties(Properties source)
{
expandAllProperties(this,source);
}
/**
* expand all properties in this from itself
*/
public void expandAllProperties()
{
expandAllProperties(this,this);
}

/**
* Searches for the property with the specified
* key in this property list. If the key is not
* found in this property list, the default
* property list, and its defaults, recursively,
* are then checked. The method returns
* <code>null</code> if the property is not found.
*
* @param key the property key.
* @return the value in this property list with
* the specified key value.
*/

public String getExpandedProperty(String key)
{
return(expandProperty(this, super.getProperty(key), MaxSubstitutionDepth));
}
public String getExpandedProperty(Properties substFrom, String key)
{
return(expandProperty(substFrom, super.getProperty(key), 1));
}
public static String getExpandedProperty(Properties source, Properties substFrom, String key)
{
return(expandProperty(substFrom, source.getProperty(key), 1));
}
public static String expandProperty(Properties substFrom, String value)
{
return(expandProperty(substFrom, value, 1));
}

/**
* Searches for the property with the specified
* key in this property list. If the key is not
* found in this property list, the default
* property list, and its defaults, recursively,
* are then checked. The method returns
* <code>null</code> if the property is not found.
*
* <p>The level parameter specifies the current
* level of recursive constant substitution. If
* the requested property value includes a
* constant, its value is substituted in place
* through a recursive call to this method,
* incrementing the level. Once level exceeds
* MAX_SUBST_DEPTH, no further constant
* substitutions are performed within the
* current requested value.
*
* @param substFrom Properties to get “variables” from
* @param me Properties to get property to expand from
* @param key the property key.
* @param amxlevel the maximum recursion level to go (> 0)
* @return the value in this property list with
* the specified key value.
*/
private static final String expandProperty(Properties substFrom, String value, int maxlevel)
{
// TODO: probably should use a string buffer but likely
// only called once at startup

done:
{
if (value == null) {
break done;
}
//Get the index of the first constant, if any
int beginIndex = 0;
int startName = value.indexOf(VariableStart, beginIndex);

while (startName != -1)
{
if(maxlevel <= 0) {
//Exceeded MaxSubstitutionDepth
break done;
}

int endName = value.indexOf(VariableEnd, startName);
if (endName == -1) {
//Terminating symbol not found
//Return the value as is
break done;
}

String constName = value.substring(startName+VariableStartLength, endName);
String constValue;
if(maxlevel > 1) {
constValue = expandProperty(substFrom, constName, maxlevel-1);
} else {
constValue = substFrom.getProperty(constName);
}

if (constValue == null) {
//Property name not found
//Return the value as is
break done;
}

//Insert the constant value into the
//original property value
String newValue = (startName>0)
? value.substring(0, startName) : “”;
newValue += constValue;

//Start checking for constants at this index
beginIndex = newValue.length();

// Append the remainder of the value
newValue += value.substring(endName+VariableEndLength);

value = newValue;

/* Look for the next expanded value */
startName = value.indexOf(VariableStart, beginIndex);
}
} // done
return(value);
}
}

props

package com.sample.custom.common;

/**
*
*/

import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.sample.custom.util.RMProperties;

public class RMWebInitListener  implements ServletContextListener
{
public RMWebInitListener() {}

public void contextInitialized(ServletContextEvent event)
{
ServletContext context = event.getServletContext();
Properties props = RMProperties.loadProperties();
context.setAttribute(“rm.properties”, props);
context.setAttribute(“rm.configuration”,RMProperties.getConfiguration());

}
public void contextDestroyed(ServletContextEvent event)
{
ServletContext context = event.getServletContext();
RMProperties config = (RMProperties)context.getAttribute(“rm.configuration”);
if(config == null) {
return;
}
config.release(event);
}
}

sp4

package com.sample.custom.common;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.ui.TargetUrlResolver;
import org.springframework.security.ui.savedrequest.SavedRequest;

/**
* @author ramesh
*/
/**
* Responsible for determining target url
*/
public class CustomTargetUrlResolverImpl implements TargetUrlResolver {

private static final String ADMIN_ROLE_TARGET_URL = “/home.action”;

/**
* I determine the target url based on the {@link Authentication} and
* whether their {@link GrantedAuthority} match any of our applications
* {@link Role} ’s.
*/
public String determineTargetUrl(final SavedRequest savedRequest,
final HttpServletRequest currentRequest, final Authentication auth) {
return ADMIN_ROLE_TARGET_URL;
}

}

sp3

package com.sample.custom.common;

import java.sql.Types;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.SqlUpdate;
import org.springframework.security.Authentication;

import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.ui.logout.LogoutHandler;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

public class CustomLogoutHandler implements LogoutHandler {

private static final String HTTP_SERVLET_REQUEST_REQUIRED = “HttpServletRequest required”;

private static final String LOGIN_HIST_UPDATE_SQL = “update schema.user_login_hist set logout_time = ? where login_hist_id = ?”;

private boolean invalidateHttpSession = true;

private DataSource dataSource;

private String schema;

/**
* This method used to perform Application Logout Activity.
* <li>Update Logout Time in USER_LOGIN_HIST table</li>
* <li>Invalidate Session</li>
* <li>Clear SecurityContextHolder</li>
* @param request
* @param response
* @param authentication
*/
public void logout(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) {
Assert.notNull(request, HTTP_SERVLET_REQUEST_REQUIRED);
if (invalidateHttpSession) {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
}
SecurityContextHolder.clearContext();
}

/**
* Query object to look up a user’s login history.
*/
protected class UpdateLogoutTimeQry extends SqlUpdate {

public UpdateLogoutTimeQry(DataSource ds) {
super(ds, getQuery(LOGIN_HIST_UPDATE_SQL,schema));
setMaxRowsAffected(1);
declareParameter(new SqlParameter(Types.TIMESTAMP));
declareParameter(new SqlParameter(Types.INTEGER));
compile();
}
}

/**
* @return the invalidateHttpSession
*/
public boolean isInvalidateHttpSession() {
return invalidateHttpSession;
}

/**
* @param invalidateHttpSession the invalidateHttpSession to set
*/
public void setInvalidateHttpSession(boolean invalidateHttpSession) {
this.invalidateHttpSession = invalidateHttpSession;
}

/**
* @return the dataSource
*/
public DataSource getDataSource() {
return dataSource;
}

/**
* @param dataSource the dataSource to set
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}

/**
* @return the schema
*/
public String getSchema() {
return schema;
}

/**
* @param schema the schema to set
*/
public void setSchema(String schema) {
this.schema = schema;
}

public static String getQuery( String qry, String schema) {

qry = qry.replace(“schema”, schema);
return qry;
}

}

sp2

/**
*
*/
package com.sample.custom.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.ui.logout.LogoutFilter;
import org.springframework.security.ui.logout.LogoutHandler;
import org.springframework.util.StringUtils;

public class CustomLogoutFilter extends LogoutFilter {

public CustomLogoutFilter(String logoutSuccessUrl, LogoutHandler[] handlers) {
super(logoutSuccessUrl, handlers);
}

/**
* Returns the target URL to redirect to after logout.
* <p>
* By default it will check for a <tt>logoutSuccessUrl</tt> parameter in
* the request and use this. If that isn’t present it will use the configured <tt>logoutSuccessUrl</tt>. If this
* hasn’t been set it will check the Referer header and use the URL from there.
*
*/
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
String targetUrl = request.getParameter(“logoutSuccessUrl”);
Integer orgId = (Integer)request.getAttribute(“sessionOrgId”);

if(!StringUtils.hasLength(targetUrl)) {
targetUrl = getLogoutSuccessUrl();
}

if (!StringUtils.hasLength(targetUrl)) {
targetUrl = request.getHeader(“Referer”);
}

if (!StringUtils.hasLength(targetUrl)) {
targetUrl = “/”;
}
if(orgId != null){
targetUrl = targetUrl + “&orgId=” + orgId;
}
request.removeAttribute(“sessionOrgId”);
return targetUrl;
}

}

sp1

package com.sample.rmcustom.common;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.jdbc.object.SqlUpdate;
import org.springframework.security.Authentication;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;

public class CustomAuthenticationProcessingFilter extends
AuthenticationProcessingFilter {

public static final String LOGIN_HIST_INSERT_SQL = “insert into schema.user_login_hist (login_hist_id,username, ip_address, login_time) values(?,?,?)”;

public static final String LOGIN_SEQ_NEXTVAL_SQL = “select nextval(’schema.user_login_hist_seq’)”;

protected SqlUpdate loginSuccessInsertQry;

protected MappingSqlQuery loginSuccessSeqGenQry;

private DataSource dataSource;

private String schema;

/**
* This method invoked when user logged in with correct credentials.
* <li>Persists user details, ip address along with login time</li>
*/
@Override
protected void onSuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, Authentication authResult)
throws IOException {
String schemaName = “sampe”;
setSchema(schemaName);
/*loginSuccessSeqGenQry = new LoginSuccessSeqGenQry(getDataSource());
List ids = (List) loginSuccessSeqGenQry.execute();
loginSuccessInsertQry = new LoginSuccessInsertQry(getDataSource());
Integer loginHistId = (Integer) ids.get(0);
loginSuccessInsertQry = new LoginSuccessInsertQry(getDataSource());
loginSuccessInsertQry.update(new Object[] {loginHistId,
authResult.getName(), request.getRemoteAddr(),
new Date(System.currentTimeMillis()) });*/
}

/**
* Query object to insert login history after successful login.
*/
protected class LoginSuccessInsertQry extends SqlUpdate {

public LoginSuccessInsertQry(DataSource ds) {
super(ds, getQuery(LOGIN_HIST_INSERT_SQL,schema));
declareParameter(new SqlParameter(Types.INTEGER));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.TIMESTAMP));
compile();
}
}

/**
* Query object to get next successful login history sequence val.
*/
protected class LoginSuccessSeqGenQry extends MappingSqlQuery {
protected LoginSuccessSeqGenQry(DataSource ds) {
super(ds, getQuery(LOGIN_SEQ_NEXTVAL_SQL,schema));
compile();
}

protected Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Integer token = rs.getInt(1);
return token;
}
}

/**
* @return the dataSource
*/
public DataSource getDataSource() {
return dataSource;
}

/**
* @param dataSource the dataSource to set
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}

/**
* @return the schema
*/
public String getSchema() {
return schema;
}

/**
* @param schema the schema to set
*/
public void setSchema(String schema) {
this.schema = schema;
}

public static String getQuery( String qry, String schema) {

qry = qry.replace(“schema”, schema);
return qry;
}

}

auth

package com.sample.custom.bo;

import java.io.Serializable;
import java.util.Date;

/**
* Represents a User Role or Authroity and maps to an entry in the AUTHORITIES table
* @hibernate.class table = “AUTHORITIES” lazy = “false”
*/
@SuppressWarnings(“serial”)
public class Authority implements Serializable {

private Integer authId;
private String authority;
private String userName;
private Date createdDate;
private String createdBy;
private Date modifiedDate;
private String modifiedBy;
/**
* @return the authId
* @hibernate.id generator-class = “sequence” column = “AUTH_ID”
* @hibernate.generator-param name=”sequence” value=”AUTHORITIES_AUTH_ID_SEQ”
*/
public Integer getAuthId() {
return authId;
}
/**
* @param authId the authId to set
*/
public void setAuthId(Integer authId) {
this.authId = authId;
}
/**
* @return the authority
* @hibernate.property column = “AUTHORITY”
*/
public String getAuthority() {
return authority;
}
/**
* @param authority the authority to set
*/
public void setAuthority(String authority) {
this.authority = authority;
}
/**
* @return the createdBy
* @hibernate.property column = “CRT_BY”
*/
public String getCreatedBy() {
return createdBy;
}
/**
* @param createdBy the createdBy to set
*/
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
/**
* @return the createdDate
* @hibernate.property column = “CRT_DT”
*/
public Date getCreatedDate() {
return createdDate;
}
/**
* @param createdDate the createdDate to set
*/
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
/**
* @return the modifiedBy
* @hibernate.property column = “MOD_BY”
*/
public String getModifiedBy() {
return modifiedBy;
}
/**
* @param modifiedBy the modifiedBy to set
*/
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
/**
* @return the modifiedDate
* @hibernate.property column = “MOD_DT”
*/
public Date getModifiedDate() {
return modifiedDate;
}
/**
* @param modifiedDate the modifiedDate to set
*/
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
/**
* @return the userName
* @hibernate.property column = “USERNAME”
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
}

Developing JasperReports using hibernate + iReport

To Develop jasper reports using hibernate in your Struts2 application these are the prerequisites

  • Download iReport tool from jasper soft http://www.jaspersoft.com/downloads, used to generate jrxml file , this file acts as a template to generate report. When we compile and export this file.
  • Download Struts2 Jasper Reports plug in from http://cwiki.apache.org/S2PLUGINS/jasperreports-plugin.html . This plug in exports the data to PDF, EXCEL,RTF,CSV and HTML reports.

Generating sample.jrxml files for hibernate data :

  1. Create a new empty report template
  2. Select Static Text and add Title for your report in “Title” band of the report.
  3. Add Column Titles in “Column Properties Band” as Static Text.
  4. Add properties of your Business Object(POJO) as fields to the template.In iReport tool in left side frame you will see elements of your reports.There in right click on Fields elements and add your BO properties as fields.
  5. While adding Fields choose data types as defined in your BO.Otherwise report compilation errors will arise.
  6. Drag and Drop added fields and arrange them in “Detail” band of the reports.
  7. Now comple the report sample.jrxml this will generate sample.jasper.

Using sample.jasper and Struts2 jasper plug in to generate pdf report:

  1. copy ireport.jar,jasperreports.jar and plugin jar into your application’s /WEB-INF/lib directory
  2. Configure your struts.xml file, in package tags extends attribute add “jasper result”.
  3. To generate report from an action add following result type.

sample.jasper

mySource

PDF

here mySource is a List object of BO’s which you should populate in your action before returning jasper result from action.