Saturday, October 20, 2012

Template method Pattern and Spring Framework

Template method Pattern and Spring Framework

Why Spring Uses Template Method Pattern?

As Spring technology configures, instantiates and maintains objects in IoC container  as beans injects them into needed dependent beans.
And Template Method Pattern is Mother of all Frameworks, and components in SpringFramework. Spring and its all Template components like JDBC Template, JMS Template are instantiating beans in the same way. Also let developer to extend them.

What is Template Method Pattern?

The template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets programmer redefine certain steps of an algorithm without changing the algorithm's structure.
If we declare a abstract class or framework it has to perform some operations, we declare all methods one method which call all the other methods to perform a respective operation.
Like if we have a class EmployeeRegister and which serves users registerEmployee() and to register employee we have to perform following three operations like
getEmployeeDetails()
generateNewRegNo()
registerNewEmployee().
These methods are abstract and let users to override. But we let the user to call only one method from outside registerEmployee().

EmployeeDO registerEmployee()
{

getEmployeeDetails();
generateNewRegNo();
registerNewEmployee();

}
So when implementing this abstraact class we have to override the these methods.
Finally this pattern let users to perform the registering also let him to override the methods.In simple words make a class "Open for Extension but closed for Modification"
like here we can extend how to do registration but not able to modify the steps.

What is Ioc?

           " Do not call me ! I will call you ! ".

First we will see the problem of "Tight Coupling".
class Customer()
{
private Address address;
private AccountDetails accountDetails;

Customer()
{
address = new Address();
accountDetails = new AccountDetails():
}
}

Here the problem is creation of instances of Address and AccountDetails.It is fully depends on Customer. So it is tightly coupled.
Now that we know the issue, let’s understand the solution. The solution definitely revolves around shifting the object creation control from the customer class to some one else. Solution comes with concept IoC it resolves the instantiating the objcets and looses the objects from other. So objects are instantiated individually at common place called IoC container and shared across beans though DI process.
And they are injected to the classes which calls them. Like in our case Address and AccountDetails are instantiated and injected to Customer instance this process called as Dependency Injection.

What are all the templates uses this Pattern?

As Spring let the users to extend its all components like JDBC Template, JMS Template, etc.,. uses this same method.
They declares its abstract components, developers have to implement them by extending. He cant modify the steps but have to extend and override the methods.
Also Spring uses all instantiating are maintained as beans created at common place and injected to other beans.

Saturday, March 10, 2012

Threads in J2EE

Hi Java Dudes,




The most confusing, critical programming in Java Programming is Thread Programming.
Even in Stand-alone running app, it needs deep understanding of JVM, Threads, and design analysis to develop app. In J2EE environment it is very pathetic, tedious job to manage them.
So we have to knwo some understand them B4 coding.
Here i am giving a overview on Thread Management in stand alone and Sprign based J2EE app.


If you need control and manage threads in


Stand alone Application :---


+ Better use "
java.util.concurrent.ThreadPoolExecutor
ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,
TimeUnit unit,BlockingQueue ;Runnable workQueue)

Give your Task you want to run Asynchronously.
Set Pool Size Maximum to limit the number of threads.
Set the Maximum alive time for threads to live in this.

corePoolSize - the number of threads to keep in the pool, even if they are idle.
maximumPoolSize - the maximum number of threads to allow in the pool.
keepAliveTime - when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
unit - the time unit for the keepAliveTime argument. (Seconds , or minutes )
workQueue - the queue to use for holding tasks before they are executed.
This is the ultimate way for Thread management in Java Apps, Swing based Apps, Stand alone Batch jobs .


What about J2EE ?


I dont know about otherframeworks like (JSF, Struts, Blah blah.....), But Spring the provides lot of Bean Drivenable Thread Executors :


I suggest to use the ultimate one :
ThreadPoolTaskExecutor.
Properties to be set same as above .

Declare it as a bean and use wher eu want to spawn threads.



Thanks

Balaji.Mathu@gmail.com

Tuesday, January 31, 2012

Sample Code For Spring JMS Template with HornetQ Messaging System in JBoss-5.1 Server

Dear Chennai Java Buddies,

****** : For Any Clarifications, Doubts
Mail to : Balaji.mathu@gmail.com



Here I am giving sample code, configuration for Create JMS Queue in Jboss with 3rd Party Messaging System (HornetQ). And giving spring configuration, code to send and receive messages throught the Queue.


