Ant, build.xml with Jenkins
It was 15th September 2005, I joined my first company NexGen Software Solutions Ltd as Project Trainee. The first day I join, I was aware of OOPS Concepts and was able to explain by writing simple Java Programs. And I was not aware of that "How the big internet applications are running, how to code for that and how to run it". But as a little ant in big ocean, I was learning Java, and able to run HelloWorld.java by compiling using javac(Java Compiler), it will be compiled into byte code,that will be later converted in executable code by JRE when running that using java.
And I was not aware of How Database works, How the Internet websites are developed using java.
Then my Lead gave me the Book: Apache Ant, and asked to learn it quickly with in a week, as it required urgently for that project. But I took 2 weeks and learned something. Then I created a small Applet program and converted it as jar using the ant by build.xml. That time I was thinking that I learned lot, and appreciated myself. This is how I got introduced with Ant, with in two weeks of my Java Career started.
Now a days we are not running the ant or maven either in eclipse or in command prompt. Instead we configure it with any of the CI(Continuous Integration Tool).
The CI tools (Jenkins or Hudson) does check-out code from svn repository , compiles them, runs unit testing, packages them and deploys the war/tar.
CI tools will take input what to compile, what to package, where to deploy from either ant scripts or from maven.
Here we will see
Section 1: Coding of sample a sample web application.
Section 2. How to write build.xml(ANT Script).
Section 3. How to install and run Jenkins.
Section 4. How to configure the application in the Jenkins.
Section 5. How to build through the Jenkins.
-----Write Sample Application
1. Open eclipse and create "Dynamic Web Project"
2. Create a sample HelloWorld web application.
3. Run it on Tomcat and confirm whether it running successfully.
4. Please confirm the project folder structure as below:
HelloWorld
|+src
| + test.hello.web
| + HelloWorldController.java
|+WebContent
| + META-INF
+ MANIFEST.MF
| + WEB-INF
| + helloworld-servlet.xml
+ web.xml
+ jsp
+ helloworld.jsp
| + lib
+ commons-logging.jar
+ spring-mvc.jar
+ spring-core.jar
+ spring-web.jar
+ spring-beans.jar
+ spring-webmvc.jar
+ spring-context.jar
+ spring-mvc.jar
|+build.xml
-----Write Ant Build Scripts
1. RightClick the project and create XML file.
2. Name it as build.xml. The folder structure, where to creat the build.xml is given above.
build file should like the below.
<?xml version="1.0" encoding="UTF-8"?>
<project name="buildwar" default="deploy" basedir=".">
<description> Compile, Package and Deploy AppajiMaamaa</description>
<!-- set global properties for this build -->
<property name="src" location="./src" />
<property name="classes" location="./build/classes" />
<property name="deployDest" location="D:\Test\apache-tomcat-6.0.37\webapps" />
<path id="project-classpath">
<!-- Libraries inside project lib folder like, Spring, Logging, Hibernate -->
<fileset dir="./WebContent/WEB-INF/lib" includes="*.jar" />
<!-- Libraries inside server lib folder like, Servlet, JSP -->
<fileset dir="D:\Test\apache-tomcat-6.0.37\lib" includes="*.jar" />
</path>
<target name="clean">
<delete dir="./build/classes">
</delete>
<echo> Cleaned old class files !</echo>
<delete>
<fileset dir="./build">
<include name="*.war" />
</fileset>
</delete>
<echo> Cleaned old war file in build folder !</echo>
</target>
<target name="cleanDeploy">
<delete>
<fileset dir="${deployDest}">
<include name="*.war" />
<exclude name="*/*.*" />
</fileset>
</delete>
<echo> Removed war files inside Server!</echo>
<delete dir="${deployDest}/appajimama">
</delete>
<echo> Removed Previous Deployment inside Server!</echo>
</target>
<target name="compile" depends="clean" description="compile the source ">
<mkdir dir="./build/classes" />
<javac includeantruntime="false" srcdir="${src}" destdir="${classes}" classpathref="project-classpath" />
<echo> Java file compiled and copied to classes folder !</echo>
</target>
<target name="buildwar" description="Building War File" depends="compile">
<war destfile="./build/appajimama.war" webxml="./WebContent/WEB-INF/web.xml">
<fileset dir="./WebContent">
<include name="**/*.jsp" />
<include name="*/*.xml" />
<include name="**/*.jar" />
</fileset>
<lib dir="./WebContent/WEB-INF/lib">
</lib>
<classes dir="./build/classes" />
</war>
</target>
<target name="deploy" depends="buildwar,cleanDeploy">
<copy file="./build/appajimama.war" todir="${deployDest}" overwrite="true">
</copy>
</target>
</project>
3. Run the above script and check the war is build and copied to tomcat\webapps.
4. Start the tomcat server and verify that there is no error.
5. Move the application into SVNRepository. If you want to know How to setup repository please read my previous posts.
http://chennai-java.blogspot.in/2014/02/configure-wandiscosubversion-188-with.html
------------Install jenkins --------------------
1. Download Jenkins.war from www.Jenkins.com
2. Copy inside the tomcat\webapps
3. Start the tomcat and open the browser with the URL http:\\localhost:8080\jenkins
4. If you are able the see the jenkins page, then it seems Jenkins server is installed successfully.
5. Configure Jenkins with Ant.
-----------Install Ant------------------------
1. Download Ant, and extract the zip.
2. Add the ANT_HOME to System Environment variable. Also add the ANT_HOME\bin to PATH variable.
3. Verify ant installation by typing "ant -version". If you get version details. Then Ant is installed successfully. Else please check the Environment path details.
-----------Configure ant inside the Jenkins---------
1. Open the Jenkins http:\\localhost:8080\jenkins
2. Go to Manage Jenkins -> Configure -> Configure System
3. Add JDK details with as like this Name : JDK 7, JAVA_HOME : C:\Program Files\JDK\1.7.0_45
4. Add JDK details with as like this Name : ANT , ANT_HOME : C:\Program Files\apache-ant-1.9.3
5. Save, Apply changes.
6. Stop the Jenkins Tomcat server and restart.
-----------Configure the HelloWorld into Jenkins------------------------
1. We were able to build and deploy using the build.xml from eclipse, now here we will see how to configure the application into Jenkins.
2. Click on New Item menu.
3. Project Name : HelloWorld
4. Source Code Management : Subversion: We need to give the subversion repository Subversion : http://localhost:7070/svn/spring_samples/branches/AppajiMaamaa1.0
If we have been setup user access for the SVNRepository, please give the username and password.
6. Build : Ant Version : Default, Targets : deploy (What ever the target we gave inside the build.xml need to be mentioned here).
7. Save, Apply
----------- Build and Deploy -----------------------
1. Now Click on the "Build Now" button.
2. To see the console, click the link inside the "Build History". It will open the another screen.
3. Now click on the "Console Output". If build is success then it will show "BUILD SUCCESSFUL, Total time: 2 seconds, Finished: SUCCESS".
4. Failure Reason : Ant path is not correct, Subversion Code Repository Path may wrong. So please verify them.
Saturday, March 1, 2014
Friday, February 28, 2014
Configure WanDiscoSubversion 1.8.8 with Apache2 -Part 2
Authorization Configuration, Restricting Users with allowed Code Bases
Once we installed Subversion, created repository and created users with passwords, now we are able to read/write code
with all users. But we need to restrict the users with specifically allocated code branches.
Here we will see how to set up the authorization to projects folders inside the repository.
1. You need to Edit Apache2/conf/subversion.conf to tell where is the authorization file is placed.
- Inside the file, you can find a line like "#AuthzSVNAccessFile /scm/home/avn.auth" - Remove the # symbol
- Instead of the /scm/home/avn.auth, give the exact location of the auth file. That is we are going to create in the step 2.
2. You need to create authz file with authorization to repository.
- Please find the authz file anywhere inside "repository/conf" and copy to your required location.
- Add the below lines
# Allowing balaji To Read Only Tags/Branches/Trunk of spring_samples[spring_samples:/]balaji=r
# Allowing balaji To Read and Write Branches of core_java_samples only
[core_java_samples:/branches]
balaji=rw
# Allowing balaji To Read only the core_java_samples trunk
[core_java_samples:/trunk]
balaji=r
3. Restart the Wandisco Subversion Service - Go to ControlPanel, Go to System and Security, Go to Administrative Tools, Go To Services
- Here you can see all the Window Services
- Please find the Wandisco Subversion Service
- Reatart
4. Verify the authorization for core_java_samples
- Open the http://localhost:7070/svn/core_java_samples, and login with balaji.
- As the balaji allowed to read only trunk -You can view(Check out) only. You cannot commit (Check in).
- As the balaji allowed to read/write branches - you can check out anc check in the code.
- As the balaji not allowed to read/write the tags - You will not see the folder.
Tips :
If you are able to access the http://localhost:7070/svn/myrepo , but if you try to add it to your Eclipse or NetBeans as the SVN repository, then you may get "403 : Forbidden Error".
Then instead of localhost , try with 127.0.0.1 or your IP address. It will resolve the 403 issue.
1. You need to Edit Apache2/conf/subversion.conf to tell where is the authorization file is placed.
- Inside the file, you can find a line like "#AuthzSVNAccessFile /scm/home/avn.auth" - Remove the # symbol
- Instead of the /scm/home/avn.auth, give the exact location of the auth file. That is we are going to create in the step 2.
2. You need to create authz file with authorization to repository.
- Please find the authz file anywhere inside "repository/conf" and copy to your required location.
- Add the below lines
# Allowing balaji To Read Only Tags/Branches/Trunk of spring_samples[spring_samples:/]balaji=r
# Allowing balaji To Read and Write Branches of core_java_samples only
[core_java_samples:/branches]
balaji=rw
# Allowing balaji To Read only the core_java_samples trunk
[core_java_samples:/trunk]
balaji=r
3. Restart the Wandisco Subversion Service - Go to ControlPanel, Go to System and Security, Go to Administrative Tools, Go To Services
- Here you can see all the Window Services
- Please find the Wandisco Subversion Service
- Reatart
4. Verify the authorization for core_java_samples
- Open the http://localhost:7070/svn/core_java_samples, and login with balaji.
- As the balaji allowed to read only trunk -You can view(Check out) only. You cannot commit (Check in).
- As the balaji allowed to read/write branches - you can check out anc check in the code.
- As the balaji not allowed to read/write the tags - You will not see the folder.
Tips :
If you are able to access the http://localhost:7070/svn/myrepo , but if you try to add it to your Eclipse or NetBeans as the SVN repository, then you may get "403 : Forbidden Error".
Then instead of localhost , try with 127.0.0.1 or your IP address. It will resolve the 403 issue.
Thursday, February 27, 2014
Configure WanDiscoSubversion 1.8.8 with Apache2-Part1
Hi All,
For long time we developers/leads will just start coding by checking-out the folder structure from any URL given b either client or by our architect. But when I worked in my first company I had a chance to setup the Subversion Server and create user account to check-out and check-in code. I am just sharing the knowledge to you. Please just follow the below process.
I installed the same in Window 8 machine with JDK 7.
WanDisco Subversion1.8.8 come with Apache2, so we don't need to install it separately.
How to Install and Setup SVN Repository
1.Download and Install WANDiscoSubversion1.8.8 from
https://www.wandisco.com/subversion/download
-
Installing will ask : Choose Subversion 1.8.8 Server
-
Destination Folder : C:\Program Files (x86)\WANdisco\Subversion
- Host
: localhost Port :7070
-
Choose :Install as windows Service
-
Repository Directory : D:\Bala\myrepository
This is the location where your
are going to save code, so probably the space should be more in real time).
-
Repository Location Prefix : /svn
- Click Install - Completed. Here
it installs the Subversion along with the Apache Http. So we dont need to setup
the Apache again.
- Next Choose all check boxes. So
it will be installed as Windows System Service. So you don't need to start
manually at each machine bootup.
2. Also Install TortoiseSVN Client from
https://www.wandisco.com/subversion/download
Now create the repositories
- Create Folder inside the
"myrepository": "core_java_samples",
"spring_samples", "hibernate_samples"
- RighClick inside the folder
"core_java_samples", there you can see two items in the menu
"SVN Checkout" and "Tortoise SVN".
-
Choose "Tortoise SVN", and Click sub-menu item "Create
Repository here".
- You
can see a popup saying that "Repository Created".
- Also click on the "Create
folder structure" button in the popup.
To have Subversion and maintain
code we need truck, branch and tag, those files will be created.
- It
will show message "Folder Structure Created".
-
http://localhost:7070/svn/core_java_samples/ - Now the repository is ready.
-
Follow the same steps inside : "spring_samples",
"hibernate_samples".
So
http://localhost:7070/svn/apring_samples/ and http://localhost:7070/svn/hibernate_samples/ -Now the 3 repository is ready.
4. Now verify them by accessing :
http://localhost:7070/svn/spring_samples/
http://localhost:7070/svn/core_java_samples/
http://localhost:7070/svn/hiernate_samples/
5. Also verify whether the trunk,branch and tag structure.
There you can see the branch, trunk and tag.
http://localhost:7070/svn/hiernate_samples/branchs
http://localhost:7070/svn/hiernate_samples/tags
http://localhost:7070/svn/hiernate_samples/trunk
Setting Access Configuration for the WandiscoSubversion1.8.8
WanDiscoSubversion 1.8.8. Installs
the Apache2 along with it. So it is not required to install it separately need.
Please confirm once again whether it is installed properly by looking into the
Installed location.
Open the location:
"C:/ProgramFiles/WanDisco/Subversion"
If you able to see the Apache2, then it is OK. Now we can
proceed to configure access control.
"C:/ProgramFiles/WanDisco/Subversion/Apache2"
AuthFile Creation
1. Go to the Apache2 home directory
""C:/ProgramFiles/WanDisco/Subversion/Apache2".
2. Go to the Apache bin directory : cd
C:/ProgramFiles/WanDisco/Subversion/Apache2/bin
3. Then you need to run htpasswd.exe - This will create the
users and password.
4. htpasswd.exe -c -m balaji mypassword
5. You will see the response like :
balaji=Wweomd215m51m29dks538.
6. Copy the above response and paste into a notepad. Save
the file in the name "passwd.htpasswd" (C:\Users\test\Desktop\). This
is the Authentication file will be referred by Apache2.
Configuring Repository
7. Now we need to configure the repository to be secured so,
please open the the Open the file "Apache2/conf/subversion.conf".
Find the Line like "
8. Modify the Block like this :
7. Now Restart the Service : Control Panel--System and
Security--Services--Wandisco Subversion--Re-Start.
<VirtualHost *:7070>
KeepAlive On
<Location /svn>
DAV svn
SVNParentPath "D:\Bala\myrepository"
RedirectMatch ^(/svn)$ $1/
AuthType Basic
AuthName "Subversion Repo"
AuthUserFile
"C:\Users\test\Desktop\passwd.htpasswd"
#AuthzSVNAccessFile /home/scm/svn.authz
Require valid-user
#Order allow,deny
#Allow from all
SVNAutoversioning on
</Location>
# Enable Subversion logging
CustomLog logs/subversion.log
combined
</VirtualHost>
Now Your Repository is Secured !
Now if you check the URLs -all will require the username and
password. Please enter the balaji and mypassword.
http://localhost:7070/svn/spring_samples/
http://localhost:7070/svn/core_java_samples/
http://localhost:7070/svn/hibernate_samples/
Now the SVN Repository is secured with authentication.
OK Lets Enjoy the Subversion with Check-outs and Check-in.
Hope this is helpful to you. Please send your feedback to Balaji.Mathu@Gmail.Com.
Configuration Management
Trunk
Trunk is the main base code of development, originating from the start of the project until the present.
Branch
Branch is a copy of code derived from trunk at certain point that is used for applying major changes to the code while preserving the integrity of the code in the trunk. If the major changes are completed according to plan, branch code will be merged back into the trunk.
Tag
Tag is a point in time on the trunk or a branch that you wish to preserve. The two main reasons for preservation would be that either this is a major release of the software, whether alpha, beta, RC or RTM, or this is the most stable point of the software before major revisions on the trunk were applied.
SCM Maintenance
So once you base code/folder structure is created in trunk, then you need to create branch from trunk. Then all developers in your team will check-out from this branch and check-in the code.Once you completed your coding phase and confirm there will be no changes, give release for deployment, then merge the code into trunk and tag it from trunk.Tags or branches will not occupy the same memory space of the code,instead occupies only the changes from trunk. So will take few bytes of memory only.
If you need to start another iteration of changes in code, you need to cut the code again from trunk. And same process to be followed.
In the point of Releasing RC 1.00 - SVN structure will be like.
Ø trunk/ - development version, soon to be 1.1
Ø branches/1.0 - upcoming 1.0.1 release
Ø tags/1.0.0 - 1.0.0 release version
In the point of Releasing RC 1.0.1 - SVN structure will be like.
Ø trunk/ - development version, soon to be 1.1
Ø branches/1.0 - upcoming 1.0.2 release
Ø tags/1.0.0 - 1.0.0 release version
Ø tags/1.0.1 - 1.0.1 release version
In the point of Releasing RC 1.0.2 - SVN structure will be like.
Ø trunk/ - development version, soon to be 1.1
Ø branches/1.0 - upcoming 1.0.3 release
Ø tags/1.0.0 - 1.0.0 release version
Ø tags/1.0.1 - 1.0.1 release version
Ø tags/1.0.2 - 1.0.2 release version
Best way of SVN management
Create a private branch before coding started. Start check-in on branch. When coding is complete, manager reviews all private branch changes and merges them to /trunk.
Pros: /trunk is guaranteed to be extremely stable at all times.
Cons: Possibly creating more merge conflicts. Requires users to do lots of extra merging.
Next : In the next post I will give the same kind of steps to install Jenkins/Hudson and start Continuous Integration.
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 "
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.
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;
}
});
}
}
****** : 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;
}
});
}
}
Friday, September 10, 2010
Subscribe to:
Posts (Atom)