Posts Tagged ‘J2EE’

Ant-Custom Tasks and Built-In Tasks.html

Wednesday, January 5th, 2011
In my previous post we have seen how to configure ant and how to use with IDE’s like eclipse. In this post we’ll look into some of the Built-In ant tasks and Custom Tasks. Ant provides lots of built-in tasks. Those task can be categorized as follows
  • Archive Tasks - Has list of all the archiving tools like JAR,WAR,EAR,TAR,ZIP and etc…
  • Audit/Coverage Tasks - Has a single task under this group which is an Code Coverage tool for Design Quality Metrics.
  • Compile Tasks - Includes the task for Code Compilation.
  • Deployment Tasks - Hot deployment task for J2EE Servers.
  • Documentation Tasks - Has JavaDoc task in this category.
  • EJB Tasks - Couple EJB related task specific to App servers.
  • Execution Tasks
  • File Tasks
  • Java2 Extensions Tasks
  • Logging Tasks
  • Mail Tasks
  • Miscellaneous Tasks
  • Pre-process Tasks
  • Property Tasks
  • Remote Tasks - Task like FTP, SCP and etc.
  • SCM Tasks - Includes few popular SCM tasks like ClearCase,CVS and VSS.
  • Testing Tasks - Supports jUnit tasks.
We’ll take few tasks like Mail tasks, Remote tasks and SCM Tasks and try to run a task from each group.
Mail Task
While running the build in an environment where a team is using SCM to commit their changes, this task will be very useful if the build is broke. By using this we can send a mail to the team along with the build errors. Since the MAIL task supports attachment also, it’ll be a very good idea to log all the errors and send it in the mail, so that the team can correct their code base and commit to SCM. The below build script has an example task which shows a simple steps to send a mail using mail task.
		<?xml version="1.0" encoding="UTF-8"?>
		<project name="AntDemo" default="sendMail">
			<target name="sendMail">
				<mail mailhost="smtp.xx.com" subject="Build Broken"  user="kumarasamy@xx.com" password="XXXXXXX">
					  <from name='Build Admin' address="buildadmin@yourcompany.com"/>
					  <to address="usersDL@domain.com"/>
					  <message>The Build has been Completed.</message>
				</mail>
			</target>
		</project>
		
Remote Task - FTP
When we run the build sometimes we use a different machine only for build and finally we’ll copy to the remote machine to deploy it on application servers, for that we can use this ftp task.The below example will show how to use the FTP
		<?xml version="1.0" encoding="UTF-8"?>
		<project name="AntDemo" default="uploadFile">
			<target name="uploadFile">
				<ftp server="ftp.xx.com"
						userid="username"
						password="password">
					<fileset dir="dist">
						<include name="*.war"/>
					</fileset>
				</ftp>
			</target>
		</project>
		
The above FTP task has very simple example, which just uploads your WAR file to your FTP server.
SCM Task - ClearCase
Clearcase is one of the widely used SCM in the industry, sometimes automating the build process is important and we can have these ant tasks provided in ant and perform few SCM tasks in ClearCase. The first step in check-in and checkout process is locking the current stream we use it for building the code base. In the same manner when these check-in and checkout process are completed we’ll have to unlock the stream we have locked it. For this Clearcase provides an command line tool called cleartool, by using this we can achieve these task in command line, Let’s see how we can use it ant by using the ClearCase ant task. Before that we’ll have the following assumptions, We’ll consider the branch name as “BuildFortheFixX.X”.
		<?xml version="1.0" encoding="UTF-8"?>
		<project name="AntDemo" default="lockStream">
			<target name="lockStream">
				<cclock objsel="brtype:BuildFortheFixX.X" />
			</target>
			<target name="unlockStream">
				<ccunlock objsel="brtype:BuildFortheFixX.X" />
			</target>
		</project>
		
The above CC tasks are equal to the following cleartool commands,

			cleartool lock brtype:project_int

			cleartool unlock brtype:project_int
		
Custom Task - ClientGen
Ant provides a way to write our own tasks, the best example will be clientgen task from weblogic which is used to generate the webservice clients from WSDL file. First We’ll we how to use this clientgen task to generate the Service Clients, then we’ll look at how to write an simple custom ant task and call it from the build script. If you are using WL8.1, We have the task defined weblogic.ant.taskdefs.webservices.clientgen.ClientGenTask in webservices.jar. We can use this task to generate the client JAR. The following example will show how to generate the Service Client JAR from a WSDL.
		<?xml version="1.0" encoding="UTF-8"?>
		<project name="AntDemo" default="buildClientJar">
		  <taskdef name="clientgen" classname="weblogic.ant.taskdefs.webservices.clientgen.ClientGenTask" />
			<target name="buildClientJar">
				<clientgen	wsdl="http://myapplication/services/MyAppWebService?wsdl"
										clientjar="dist/MyApprClient.jar"
										packageName="com.techmaddy.client"
										serviceName="MyAppWebService" />
			</target>
		</project>
		
