顯示具有 Spring 標籤的文章。 顯示所有文章
顯示具有 Spring 標籤的文章。 顯示所有文章

2008年8月31日 星期日

How to add scripting support in your application

This is a very interesting question, I encountered these days.
Here is the question I was asked. "How to let some behaviors can be changed after system deploy"
The first idea comes to my mind is using late binding design pattern such as factory pattern.
If the factory pattern can be accepted, all I have to do is providing a properties file for customize setting and designing a factory class using a reflect method to load the specified class in the properties file.
Unforunatly, the factory pattern was not accepted, due to the setting of customize environment would be too complex for our user. Hence, I need a customize environement like Visual Basic Application in MS-Office. In Spring framework [1], they do provide the integration with several dynamic languages, such as Ruby, Groovy and Beanshell.
In my system, I hope all the service classes can be customized. Hence, I design a customize service interface with following functions to support the scripting environment.



public interface Action
{
public void setDao(Dao dao);
public void input(Map arg);
public boolean validate();
public void doActionPre();
public boolean doAction();
public void doActionPost();
}
public interface Service
{
public void setXXXXAction(Action action);
}

The second step import the dynamic-language-backed bean's XML schema definition as following:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">

Then define the dynamic-language-backed bean

<lang:groovy refresh-check-delay="60000" id="scriptCustomizeAction" script-source="classpath:CustomizeAction.groovy">
<lang:property name="dao" ref="myDao"/>
</lang:groovy>

<!-- an otherwise normal bean that will be injected by the Groovy-backed Messenger -->
<bean id="myService" class="x.y.MyService">
<property name="xXXXAction" ref="scriptCustomizeAction" />
</bean>



/*CustomizeAction.groovy*/
package x.y;
class CustomizeAction implements Action
{

public void setDao(Dao dao)
{

}
public void input(Map arg)
{

}
public boolean validate()
{
}
public void doActionPre()
{
}
public boolean doAction()
{
}
public void doActionPost()
{
}
}

Here are some points you must be aware in your scripting task[4].

  • The "scope" of the scripting bean is "singleton" in default. It also can be prototype.
  • If your scripting beans do not implements any java interface and you try to inject one scripting bean into another scripting bean as property, your program will throw Exception because springframework cannot use reflection to find the proper set method.
  • If you use groovy as your dynamic language, please don't define more than one class per Groovy source file.
Finally, we need some libraries to enable the dynamic language feature in Spring framework.
  • groovy-1.5.5.jar
  • asm-2.2.3.jar
  • antlr-2.7.6.jar

Reference.
  1. http://static.springframework.org/spring/docs/2.0.x/reference/dynamic-language.html
  2. http://book.javanb.com/Professional-Java-Development-with-the-Spring-Framework/BBL0079.html
  3. http://www.javaworld.com/javaworld/jw-10-2003/jw-1003-beanshell.html
  4. http://scriptlandia.blogspot.com/2007/03/how-to-build-completely-dynamic-example.html
  5. http://www.xeniumhk.com/blog/?postid=54

2008年8月19日 星期二

JUnit4, Spring, and Ant integration

JUnit4[1] provides a set of annotations to help programmer write unit test with more easy way. you can find an introduction documents on the JUint offical web site.
Spring 2.5.5[2] is the latest Spring framework release. In this release, annotation programming support is also an important focus. Spring framework provides an enhanced
class named SpringJUnit4ClassRunner, which is a custom extension of JUnit4ClassRunner.
So, I use this new feature into my test cases and list as following.

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({})
@ContextConfiguration(locations={"/applicationContext.xml"})
public class OrderProcessDaoTest extends AbstractJUnit4SpringContextTests {

@Autowired
private OrderProcessDAO orderDao;

@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
}

@Test
public void testGetNewOrders() {
if(orderDao == null)
fail("orderDao is null");
}
}

I also have an ant script to help me organize the build process.
The version of ant package is 1.7.1
Everything looks perfect, isn't it?

Well, the nightmare came to me when the first time I entered the "ant test-dao".

The ant output report a error said a method testAborted is not found.
then, another error came out said org.junit.internal.runners.JUnit4ClassRunner class not found.

I try to find the solution on the web.
[news.eclipse.platform] Ant junit 4 problem http://dev.eclipse.org/newslists/news.eclipse.platform/msg65786.html
Spring 2.5: Eclipse reports "JUnit4ClassRunner cannot be resolved" http://forum.springframework.org/showthread.php?t=47289
Named TestSuite gives error in JUnit_4.1 used w/Eclipse http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=68&t=001783
Problems running JUnit http://www.nabble.com/Problems-running-JUnit-td6915754.html
... you can find more just using "junit4 testAborted" as keyword to google.

Then I reviewed my enviroment, I found there exist several different version of junit.
In eclipse, junit 4.3 is in the feature plugin folder.
In ant's lib folder, there exists an junit 3.8.jar
In spring's lib folder, there exists an junit 4.4.jar.

In order to pass all the error found by the compiler, I choose spring's junit as my primary junit jar file.
After remove and redirect the classpath to junit.4.4 I solved this problem.

One strange thing I found is the junit.jar in spring framework seems inconsistency from JUnit offical site.
Once, I used the JUnit from spring everything is perfect.

Reference.
1.http://www.junit.org/
2.http://www.springframework.org/

2008年7月23日 星期三

Build Spring & Hibernate based application from scratch

Introduce
I was used to develop my system based on some well designed and integrated framework such as Appfuse. The integrated framework can shorten a lot of development time. So, I never think about build my own application from scratch. Until I starting to code the system for my PHD dissertation.
The major goal of dissertation is to develop a manufacture information platform for distributed mass customization by using inteligence agent. In order to let my agent can inline with my previous development effort, Spring and Hibernate framework integration become my first step to conquer.

Project Layout
Figure 1. shows the project layout. The most important things in Figure 1 is the lib folder.


Figure 1. Project layout
In order to use Spring and Hibernate in my project, I have to import these related jar files into the build path of my project.
The most easy way to test the project layout is correct or not is write a small program to load the Spring configuration.
For Example, create a Java class with a static main function and in the declare area put the following code.


protected final static ApplicationContext ctx;
static{
String[] paths = {"applicationContext.xml",};
ctx = new FileSystemXmlApplicationContext(paths);
}

public static void main(String[] args)
throws IOException
{
}

Well, you will need the Spring configuration file. I named this configuration as ApplicationContext.xml and list as following:

<?xml version="1.0" encoding="UTF-8"?>
<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.5.xsd"
>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/agentpjm?useUnicode=true&amp;characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="h300"/>
<property name="maxActive" value="100"/>
<property name="maxIdle" value="30"/>
<property name="maxWait" value="1000"/>
<property name="defaultAutoCommit" value="true"/>
<property name="removeAbandoned" value="true"/>
<property name="removeAbandonedTimeout" value="60"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="hibernateProperties">
<value>
hibernate.dialect=${hibernate.dialect}
hibernate.query.substitutions=true 'Y', false 'N'
hibernate.cache.use_second_level_cache=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
</value>
<!-- Turn batching off for better error messages under PostgreSQL -->
<!-- hibernate.jdbc.batch_size=0 -->
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>

Put this file in the root of the project folder and run the program, there should be no exception appear in the window, then we can start to add Hibernate configuration and prepare the data access object(DAO).

Reference.
  1. http://www.findjar.com
  2. http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/
  3. http://www.hibernate.org/hib_docs/reference/en/html/session-configuration.html