HornetQ Introduction & Why we go for:


1> HornetQ is an open source project to build multi-protocol (TCP, SSL, Servlet), embeddable, very high performance, clustered, asynchronous Messaging System from JBoss.
2> It can be used as standalone, or on any application server, or embedded in our applications.
3> It delivers amazing messaging performance.
4> It provides seamless clustering capabilities.
5> Most Important: It is the default messaging system in JBoss-6.0 / forthcoming JBoss Servers.
6> Security Features of JBoss – JAAS can be implemented.



HornetQ Installation on JBoss Server 4.x/ 5.x:


1> Download the latest from http://www.jboss.org/hornetq/downloads.html. Extract it.
2> As we want to embed HornetQ in JBoss we have to run the script build.sh located in “ HORNETQ-HOME/config/jboss-as-4” or “ HORNETQ-HOME/config/jboss-as-5”. Before that we have to set up JBOSS_HOME path.
3> After the script ran it will create two additional JBoss configurations in JBoss are “default-with-hornetq” and “all-with-hornetq” inside /server folder. These folders have the configurations files for HornetQ.
4> Also the needed HornetQ API jars will be created in JBoss’s lib folder. So now the JBoss is ready with HornetQ.


1. HornetQ Queues Configuration in JBoss:
/Servers/jboss-5.1/server/default/deploy/hornetq.sar/hornetq-jms.xml
----connection-factory name="MyConnectionFactory"--
----connectors--
----connector-ref connector-name="in-vm"/--
----/connectors--
----entries--
----entry name="java:jms/MyConnectionFactory"/--
----entry name="java:jms/MyConnectionFactory"/--
----/entries--
----/connection-factory--
----queue name="myQueueOne"--
----entry name="java:jms/queue/myQueueOne"/--
----durable--true--/durable--
----/queue--

--queue name="myQueueTwo"--
--entry name="java:jms/queue/myQueueTwo"/--
--durable--true--/durable--
--/queue--

2. Spring JMS Template Configuration:
2.1 ~/MyApplication.war/WEB-INF/config/spring/jndi-lookup.xml

--?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:p="http://www.springframework.org/schema/p"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"--
--jee:jndi-lookup id="connectionFactory" jndi-name="java:jms/MyConnectionFactory" resource-ref="true"/--
--jee:jndi-lookup id="myQueueOne" jndi-name="java:jms/queue/myQueueOne" resource-ref="true"/--
--jee:jndi-lookup id="myQueueTwo" jndi-name="java:jms/queue/myQueueTwo" resource-ref="true"/--
--/beans--


2.2 ~/MyApplication.war/WEB-INF/config/spring/jms-listener.xml
--?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:util="http://www.springframework.org/schema/util"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"--
--bean id="queueOneTemplate" class="org.springframework.jms.core.JmsTemplate"--
--property name="connectionFactory" ref="connectionFactory" /--
--property name="defaultDestination" ref="myQueueOne" /--
--property name="pubSubDomain" value="false" /--
--property name="receiveTimeout" value="1000" /--
--/bean--
--bean id="queueTwoTemplate" class="org.springframework.jms.core.JmsTemplate"--
--property name="connectionFactory" ref="connectionFactory" /--
--property name="defaultDestination" ref="myQueueTwo" /--
--property name="pubSubDomain" value="false" /--
--property name="receiveTimeout" value="1000" /--
--/bean--
--!—My Queue Listeners ----
--bean id="queueOneListener"
class="com.test.jms.msg.listeners.MyQueueOneListener"--
--/bean--
--bean id="queueTwoListener"
class="com.test.jms.msg.listeners.MyQueueTwoListener"--
--/bean--


--!-- Container for MyQueue Message and Delegation ----
--bean id="queueOneContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer"--
--property name="taskExecutor" ref="mdpPoolTaskExecutor" /--
--property name="connectionFactory" ref="connectionFactory" /--
--property name="messageListener" ref="queueOneListener" /--
--property name="destination" ref="myQueueOne" /--
--property name="concurrentConsumers" value="5" /--
--property name="maxConcurrentConsumers" value="50" /--
--property name="pubSubDomain" value="false" /--
--property name="cacheLevelName" value="CACHE_CONSUMER" /--
--property name="idleTaskExecutionLimit" value="100" /--
--property name="sessionTransacted" value="true" /--
--property name="autoStartup" value="true" /--
--/bean--