If we look at the taskdef, it points to class ClientGenTask, As we explained earlier every ant task is associated with individual java class. If we write an custom ant task, that should extend a Class org.apache.tools.ant.Task. This is the first and foremost thing we should be doing this. Then it should be overriding the execute() from Task. These two are the important thing we have to notice while writing the custom AntTask. After this we can package this class into a JAR and use it like “clientgen” from Weblogic, by making use of taskdef.
Custom Task - MySimpleTask
In this example we’ll look into how to create our own task and call it from a build script. As i mentioned earlier we need to have class with extends Task and overriding the execute() method. Look at the below example
			package com.techmaddy.ant.taskdefs;

			import org.apache.tools.ant.Project;
			import org.apache.tools.ant.Task;

			public class MySimpleTask extends Task  {
				public void execute() {
					  log("My Simple Task", Project.MSG_INFO);
					  System.out.println("Demo MySimpleTask");
				   }
			}
		
I have used the log method from Task, to place the logs to exact place where the logs from ant is getting added, using SOP is not recommended. Complie this class and package into a JAR and use it your build script. The below is the example for the Build Script which makes a call to MySimpleTask.
			<?xml version="1.0" encoding="UTF-8"?>
			<project name="AntDemo" default="myOwnCustomTask">

				<taskdef name="mysimpletask" classname="com.techmaddy.ant.taskdefs.MySimpleTask" />

				<target name="myOwnCustomTask">
					<mysimpletask/>
				</target>

			</project>
		
The below image shows the output.
Ant-Custom Task
Library Dependencies
1. For Mail task you need to have mail.jar and activation.jar.
2. For FTP task you need to have commons-net.x.x.jar and jakarta-oro-x.x.jar.
3. For Clientgen task you need to have weblogic.jar, webservice.jar and tools.jar.
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Logging in J2EE Applications

Tuesday, June 1st, 2010
Logging is the one of the most important quality a software developer should have as a practice while coding for their applications. Logging serves as many purpose from debugging the application when a developer encounters an issue, trouble shooting the users issue, when it’s in production mode and can be used to fine tune our application with some performance measures. So logging becomes so important in a Web Application. So what are the ways we can add logging to our application which is developed in J2EE platform, there are many ways to do, they are,
  • Using Logging Framework - Log4J, SL4J, Java Logging API and Apache Commons Logging. These logging framework provides lots of functionality built-in. These frameworks defines three different processors for logging. They are Loggers, Formaters and Appenders. And these frameworks provides many levels for logging also. These frameworks provides many means of organizing your logs like Storing into Files, Database tables and some times these framework will help us in sending the email alerts also. There are many open source loggers can be found here.
  • Custom Developed Loggers - This mayn’t be complete logging solution. Sometimes we may need to code our own way of logging, this depends on our requirement to log. For example We may wanted to just to record only the user actions in all of the screens in an application and the admin needs the screen to see all the action done by that particular user with some more criteria like date etc… This time instead me adding one more framework and cluttering the application configuration, we can simply make use of the existing JDBC connection and store all the actions on the same database where we do store our application data. The other scenario i can think off here is, say for example i’m planning to log many details from each and every request of the user, in this case logging becomes heavier to maintain for the containers, this time we can try use our own loggers with pooling of objects on the user basis.
