Archive

Posts Tagged ‘J2EE’

Logging in J2EE Applications

June 1st, 2010 kumarasamy No comments
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

May 25th, 2010 kumarasamy No comments
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)
Categories: General, Java, ORM, Tools Tags: , ,

Generating Domain Objects Using Hibernate

May 20th, 2010 kumarasamy No comments
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

I’ve added the update and delete operations in CRUDTest and it has been updated as follows
		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();
				}
			}

		}
	
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 playerPlugin by wpburn.com wordpress themes