Friday, May 11, 2012

Spring Configuratiosn for JTA Transaction - XA datasource (Mysql) + Atomikos Transaction manager + Spring Transaction annotations





Mysql complaint mysql xa datasource  and Atomikos connection pooling



 <bean id="dataSource" class="com.atomikos.jdbc.AtomikosDataSourceBean"
  init-method="init" destroy-method="close">
  <property name="uniqueResourceName" value="MAIN-ATOMIKOS-CONNECTION" />
  <property name="poolSize" value="${initialSize}" />
  <property name="xaDataSourceClassName"
   value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" />
  <property name="xaProperties" ref="databaseProperties" />
  <property name="testQuery" value="select 1" />
 </bean>




database.properties


<util:properties id="databaseProperties"
  location="classpath:database.properties" />



url=jdbc\:mysql\://localhost\:3306/<DBNAME>
user=root
password=
autoReconnect=true
autoReconnectForConnectionPools=true
autoReconnectForPools=true
pinGlobalTxToPhysicalConnection=true


Transaction specific Config

Following settings are for enabling transactions

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" 
  init-method="init" destroy-method="close"> 
           <property name="forceShutdown"> <value>true</value> </property> 
</bean>

<bean id="atomikosUserTransaction" 
  class="com.atomikos.icatch.jta.UserTransactionImp">
            <property name="transactionTimeout" 
  value="300"/> 
</bean> 

<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"> 
  <property name="transactionManager"> <ref bean="atomikosTransactionManager" 
  /> </property> 
              <property name="userTransaction"> <ref bean="atomikosUserTransaction" 
  /> </property> 
</bean> 




Just adding spring Spring annotation - will now enable transaction on required methods.


Wednesday, March 21, 2012

Finding java thread which takes highest CPU

1 .Get the process id of java process

ps -aefww

2. Get all threads and CPU it consumes

ps -eLo pid,lwp,nlwp,ruser,pcpu,stime,etime,args|grep PROCESS ID

Convert llwp from decimal to hex (so 8245 would be 2035)

3. Take thread dump of java process

now open the thread dump with text editor and search for 2035, you will find something similar:
"TP-Processor234786" daemon prio=10 tid=0x00002aaad8024800 nid=0x2035 runnable [0x00002aaadef29000]
java.lang.Thread.State: RUNNABLE
at java.util.HashMap.get(HashMap.java:303)
at ......


Ref :http://javadrama.blogspot.co.uk/2012/02/why-is-java-eating-my-cpu.html

Friday, February 4, 2011

Spring AOP - Changing target of a Proxy at runtime

I had a pretty strange usecase where i wanted to change the target object of the proxy and runtime. Spring makes it so simple to use.

My usecase was as follows



ApplicationContext ctx = new ClassPathXmlApplicationContext(
"classpath:META-INF/spring/aop-poc-module-context.xml");
AccountDAO accountDao = (AccountDAO) ctx.getBean("accountDao");

IAccount account = accountDao.getById(123);

System.out.println("account" + account);

account.setName("sudheer");

System.out.println("account" + account);



Is a property is change on the entity , i want to change the entity object itself , that is , in the above use two sysouts will print different objects.

The use case arose because i was using a cache(infinispan) which did not allow modifying POJOs outside a transaction scope.

I did achieve the same using the follwing



public class AccountDAO {

private Advisor advisor;

//This is get methods of the accountDao

public IAccount getById(long id) {
//creating new account - to mock database behavior
IAccount a = new Account(369, "suji");
//Using spring factory
ProxyFactory pf = new ProxyFactory();
pf.setExposeProxy(true);
pf.addInterface(IAccount.class);
//Using by own Target source to change the Target
pf.setTargetSource(new SwappableTargetSource(a));
//advisor which holds the advice and pointcut
pf.addAdvisor(advisor);
return (IAccount) pf.getProxy();
}

public void setAdvisor(Advisor advisor) {
this.advisor = advisor;
}

}



My advice class