What are the things should be logged?
There are some categories of information which always has to be logged, they are Error(s) and Exception(s). Apart from these login and logout information, SQL queries and their execution times, parameters if we have any for prepared statement(including Stored Procedures), if we have any interfacing application then the request and response information, basically all the domain objects(internal data structures in the application), each and every user actions like button clicks, session time out for the user session also can be logged for better troubleshooting and debugging purposes. But it’s completely developers duty that they log the IP Address for the Client, Browser Agent, TimeStamp and the user id/information are getting captured in the log information this will make a real big impact on the debugging for web applications.
In my previous experience i have come across some logging mechanisms where they’ve used their own logging tools(basically this made me to write about the custom logging frameworks). Little more details about it.
Using JDBC with DB tables - The basic idea here is have a dB table for user history, store the important actions from the user(s) like button clicks, important queries. But we have to make sure that we are making use of the connection pool, otherwise this becomes costly inside our application and the number of connections shoots up always. The advantage of this approach is easy way of accessing the logs, i.e. a screen inside the same application show this log. Admin of the application can look into these details and can identify few issues of the users. The user’s action sequence can be identified easily. The major drawbacks of this approach is when there is an huge data available as history, then the admin page loading time will become more, the only option to have an archive mechanism to solve this issue.
Using File System -  This approach is like Log4j where we’ll make use of files to write our logs and this can be rotated on daily basis. And this can be divided further more saying the application logs and the DB logs can be separated into two different files. And further more this can be used for each and every module in the application can have two files like application log and database logs. But this approach can be used to log each and every action/request from the user with data. And the naming convention can be on the unique user id. Each user session contains the pool of these objects so that the number of I/O operations are not exceeding the limits. This would be very good approach in logging for a web application since each and every request for the server will be logged for that particular user.
The final important thing here is, what ever the method we follow to log the details we should be able to troubleshoot/debug the applications easily/fastly, even it’s going to be in production. The logging is an very important factor that we should be considering when we think of designing/developing an web application.
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Simple CRUD Operation With Hibernate

Tuesday, May 25th, 2010
In my previous post Hibernate, the ORM Library for Java, we have seen the General introduction of ORM Tools and how to configure the hibernate to use it in our applications. In this post we”ll look at the simple examples of DB Operations using Hibernate.
Please have all the libraries needed to work with MySQL with Hibernate, the most important libraries are hibernate3.jar and mysqlconnector.jar.(If you are using MyEclipse, that”ll help you in adding those jars). For using the MySQL the hibernate configuration will look like the following.
		<hibernate-configuration>
			<session-factory>
				<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
				<property name="hibernate.connection.url">jdbc:mysql://localhost/Singer</property>
				<property name="hibernate.connection.username">root</property>
				<property name="connection.password">demo</property>
				<property name="connection.pool_size">1</property>
				<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
				<property name="show_sql">true</property>
				<property name="hbm2ddl.auto">create</property>
			</session-factory>
		</hibernate-configuration>
	
For domain class we”ll take the example of Singer, Who performs some stage shows. As of now we”ll add two properties for him, Which is id and the name of the singer. So we”ll have to configure the Singer.hbm.xml file for Singer as follows.
		<hibernate-mapping>
			<class name="com.techmaddy.singer" table="TBL_SINGER">
			<meta attribute="class-description">Domain Object for Singer</meta>
				<id name="singerId" type="long" column="SINGER_ID">
					<generator class="native"/>
				</id>
				<property name="singerName" type="string" column="SINGER_NAME" not-null="true" />
			</class>
		</hibernate-mapping>
	
We can make use of the MyEclipse’’s “Hibernate Reverse Engineering” option from the database perspective, so that we can easily generate the Singer.hbm.xml and Singer.java domain class also.

		package com.techmaddy.singer;

		public class Singer implements java.io.Serializable {

			private Long singerId;
			private String singerName;

			public Singer() {}

			public Singer(String singerName) {
				this.singerName = singerName;
			}

			public Long getSingerId() {
				return this.singerId;
			}

			public void setSingerId(Long singerId) {
				this.singerId = singerId;
			}

			public String getSingerName() {
				return this.singerName;
			}

			public void setSingerName(String singerName) {
				this.singerName = singerName;
			}
		}
		
This above code ss an domain class for Singer, It’’s just nothing but an POJO or we can say an JavaBean. The other important component fo Hibernate is SessionFactory. The SessionFactory provides the session to work with RDBMS. SessionFactory should be created only once per application on web container. SessionFactory can be created many ways, most of the time SessionFactory will be created as a Singleton utility class.By using the following methods, we can creating the SessionFactory, they are
  • An Utility Class with Singleton - A Singleton class with the option to create an SessionFactory and then the object can be made available to JVM.
  • From an Servlet - A servlet which is loaded on startup of the container and the service method pushes the object into an Singleton Utility class
  • Static Block - inside a static block in some sort of Utility Java class that can be used in program code to retrieve SessionFactory

We”ll implement the third option to create the SessionFactory.


		package com.techmaddy.singer

		public class FactoryUtil {

		//Static Session Factory
		private static org.hibernate.SessionFactory sessionFactory;

		private FactoryUtil() {}

		static {

			//Creates the SessionFactory based on the XML Configuration
			Configuration configs = new Configuration();
			sessionFactory = configs.configure().buildSessionFactory();
		}

		public static SessionFactory getInstance() {
			return sessionFactory;
		}

		public Session openSession() {
			return sessionFactory.openSession();
		}

		public Session getCurrentSession() {
			return sessionFactory.getCurrentSession();
		}

		public static void close() {
			if (sessionFactory != null)
				sessionFactory.close();
			sessionFactory = null;
		}
	}
