To these I'd just like to add Implementing REST Web Services: Best Practices and Guidelines, which I find useful for implementing REST based web services.
- "Best practices for Web services" series: Part 1 through Part 12 (developerWorks)
- "Web Services Architectures and Best Practices" (developerWorks)
- "Best practices for Web services versioning" (developerWorks)
- "Best Practices and Web services Profiles" (developerWorks)
- "Web services performance best practices" (WAS InfoCenter)
- "Web services migration best practices" (WAS InfoCenter)
- WebSphere Version 6 Web Services Handbook Development and Deployment (Redbook)
- Web Services Handbook for WebSphere Application Server 6.1 (Redbook)
- IBM WebSphere DataPower SOA Appliances Part III: XML Security Guide (Redbook)
- "Web services with SOAP over JMS in IBM WebSphere Process Server or IBM WebSphere Enterprise Service Bus" (developerWorks)
- "Web services SOAP/JMS protocol" (WAS InfoCenter)
- "HTTP and JMS transport methods" (RAD InfoCenter)
Tuesday, July 08, 2008
Web Service Best Practices
Bobby Woolf at IBM has a list of articles with best practices for working with Web Services. Most of these links are IBM resources.
Thursday, April 17, 2008
Integrating Spring and Hibernate: Transactions
In the previous post, I described different ways in which spring and hibernate can
be integrated. In this post I will describe how to use Spring's transaction features
in hibernate. The following methods of transaction management with spring and hibernate are discussed.
The easiest way to check if transactions are working for this example is to remove the transaction declarations for the getStockQuote() method. Removing transactions will cause the following exception
There's More ...
For this example, start off with the following as described in the "Integrating Spring and Hibernate" post.
The following main class can be used:SpringHibernateTest.java
Note that here we use an Interface IPortfolioService, and also note the change to ApplicationContext instead of a BeanFactory.
The reason for using ApplicationContext is enable the use of AOP for declarative transaction management. Also we are not expecting any return to the main class as all the execution is expected to happen in the transaction context.
The Portfolio Service Interface:IPortfolioService.java
Declarative transaction management in Spring has the advantage of being less invasive. There is no need for changing application code when using declarative transactions. All you have to do is to modify the application context.
The Service class will be same for all the modes of Declarative transaction management described below.PortfolioService.java
In this method, you have to define a proxy for the bean that will be made transactional.applicationContext.xml
Note that the transactionInterceptor and hibernateTransactionInterceptor are declared. While transactionInterceptor is used to set the transaction properties, the hibernateTransactionInterceptor will manage the hibernate transactions.
applicationContext.xml Using Schema-based declarative transaction management is a lot simpler and a lot cleaner. However it is adviced that this method not be used in conjunction with explicit auto-proxying using BeanNameAutoProxyCreator, as it might raise issues like advice not being woven etc. Note that the AOP pointcut is defined to be all methods on the IPortfolioService inteface.
Schema-based Declarative Transaction Management with Annotations
applicationContext.xml When using annotations, you only have to declare the transaction manager and add <tx:annotation-driven/> to the application context. If the transaction manager is named "transactionManager" then you don't have to declare a transaction-manager attribute for <tx:annotation-driven/> as it happens to be the default value for that attribute.
Also we have to declare the pointcuts in the Service class itself. Note that as annotations are not inherited, declaring the annotations has to be done at the class level.
For programmatic transaction management in spring, you will need a PlatformTransctionManger in your bean which will be used to create a TransactionTemplate. The TransactionTemplate is used in the same way the HibernateTemplate was used in previous example. Additionally you will have to create a HibernateTransactionManager as shown in the above example.PortfolioService.java
be integrated. In this post I will describe how to use Spring's transaction features
in hibernate. The following methods of transaction management with spring and hibernate are discussed.
- Declarative Transaction Mangement with AOP Interceptors
- Schema-based Declarative Transaction Management
- Schema-based Declarative Transaction Management with Annotations
- Programmatic Transaction Management
The easiest way to check if transactions are working for this example is to remove the transaction declarations for the getStockQuote() method. Removing transactions will cause the following exception
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
There's More ...
For this example, start off with the following as described in the "Integrating Spring and Hibernate" post.
- The bean StockQuoteBean
- The Portfolio classes : PortfolioDAO, PortfolioDAOSupport and PortfolioDAOTemplate
- The hibernate mapping file stockquote.hbm.xml
The following main class can be used:
package springhibernate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringHibernateTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
IPortfolioService portfolioService = (IPortfolioService) ctx.getBean("portfolioService");
System.out.println("Portfolio Service type : " + portfolioService.getClass());
portfolioService.getStockQuote("123");
}
}
Note that here we use an Interface IPortfolioService, and also note the change to ApplicationContext instead of a BeanFactory.
The reason for using ApplicationContext is enable the use of AOP for declarative transaction management. Also we are not expecting any return to the main class as all the execution is expected to happen in the transaction context.
The Portfolio Service Interface:
package springhibernate;
import beans.StockQuoteBean;
public interface IPortfolioService {
public void getStockQuote(String id);
public void updateStockQuote(StockQuoteBean stockQuoteBean);
}
Declarative Transaction Management
Declarative transaction management in Spring has the advantage of being less invasive. There is no need for changing application code when using declarative transactions. All you have to do is to modify the application context.
The Service class will be same for all the modes of Declarative transaction management described below.
package springhibernate;
import beans.StockQuoteBean;
import dao.PortfolioDAO;
public class PortfolioService implements IPortfolioService {
private PortfolioDAO portfolioDAO;
public void getStockQuote(String id) {
StockQuoteBean result = portfolioDAO.getStockQuote(id);
System.out.println("Result in Service : " + result.getStockSymbol());
}
public void updateStockQuote(StockQuoteBean stockQuoteBean) {
portfolioDAO.updateStockQuote(stockQuoteBean);
}
public PortfolioDAO getPortfolioDAO() {
return portfolioDAO;
}
public void setPortfolioDAO(PortfolioDAO portfolioDAO) {
this.portfolioDAO = portfolioDAO;
System.out.println("Setting portfolio DAO to : " + portfolioDAO.getClass());
}
}
Declarative Transaction Management with AOP Interceptor
In this method, you have to define a proxy for the bean that will be made transactional.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="portfolioDAOTemplate" class="dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioDAOSupport" class="dao.PortfolioDAOSupport">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="myPortfolioService" class="springhibernate.PortfolioService">
<property name="portfolioDAO" ref="portfolioDAOTemplate"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributeSource">
<value>springhibernate.PortfolioService.*=PROPAGATION_REQUIRED</value>
</property>
</bean>
<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="portfolioService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="myPortfolioService"></property>
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
<property name="username" value="appUser" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>stockquote.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Note that the transactionInterceptor and hibernateTransactionInterceptor are declared. While transactionInterceptor is used to set the transaction properties, the hibernateTransactionInterceptor will manage the hibernate transactions.
Schema-based Declarative Transaction Management
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="portfolioDAOTemplate" class="dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioDAOSupport" class="dao.PortfolioDAOSupport">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioService" class="springhibernate.PortfolioService">
<property name="portfolioDAO" ref="portfolioDAOTemplate"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<aop:config>
<aop:pointcut id="serviceMethods" expression="execution(* springhibernate.IPortfolioService.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
<tx:attributes>
<tx:method name="*" propagation="REQUIRES_NEW" />
</tx:attributes>
</tx:advice>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
<property name="username" value="appUser" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>stockquote.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Schema-based Declarative Transaction Management with Annotations
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="portfolioDAOTemplate" class="dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioDAOSupport" class="dao.PortfolioDAOSupport">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioService" class="springhibernate.PortfolioService">
<property name="portfolioDAO" ref="portfolioDAOTemplate"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
<property name="username" value="appUser" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>stockquote.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Also we have to declare the pointcuts in the Service class itself. Note that as annotations are not inherited, declaring the annotations has to be done at the class level.
@Transactional
public class PortfolioService implements IPortfolioService {
private PortfolioDAO portfolioDAO;...
Programmatic Transaction Management
For programmatic transaction management in spring, you will need a PlatformTransctionManger in your bean which will be used to create a TransactionTemplate. The TransactionTemplate is used in the same way the HibernateTemplate was used in previous example. Additionally you will have to create a HibernateTransactionManager as shown in the above example.
package springhibernate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import beans.StockQuoteBean;
import dao.PortfolioDAO;
public class PortfolioServiceTransaction implements IPortfolioService{
private PortfolioDAO portfolioDAO;
private PlatformTransactionManager transactionManager;
public void getStockQuote(final String id) {
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
public void doInTransactionWithoutResult(TransactionStatus status) {
StockQuoteBean result = portfolioDAO.getStockQuote(id);
System.out.println("Symbol in transaction " + result.getStockSymbol());
}
});
}
public void updateStockQuote(final StockQuoteBean stockQuoteBean) {
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
public void doInTransactionWithoutResult(TransactionStatus status) {
portfolioDAO.updateStockQuote(stockQuoteBean);
}
});
}
public PortfolioDAO getPortfolioDAO() {
return portfolioDAO;
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void setPortfolioDAO(PortfolioDAO portfolioDAO) {
this.portfolioDAO = portfolioDAO;
System.out.println("Setting portfolio DAO to : " + portfolioDAO.getClass());
}
}
Monday, April 14, 2008
Integrating Spring and Hibernate
This post applies to integrating Spring framework 2.5.3 and Hibernate 3.0.
The Spring framework provides extensive support for data access through the use of support classes (JdbcDaoSupport, JdbcTemplate etc.), and extensive exception hierarchy to wrap any platform specific SQLException into an exception in the spring exception hierarchy. Additionally Spring framework also provides good support for integrating with ORM technologies like Hibernate and iBatis etc. This post will show how to integrate Spring framework with Hibernate ORM. There's more ...
The Spring framework provides extensive support for data access through the use of support classes (JdbcDaoSupport, JdbcTemplate etc.), and extensive exception hierarchy to wrap any platform specific SQLException into an exception in the spring exception hierarchy. Additionally Spring framework also provides good support for integrating with ORM technologies like Hibernate and iBatis etc. This post will show how to integrate Spring framework with Hibernate ORM. There's more ...
- Create the bean: The bean here represents a simple stock quote
package beans;
public class StockQuoteBean {
private String quoteId;
private String stockSymbol;
private String name;
public String getQuoteId() {
return quoteId;
}
public void setQuoteId(String quoteId) {
this.quoteId = quoteId;
}
public String getStockSymbol() {
return stockSymbol;
}
public void setStockSymbol(String stockSymbol) {
this.stockSymbol = stockSymbol;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}StockQuoteBean.java - Create a Hibernate Mapping file for the bean:
<?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="beans.StockQuoteBean" table="STOCK_QUOTES" lazy="false">
<id name="quoteId" column="quote_id">
<generator class="assigned" />
</id>
<property name="stockSymbol">
<column name="stock_symbol" />
</property>
<property name="name">
<column name="name" />
</property>
</class>
</hibernate-mapping>stockquote.hbm.xml
The one important thing to note here is that in the declaration, a [lazy="false"] has been added to the mapping for the stockquote bean. The reason for this is that in hibernate 3, lazy initialization is turned on by default. This raises a problem when used with spring's HibernateCallback. The spring HibernateTemplate.execute() by default closes any open sessions upon completion. When used with lazy initialization you may get a LazyInitializationException like the followingorg.hibernate.LazyInitializationException: could not initialize proxy - no Session
If you want to use lazy initialization with HibernateCallback, you will have to use this within a transaction context. The javadoc for HibernateTemplate specifies this explicitlyNote that operations that return an Iterator (i.e. iterate) are supposed
to be used within Spring-driven or JTA-driven transactions (with
HibernateTransactionManager, JtaTransactionManager, or EJB CMT). Else, the
Iterator won't be able to read results from its ResultSet anymore, as the
underlying Hibernate Session will already have been closed.
Lazy loading will also just work with an open Hibernate Session, either within a
transaction or within OpenSessionInViewFilter/Interceptor. Furthermore, some
operations just make sense within transactions, for example: contains, evict,
lock, flush, clear. - The service class: The service class simply acts as an intermediary between the client and the DAO classes.
package springhibernate;
import beans.StockQuoteBean;
import dao.PortfolioDAO;
public class PortfolioService {
private PortfolioDAO portfolioDAO;
public StockQuoteBean getStockQuote(String id) {
StockQuoteBean result = portfolioDAO.getStockQuote(id);
return result;
}
public void updateStockQuote(StockQuoteBean stockQuoteBean) {
portfolioDAO.updateStockQuote(stockQuoteBean);
}
public PortfolioDAO getPortfolioDAO() {
return portfolioDAO;
}
public void setPortfolioDAO(PortfolioDAO portfolioDAO) {
this.portfolioDAO = portfolioDAO;
System.out.println("Setting portfolio DAO to : " + portfolioDAO.getClass());
}
}PortfolioService.java - The DAO interface:
package dao;
import beans.StockQuoteBean;
public interface PortfolioDAO {
public StockQuoteBean getStockQuote(String id);
public void updateStockQuote(StockQuoteBean bean);
public StockQuoteBean getStockQuote_hibernateTemplate(String id);
public void updateStockQuote_hibernateTemplate(StockQuoteBean bean);
}PortfolioDAO.java - The DAO Classes: The DAO classes shows the different ways in which the Hibernate calls can be made using the Spring support classes. There are three primary ways in which these calls can be made
- Using the HibernateCallback
- Using the HibernateTemplate directly
- Using the hibernate native calls using Session
- Using Composition, with HibernateTemplate
- Using Inheritance by extending HibernateDaoSupport
- Using HibernateTemplate
package dao;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import beans.StockQuoteBean;
public class PortfolioDAOTemplate implements PortfolioDAO{
private HibernateTemplate hibernateTemplate;
public PortfolioDAOTemplate() {
System.out.println("Init transaction dao");
}
public StockQuoteBean getStockQuote(final String id) {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
return session.load(StockQuoteBean.class, id);
}
};
return (StockQuoteBean) hibernateTemplate.execute(callback);
}
public void updateStockQuote(final StockQuoteBean StockQuoteBean) {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
session.saveOrUpdate(StockQuoteBean);
return null;
}
};
hibernateTemplate.execute(callback);
}
public void updateStockQuote_hibernateTemplate(StockQuoteBean StockQuoteBean) {
hibernateTemplate.update(StockQuoteBean);
}
public StockQuoteBean getStockQuote_hibernateTemplate(String id) {
List<StockQuoteBean> transactions = hibernateTemplate.find("from beans.StockQuoteBean stockQuoteBean where stockQuoteBean.quoteId=?", id);
return transactions.get(0);
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}PortfolioDAOTemplate
This class shows how to use the HibernateTemplate to make calls to Hibernate. The getStockQuote() and updateStockQuote() methods use HibernateCallback class, note that when using HibernateCallback, it is necessary to either do it in a transactional context or turn off lazy initialization. While the getStockQuote_hibernateTemplate() and updateStockQuote_hibernateTemplate() make calls using hibernateTemplate directly. Also note that the parameters to the getStockQuote(), and updateStockQuote() methods are marked final. - Using HibernateDaoSupport
package dao;
import java.util.List;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import beans.StockQuoteBean;
public class PortfolioDAOSupport extends HibernateDaoSupport implements PortfolioDAO {
public void updateStockQuote(StockQuoteBean stockQuoteBean) {
Query query = getSession().createQuery("update beans.StockQuoteBean set stockSymbol=? where quoteId=?");
query.setString(0, stockQuoteBean.getStockSymbol());
query.setString(1, stockQuoteBean.getQuoteId());
query.executeUpdate();
}
public StockQuoteBean getStockQuote(String id) {
Query query = getSession().createQuery("from beans.StockQuoteBean stockQuoteBean where stockQuoteBean.quoteId=?");
query.setString(0, id);
List results = query.list();
if(results == null || results.size() == 0) {
throw new RuntimeException("No result");
}
return (StockQuoteBean)results.get(0);
}
public void updateStockQuote_hibernateTemplate(StockQuoteBean StockQuoteBean) {
getHibernateTemplate().update(StockQuoteBean);
}
public StockQuoteBean getStockQuote_hibernateTemplate(String id) {
List<StockQuoteBean> transactions = getHibernateTemplate().find("from beans.StockQuoteBean stockQuoteBean where stockQuoteBean.quoteId=?", id);
return transactions.get(0);
}
}PortfolioDAOSupport
This class uses HibernateDaoSupport to get instances of HibernateTemplate, and the Hibernate Session. The getStockQuote() and updateStockQuote() in this class make calls to hibernate session directly.
- The application context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="portfolioDAOTemplate" class="dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioDAOSupport" class="dao.PortfolioDAOSupport">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioService" class="springhibernate.PortfolioService">
<property name="portfolioDAO" ref="portfolioDAOSupport"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
<property name="username" value="appUser" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>stockquote.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>applicationContext.xml - The SessionFactory is defined with the datasource and mapping-resources. The hibernate specific properties are defined under the hibernateProperties property.
- The HibernateTemplate uses are reference to the SessionFactory.
- The HibernateTemplate is used as a reference to the DAO classes.
- The porfolioService bean in uses a reference to the PortfolioDAO, which can be switched between the dao.PortfolioDAOSupport and dao.PortfolioDAOTemplate beans
- The main class
package springhibernate;
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;
import beans.StockQuoteBean;
public class SpringHibernateTest {
public static void main(String[] args) {
Resource resource = new FileSystemResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
PortfolioService portfolioService = (PortfolioService) factory.getBean("portfolioService");
StockQuoteBean result = portfolioService.getStockQuote("123");
System.out.println(result.getStockSymbol());
empResult.setStockSymbol("GOOG");
portfolioService.updateStockQuote(result);
}
}SpringHibernateTest.java - Necessary JAR files:
- commons-logging-1.1.1.jar
- hibernate3.jar
- dom4j-1.6.1.jar
- ojdbc14.jar
- commons-collections-3.2.jar
- log4j-1.2.15.jar
- commons-dbcp.jar
- commons-pool.jar
- spring.jar
- cglib-nodep-2.1_3.jar
- antlr-2.7.6.jar
- jta.jar
Friday, April 11, 2008
Struts 2 Custom Validators
Struts 2 allows the use of Custom validators through the @CustomValidator annotation. The @CustomValidator annotation takes two mandatory parameters, type and message
To run this sample, follow these steps... There's More
- type: Refers to the "name" given to the validator in the validators.xml file.
- message: Message to be displayed when this validator fails.
To run this sample, follow these steps... There's More
- Create a simple struts project as described in the previous example, Struts 2 Validation : Annotations
- Create the new validator by extending the FieldValidatorSupport class
package validators;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
public class NumberFieldValidator extends FieldValidatorSupport {
public void validate(Object object) throws ValidationException {
String fieldName = getFieldName();
Object value = this.getFieldValue(fieldName, object);
if (!(value instanceof String)) {
return;
}
String str = ((String) value).trim();
if (str.length() == 0) {
return;
}
try {
Double.parseDouble(str);
}catch(NumberFormatException nfe) {
addFieldError(fieldName, object);
return;
}
try {
Integer.parseInt(str);
}catch(NumberFormatException nfe) {
addFieldError(fieldName, object);
return;
}
}
}NumberFieldValidator.java - The custom validator may extend the FieldValidatorSupport or the ValidatorSupport classes.
- The FieldValidatorSupport class extends ValidatorSupport to add field specific information to the Field.
- The is numeric check is performed by trying to convert the input string to Integer or Double and catching any exception.
- The addFieldError method is used add any failed validations to the list of errors to be displayed.
- The getFieldName and getFieldValue methods are implemented in the superclasses to retrieve the field name and field value for the field beign validated.
- Declare the new custom validator in the validators.xml file. The validators.xml file must be in the classpath of the application.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Config 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<validators>
<validator name="numericField" class="validators.NumberFieldValidator"/>
</validators>validators.xml
Note: The name attribute of the validator must match the type attribute of the @CustomValidator Annotation used in the Action class. - Add the additional check to the Action class setPrice() method.
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Price Required")
@CustomValidator(type = "numericField", message = "Price must be a number")
public void setPrice(String price) {
this.price = price;
}AddTransactionAction.java
Note: the type attribute of the @CustomValidator Annotation must match the name of the validator as defined in the validators.xml file.
Struts 2 Validation : Annotations
In a previous post, I described how to use validations in Struts 2, using XML validation rules. This post will show how to use Annotation based validation in Struts 2. For this example I used the add transaction part of google's portfolio manager (noticed that they do not have validations over there). Struts 2 provides a number of validators for XML based validation rules. All of them have respective annotations defined and can be used in place of XML validation rules. In the example, we will use the @RequiredStringValidator, @RegexFieldValidator and also see how to parameterize messages when using annotations.
Follow these steps to implement the example ... There's more
Follow these steps to implement the example ... There's more
- Create a dynamic web project in Eclipse.
- Copy the following jar files into the WEB-INF/lib directory, all these files are available with sturts download.
- struts2-core-2.0.11.1.jar
- xwork-2.0.4.jar
- freemarker-2.3.8.jar
- commons-logging-1.1.1.jar
- ognl-2.6.11.jar
- Update your web deployment desciptor to include the sturts filter dispatcher.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>struts2Validation</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>WEB-INF/web.xml - Create the input JSP
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Add Transaction</title>
</head>
<body>
<s:form action="addTransaction" validate="true" method="post">
<s:fielderror />
<table>
<tr>
<td>Symbol</td>
<td><s:textfield name="symbol"></s:textfield></td>
</tr>
<tr>
<td>Type</td>
<td><s:select name="type" list="#{'':'Select One', 'BUY':'Buy','SELL':'Sell','BUY_COVER':'Buy to Cover','SELL_SHORT':'Sell Short'}">
</s:select></td>
</tr>
<tr>
<td>Date</td>
<td><s:textfield name="date" ></s:textfield></td>
</tr>
<tr>
<td>Number of Shares</td>
<td><s:textfield name="numberOfShares"></s:textfield></td>
</tr>
<tr>
<td>Price</td>
<td><s:textfield name="price"></s:textfield></td>
</tr>
<tr>
<td>Commission</td>
<td><s:textfield name="comission"></s:textfield></td>
</tr>
<tr>
<td>Notes</td>
<td><s:textfield name="notes"></s:textfield></td>
</tr>
<tr>
<td colspan="2"> <s:submit name="submit" value="submit"></s:submit>
<s:submit name="submitNoValidate" value="submit without validation" method="noValidation"></s:submit> </td>
</tr>
</table>
</s:form>
</body>
</html>transactions.jsp
Note: The method="noValidation" indicates to struts that on submission, the noValidation() method will be invoked on the AddTransactionAction class. - Create the output JSP
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Transaction Added</title>
</head>
<body>
<s:bean name="actions.AddTransactionAction" id="addTransaction" ></s:bean>
<table>
<tr>
<td colspan="2">The following transaction has been added to your portfolio</td>
</tr>
<tr>
<td>Symbol</td>
<td><s:label name="symbol" value="%{symbol}" /></td>
</tr>
<tr>
<td>Type</td>
<td><s:label name="type" value="%{type}" />
</td>
</tr>
<tr>
<td>Date</td>
<td><s:label name="date" value="%{date}"/></td>
</tr>
<tr>
<td>Number of Shares</td>
<td><s:label name="numberOfShares" value="%{numberOfShares}"></s:label></td>
</tr>
<tr>
<td>Price</td>
<td><s:label name="price" value="%{price}"></s:label></td>
</tr>
<tr>
<td>Commission</td>
<td><s:label name="comission" value="%{comission}"></s:label></td>
</tr>
<tr>
<td>Notes</td>
<td><s:label name="notes" value="%{notes}"></s:label></td>
</tr>
</table>
</body>
</html>done.jsp - Create the Action class
package actions;
import org.apache.struts2.interceptor.validation.SkipValidation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
import com.opensymphony.xwork2.validator.annotations.Validation;
@Validation
public class AddTransactionAction extends ActionSupport {
private String symbol;
private String type;
private String date;
private String numberOfShares;
private String price;
private String comission;
private String notes;
public String execute() throws Exception {
System.out.println("In Execute");
return SUCCESS;
}
@SkipValidation
public String noValidation() throws Exception {
System.out.println("In Novalidation");
return SUCCESS;
}
public String getSymbol() {
return symbol;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Symbol Required")
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getType() {
return type;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Type Required")
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Date Required")
@RegexFieldValidator(type=ValidatorType.FIELD, message="",key="date.error.message", expression = "[0-9][0-9]/[0-9][0-9]/[1-9][0-9][0-9][0-9]")
public void setDate(String date) {
this.date = date;
}
public String getNumberOfShares() {
return numberOfShares;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = " Number of Shares Required")
public void setNumberOfShares(String numberOfShares) {
this.numberOfShares = numberOfShares;
}
public String getPrice() {
return price;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Price Required")
public void setPrice(String price) {
this.price = price;
}
public String getComission() {
return comission;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Comission Required")
public void setComission(String comission) {
this.comission = comission;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}AddTransactionAction.java
Note:- The annotation @Validation is used to indicate that the current action might need validation. The validations on a method level can be skipped using the @SkipValidation annotation on the method.
- The method noValidations() uses the @SkipValidation annotation, you can see this when you click on "Submit without validation" in the JSP
- The @RequiredStringValidator annotation is used to indicate a Required Strint similar to the following xml rule
<validators>
<field name="numberOfShares">
<field-validator type="requiredstring">
<message>Number of Share is required</message>
</field-validator>
</field>
</validators> - On the date field, I used a @RegexFieldValidator annotation, so that the date field will be mandated to have a given format.
- Parameterized messages: You will notice that the message attribute of the @RegexFieldValidator is set to an empty string, while the key is set to a value. This is due to the fact that the message attribute is mandatory, and the key attribute is used to denote the message key from the properties files. The parameters can be retrieved in the properties files using the ${date} notation where the "date" variable is expected to available in the value stack
- Create a definition for the action in struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="struts2Validation" extends="struts-default">
<action name="addTransaction"
class="actions.AddTransactionAction">
<result name="success">done.jsp</result>
<result name="input">transactions.jsp</result>
</action>
</package>
</struts>struts.xml
Note: The result with name "input" is because the validator returns the result to input when validation fails. - Create the properties file for messages
date.error.message=Date ${date} is not properly formatted.
package.properties
Note: In the properties file, ${date} is used to retrieve the "date" value from the value stack, this is the way Struts 2 supports parameterization. - Create the struts.properties file to set the theme to simple theme, so that you have more control how the UI components are laid out.
struts.ui.theme=simple
struts.properties
Tuesday, April 01, 2008
Integrating Struts 2.0 and tiles
I am currently evaluating some web frameworks for a pet project and was trying to implement Struts 2 with tiles. Neither the Sturts 2 website, nor the tiles website gave an easy way to integrated Struts 2 and tiles. It took me a while to get them to work together. This post describes a way I figured out how to integrate Struts 2 with tiles. Struts 2 provides a plugin for integrating tiles 2. This plugin is included in the complete bundle (struts-2.x.x.x-all.zip). The following are are the steps needed to integrate struts2 with tiles.
Skip to Sample Code
Skip to Sample Code
- Download the struts complete bundle from the struts 2 website
- Download tiles 2 from tiles 2 website
- Download the tiles dependencies from the jakarta commons site
- Commons BeanUtils 1.7.0 or above
- Commons Digester 1.8 or above
- Commons Logging 1.1 or above
- Create the layout page, and related files (except the layout, all the other files are basic jsps )
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<table width="100%" height="100%">
<tr height="20%">
<td colspan="2" align="center" bgcolor="skyblue">
<tiles:insertAttribute name="header" /></td>
</tr>
<tr>
<td bgcolor="cyan" width="75%"><tiles:insertAttribute name="body" /></td>
</tr>
<tr height="20%">
<td colspan="2" align="center" bgcolor="skyblue"><tiles:insertAttribute name="footer" /></td>
</tr>
</table>
</body>
</html> - Create the HelloWorld Action class
package example;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport {
public String execute() throws Exception {
System.out.println("Hello World");
return SUCCESS;
}
} - Configure the Web Deployment descriptor by adding a tiles listener to the web.xml file of your web application.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>tilesTest</display-name>
<listener>
<listener-class>
org.apache.struts2.tiles.StrutsTilesListener
</listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app> - Configure struts to work with tiles, this can be done by either
- Extending the sturts package from "tiles-default"
<package name="tilesTest" extends="tiles-default">
OR - Declaring a new "result-type", tiles, that will map to "org.apache.struts2.views.tiles.TilesResult"
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
- Extending the sturts package from "tiles-default"
- Set the type of the results in the package to "tiles"
<result name="success" type="tiles">helloworld.home</result>
struts.xml<?xml version="1.0" encoding="UTF-8" ?>
Note that the result "helloword.home" must match the definition name in tiles.xml file.
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="tilesTest" extends="struts-default">
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<action name="helloWorld" class="example.HelloWorld">
<result name="success" type="tiles">helloworld.home</result>
</action>
</package>
</struts> - Create definitions for tiles in WEB-INF/tiles.xml file.
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="helloworld.home" template="/layouts/layout.jsp">
<put-attribute name="header" value="/layouts/header.jsp" />
<put-attribute name="body" value="/index.html" />
<put-attribute name="footer" value="/layouts/footer.jsp" />
</definition>
</tiles-definitions> - The following is a list of jar files used for this example (copied to the WEB-INF/lib directory)
- commons-beanutils.jar
- commons-digester-1.8.jar
- commons-logging-1.1.1.jar
- freemarker-2.3.8.jar
- ognl-2.6.11.jar
- struts2-core-2.0.11.1.jar
- struts2-tiles-plugin-2.0.11.1.jar
- tiles-api-2.0.5.jar
- tiles-core-2.0.5.jar
- tiles-jsp-2.0.5.jar
- xwork-2.0.4.jar
- This example was implemented on tomcat 6.0.16, with Java 5 update 11
Friday, March 28, 2008
BlazeDS for Java-Flex communication
BlazeDS is a server-based Java remoting and web messaging technology that enables communication between back-end Java applications and Adobe Flex applications running in the browser. In this post, I describe a way (may not be the best) I was able to successfully to build a simple application using BlazeDS and Flex. The application is build using eclipse and ant, rather than using FlexBuilder. Following are the main steps that you have to follow to implement the example.
- Install tomcat
- Install Flex sdk
- Download BlazeDS web application.
- Create tomcat user with manager permisison
- Create dynamic web project in eclipse
- Create java file
- Create mxml file
- Update the config files in the WEB-INF/flex directory of the web application
- Copy flexTasks.tasks to the root directory.
- Create build file
- Copy catalina-ant.jar and flextasks.jar into ant lib directory, add them to ant runtime in eclipse.
- Build application using ant
- Install tomcat: This example was implemented on Tomcat 6.0.16
- Install Flex sdk: You can download the flex sdk from here The example was implemented on Flex 3.0.0
- Download BlazeDS:Download the BlazeDS web application from here
- Create tomcat user with manager permisison: In the TOMCAT_HOME/tomcat-users.xml, add the following line
<role rolename="manager"/>
<user username="abhi" password="abhi" roles="manager"/> - Create dynamic web project in eclipse by importing the BlazeDS Web application war file.
- Create java fileThe java class simply echoes the data input in the textbox shown in the browser.
package hello;
public class HelloWorld {
public String sayHelloTo(String str) {
System.out.println("Hello " + str);
return "Hello " + str;
}
} - Create mxml fileThe mxml file simply shows a text box and a submit button. A label will be displayed below the textbox with the word "Hello" appended to the input text.
<?xml version="1.0" encoding="utf-8"?>
Note: Defining the remote object enables you to make calls to the remote Java classes as if they are local action script classes.
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" viewSourceURL="srcview/index.html">
<mx:Script>
<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
[Bindable]
private var helloResult:String;
private function sayHelloTo():void {
ro.sayHelloTo(inputText.text);
}
private function resultHandler(event:ResultEvent):void
{
helloResult = event.result as String;
}
]]>
</mx:Script>
<mx:RemoteObject id="ro" destination="helloworld" result="resultHandler(event)" />
<mx:HBox width="100%">
<mx:TextInput id="inputText"/>
<mx:Button label="Submit" click="sayHelloTo()"/>
</mx:HBox>
<mx:Label text="{helloResult}"/>
</mx:Application> - Update the configuration files For this example, you only have to update one config file, WEB-INF/flex/remoting-config.xml, to add a new destination, the HelloWorld class.
<?xml version="1.0" encoding="UTF-8"?>
<service id="remoting-service"
class="flex.messaging.services.RemotingService">
<adapters>
<adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter" default="true"/>
</adapters>
<default-channels>
<channel ref="my-amf"/>
</default-channels>
<destination id="helloworld">
<properties>
<source>hello.HelloWorld</source>
</properties>
</destination>
</service> - Copy flexTasks.tasks to the root directory.
- Create build fileThe ant build file uses two flex specific tasks,
mxmlc
to compile the mxml file andhtml-wrapper
to create a html wrapper that contains the created swf file.<project name="helloWorldServer" default="build" basedir=".">
<!-- ===================== Property Definitions =========================== -->
<property file="build.properties" />
<property file="${user.home}/build.properties" />
<!-- ==================== File and Directory Names ======================== -->
<property name="app.name" value="helloWorldServer" />
<property name="app.path" value="/${app.name}" />
<property name="app.version" value="0.1-dev" />
<property name="build.home" value="${basedir}/build" />
<property name="catalina.home" value="C:/unzipped/apache-tomcat-6.0.16" />
<property name="dist.home" value="${basedir}/dist" />
<property name="docs.home" value="${basedir}/docs" />
<property name="manager.url" value="http://localhost:8080/manager" />
<property name="src.home" value="${basedir}/src" />
<property name="web.home" value="${basedir}/WebContent" />
<property name="manager.username" value="abhi" />
<property name="manager.password" value="abhi" />
<property name="FLEX_HOME" value="C:/Adobe/Flex" />
<property name="APP_ROOT" value="${basedir}/WebContent" />
<!-- ==================== External Dependencies =========================== -->
<!-- ==================== Compilation Classpath =========================== -->
<path id="compile.classpath">
<fileset dir="${catalina.home}/bin">
<include name="*.jar" />
</fileset>
<pathelement location="${catalina.home}/lib" />
<fileset dir="${catalina.home}/lib">
<include name="*.jar" />
</fileset>
</path>
<!-- ================== Custom Ant Task Definitions ======================= -->
<taskdef resource="org/apache/catalina/ant/catalina.tasks" classpathref="compile.classpath" />
<taskdef resource="flexTasks.tasks" classpath="c:/ant/lib/flexTasks.jar" />
<!-- ==================== Compilation Control Options ==================== -->
<property name="compile.debug" value="true" />
<property name="compile.deprecation" value="false" />
<property name="compile.optimize" value="true" />
<!-- ==================== All Target ====================================== -->
<target name="all" depends="clean,build" description="Clean build and dist directories, then compile" />
<!-- ==================== Clean Target ==================================== -->
<target name="clean" description="Delete old build and dist directories">
<delete dir="${build.home}" />
<delete dir="${dist.home}" />
</target>
<!-- ==================== Compile Target ================================== -->
<target name="build" depends="prepare" description="Compile Java sources">
<!-- Compile Java classes as necessary -->
<mkdir dir="${build.home}/WEB-INF/classes" />
<javac srcdir="${src.home}" destdir="${build.home}/WEB-INF/classes" debug="${compile.debug}" deprecation="${compile.deprecation}" optimize="${compile.optimize}">
<classpath refid="compile.classpath" />
</javac>
<!-- Copy application resources -->
<copy todir="${build.home}/WEB-INF/classes">
<fileset dir="${src.home}" excludes="**/*.java" />
</copy>
</target>
<!-- ==================== Dist Target ===================================== -->
<target name="dist" depends="build,javadoc" description="Create binary distribution">
<!-- Copy documentation subdirectories -->
<mkdir dir="${dist.home}/docs" />
<copy todir="${dist.home}/docs">
<fileset dir="${docs.home}" />
</copy>
<!-- Create application JAR file -->
<jar jarfile="${dist.home}/${app.name}-${app.version}.war" basedir="${build.home}" />
<!-- Copy additional files to ${dist.home} as necessary -->
</target>
<!-- ==================== Flex targets ==================================== -->
<target name="appcompile" depends="install">
<mxmlc file="${APP_ROOT}/helloWorld.mxml" context-root="/helloWorldServer" keep-generated-actionscript="true" services="${web.home}/WEB-INF/flex/services-config.xml" output="${catalina.home}/webapps/${app.name}/helloWorld.swf">
<compiler.library-path dir="${FLEX_HOME}/frameworks" append="true">
<include name="${web.home}/WEB-INF/lib/" />
</compiler.library-path>
<load-config filename="${FLEX_HOME}/frameworks/flex-config.xml" />
<source-path path-element="${FLEX_HOME}/frameworks" />
</mxmlc>
</target>
<target name="createHtmlWrapper" depends="appcompile">
<html-wrapper application="${APP_ROOT}/helloWorld.mxml" output="${catalina.home}/webapps/${app.name}" swf="helloWorld" />
</target>
<!-- ==================== Install Target ================================== -->
<target name="install" depends="build" description="Install application to servlet container">
<deploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" localWar="file://${build.home}" />
</target>
<!-- ==================== Javadoc Target ================================== -->
<target name="javadoc" depends="build" description="Create Javadoc API documentation">
<mkdir dir="${dist.home}/docs/api" />
<javadoc sourcepath="${src.home}" destdir="${dist.home}/docs/api" packagenames="*">
<classpath refid="compile.classpath" />
</javadoc>
</target>
<!-- ====================== List Target =================================== -->
<target name="list" description="List installed applications on servlet container">
<list url="${manager.url}" username="${manager.username}" password="${manager.password}" />
</target>
<!-- ==================== Prepare Target ================================== -->
<target name="prepare">
<!-- Create build directories as needed -->
<mkdir dir="${build.home}" />
<mkdir dir="${build.home}/WEB-INF" />
<mkdir dir="${build.home}/WEB-INF/classes" />
<!-- Copy static content of this web application -->
<copy todir="${build.home}">
<fileset dir="${web.home}" />
</copy>
<!-- Copy external dependencies as required -->
<mkdir dir="${build.home}/WEB-INF/lib" />
<!-- Copy static files from external dependencies as needed -->
<!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** -->
</target>
<!-- ==================== Reload Target =================================== -->
<target name="reload" depends="build" description="Reload application on servlet container">
<reload url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" />
</target>
<!-- ==================== Remove Target =================================== -->
<target name="remove" description="Remove application on servlet container">
<undeploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" />
</target>
</project> - Addtional ant configuration: Copy catalina-ant.jar and flextasks.jar into ant lib directory, add them to ant runtime in eclipse.
- To build and install the file, simply run the createHtmlWrapper target in ant
- The ant build file was created using the base build.xml file available on apache tomcat website.
- The config files are used as is available with the BlazeDS service.
Subscribe to:
Posts (Atom)
Popular Posts
-
This post will describe how to create and deploy a Java Web Application war to Heroku using Heroku CLI. You will need a basic understanding ...
-
In a previous post, I described how to use Quartz scheduler for scheduling . In this post, I describe the configuration changes required for...
-
The previous post described how to implement a JMS messaging client using Spring JMS . This post will describe how to implement the Message ...
-
New posts with iText 5.5.12 Following are two new posts for PDF Merge with iText 5.5.12 Merge PDF files using iText 5 Merge and Paginate PDF...
-
JUnit 4 introduces a completely different API to the older versions. JUnit 4 uses Java 5 annotations to describe tests instead of using in...
-
Previously, I wrote a post describing the use of Apache Axis to create and consume Web Services from Java . In this post, I will describe ho...
-
In this post we will see how to do an offline install Jenkins and required plugins on a Red Hat Enterprise Linux Server release 7.3. This is...
-
In the past, I had a few posts on how to implement pagination using displaytag( 1 , 2 ). That solution is feasible only with small result se...
-
Acegi Security provides a comprehensive security solution for J2EE-based enterprise software applications, built using the Spring Framework...
-
I came know of this quite recently. I find it quite useful. Apart from being able share your bookmarks across browsers, you can now share th...