--bean id="queueTwoContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer"--
--property name="taskExecutor" ref="mdpPoolTaskExecutor" /--
--property name="connectionFactory" ref="connectionFactory" /--
--property name="messageListener" ref="queueTwoListener" /--
--property name="destination" ref="myQueueTwo" /--
--property name="concurrentConsumers" value="1" /--
--property name="maxConcurrentConsumers" value="5" /--
--property name="pubSubDomain" value="false" /--
--property name="cacheLevelName" value="CACHE_CONSUMER" /--
--property name="idleTaskExecutionLimit" value="100" /--
--property name="sessionTransacted" value="true" /--
--property name="autoStartup" value="true" /--
--/bean--
--bean id="mdpPoolTaskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"--
--property name="corePoolSize" value="5" /--
--property name="maxPoolSize" value="50" /--
--property name="queueCapacity" value="250" /--
--property name="threadNamePrefix" value="MDP-WorkerThread" /--
--/bean--

--/beans--


3. Application Code to Perform Messaging:
3.1 com.test.jms.msg.listeners.MyQueueOneListener

package com.test.jms.msg.listeners;

import java.util.StringTokenizer;
import java.util.concurrent.Executor;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import org.springframework.jms.core.JmsTemplate;


/**
* @author balaji_madhaiyan
*
*/
public class MyQueueOneListener implements MessageListener
{
private JmsTemplate actionRequestTemplate,actionResponseTemplate;
public void onMessage(Message mesg)
{
System.out.println("New Message Received");
ObjectMessage msg = (ObjectMessage) mesg;
try
{
MessageDO vo = (MessageDO) msg.getObject();
String str = null;
str = vo.getMsg();
System.out.println("Message Received at MyQueueOneListener:"+ str);
}
catch (JMSException e)
{
System.out.println("Error at MyQueueOneListener : "+e.getMessage());
}
}

3.2 com.test.jms.msg.listeners.MyQueueTwoListener
package com.test.jms.msg.listeners;

import java.util.StringTokenizer;
import java.util.concurrent.Executor;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import org.springframework.jms.core.JmsTemplate;


/**
* @author balaji_madhaiyan
*
*/
public class MyQueueTwoListener implements MessageListener
{

private JmsTemplate actionRequestTemplate,actionResponseTemplate;
public void onMessage(Message mesg)
{
System.out.println("New Message Received");
ObjectMessage msg = (ObjectMessage) mesg;
try
{
MessageDO vo = (MessageDO) msg.getObject();
String str = null;
str = vo.getMsg();
System.out.println("Message Received at MyQueueTwoListener:"+ str);
}
catch (JMSException e)
{
System.out.println("Error at MyQueueOneListener : "+e.getMessage());
}

}
3.3 com.test.jms.msg.listeners.MyMessageDO
package com.test.jms.msg.do;

import java.io.Serializable;
public class MessageDO implements Serializable
{

private String type;
private String msg;

public MessageDO(String type, String msg)
{
super();
this.type = type;
this.msg = msg;
}


public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public String getMsg()
{
return msg;
}
public void setMsg(String msg)
{
this.msg = msg;
}
}


3.3 com.test.jms.msg.listeners.MyMessageSender
package com.test.jms.msg.senders;

import java.util.List;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.scheduling.annotation.Scheduled;
import com.test.jms.msg.listeners.MyMessageDO;
import com.test.jms.msg.listeners.MyQueueTwoListener;
import com.test.jms.msg.listeners.MyQueueTwoListener;

public class MyMessageSender
{
@Autowired
private JmsTemplate queueOneTemplate, queueTwoTemplate;

//To Queue One
private void pushToQueueOne()
{
queueOneTemplate.send(new MessageCreator()
{
public Message createMessage(Session session) throws JMSException
{
ObjectMessage msg = session.createObjectMessage();
MessageDO dObj = new MessageDO("Msg", message);
msg.setObject(dObj);
return msg;
}
});
}
//To Queue Two
private void pushToQueueOne()
{
queueTwoTemplate.send(new MessageCreator()
{
public Message createMessage(Session session) throws JMSException
{
ObjectMessage msg = session.createObjectMessage();
MessageDO dObj = new MessageDO("Msg", message);
msg.setObject(dObj);
return msg;
}
});
}
}