The above code creates the SessionFactory, since the creation of SessionFactory is in Static block, we”ll be able control the creation of SessionFactory object. By this way we””l have the control of creating the session obejcts. The SessionFactory reads the hibernate cfg xml and then it creates the session object for our application. We are all set to go and write our class, to test the hibernate.
Basically we”ll look into the example of CRUD by making use of the Hibernate Session object.
			package com.techmaddy.singer;

			import org.hibernate.HibernateException;
			import org.hibernate.Session;
			import org.hibernate.Transaction;

			public class CRUDTest {

				public static void main(String[] args) {
					CRUDTest crudTest = new CRUDTest();
					Long singer = crudTest.insertSinger("Jason");
					singer = crudTest.insertSinger("Jerry");
					singer = crudTest.insertSinger("Chun");
				}

				public Long insertSinger(String singerName) {
					Session session = FactoryUtil.getSessionFactory().openSession();
					Transaction transaction = null;
					Long singerId = null;

					try {
						transaction = session.beginTransaction();
						Singer singer = new Singer();
						singer.setSingerName(singerName);
						singerId = (Long)session.save(singer);
						transaction.commit();
					}
					catch (HibernateException e) {
						transaction.rollback();
						e.printStackTrace();
					}
					finally {
						session.close();
					}
				return singerId;
			}
		}
When we run this following code, we”ll get the output in the console as follows,this is since we mentioned “show_sql” property in hibernate.cfg.xml to “true”.
Console
After executing this statement, we can check the database for inserted values.

Transaction

The CRUDTest is now hadnling update and delete operations, so the above class has been to changed to the following,

			package com.techmaddy.singer;

			import java.util.Iterator;
			import java.util.List;
			import org.hibernate.HibernateException;
			import org.hibernate.Session;
			import org.hibernate.Transaction;

			public class CRUDTest {

				public static void main(String[] args) {

					CRUDTest crudTest = new CRUDTest();
					Long singer = crudTest.insertSinger("William");
					singer = crudTest.insertSinger("Jerry");
					Long tempSinger = singer;
					singer = crudTest.insertSinger("Stanley");
					crudTest.listSinger();
					crudTest.updateSinger(singer,"Chun");
					crudTest.deleteSinger(tempSinger);
				}

				public Long insertSinger(String singerName) {

					Session session = HibernateSessionFactory.getSessionFactory().openSession();
					Transaction transaction = null;
					Long singerId = null;
					try {
						transaction = session.beginTransaction();
						Singer singer = new Singer();
						singer.setSingerName(singerName);
						singerId = (Long)session.save(singer);
						transaction.commit();
					}
					catch (HibernateException e) {
						transaction.rollback();
						e.printStackTrace();
					}
					finally {
						session.close();
					}
					return singerId;
				}

				public void listSinger() {
					Session session = HibernateSessionFactory.getSessionFactory().openSession();
					Transaction transaction = null;

					try {
						transaction = session.beginTransaction();
						List singers = session.createQuery("FROM Singer").list();
						for (Iterator iterator = singers.iterator(); iterator.hasNext();) {
							Singer singer = (Singer) iterator.next();
							System.out.println(singer.getSingerName());
						}
						transaction.commit();
					}
					catch (HibernateException e) {
						transaction.rollback();
						e.printStackTrace();
					}
					finally {
						session.close();
						}
					}

					public void updateSinger(Long singerId, String singerName) {
						Session session = HibernateSessionFactory.getSessionFactory().openSession();
						Transaction transaction = null;

						try {
							transaction = session.beginTransaction();
							Singer singer = (Singer) session.get(Singer.class, singerId);
							singer.setSingerName(singerName);
							session.update(singer);
							transaction.commit();
						}
						catch (HibernateException e) {
							transaction.rollback();
							e.printStackTrace();
						}
						finally {
							session.close();
						}
					}

					public void deleteSinger(Long singerId) {
						Session session = HibernateSessionFactory.getSessionFactory().openSession();
						Transaction transaction = null;
						try {
							transaction = session.beginTransaction();
							Singer singer = (Singer) session.get(Singer.class, singerId);
							session.delete(singer);
							transaction.commit();
						}
						catch (HibernateException e) {
							transaction.rollback();
							e.printStackTrace();
						}
						finally {
							session.close();
						}
					}
				}
All Transaction
Final Result
Download
To download the War file for Singer Click Here
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Get Adobe Flash player