public class SwappableBeforeAdvice implements MethodBeforeAdvice {

@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("Before advice called");

if (!((IAccount) target).isWritable()) {

//Changing the target source based on specific business condition
((SwappableTargetSource) ((Advised) AopContext.currentProxy())
.getTargetSource()).swap(new Account(56, "dan"));
}

}
}



My custom target source



public class SwappableTargetSource implements TargetSource {

private Object target;

public SwappableTargetSource(Object initialTarget) {
this.target = initialTarget;
}

public synchronized Class<?> getTargetClass() {
return this.target.getClass();
}

public final boolean isStatic() {
return false;
}

public synchronized Object getTarget() {
return this.target;
}

public void releaseTarget(Object target) {
// nothing to do
}

public synchronized void swap(Object newTarget)
throws IllegalArgumentException {
this.target = newTarget;
}

@Override
public boolean equals(Object other) {
return (this == other || (other instanceof SwappableTargetSource && this.target
.equals(((SwappableTargetSource) other).target)));
}

@Override
public int hashCode() {
return SwappableTargetSource.class.hashCode();
}

@Override
public String toString() {
return "SwappableTargetSource for target: " + this.target;
}

}



These are the spring xml configuration.



<bean id="accountDao" class="com.test.dao.account.AccountDAO">
<property name="advisor" ref="settersAdvisor" />
</bean>

<bean id="swapableBeforeAdvice" class="com.test.framework.SwappableBeforeAdvice"/>



This is the advice which advise all setter methods on the bean



<bean id="settersAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="swapableBeforeAdvice" />
</property>
<property name="patterns">
<list>
<value>.*set.*</value>
</list>
</property>
</bean>



Thanks to this post in spring forum which helped me do this.

http://forum.springsource.org/showthread.php?t=102784

Unit test framework with Liquibase+HsqlDb+Spring transactions

When looking at options for testing DAO classes I came up with a framework using the following

1. Liquibase - For maintaing data/schema scripts

2. HSQLDB - Inmemory database for test cases

3. Spring transactions - For maintaining clean state between two test cases which make DB updates i .e all data changes made by the test cases will be rolled back by the end of the test case.


I am using spring beans to initialize all the above. I will explain each of them in detail.

1. Initializing the HSQLDB



<context:property-placeholder
location="classpath*:tspex-test-inmemorydatabase.properties" />

<bean id="hsqlDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${database.driverClassName}">
<property name="url" value="${database.url}">
<property name="username" value="${database.username}">
<!-- <property name="password" value="${jdbc.password}"> -->
</bean>



All the values will be picked up from the file mentioned in the classpath.

2. Setting up Liquibase

I am using the following method to initialize Liquibase



public class TestFramework {

private DataSource dataSource;

public void initializeLiquiBase(String changeLogFile) throws Exception {
Connection conn = dataSource.getConnection();
Liquibase liquibase = new Liquibase(changeLogFile,
new ClassLoaderResourceAccessor(), new HsqlConnection(conn));
// Uncomment the following line when testing with mysql database
/*
* Liquibase liquibase = new Liquibase(changeLogFile, new
* ClassLoaderResourceAccessor(), new JdbcConnection(conn));
*/

liquibase.update("");
conn.close();
}

public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}

}



Corresponding spring configuration.



<bean id="testFramework" class="com.mycompany.framework.unittest.TestFramework">
<property name="dataSource" ref="hsqlDataSource">
</bean>



The changeLogFile will be provided by the user of the frame work , which i will explain shortly.


3. Setting up Spring transactions.



<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="hsqlDataSource">
</bean>

<tx:annotation-driven manager="transactionManager">



These are the only classes/configuration present in my framework

The maven dependencies required are as follows



<dependency>
<groupid>org.hsqldb</groupid>
<artifactid>hsqldb</artifactid>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupid>org.liquibase</groupid>
<artifactid>liquibase-core</artifactid>
<version>2.0.0</version>
</dependency>
<dependency>
<groupid>org.liquibase</groupid>
<artifactid>liquibase-plugin</artifactid>
<version>1.9.5.0</version>
</dependency>
<dependency>
<groupid>junit</groupid>
<artifactid>junit</artifactid>
<version>4.7</version>
</dependency>



