https://medium.com/@gayan.dissanayake/using-helm-chart-in-spring-boot-application-daf178a9fd3f
Tuesday, September 3, 2024
Monday, September 2, 2024
Sunday, September 1, 2024
Thursday, March 24, 2016
Employee salary calculation using Drool
before start this example you need to have basic understanding about Drools and this example shows how to calculate salary based on different business logic if you have any issues regarding this example you can contact me.
following component are used to calculate salary
- basic Salary
- vehicle Rental Allowance
- traveling Allowance
- tax Percentage
- salary Amount
- SKU_H("daily", "Daily Workers")
- SKU_B("monthly", "Monthly paid workers")
- BHL("contract", "Contract worker")
and .drl files
my example i have integrate Drools with Spring please refer drools-context.xml
need to import this xml though applicationContext.xml file as follows
basic_salary.drl
vehicleRental.drl
tax.drl
salary_calculation.drl
please find maven dependence details below
/**
* Created with IntelliJ IDEA.
* User: Gayan Dissanayake
* Date: 02.11.15
*/
public enum EmployeeType {
SKU_H("daily", "Daily Workers"),
SKU_B("monthly", "Monthly paid workers"),
BHL("contract", "Contract worker");
private final String type;
private final String description;
private EmployeeType(String type, String description) {
this.type = type;
this.description = description;
}
public String getType() {
return type;
}
public String getDescription() {
return description;
}
}
Employee.java
package com.goodhope.fas.drools.model;
import com.goodhope.fas.drools.enums.EmployeeType;
/**
* Created with IntelliJ IDEA.
* User: Gayan Dissanayake
* Date: 02.11.15
*/
public class Employee {
private final EmployeeType employeeType;
private String employeeName;
private String employeeTypeDescription;
private double baseSalary;
private double vehicleRental;
private double travellingAllowance;
private double taxPercentage;
private double salaryAmount;
public Employee(EmployeeType employeeType) {
this.employeeType = employeeType;
employeeTypeDescription = employeeType.getDescription();
}
public EmployeeType getEmployeeType() {
return employeeType;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeTypeDescription() {
return employeeTypeDescription;
}
public void setEmployeeTypeDescription(String employeeTypeDescription) {
this.employeeTypeDescription = employeeTypeDescription;
}
public double getBaseSalary() {
return baseSalary;
}
public void setBaseSalary(double baseSalary) {
this.baseSalary = baseSalary;
}
public double getVehicleRental() {
return vehicleRental;
}
public void setVehicleRental(double vehicleRental) {
this.vehicleRental = vehicleRental;
}
public double getTravellingAllowance() {
return travellingAllowance;
}
public void setTravellingAllowance(double travellingAllowance) {
this.travellingAllowance = travellingAllowance;
}
public double getTaxPercentage() {
return taxPercentage;
}
public void setTaxPercentage(double taxPercentage) {
this.taxPercentage = taxPercentage;
}
public double getSalaryAmount() {
return salaryAmount;
}
public void setSalaryAmount(double salaryAmount) {
this.salaryAmount = salaryAmount;
}
}
ProcessingFactory.java
package com.goodhope.fas.drools.factory;
/**
* Created with IntelliJ IDEA.
* User: Gayan Dissanayake
* Date: 02.11.15
*/
public interface ProcessingFactory
T createProcessingObject(V inputObject);
}
ProcessingFactoryImpl.java
package com.goodhope.fas.drools.factory.drools;
import com.goodhope.fas.drools.factory.ProcessingFactory;
import org.drools.runtime.StatefulKnowledgeSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
/**
* Created with IntelliJ IDEA.
* User: Gayan Dissanayake
* Date: 02.11.15
*/
@Component("ProcessingFactoryImpl")
public class ProcessingFactoryImpl implements ProcessingFactory
@Autowired
private ApplicationContext applicationContext;
@Override
public StatefulKnowledgeSession createProcessingObject(String beanId) {
return (StatefulKnowledgeSession)applicationContext.getBean(beanId);
}
}
SalaryService.java
package com.goodhope.fas.drools.service;
/**
* Created with IntelliJ IDEA.
* User: Gayan Dissanayake
* Date: 02.11.15
*/
public interface SalaryService
void calculateSalary(T input);
}
SalaryServiceImpl.java
package com.goodhope.fas.drools.service.drools;
import com.goodhope.fas.drools.factory.ProcessingFactory;
import com.goodhope.fas.drools.model.Employee;
import com.goodhope.fas.drools.service.SalaryService;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.StatelessKnowledgeSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Gayan Dissanayake
* Date: 02.11.15
*/
@Component("SalaryServiceImpl")
public class SalaryServiceImpl implements SalaryService
- > {
private static final Logger LOGGER = LoggerFactory.getLogger(SalaryServiceImpl.class);
private static final String SALARY_K_SESSION="salaryKSession";
@Autowired
@Qualifier("ProcessingFactoryImpl")
ProcessingFactory
@Override
public void calculateSalary(List
LOGGER.debug("Running employee Salary logic");
Logger logger = LoggerFactory.getLogger(SalaryServiceImpl.class);
StatefulKnowledgeSession statefulKnowledgeSession = processingFactory.createProcessingObject(SALARY_K_SESSION);
statefulKnowledgeSession.setGlobal("logger", logger);
LOGGER.debug("Running rules for employees...");
if(input!=null && !input.isEmpty()){
for(Employee employee :input){
statefulKnowledgeSession.insert(employee);
}
}
statefulKnowledgeSession.fireAllRules();
LOGGER.debug("...finished running employees.");
}
}
calling class
setter injection by spring
@Autowired
@Qualifier("SalaryServiceImpl")
SalaryService processingService;
salary calculation method
public void calculateSalary() throws SalaryCalculationException {
List
for(int i=0;i<100 br="" i=""> Employee emp1 = new Employee(EmployeeType.SKU_H);
emp1.setEmployeeName("Emp 1 Name "+i);
Employee emp2 = new Employee(EmployeeType.SKU_B);
emp2.setEmployeeName("Emp 2 Name "+i);
Employee emp3 = new Employee(EmployeeType.BHL);
emp3.setEmployeeName("Emp 3 Name "+i);
list.add(emp1);
list.add(emp2);
list.add(emp3);
System.out.println("Adding "+i);
processingService.calculateSalary(list);
}
for(Employee employee:list){
System.out.println(employee.getEmployeeName()+"-"+employee.getSalaryAmount());
}
} 100>
Wednesday, March 6, 2013
Detect Home folder using java
import javax.swing.filechooser.*;
public class DriveTypeInfo {
public static void main(String[] args)
{
FileSystemView fsv = FileSystemView.getFileSystemView();
System.out.println("Home directory: " + fsv.getHomeDirectory());
File[] f = File.listRoots();
for (File aF : f) {
System.out.println("Drive: " + aF);
System.out.println("Display name: " + fsv.getSystemDisplayName(aF));
}
}
}
Sunday, October 30, 2011
Calling EJB mehod from java class
public class TestEJBClient {
public static void main(String[] args) throws NamingException, CreateException, RemoteException {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");//put correct server host and port
p.put(Context.PROVIDER_URL, "jnp://localhost:1099");
Context jndiContext = new javax.naming.InitialContext(p);
SessionHome home = (SessionHome) jndiContext.lookup("example1/PublicSession");
Session bean = home.create();
//calling EJB bean method
bean.echo("Hello");
}
}
Monday, March 28, 2011
putting object to MQ and read objects from EJB Messaging Bean
========================
QueueConnection queueConnection = null;
QueueSession jmsSession = null;
try {
Hashtable hashtable=new Hashtable();
hashtable.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
hashtable.put("java.naming.provider.url","jnp://localhost:1099");
QueueConnection queueConnection =MessagingServiceMDBUtil.getQueueConnection(hashtable);
jmsSession = queueConnection.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);
QueueSender sender = jmsSession.createSender(MessagingServiceMDBUtil.getQueue(LookupUtil.lookupMessagingConfig().getJndiProperties()));
// create the message
ObjectMessage message = jmsSession.createObjectMessage();
ArrayList msgList = new ArrayList();
//Object
Student studentObj=new Student();
studentObj.setFristName("Gayan");
studentObj.setLastName("Dissanayake");
msgList.add(studentObj);
message.setObject(msgList);
//send the message
sender.send(message);
sender.close();
log.debug("Message is written to jms queue");
} catch (JMSException e) {
log.error("Sending message via jms failed", e);
} catch (NamingException e) {
log.error("Sending message via jms failed", e);
} catch(ModuleException moduleException) {
log.error("Sending message via jms failed", moduleException);
} finally {
if (queueConnection != null){
try {
queueConnection.close();
log.debug("Closed jms queue connection");
} catch (JMSException e) {
log.error("Closing jms queue connection failed", e);
}
}
if (jmsSession != null){
try {
jmsSession.close();
if (log.isDebugEnabled()) log.debug("Closed jms session");
} catch (JMSException e) {
if (log.isDebugEnabled()) log.error("Closing jms session failed", e);
}
}
}
EJB Messaging Bean
===================
public class MessagingServiceMDB implements MessageDrivenBean, MessageListener {
private static final long serialVersionUID = -6583759698965963589L;
private final Log logger = LogFactory.getLog(getClass());
public void onMessage(Message message){
try {
logger.debug("Entered MessagingServiceMDB.onMessage()");
ObjectMessage objMessage = (ObjectMessage)message;
ArrayList msgProfiles = (ArrayList)objMessage.getObject();
//do business logic here using MQ object
logger.debug("Entered MessagingServiceMDB.onMessage()");
} catch (JMSException jmsException) {
logger.error("Exception in MessagingServiceMDB:onMessage() " + jmsException.getMessage(), jmsException);
} catch (Exception exception) {
logger.error("Exception in MessagingServiceMDB:onMessage() " + exception.getMessage(), exception);
}
}
public void setMessageDrivenContext(MessageDrivenContext cxt) throws EJBException {}
public void ejbRemove() throws EJBException {}
public void ejbCreate() throws EJBException {}
}
add following to ejb-jar.xml
============================
<message-driven >
<description><![CDATA[MessagingServiceMDB Message Driven Bean]]></description>
<display-name>MessagingServiceMDB</display-name>
<ejb-name>MessagingServiceMDB</ejb-name>
<ejb-class>com.isa.holidays.messaging.service.MessagingServiceMDB</ejb-class>
<transaction-type>Container</transaction-type>
<acknowledge-mode>Auto-acknowledge</acknowledge-mode>
<message-driven-destination>
<destination-type>javax.jms.Queue</destination-type>
</message-driven-destination>
<resource-ref >
<res-ref-name>jms/QCF</res-ref-name>
<res-type>javax.jms.QueueConnectionFactory</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</message-driven>
Read/Write excel files using Apache POI - (the Java API for Microsoft Documents)
==========
poi-2.5.1.jar
Sample Code
===========
import java.io.FileInputStream;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Vector;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class ReadExcelFile
{
public ReadExcelFile()
{
}
public static void main(String args[])
{
String fileName = "C:\\Sample.xls";
Vector dataHolder = ReadCSV(fileName);
printCellDataToConsole(dataHolder);
}
public static synchronized Vector ReadCSV(String fileName)
{
Vector cellVectorHolder = new Vector();
try
{
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
int noOfsheets = myWorkBook.getNumberOfSheets();
for(int i = 0; i < noOfsheets; i++)
{
HSSFSheet mySheet = myWorkBook.getSheetAt(i);
Vector cellStoreVector;
for(Iterator rowIter = mySheet.rowIterator(); rowIter.hasNext(); cellVectorHolder.addElement(cellStoreVector))
{
HSSFRow myRow = (HSSFRow)rowIter.next();
Iterator cellIter = myRow.cellIterator();
cellStoreVector = new Vector();
HSSFCell myCell;
for(; cellIter.hasNext(); cellStoreVector.addElement(myCell))
myCell = (HSSFCell)cellIter.next();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return cellVectorHolder;
}
private static synchronized void printCellDataToConsole(Vector dataHolder)
{
for(int i = 0; i < dataHolder.size(); i++)
{
Vector cellStoreVector = (Vector)dataHolder.elementAt(i);
System.out.println("Start getting rows");
for(int j = 0; j < cellStoreVector.size(); j++)
{
HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
System.out.println((new StringBuilder()).append("reading column no -").append(myCell.getCellNum()).toString());
String stringCellValue = "";
if(myCell.getCellNum() == 0)//1st column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
if(myCell.getCellNum() == 1)//2nd column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
if(myCell.getCellNum() == 2)//3rd column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
if(myCell.getCellNum() == 3)//4th column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
if(myCell.getCellNum() == 4)//5th column is Number based cell
stringCellValue = String.valueOf(myCell.getNumericCellValue());
if(myCell.getCellNum() == 5)//6th column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
System.out.println((new StringBuilder()).append(stringCellValue).append("\t").toString());
}
System.out.println("end getting rows");
}
}
}
File Upload to server by Servlet(or JSP)
========
<FORM id="upform" name="upform" ENCTYPE='multipart/form-data' action="<URL>" method='POST'>
<INPUT type='file' name='uploadfile'>
<INPUT type='submit' value='upload'>
</FORM>
Needed Lib
===========
commons-fileupload-1.2.2.jar
commons-io-1.4.jar
Needed imports
===============
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
Sample Code Segment
===================
//String fileSavePath="/var/uploaded/"; linux
String fileSavePath="c:\uploaded";
if(ServletFileUpload.isMultipartContent(request))
{
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
List fileItemsList = null;
try
{
fileItemsList = servletFileUpload.parseRequest(request);
}
catch(FileUploadException e)
{
System.err.println((new StringBuilder()).append("inside uploadUpdateACtion while parsing Exception is [").append(e.getMessage()).append("]").toString());
throw new Exception((new StringBuilder()).append("inside uploadUpdateACtion while parsing Exception is [").append(e.getMessage()).append("]").toString());
}
Iterator iterator = fileItemsList.iterator();
FileItem fi = (FileItem)iterator.next();
String fileName = fi.getName();
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
String saveFile = (new StringBuilder()).append(fileSavePath).append(fileName).toString();
if("".equalsIgnoreCase(fileName))
throw new Exception("Please choose file to upload");
try
{
fi.write(new File(saveFile));
}
catch(Exception e)
{
System.err.println((new StringBuilder()).append("inside uploadUpdateACtion while writing the uploded file Exception is [").append(e.getMessage()).append("]").toString());
throw new Exception((new StringBuilder()).append("inside uploadUpdateACtion while writing the uploded file Exception is [").append(e.getMessage()).append("]").toString());
}
}
Sunday, November 7, 2010
load sub tables data without using hibernate lazy="false"
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
@Repository
public class StudentDaoHibernateImpl extends HibernateDaoSupport implements StudentDao {
public Student getStudent(long studentId) thows StudentRetrieveException {
try {
//get hibernate session
Criteria crit = getSession().createCriteria(Student.class);
//join sub table
crit.setFetchMode("Subject", FetchMode.JOIN);
//filter student
crit.add(Restrictions.eq("studentId", studentId));
//create alias
crit.createAlias("Subject","sub");
//order by subject ID
crit.addOrder(Order.asc("sub.subjectId"));
//return result
return (Student) crit.uniqueResult();
} catch (HibernateException e) {
throw new StudentRetrieveException("Student Retrieve Problem",e);
}
}
}
Thursday, May 13, 2010
Simple Spring & Hibernate Example
==========
hibernate3.jar
antlr-2.7.6.jar
asm.jar
asm-attrs.jar
cglib-2.1.3.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.6.1.jar
hibernate3.jar
jstl.jar
jta.jar
log4j-1.2.11.jar
mysql-connector-java-3.0.9-stable-bin.jar
spring.jar
standard.jar
spring.tld
1. Configure Web Xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Test</display-name>
<description>Spring Base Application</description>
<context-param>
<param-name>contextConfigLocations</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>
index.html
</welcome-file>
</welcome-file-list>
</web-app>
2.Configure Spring-Servlet XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="order" value="1"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<bean name="/userLogin.htm" class="web.controllers.UserLoginController">
<property name="managerService" ref="managerService"/>
</bean>
<bean id="saveUserValidator" class="web.validators.SaveUserValidator"/>
<bean id="addUserController" class="web.controllers.AddUserController">
<property name="sessionForm" value="false"/>
<property name="bindOnNewForm" value="false"/>
<property name="commandName" value="user"/>
<property name="commandClass" value="domain.User"/>
<property name="validator" ref="saveUserValidator"/>
<property name="formView" value="AddUser"/>
<property name="managerService" ref="managerService"/>
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<bean id="signonInterceptor" class="web.controllers.SignonInterceptor"/>
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop
key="org.springframework.dao.DataIntegrityViolationException">dberror</prop>
<prop key="org.hibernate.HibernateException">dberror</prop>
<prop key="java.lang.RuntimeException">dberror</prop>
<prop key="org.apache.jasper.JasperException">dberror</prop>
<prop key="javax.servlet.ServletException">dberror</prop>
</props>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="order" value="2"/>
<property name="interceptors">
<list>
<ref bean="signonInterceptor"/>
</list>
</property>
<property name="mappings">
<props>
<prop key="/AddUser.htm">addUserController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views"/>
</bean>
</beans>
3.Configure AppicationContext XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- ========================= GENERAL DEFINITIONS ========================= -->
<!-- Transactional proxy for the primary business objects -->
<bean id="managerService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref local="managerServiceTarget"/>
</property>
<property name="proxyTargetClass" value="false"/>
<property name="proxyInterfaces">
<list>
<value>service.ManagerService</value>
</list>
</property>
</bean>
<!-- DAO -->
<bean id="userDao" class="dao.hibernate.UserDaoHibernateImpl"/>
<!-- Business Objects -->
<bean id="managerServiceTarget" class="service.ManagerServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
</beans>
4. Hibernate Configuration
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.datasource">java:PostgresDS</property>
<!--<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>-->
<!--<property name="connection.url">jdbc:oracle:thin:@serverip:port:sid</property>-->
<!--<property name="connection.username">xxxx</property>-->
<!--<property name="connection.password">xxxx</property>-->
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<!-- print SQL to stdout -->
<property name="show_sql">false</property>
<property name="format_sql">false</property>
<mapping resource="domain/user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5.AddUser.jsp
<%@ taglib prefix="spring" uri="spring.tld" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><link rel="stylesheet" href="pop_style.css"></link>
<title>Welcome to Clinic Portal</title>
<style type="text/css">
</style>
<link href="eHosStoreStyles.css" rel="stylesheet" type="text/css">
</head>
<body onload="document.my.username.focus();" onkeydown="" leftmargin="0"
topmargin="0" rightmargin="0" bottommargin="0" class="optionsTop">
<table width="100%" height="0" border="0" style="border-collapse: collapse"
cellpadding="0" cellspacing="0">
<tr>
<td width="1%" height="30" align="left" background="Images/titleMiddle.gif"
class="titles">
<img src="Images/titleCorner.gif" width="30" height="30" border="0"></td>
<td valign="middle" background="Images/titleMiddle.gif" class="titles">
<p style="margin-right:10">
<strong><font face="Times New Roman, Times, serif" color="#000099">Add
User</font></strong></p></td>
</tr>
<br>
<form name="my" id="my" method="post" >
<table border="0" width="59%" height="100" align="center" class="bodyTable">
<tr>
<td height="10" valign="top"> <div align="center">
<spring:hasBindErrors name="user"><font color="red">
<b><fmt:message key="addUser.error.heading"/></b></font>
</spring:hasBindErrors>
<br>
</div>
</td>
</tr>
<tr>
<td class="rowgrey">
<spring:bind path="user.username">User Name
:</td>
<td width="477" align="left" class="rowgrey"><input size="40" type="text"
value="${status.value}" name="username" >
<font color="red">${status.errorMessage}</font>
</spring:bind>
</td>
</tr>
<tr>
<td class="rowgrey"><spring:bind path="user.firstName">First Name
:</td>
<td width="477" align="left" class="rowgrey"><input size="40" type="text"
value="${status.value}" name="firstName" >
<font color="red">${status.errorMessage}</font>
</spring:bind>
</td>
</tr>
<tr>
<td class="rowgrey"><spring:bind path="user.lastName">Last Name
:</td>
<td width="477" align="left" class="rowgrey"><input size="40" type="text"
value="${status.value}" name="lastName" >
<font color="red">${status.errorMessage}</font>
</spring:bind>
</td>
</tr>
<tr>
<td class="rowgrey"><spring:bind path="user.userpwd">Password
:</td><td width="477" align="left" class="rowgrey">
<input type="password" value="${status.value}" size="40" id="userpwd"
name="userpwd" >
<font color="red">${status.errorMessage}</font>
</spring:bind> </td>
</tr>
<tr>
<td class="rowgrey"><spring:bind path="user.userpwd">Confirm
Password
:</td><td width="477" align="left" class="rowgrey">
<input type="password" value="${status.value}" id="pwd" size="40" name="pwd" >
<font color="red">${status.errorMessage}</font>
</spring:bind> </td>
</tr>
<tr>
<td class="rowgrey"><spring:bind path="user.usertype"> User
Type
:</td>
<td width="477" align="left" class="rowgrey">
<select name="usertype" >
<option value="A">Administrator</option>
<option value="U">User</option>
</select>
<font color="red">${status.errorMessage}</font>
</spring:bind> </td>
</tr>
<tr>
<td
class="rowgrey">
</td>
<td width="477" align="left" class="rowgrey">
<input type="submit" id="submit" name="submit" class="buttons" value="Add User">
</td>
</tr>
</table>
</form>
<p><b> </b></p>
</body>
<script type="text/javascript" language="JavaScript1.2"
src="pop_events.js"></script>
</html>
6.Configure views.properties file
Home.class=org.springframework.web.servlet.view.JstlView
Home.url=/WEB-INF/jsp/home.jsp
AddUser.class=org.springframework.web.servlet.view.JstlView
AddUser.url=/WEB-INF/jsp/AddUser.jsp
7.configure messages.properties File
addUser.title=Add User page
addUser.error.heading=Please fix all the errors!
addUser.error.username.missing=The User Name field is missing
addUser.error.userpwd.missing=The password field is missing
addUser.error.usertype.missing=The Usertype is missing
8.DAO Class
package dao.hibernate;
import java.util.List;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.hibernate.*;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Expression;
import domain.User;
import dao.UserDao;
public class UserDaoHibernateImpl implements UserDao
{
public void saveUser(User user)throws HibernateException {
Session session = null;
Transaction tx = null;
try {
// Open a new session or get the current session
session = SessionProvider.currentSession();
// Begin the transaction
tx = session.beginTransaction();
session.saveOrUpdate(user);
//SessionProvider.closeSession();
// Commit the transaction
tx.commit();
SessionProvider.closeSession();
tx = null;
} catch( HibernateException e ) {
try{
tx.rollback();
} catch (HibernateException cannotRollback) {
// log this error
}
throw e;
//e.printStackTrace();
} finally {
// Close the session
if (session != null) SessionProvider.closeSession();
}
}
public void updateUser(User user1)throws HibernateException {
Session session = null;
Transaction tx = null;
try {
// Open a new session or get the current session
session = SessionProvider.currentSession();
// Begin the transaction
tx = session.beginTransaction();
User loaduser = (User) session.load(User.class, user1.getUserId(),
LockMode.UPGRADE);
loaduser.setUserId( user1.getUserId() );
loaduser.setStatus(user1.getStatus());
//loaduser.setUsername();
loaduser.setUserpwd(user1.getUserpwd());
loaduser.setUsertype(user1.getUsertype());
loaduser.setFirstName(user1.getFirstName());
loaduser.setLastName(user1.getLastName());
session.update(loaduser);
tx.commit();
SessionProvider.closeSession();
// Commit the transaction
tx = null;
} catch( HibernateException e ) {
try{
tx.rollback();
} catch (HibernateException cannotRollback) {
// log this error
}
throw e;
// e.printStackTrace();
} finally {
if (session != null) SessionProvider.closeSession();
}
}
public User getUser(String userName) throws HibernateException {
// Open a new session or get the current session
Session session = SessionProvider.currentSession();
User loaduser = new User();
try{
//loaduser = (user) session.get(user.class, userName);
Criteria crit = session.createCriteria(User.class);
crit.add(Restrictions.eq("username",userName));
crit.setMaxResults(1);
loaduser=(User) crit.uniqueResult();
} catch(HibernateException unexpected){
throw unexpected;
} finally{
if (session != null) SessionProvider.closeSession();
}
return loaduser;
}
public List getAllUser() throws HibernateException {
// Open a new session or get the current session
Session session = SessionProvider.currentSession();
List results =new ArrayList();
try{
Criteria crit = session.createCriteria(User.class);
results=crit.list();
} catch(HibernateException unexpected){
throw unexpected;
} finally{
if (session != null) SessionProvider.closeSession();
}
return results;
}
public void deleteUser(int jobid) throws HibernateException {
Session session = SessionProvider.currentSession();
try{
Transaction tx = session.beginTransaction();
User mm = loaduser(jobid);
session.delete( mm );
tx.commit();
}catch (Exception e){
e.printStackTrace();
}finally{
if (session != null) SessionProvider.closeSession();
}
}
public User loaduser( int id )throws HibernateException {
Session session = SessionProvider.currentSession();
User loaduser=new User();
try{
loaduser= (User) session.load(User.class, id );
}catch (Exception e){
e.printStackTrace();
}finally{
if (session != null) SessionProvider.closeSession();
}
return loaduser;
}
public List searchUser(String userName){
Session session = SessionProvider.currentSession();
List results = null;
try{
Criteria crit = session.createCriteria(User.class);
crit.add(Expression.like( "username","%"+userName.toUpperCase()+"%" ) );
results=crit.list();
} catch(HibernateException unexpected){
throw unexpected;
} finally{
if (session != null) SessionProvider.closeSession();
}
return results;
}
}
9. SessionProvider.class
package dao.hibernate;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
public class SessionProvider
{
private static final SessionFactory sessionFactory;
public static final ThreadLocal session = new ThreadLocal();
private static int dbSessionCount;
static
{
try
{
sessionFactory = new
Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
catch (HibernateException ex)
{
ex.printStackTrace();
throw new RuntimeException("Exception building SessionFactory: " +
ex.getMessage(), ex);
}
}
public static Session currentSession() throws HibernateException
{
Session s = (Session) session.get();
//System.out.println("--------------CurrentSession------------"+dbSessionCount);
if (s == null)
{
dbSessionCount++;
s = sessionFactory.openSession();
System.out.println("--------------OpenSession------------"+dbSessionCount);
s.setFlushMode(FlushMode.COMMIT);
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException
{
Session s = (Session) session.get();
session.set(null);
if (s != null)
{
dbSessionCount--;
s.close();
System.out.println("--------------ClosedSession------------"+dbSessionCount);
}
}
}
10.ManagerServiceImpl.java
/*
* JStockManager Project
*/
package service;
import java.util.List;
//
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//
//
import dao.*;
import domain.*;
public class ManagerServiceImpl implements ManagerService {
private Log logger = LogFactory.getLog(this.getClass());
private UserDao userDao;
public void setUserDao(UserDao UserDao) {
this.userDao = UserDao;
}
// insert
-----------------------------------------------------------------------------------------------
public void saveUser(User user) throws Exception {
this.logger.info("entering method saveUser");
try {
userDao.saveUser(user);
} catch (Exception e) {
String msg = "Could not saveUser " + e.toString();
this.logger.error(msg, e);
throw e;
}
}
// update
-----------------------------------------------------------------------------------------------
public void updateUser(User user) throws Exception {
this.logger.info("entering method updateUser");
try {
this.userDao.updateUser(user);
} catch (Exception e) {
String msg = "Could not updateUser";
this.logger.error(msg, e);
throw e;
}
}
// delete
-----------------------------------------------------------------------------------------------
public void deleteUser(int userid) {
this.logger.info("entering method deleteUser");
try {
this.userDao.deleteUser(userid);
} catch (Exception e) {
String msg = "Could not deleteUser";
this.logger.error(msg, e);
}
}
// get
-----------------------------------------------------------------------------------------
public User getUser(String userName) {
this.logger.info("entering method getUser");
try {
return this.userDao.getUser(userName);
} catch (Exception e) {
String msg = "Could not getUser for id of " + userName;
this.logger.error(msg, e);
return null;
}
}
// get
all----------------------------------------------------------------------------------
public List getAllUser() {
this.logger.info("entering method getAllUser");
try {
return this.userDao.getAllUser();
} catch (Exception e) {
String msg = "Could not getAllUser products";
this.logger.error(msg, e);
return null;
}
}
//search-----------------------------------------------------------------------
public List searchUser(String userName){
this.logger.info("entering method searchUser");
try {
return this.userDao.searchUser(userName);
} catch (Exception e) {
String msg = "Could not searchSuplier products";
this.logger.error(msg, e);
return null;
}
}
//-----------------------------------------------------------
}
11.SaveUserValidator.java
package web.validators;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import domain.User;
public class SaveUserValidator implements Validator
{
public boolean supports(Class checkMe)
{
return checkMe.equals(User.class);
}
public void validate(Object object, Errors errors)
{
User user1 = (User) object;
if (user1 == null)
{
errors.rejectValue("user", "SaveUser.error.novalue",
"Value required.");
}
String name= "";
String pwd = "";
String type="";
String firstName="";
String lastName="";
if(user1!=null){
name= user1.getUsername();
pwd = user1.getUserpwd();
type=user1.getUserType();
firstName=user1.getFirstName();
lastName=user1.getLastName();
}
if ((name == null) || (name.length() < 1))
{
errors.rejectValue("username", "SaveUser.error.name.missing",
"name is missing.");
}
if ((firstName == null) || (firstName.length() < 1))
{
errors.rejectValue("firstName", "SaveUser.error.name.missing",
"first Name is missing.");
}
if ((lastName == null) || (lastName.length() < 1))
{
errors.rejectValue("lastName", "SaveUser.error.name.missing",
"last Name is missing.");
}
if ((pwd == null) || (pwd.length() < 1))
{
errors.rejectValue("userpwd", "SaveUser.error.name.missing",
"pwd is missing.");
}
if ((type== null) || (type.length() < 1))
{
errors.rejectValue("usertype", "SaveUser.error.name.missing",
"type is missing.");
}
}
}
12.AddUserController.java
package web.controllers;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import service.ManagerService;
import domain.User;
public class AddUserController extends SimpleFormController
{
private ManagerService ManagerService;
private String name;
private String ip;
private String serverMsg="";
public void setManagerService(ManagerService ManagerService) {
this.ManagerService = ManagerService;
}
public ModelAndView onSubmit(Object object) {
try{
User user1 = (User)object;
user1.setStatus(1);
user1.setUserpwd(user1.getUserpwd());
ManagerService.saveUser(user1);
}
catch(Exception e)
{
e.printStackTrace();
serverMsg=e.getCause().getMessage();
}
return new ModelAndView("Home");
}
protected Map referenceData(HttpServletRequest request)
throws ServletException
{
Map refData = new HashMap();
try{
UserSession user = (UserSession)
request.getSession(true).getAttribute("userSession");
name = user.getName();
ip = user.getIp();
}
catch(Exception e)
{
e.printStackTrace();
}
return refData;
}
}
13.SignonInterceptor.java
package web.controllers;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;
public class SignonInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse
response, Object handler)
throws Exception {
UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
if (userSession == null) {
request.setAttribute("exception","User has LogOut Please Login!");
response.sendRedirect("errorPage.jsp");
return false;
}
else {
return true;
}
}
}
14.UserLoginController.java
package web.controllers;
import domain.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import service.ManagerService;
import Utility.Constants;
public class UserLoginController
implements Controller {
private ManagerService ManagerService;
Logger logger;
public UserLoginController() {
}
public void setManagerService(ManagerService managerService) {
this.ManagerService = managerService;
logger = Logger.getLogger("web/controllers/UserLoginController");
logger.setLevel(Level.ALL);
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String username = "gayan";
String password = "123";
String utype = "A";
int state = 0;
String name = "";
String place = "";
String type_ = "";
String dbPassword = "";
String ip = request.getRemoteAddr().trim();
System.out.println("---------------Attempt to login---------" + utype);
UserSession userSession = new UserSession();
userSession.setName(name);
userSession.setPlace(place);
userSession.setType_(type_);
userSession.setIp(ip);
userSession.setPwd(dbPassword);
request.getSession(true).setAttribute("userSession", userSession);
// ManagerService.getUser(username);
System.out.println("---------------Succesfull login---------" + utype);
return new ModelAndView("Home");
}
}
15.UserSession.java
package web.controllers;
public class UserSession {
private String name;
private String ip;
private String place; // user's place
private String type_; // to identify the what kind of user is trying to login
private String pwd;
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public void setName(String name) {
this.name = name;
}
public void setIp(String ip) {
this.ip = ip;
}
public void setPlace(String place) {
this.place = place;
}
public void setType_(String type_) {
this.type_ = type_;
}
public UserSession() {
}
public String getName() {
return name;
}
public String getType_() {
return type_;
}
public String getPlace() {
return place;
}
public String getIp() {
return ip;
}
}
16.User.java
package domain;
import java.io.Serializable;
/**
* Category business object.
*
* @author <a href="mailto:gayand@ceit.pdn.ac.lk">Gayan Dissanayake</a>
*/
public class User implements Serializable {
private int userId;
private String username;
private String userpwd;
private int status;
private String usertype;
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUsertype() {
return usertype;
}
public void setUsertype(String usertype) {
this.usertype = usertype;
}
/**
* Default constructor.
*/
public User() {
}
public String getUserType() {
return this.usertype;
}
public void setUserType(String usertype) {
this.usertype = usertype;
}
public String getUsername() {
return this.username;
}
public void setUsername(String newUsername) {
this.username = newUsername;
}
}
17.user.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="domain.User" table="user">
<id name="userId" column="userId" type="int">
<generator class="native"/>
</id>
<property name="username" column="username" type="java.lang.String"/>
<property name="userpwd" column="userpwd" type="java.lang.String"/>
<property name="status" column="status" type="int"/>
<property name="usertype" column="usertype" type="java.lang.String"/>
<property name="firstName" column="firstName" type="java.lang.String"/>
<property name="lastName" column="lastName" type="java.lang.String"/>
</class>
</hibernate-mapping>
18.postgres-ds.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- ===================================================================== -->
<!-- -->
<!-- JBoss Server Configuration -->
<!-- -->
<!-- ===================================================================== -->
<!-- $Id: postgres-ds.xml,v 1.3 2004/09/15 14:37:40 loubyansky Exp $ -->
<!-- ==================================================================== -->
<!-- Datasource config for Postgres -->
<!-- ==================================================================== -->
<datasources>
<local-tx-datasource>
<jndi-name>PostgresDS</jndi-name>
<connection-url>jdbc:postgresql://localhost/astro</connection-url>
<driver-class>org.postgresql.Driver</driver-class>
<user-name>postgres</user-name>
<password>mysql</password>
<!-- sql to call when connection is created
<new-connection-sql>some arbitrary sql</new-connection-sql>
-->
<!-- sql to call on an existing pooled connection when it is obtained from pool
<check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
-->
<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
<metadata>
<type-mapping>PostgreSQL 7.2</type-mapping>
</metadata>
</local-tx-datasource>
<local-tx-datasource>
<jndi-name>PostgresDS1</jndi-name>
<connection-url>jdbc:postgresql://localhost/starfriends</connection-url>
<driver-class>org.postgresql.Driver</driver-class>
<user-name>postgres</user-name>
<password>mysql</password>
<!-- sql to call when connection is created
<new-connection-sql>some arbitrary sql</new-connection-sql>
-->
<!-- sql to call on an existing pooled connection when it is obtained from pool
<check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
-->
<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
<metadata>
<type-mapping>PostgreSQL 7.2</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>
Tuesday, February 2, 2010
Differance between hibernate session find() vs get(),load();
get() and load() returns >>>>>>>>>> object
but find() returns >>>>>>>>> List
cascade Attribute in Hibernate .hbm.xml
1) cascade="none", the default, tells Hibernate to ignore the association.
2) cascade="save-update" tells Hibernate to navigate the association when the
transaction is committed and when an object is passed to save() or
update() and save newly instantiated transient instances and persist changes to
detached instances.
3) cascade="delete" tells Hibernate to navigate the association and delete persistent
instances when an object is passed to delete().
4) cascade="all" means to cascade both save-update and delete, as well as
calls to evict and lock.
5) cascade="all-delete-orphan" means the same as cascade="all" but, in addition,
Hibernate deletes any persistent entity instance that has been removed
(dereferenced) from the association (for example, from a collection).
6) cascade="delete-orphan" Hibernate will delete any persistent entity
instance that has been removed (dereferenced) from the association (for
example, from a collection).
Advantage of Hibernate session load() vs get()
thrown.
The load() method never returns null.
The get() method returns
null if the object can’t be found.
The get() method will return a FULL initialized object if nothing is on the session cache, that means several DB hits depending on your mappings.
While the load() method will return a proxy (or the instance if already initialized), allowing lazy initialization and thus better performance
Choosing between get() and load() is easy: If you’re certain the persistent
object exists, and nonexistence would be considered exceptional, load() is a
good option. If you aren’t certain there is a persistent instance with the given
identifier, use get() and test the return value to see if it’s null.
Monday, December 28, 2009
AOP in Spring Example
/**
* Created by IntelliJ IDEA.
* User: Gayan-Laptop
* Date: Dec 22, 2009
* Time: 1:49:12 AM
* To change this template use File | Settings | File Templates.
*/
public interface Adder {
public int add(int a, int b);
}
=====================================================
package aop;
/**
* Created by IntelliJ IDEA.
* User: Gayan-Laptop
* Date: Dec 22, 2009
* Time: 1:51:13 AM
* To change this template use File | Settings | File Templates.
*/
public class AdderImpl implements Adder {
public int add(int a, int b) {
return a + b;
}
}
===============================================================
package aop;/**
* Created by IntelliJ IDEA.
* User: Gayan-Laptop
* Date: Dec 22, 2009
* Time: 1:53:20 AM
* To change this template use File | Settings | File Templates.
*/
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class LogAfterReturningAdvice implements AfterReturningAdvice {
public void afterReturning(Object returnValue, Method method, Object[] args,
Object target) throws Throwable {
System.out.println("After Normal Return from Method (here you can remove attribute in session )");
}
}
=============================================================
package aop;/**
* Created by IntelliJ IDEA.
* User: Gayan-Laptop
* Date: Dec 22, 2009
* Time: 1:53:53 AM
* To change this template use File | Settings | File Templates.
*/
import org.springframework.aop.ThrowsAdvice;
import java.lang.reflect.Method;
public class LogAfterThrowsAdvice implements ThrowsAdvice {
public void afterThrowing(Method method, Object[] args, Object target,
Exception exception) {
System.out.println("Exception is thrown on method " + method.getName());
}
}
======================================================
package aop;/**
* Created by IntelliJ IDEA.
* User: Gayan-Laptop
* Date: Dec 22, 2009
* Time: 1:54:23 AM
* To change this template use File | Settings | File Templates.
*/
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class LogAroundAdvice implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("LogAroundAdvice invoke method (here you can check method Arguments validation) ");
Object arguments[] = methodInvocation.getArguments();
int number1 = ((Integer) arguments[0]).intValue();
int number2 = ((Integer) arguments[1]).intValue();
if (number1 == 0 && number2 == 0) {
throw new Exception("Dont know how to add 0 and 0!!!");
}
if(number2==0){
throw new Exception("Dont know how to divide by 0 !!!");
}
return methodInvocation.proceed();
}
}
==========================================================
package aop;/**
* Created by IntelliJ IDEA.
* User: Gayan-Laptop
* Date: Dec 22, 2009
* Time: 1:52:11 AM
* To change this template use File | Settings | File Templates.
*/
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class LogBeforeCallAdvice implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target) {
System.out.println("Before Calling the Method (here you can check user sessions) ");
}
}
=======================================================
package aop;
/**
* Created by IntelliJ IDEA.
* User: Gayan-Laptop
* Date: Dec 22, 2009
* Time: 2:18:15 AM
* To change this template use File | Settings | File Templates.
*/
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class AdderTest {
public static void main(String args[]) {
try {
Resource resource = new FileSystemResource("./aop-test.xml");
BeanFactory factory = new XmlBeanFactory(resource);
try{
Adder adder = (Adder) factory.getBean("adder");
System.out.println("------------- TEST CASE 1 ---------------");
int result = adder.add(10, 10);
System.out.println("Result = " + result);
System.out.println("------------- TEST CASE 2 ---------------");
result = adder.add(100, 10);
System.out.println("Result = " + result);
System.out.println("------------- TEST CASE 3 ---------------");
result = adder.add(101, 110);
System.out.println("Result = " + result);
System.out.println("------------- TEST CASE 4 ---------------");
result = adder.add(0, 0);
System.out.println("Result = " + result);
}catch(Exception e){
e.printStackTrace();
}
try{
Divider divider = (Divider) factory.getBean("divider");
System.out.println("------------- TEST CASE 5 ---------------");
int result2 = divider.divide(6,3);
System.out.println("Result = " + result2);
System.out.println("------------- TEST CASE 6 ---------------");
result2 = divider.divide(12,3);
System.out.println("Result = " + result2);
System.out.println("------------- TEST CASE 7 ---------------");
result2 = divider.divide(16,3);
System.out.println("Result = " + result2);
System.out.println("------------- TEST CASE 9 ---------------");
result2 = divider.divide(6,0);
System.out.println("Result = " + result2);
}catch(Exception e){
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
================================================================
aop-test.xml file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<!-- Advices -->
<bean id="beforeCall" class="aop.LogBeforeCallAdvice"/>
<bean id="afterCall" class="aop.LogAfterReturningAdvice"/>
<bean id="throwCall" class="aop.LogAfterThrowsAdvice"/>
<bean id="aroundCall" class="aop.LogAroundAdvice"/>
<!-- Implementation Class -->
<bean id="adderImpl" class="aop.AdderImpl"/>
<bean id="dividerImpl" class="aop.DividerImpl"/>
<!-- Proxy Implementation Class -->
<bean id="adder" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>aop.Adder</value>
</property>
<property name="interceptorNames">
<list>
<value>beforeCall</value>
<value>afterCall</value>
<value>throwCall</value>
<value>aroundCall</value>
</list>
</property>
<property name="target">
<ref bean="adderImpl"/>
</property>
</bean>
<bean id="divider" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>aop.Divider</value>
</property>
<property name="interceptorNames">
<list>
<value>beforeCall</value>
<value>afterCall</value>
<value>throwCall</value>
<value>aroundCall</value>
</list>
</property>
<property name="target">
<ref bean="dividerImpl"/>
</property>
</bean>
</beans>
Monday, December 21, 2009
jdom Example
<?xml version="1.0" encoding="UTF-8"?>
<database>
<main id="jdbcconnecter">
<driver id="jdbc">oracle.jdbc.driver.OracleDriver</driver>
<url id="java mysql">jdbc:oracle:thin:@XXXXXXXX:XXX</url>
<username uname="defult">XXXX</username>
<password password="defult">XXX</password>
</main>
</database>
public void setConnectionData(){
try{
String filename ="dataconnect.xml";
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File(filename));
Element root = doc.getRootElement();
List servlets = root.getChildren("main");
Iterator i = servlets.iterator();
while (i.hasNext()) {
Element servlet = (Element) i.next();
driver= servlet.getChild("driver").getTextTrim();
url=servlet.getChild("url").getTextTrim();
username=servlet.getChild("username").getTextTrim();
password=servlet.getChild("password").getTextTrim();
}//end while
}catch(Exception e){
e.printStackTrace();
}
}
Wednesday, December 16, 2009
Ant Script to compile,deploy,test EJB Appication
<project name="jblog" default="ear">
<property environment="env"/>
<property name="jboss.home" value="${env.JBOSS_HOME}"/>
<property name="jboss.server.dir" value="${jboss.home}/server/default"/>
<property name="jboss.deploy.dir" value="${jboss.server.dir}/deploy"/>
<property name="source.dir" value="src"/>
<property name="classes.dir" value="classes"/>
<property name="docs.dir" value="docs"/>
<property name="docs.test.dir" value="${docs.dir}/test"/>
<property name="docs.api.dir" value="${docs.dir}/api"/>
<property name="app.ear" value="${ant.project.name}.ear"/>
<property name="app.war" value="${ant.project.name}.war"/>
<property name="app.ejb.jar" value="${ant.project.name}-ejb.jar"/>
<property name="app.client.jar" value="${ant.project.name}-client.jar"/>
<property name="app.test.jar" value="${ant.project.name}-test.jar"/>
<property name="test.args" value=""/>
<property name="test.include" value="**/*Test.class"/>
<property name="test.exclude" value=""/>
<property name="db.url" value="jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1111:sid"/>
<property name="db.user" value="ehosbk"/>
<property name="db.password" value="ehosbk"/>
<property name="db.driver" value="oracle.jdbc.driver.OracleDriver"/>
<!-- compile classpath -->
<path id="compile.class.path">
<pathelement location="${env.J2EE_HOME}/lib/j2ee.jar"/>
<pathelement location="${env.JUNIT_HOME}/junit-4.4.jar"/>
</path>
<!-- test classpath -->
<path id="test.class.path">
<pathelement location="."/>
<pathelement location="${app.test.jar}"/>
<pathelement location="${app.client.jar}"/>
<pathelement location="${jboss.home}/client/jbossall-client.jar"/>
<pathelement location="${jboss.home}/server/default/lib/classes12.jar"/>
<path refid="compile.class.path"/>
</path>
<!-- all -->
<target name="all" depends="clean,ear,deploy,test"/>
<!-- compile -->
<target name="compile">
<mkdir dir="${classes.dir}"/>
<javac srcdir="${source.dir}" destdir="${classes.dir}"
classpathref="compile.class.path" debug="yes"/>
<copy todir="${classes.dir}">
<fileset dir="${source.dir}">
<include name="META-INF/**"/>
</fileset>
</copy>
</target>
<!-- jar -->
<target name="jar" depends="compile">
<jar jarfile="${app.ejb.jar}">
<fileset dir="${classes.dir}">
<include name="META-INF/ejb-jar.xml"/>
<include name="META-INF/jboss.xml"/>
<include name="META-INF/jbosscmp-jdbc.xml"/>
<include name="**/*.class"/>
<exclude name="**/test/**"/>
</fileset>
</jar>
<jar jarfile="${app.client.jar}">
<fileset dir="${classes.dir}">
<include name="**/Author.class"/>
<include name="**/Story.class"/>
<include name="**/Blog.class"/>
<include name="**/*Home.class"/>
</fileset>
</jar>
<jar jarfile="${app.test.jar}">
<fileset dir="${classes.dir}">
<include name="**/test/**"/>
</fileset>
</jar>
</target>
<!-- war -->
<target name="war">
<jar jarfile="${app.war}">
<fileset dir="${source.dir}">
<include name="WEB-INF/web.xml"/>
<include name="*.jsp"/>
</fileset>
</jar>
</target>
<!-- ear -->
<target name="ear" depends="jar,war">
<jar jarfile="${app.ear}">
<fileset dir="${classes.dir}">
<include name="META-INF/application.xml"/>
<include name="${app.ejb.jar}"/>
</fileset>
<fileset dir=".">
<include name="${app.ejb.jar}"/>
<include name="${app.war}"/>
</fileset>
</jar>
</target>
<!-- deploy -->
<target name="deploy">
<copy file="${app.ear}" todir="${jboss.deploy.dir}"/>
</target>
<!-- undeploy -->
<target name="undeploy">
<delete file="${jboss.deploy.dir}/${app.ear}" quiet="true"/>
</target>
<!-- test -->
<target name="test">
<!-- Make docs. dir. -->
<mkdir dir="${docs.test.dir}"/>
<!-- Run test. -->
<junit fork="true" printsummary="on" showoutput="true"
failureproperty="test.failures" errorproperty="test.errors">
<sysproperty key="db.url" value="${db.url}"/>
<sysproperty key="db.user" value="${db.user}"/>
<sysproperty key="db.password" value="${db.password}"/>
<sysproperty key="db.driver" value="${db.driver}"/>
<jvmarg line="${test.args}"/>
<classpath refid="test.class.path"/>
<formatter type="xml"/>
<batchtest todir="${docs.test.dir}">
<fileset dir="${classes.dir}">
<include name="${test.include}"/>
<exclude name="${test.exclude}"/>
</fileset>
</batchtest>
</junit>
<!-- Run report. -->
<junitreport todir="${docs.test.dir}">
<fileset dir="${docs.test.dir}">
<include name="TEST-*.xml"/>
</fileset>
<report format="frames" todir="${docs.test.dir}"/>
</junitreport>
<!-- Fail if failures or errors. -->
<fail if="test.failures">Test failures.</fail>
<fail if="test.errors">Test errors.</fail>
</target>
<!-- clean -->
<target name="clean">
<delete includeEmptyDirs="true" quiet="true">
<fileset dir=".">
<include name="*.jar"/>
<include name="*.war"/>
<include name="*.ear"/>
<include name="junit*.properties"/>
</fileset>
<fileset dir="${classes.dir}"/>
<fileset dir="${docs.dir}"/>
</delete>
</target>
</project>