Now let me explain how the framework will be used by the classes testing the framework


A typical test class for DAO will be as follows



@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath*:/META-INF/spring/unit-test-framework-module-context.xml",
"classpath*:/META-INF/spring/test-spring-jdbc-module-context.xml" })
public class TestAccountDAOSpringJdbc {

@Autowired
private TestFramework testFramework;

@Autowired
private AccountDAOSpringJdbc accountDao;

@Test
public void setUpBeforeClass() throws Exception {
System.out.println("Setup before class called");
testFramework.initializeLiquiBase("accounts-data-changelog-1.0.xml");


@Test
@Transactional
public void testSaveUpdate() throws Exception {
// Create a new Account
Account account = accountDao.get(1);
account.setUsername("newaccount");
account.setTitle("Mr");

........


}



The important thing to note here are

1. Initializing the framework beans - which contains HSQLDB and spring transaction initialization.

2. Initializing the test framework with liquibase scripts

This ensure that the database tables are created and test data is inserted before test cases run.

Ref: http://www.liquibase.org/

3. Using @Transactional annotation before test cases which updates the Database . This ensures that test cases do not commit anything into DB and all test cases can be independent of each other.

With some infrastructure setup like this , writing test cases for DAO become very easy.

Friday, January 21, 2011

Bamboo

Bamboo is another available tool for setting Continuous Integration in your environment. Its one of the simplest tools i have come across for building a continuous integration system.

http://www.atlassian.com/software/bamboo/

The website shows a 10 minute tutorial which helps in setting up and starting the continuous integration server. The configuration options with this tool are very simple and helps in setting up the environment through the user interface available in this tool.

It has easy integration with build tools like Maven, Ant etc.

Maven

I have been using ant for a pretty long time and i was very comfortable with the flexibility it gives , until i started using Maven. Its almost been a month since i have started using maven , and i feel i will never go back to ant.

Maven works on the principle on "Convention over Configuration" .

Basic convention is each module builds a single artifact and there is a pom file associated with each module which describes all the dependencies required by the module and the properties of the module. The pom file when run can help you do a lot of things like

Compile the code.
Build the Jar
Run the test cases.
Build Java Docs ...etc and many more

Each of the above tasks belong to a particular phase in the Maven build cycle. The best things to use Maven is with a IDE like Eclipse or STS which has complete support for maven.

After i thought about writing the basics of Maven , i came across this blog from spring source which in details explains about the basics of Maven which should be a good starting point.

http://blog.springsource.com/2011/01/17/green-beans-getting-started-with-maven-and-spring/

Maven comes in with easy integration for build tools like Bamboo, Hudson and Cruisecontrol.

Once you start using Maven managing the modules. its version and its dependencies becomes a very simple task.

Wednesday, November 3, 2010

Spring Bean Life Cycle Phases

I want to demonstrate the bean Life Cycle with a help of a simple Example.

Phase 1. BeanPostProcessor: Bean definitions are changes here.

[Example : Property file replacement as property values.]

Phase 2: Object Creation Phase

Phase 3 :Setting Required Dependencies

Phase 4: Initialization Phase


There is a separate phase called BeanPostProcessor phase in which there the bean itself can be changes.

The org.springframework.beans.factory.config.BeanPostProcessor interface consists of exactly two callback methods. When such a class is registered as a post-processor with the container (see below for how this registration is effected), for each bean instance that is created by the container, the post-processor will get a callback from the container both before any container initialization methods (such as afterPropertiesSet and any declared init method) are called, and also afterwards. The post-processor is free to do what it wishes with the bean instance, including ignoring the callback completely.

Spring uses runtime AOP and hence creates proxy based implementation using this phase.
Since AOP auto-proxying is implemented as a BeanPostProcessor itself, no BeanPostProcessors
or directly referenced beans are eligible for auto-proxying (and thus will not have aspects 'woven' into them.

In my sample example i will not be talking about BeanFactoryPostProcessorPhase or BeanPostProcessor instaed will be concentrating on the phases.

Consider teh following three simple classes.



public class Bean1{

private Bean2 bean2;

private Bean3 bean3;

public void setBean3(Bean3 bean3) {
this.bean3 = bean3;
System.out.println("Setter Called For bean3");
}


public Bean1(Bean2 bean2) {
super();
this.bean2 = bean2;
System.out.println("Bean 1 constructor called");
}

public void init() {
System.out.println("Init of bean1 method called");
}

}






public class Bean2 {

private Bean1 bean1;

public Bean2() {
super();
System.out.println("Bean2 constructior Called");
}

public void setBean1(Bean1 bean1) {
this.bean1 = bean1;
System.out.println("Setter Called");
}

public void init() {
System.out.println("Init of bean2 method called");
}

}






public class Bean3 {

public Bean3() {
super();
System.out.println("Construictor Called for Bean3");
}

private Bean1 bean1;

public void setBean1(Bean1 bean1) {
this.bean1 = bean1;
System.out.println("Setter for Bean1 Called in Bean3");
}

public void init() {
System.out.println("Init Called For Bean3");
}

}




The spring xml will be as follows



<bean id="bean1" class="com.test.Bean1" init-method="init">
<constructor-arg ref="bean2"></constructor-arg>
<property name="bean3" ref="bean3"></property>
</bean>

<bean id="bean2" class="com.test.Bean2" init-method="init">
</bean>

<bean id="bean3" class="com.test.Bean3" init-method="init">
<property name="bean1" ref="bean1"></property>
</bean>




OutPut :

Bean2 constructior Called
Init of bean2 method called
Bean 1 constructor called
Construictor Called for Bean3
Setter for Bean1 Called in Bean3
Init Called For Bean3
Setter Called For bean3
Init of bean1 method called

Let me explain how this workz

Phase 2: Object Creation Phase
Phase 3: Initialization Phase
Phase 4: Setting Required Dependencies


bean1 : Phase2(started) - Tries to create object.Since the constructor requires bean2 goes to beans 2

bean2 : Phase2(started->completed) - Creates teh object(Hence sysout from constructor)
bean2 : Phase3(started->completed) - Nothing to be done as no property setters are present
bean2 : Phase4(started->completed) - Calls init method(As there are no property values to be Set)

bean1 : Phase2(completed) - Since beans 2 is ready this phase will complete(constructor sysout printed)
bean2 : Phase3(started) - Checks for dependency and finds bean3

bean3 : Phase2(started->completed) - Creates teh object(Hence sysout from constructor)
bean3 : Phase3(started->completed) - Sets the dependencies. [******** beans 3's init is called b4 bean1's init]
bean3 : Phase4(started->completed) - Init method called.

bean1 : Phase3(started->completed) - Setters called
bean1 : Phase4(started->completed) - Init Method called.


Hence all the beans go through these individual life cycle methods.

The following is the ordering for initialization methods based on the approach followed for initializing:
[All these are part of Phase4 above]
• Methods annotated with @PostConstruct
• afterPropertiesSet() as defined by the InitializingBean callback interface
• A custom configured init() method


In all the cases spring tries to ensure that before dependencies(beans) are set , the dependency(bean) is properly initialized.(dependency set and init called). {**** -Not always true for simple property injection - i. e before bean is injected its(injected bean) init may not have been called }

This is strict for Constructor injection.[In the above case if we try to modify the bean definition for bean 3 as follows]

<bean id="bean2" class="com.test.Bean2" init-method="init">
<property name="bean1" ref="bean1"></property>
</bean>


We get the following Exception

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'bean1': Requested bean is currently in creation: Is there an unresolvable circular reference?


This is because bean1's constructor depends on bean2. and bean2 has a setter which is bean1. Bean2 just after completing phase 2(object creation will not be injected into constructor , will wait for all phases to complete)

***** - But this is not the case with simple property injected.

Ex : Bean1 and Bean 2 injected visa versa will work fine.

 
Free Domain Names @ .co.nr!