Archive for December, 2010

2010 Year – Learnings & Reviews

December 30, 2010

Learning from experiences can be done in either way.

+ve Learning – Learn from good things happened around you. This enhances your +ve actions or decisions.
-ve Learning – Learn from bad things happened around you. This helps to evade your -ve actions or decisions in the future.

Want success or achieve your goals in life; you should have both technical as well as personal development skills. You have to shape your mind to tackle all the hindrances in the goal path.
I have summarized few points which would be useful for readers.

Our Words
Be careful of your words when you interact or communicate with surrounding people. At any cause your words should not hurt or offend anyone. This includes your parents, sisters, brothers and close friends too.

Perhaps your situations made you react offensively, but you never know this could lead to fragile relationships. Even though they hurt you, don’t repeat the same to them. Always keep this in mind.

Think TWICE before you speak. ~ Mani

Assumption

Assumption is the WORST enemy for us.

Don’t assume things either officially or personally.  Officially, it may navigate to wrong path and end up in rework. Personally, creates a bad rapport with souls around you.

Just spend time to examine and know the factual.

Be Patience
Some ugly moments might stir up anger. Try to control and be rational.

It’s better to be silent instead of uttering hurtful words.

Change

மாற்றங்கள் மனிதர்களுக்கு தேவை. ~ மணி

Change is required for every human being. Yes, it’s hard to accept because our minds can’t accept the change easily. Also, make sure that your change doesn’t affect others and be wary of this decision.

Measure your endurance how flexible are you when conditions, circumstances change suddenly.

Egoism

Leave your ego at the feet before interacting with your friends. ~ Mani

Want to be more successful in life – Remove your egos.
It’s very hard to do it, but this will give you a nice relationship between your friends.

Passion
Drive in the path of your passion or interests, put 100% efforts in interested areas. You can reach the satisfied success in your life. Don’t suppress your feelings instead express it and live your life.

Minimum settings to succeed –

Do not work on anything you are not interested in.

Adaptability
Adaptability is essential for everyone; you have to personalize yourself for the conditions and circumstances. Also, have the ability to respond effectively to the challenging environment.

More precisely, have to somewhat adjust your character to cope up with current situation, this would benefit in long-term.

Audacity
Have the courage to face any actions in your life. Take calculated risk to go to the next level of your life. Do not panic. The more success resides in the risk parts of life.

Year-End Review
It’s time to examine what you have accomplished this year.  Self evaluate with following questions.

  • Career goals – Did I achieve my goals?
  • What I have learned?
  • What new skills/technologies I have learned?
  • Am I happy/satisfy with my current work?
  • What’s my dream – Did I make any progress to achieve?

Once completed the review, you should know yourself where you are, where you have been, where you want to go.

Have some specific goals and action steps to progress next year.

Note: I would suggest readers to add your learning to this blog as comments, in fact will benefit others.

Planning to share more technical info, do track by subscribing.

Wish you Happy New Year 2011.

Coding to Interfaces

December 18, 2010

Coding to an interface rather than to implementation. This makes your software/application easier to extend. In other words, your code will work with all the interface’s subclasses, even ones that have not been created yet.

Anytime if you are writing code that interacts with subclasses, you have two choices either; your code directly interacts with subclasses or interacts with interface. Like this situation, you should always favor/prefer to coding to an interface, not the implementation.

I have created a simple example with JDK classes & interface which demonstrates its benefits.

CodingToAnInterface.java

 import java.util.Hashtable;
 import java.util.LinkedHashMap;
 import java.util.Map;

 public class CodingToAnInterface {

 public static void main(String[] args) {
 // Coding to a class : Creating new instance of Hashtable & Assign it to the class.
 Hashtable subject = new Hashtable();
 CodingToClass c2c = new CodingToClass();
 subject = c2c.addSubject(subject);
 System.out.println("CodingToClass : Hashtable : subject : "+subject);

 // Coding to an interface : Creating new instance of Hashtable & Assign it to the Map interface object.
 Map subj = new Hashtable();
 CodingToIntf c2i = new CodingToIntf();
 subj = c2i.addSubject(subj);
 System.out.println("CodingToInterface : Instantiated Hashtable : subject : "+subj);

 // Now, we have a requirement to show subjects in the order it was inserted. Let’s make a simple change from Hashtable to LinkedHashMap.
 subj = new LinkedHashMap();
 subj = c2i.addSubject(subj);
 System.out.println("CodingToInterface : Instantiated LinkedHashMap : subject : "+subj);
 }
 }

 class CodingToClass{
 // Method argument & return type are defined with class name Hashtable. This allows only Hashtable class as parameter.
 public Hashtable addSubject(Hashtable subject) {
 subject.put("Subject1", 50);
 subject.put("Subject2", 70);
 subject.put("Subject3", 60);
 subject.put("Subject4", 80);
 return subject;
 }
 }

 class CodingToIntf{
 // Method argument & return type are defined with interface Map. This allows to send various possible interface subclasses.
 public Map addSubject(Map subject) {
 subject.put("Subject1", 50);
 subject.put("Subject2", 70);
 subject.put("Subject3", 60);
 subject.put("Subject4", 80);
 return subject;
 }
 }
 

Output

CodingToClass : Hashtable : subject : {Subject4=80, Subject3=60, Subject2=70, Subject1=50}
CodingToInterface : Instantiated Hashtable : subject : {Subject4=80, Subject3=60, Subject2=70, Subject1=50}
CodingToInterface : Instantiated LinkedHashMap : subject : {Subject1=50, Subject2=70, Subject3=60, Subject4=80}

In the above example, initially assigned Hashtable object to interface Map object instead of Hashtable class. Later, we have a requirement to show the subjects in the order we have inserted into it. So we need to change the code and this can be easily achieved here by simply changed the instantiation part from Hashtable to LinkedHashMap without touching addSubject part.
However in coding to class, we have to change all the places where Hashtable is being used.

Instead of your code being able to work with only specific subclass called Hashtable, you are able to work with more generic Map interface. In future, it’s easier to change into some other sub class of Map interface.

Advantages

  • App/Software is easier to extend
  • Adds Flexibility to your App.
  • Helps to maintain the loose coupling of code.

Thread vs Runnable

December 10, 2010

Thread is a block of code which can execute concurrently with other threads in the JVM. You can create and run a thread in either ways; Extending Thread class, Implementing Runnable interface.

Both approaches do the same job but there have been some differences. Almost everyone have this question in their minds: which one is best to use? We will see the answer at the end of this post.

The most common difference is

  • When you extends Thread class, after that you can’t extend any other class which you required. (As you know, Java does not allow inheriting more than one class).
  • When you implements Runnable, you can save a space for your class to extend any other class in future or now.

However, the significant difference is.

  • When you extends Thread class, each of your thread creates unique object and associate with it.
  • When you implements Runnable, it shares the same object to multiple threads.

The following example helps you to understand more clearly.

ThreadVsRunnable.java


class ImplementsRunnable implements Runnable {

 private int counter = 0;

 public void run() {
 counter++;
 System.out.println("ImplementsRunnable : Counter : " + counter);
 }
 }

 class ExtendsThread extends Thread {

 private int counter = 0;

 public void run() {
 counter++;
 System.out.println("ExtendsThread : Counter : " + counter);
 }
 }

 public class ThreadVsRunnable {

 public static void main(String args[]) throws Exception {
 //Multiple threads share the same object.
 ImplementsRunnable rc = new ImplementsRunnable();
 Thread t1 = new Thread(rc);
 t1.start();
 Thread.sleep(1000); // Waiting for 1 second before starting next thread
 Thread t2 = new Thread(rc);
 t2.start();
 Thread.sleep(1000); // Waiting for 1 second before starting next thread
 Thread t3 = new Thread(rc);
 t3.start();

 //Creating new instance for every thread access.
 ExtendsThread tc1 = new ExtendsThread();
 tc1.start();
 Thread.sleep(1000); // Waiting for 1 second before starting next thread
 ExtendsThread tc2 = new ExtendsThread();
 tc2.start();
 Thread.sleep(1000); // Waiting for 1 second before starting next thread
 ExtendsThread tc3 = new ExtendsThread();
 tc3.start();
 }
 }

Output of the above program.

ImplementsRunnable : Counter : 1
ImplementsRunnable : Counter : 2
ImplementsRunnable : Counter : 3
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1

In the Runnable interface approach, only one instance of a class is being created and it has been shared by different threads. So the value of counter is incremented for each and every thread access.

Whereas, Thread class approach, you must have to create separate instance for every thread access. Hence different memory is allocated for every class instances and each has separate counter, the value remains same, which means no increment will happen because none of the object reference is same.

When to use Runnable?
Use Runnable interface when you want to access the same resource from the group of threads. Avoid using Thread class here, because multiple objects creation consumes more memory and it becomes a big performance overhead.

Apart from this, object oriented designs have some guidelines for better coding.

  • Coding to an interface rather than to implementation. This makes your software/application easier to extend. In other words, your code will work with all the interface’s subclasses, even ones that have not been created yet.
  • Interface inheritance (implements) is preferable – This makes your code is loosely coupling between classes/objects.(Note : Thread class internally implements the Runnable interface)

Example: coding to an interface.

Map subject = new HashMap();

Assigning HashMap object to interface Map,  suppose in future if you want to change HashMap to Hashtable or LinkedHashMap you can simple change in the declaration part is enough rather than to all the usage places. This point has been elaborately explained here.

Which one is best to use?

Ans : Very simple, based on your application requirements you will use this appropriately. But I would suggest, try to use interface inheritance i.e., implements Runnable.

Example : 

Map subject = new HashMap();

Assigning HashMap object to interface Map,  suppose in future if you want to change HashMap to Hashtable or LinkedHashMap you can simple change in the declaration area is enough rather than to all the usage places. I will explain this elaborately in the upcoming post.

 

Struts Example

December 7, 2010

Let’s see, how to develop a simple web application using Struts. Prior to this, want to learn about Struts basics go through these blogs Struts Basics & Struts Dispatch Action.
Before starting the application, download Tomcat-6.0.29.zip & Struts-1.3.10.zip

Follow the basic steps to configure struts in tomcat.

  • Unzip the tomcat zip file, you can get the folder apache-tomcat-6.0.29
  • Unzip the struts zip file, from that copy all jars from struts-1.3.10\lib directory to apache-tomcat-6.0.29\lib directory.
  • Copy the struts-1.3.10\src\taglib\src\main\resources\META-INF\tld\struts-html.tld file and place it under apache-tomcat-6.0.29\webapps\examples\WEB-INF directory.

Tomcat zip has the sample examples of jsp/servlet, which has been present under webapps/examples directory. We can use the same for developing our simple struts web application(Books Store).

In this app you are able to view the complete details of available books by accessing the url http://localhost:8080/examples/showbooks.do. From this page, you can do the basic operations like Add/Edit/Delete book.

Following steps are tell you how to implement this web app, what are the settings required to configure and where to place the action classes & jsp files.

web.xml or Deployment Descriptor.
We have to configure about ActionServlet in web application. This can be done by adding the following servlet definition to the apache-tomcat-6.0.29\webapps\examples\WEB-INF\web.xml file.

 <servlet>
 <servlet-name>action</servlet-name>
 <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
 <init-param>
 <param-name>config</param-name>
 <param-value>/WEB-INF/struts-config.xml</param-value>
 </init-param>
 <init-param>
 <param-name>validate</param-name>
 <param-value>true</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>
 

Servlet Mappings tells when the action should be executed.

 <servlet-mapping>
 <servlet-name>action</servlet-name>
 <url-pattern>*.do</url-pattern>
 </servlet-mapping>
 

To use HTML tag lib, you must add the following tag library entries into web.xml file.

 <taglib>
 <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
 <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
 </taglib>
 

struts-config.xml
This file is used to configure the struts framework details of a web application contains form-bean, action-mappings definitions.Add this file under apache-tomcat-6.0.29\webapps\examples\WEB-INF directory.

 <?xml version="1.0" encoding="ISO-8859-1" ?>
 <!DOCTYPE struts-config PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
 "http://struts.apache.org/dtds/struts-config_1_3.dtd" >

 <struts-config>
 <!-- Form Bean Definitions -->
 <form-beans>
 <form-bean name="BookForm" type="com.books.BookForm"/>
 </form-beans>

 <!--  Action Mapping Definitions  -->
 <action-mappings>
 <action path="/showbooks"
 type="com.books.ShowBooks"
 validate="false"
 scope="session">
 <forward name="success" path="/jsp/books/books.jsp"/>
 </action>

 <!-- Example of Struts Dispatch Action : has the extra attribute parameter-->
 <action path="/bookaction"
 type="com.books.BookActions"
 parameter="actionMethod"
 name="BookForm"
 validate="false"
 scope="session">
 <forward name="addBook" path="/jsp/books/addbook.jsp"/>
 <forward name="editBook" path="/jsp/books/editbook.jsp"/>
 <forward name="deleteBook" path="/jsp/books/deletebook.jsp"/>
 </action>
 </action-mappings>
 </struts-config>
 

ShowBooks.java
Action class used to show the book details page. In this example, I used class objects to store the book details you can use database to store the content of your app. This class been invoked when you access this url http://localhost:8080/examples/showbooks.do from the web browser.

 package com.books;

 import org.apache.struts.action.ActionForm;
 import org.apache.struts.action.ActionMapping;
 import org.apache.struts.action.ActionForward;
 import org.apache.struts.action.Action;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 public class ShowBooks extends Action
 {
 public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Show Books List");
 Books b = Books.getInstance();
 request.setAttribute("booksList", b.getBookList());
 return mapping.findForward("success");
 }
 }
 

Books.java
Class used to store the book details i.e., app data is persisted in jvm memory, this will get lost once you restarted the tomcat server. So you can use databases to store your application data.

 package com.books;

 import java.util.Map;
 import java.util.HashMap;
 import java.util.List;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.Set;

 class Books {

 int bookIdCount = 1000;
 Map<Integer, StoreBook> bookMap = new HashMap<Integer, StoreBook>();
 private static Books books = null;

 private Books() {
 }

 public static Books getInstance() {
 if (books == null) {
 books = new Books();
 }
 return books;
 }

 public void storeBook(String bookName, String authorName, int bookCost) {
 StoreBook sb = new StoreBook();
 bookIdCount++;
 sb.addBook(bookIdCount, bookName, authorName, bookCost);
 bookMap.put(bookIdCount, sb);
 }

 public void updateBook(int bookId, String bookName, String authorName, int bookCost) {
 StoreBook sb = bookMap.get(bookId);
 sb.updateBook(bookName, authorName, bookCost);
 }

 public Map searchBook(int bookId) {
 return bookMap.get(bookId).getBooks();
 }

 public void deleteBook(int bookId) {
 bookMap.remove(bookId);
 }
 // Inner Class used to persist the app data ie) book details.
 class StoreBook {

 private String bookName;
 private String authorName;
 private int bookCost;
 private int bookId;

 StoreBook() {
 }

 public void addBook(int bookId, String bookName, String authorName, int bookCost) {
 this.bookId = bookId;
 this.bookName = bookName;
 this.authorName = authorName;
 this.bookCost = bookCost;
 }

 public void updateBook(String bookName, String authorName, int bookCost) {
 this.bookName = bookName;
 this.authorName = authorName;
 this.bookCost = bookCost;
 }

 public Map getBooks() {
 Map books = new HashMap();
 books.put("BookId", this.bookId);
 books.put("BookName", this.bookName);
 books.put("AuthorName", this.authorName);
 books.put("BookCost", this.bookCost);
 return books;
 }
 }

 public List getBookList() {
 List booksList = new ArrayList();
 Set s = bookMap.keySet();
 Iterator itr = s.iterator();
 while (itr.hasNext()) {
 booksList.add(bookMap.get((Integer)itr.next()).getBooks());
 }
 return booksList;
 }
 }
 


BookForm.java

Form bean class has the getter & setter methods of corresponding form input elements. With this, you can get and set the value of form elements in the Action class.

 package com.books;

 import org.apache.struts.action.ActionForm;

 public class BookForm extends ActionForm {

 private String bookName;
 private String authorName;
 private int bookCost;
 private int bookId;

 public BookForm() {
 super();
 }

 public String getBookName() {
 return bookName;
 }
 public void setBookName(String bookName) {
 this.bookName = bookName;
 }

 public String getAuthorName() {
 return authorName;
 }
 public void setAuthorName(String authorName) {
 this.authorName = authorName;
 }

 public int getBookCost() {
 return bookCost;
 }
 public void setBookCost(int bookCost) {
 this.bookCost = bookCost;
 }

 public int getBookId() {
 return bookId;
 }
 public void setBookId(int bookId) {
 this.bookId = bookId;
 }
 }
 

BookActions.java
It’s an example of struts DispatchAction class, each and every action/function of book has equivalent methods to process it. This class been invoked when you access these url’s from the web browser.
Add Book : http://localhost:8080/examples/bookaction.do?actionMethod=AddBook
Edit Book : http://localhost:8080/examples/bookaction.do?actionMethod=EditBook&bookId=1008
Delete Book : http://localhost:8080/examples/bookaction.do?actionMethod=DeleteBook

 package com.books;

 import org.apache.struts.action.ActionForm;
 import org.apache.struts.action.ActionMapping;
 import org.apache.struts.action.ActionForward;
 import org.apache.struts.actions.DispatchAction;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 import java.util.Map;

 public class BookActions extends DispatchAction
 {
 public ActionForward AddBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Add Book Page");
 return mapping.findForward("addBook");
 }

 public ActionForward EditBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Edit Book Page");
 int bookId = Integer.parseInt(request.getParameter("bookId"));

 Books b = Books.getInstance();
 Map bookDet = b.searchBook(bookId);

 //Used form bean class methods to fill the form input elements with selected book values.
 BookForm bf = (BookForm)form;
 bf.setBookName(bookDet.get("BookName").toString());
 bf.setAuthorName(bookDet.get("AuthorName").toString());
 bf.setBookCost((Integer)bookDet.get("BookCost"));
 bf.setBookId((Integer)bookDet.get("BookId"));
 return mapping.findForward("editBook");
 }

 public ActionForward SaveBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Save Book");
 //Used form bean class methods to get the value of form input elements.
 BookForm bf = (BookForm)form;
 String bookName = bf.getBookName();
 String authorName = bf.getAuthorName();
 int bookCost = bf.getBookCost();

 Books b = Books.getInstance();
 b.storeBook(bookName, authorName, bookCost);
 return new ActionForward("/showbooks.do", true);
 }

 public ActionForward UpdateBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Update Book");
 BookForm bf = (BookForm)form;
 String bookName = bf.getBookName();
 String authorName = bf.getAuthorName();
 int bookCost = bf.getBookCost();
 int bookId = bf.getBookId();

 Books b = Books.getInstance();
 b.updateBook(bookId, bookName, authorName, bookCost);
 return new ActionForward("/showbooks.do", true);
 }

 public ActionForward DeleteBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Delete Book");
 int bookId = Integer.parseInt(request.getParameter("bookId"));
 Books b = Books.getInstance();
 b.deleteBook(bookId);
 return new ActionForward("/showbooks.do", true);
 }
 }
 

books.jsp
File used to show the available books in the app store. This page is being forwarded from the ShowBooks action class.

 <%@ page import="java.util.HashMap"%>
 <%@ page import="java.util.Map"%>
 <%@ page import="java.util.List"%>
 <%@ page import="java.util.ArrayList"%>
 <%@ page import="java.util.Iterator"%>
 <html>
 <body>
 <p><b>Struts Example - Simple Book Store App</b></p>
 <b>Available Books</b>
 <form name="bookform" action="/examples/bookaction.do">
 <table style="background-color:#82CAFA;">
 <tr style="color:yellow;"><th>&nbsp;</th><th>Book Name</th><th>Author Name</th><th>Book Cost</th></tr>
 <%List bookList = (ArrayList)request.getAttribute("booksList");
 Iterator itr = bookList.iterator();
 while(itr.hasNext()){
 Map map = (HashMap)itr.next();
 %>
 <tr><td><input type="radio" name="bookId" value='<%=map.get("BookId")%>' onclick="javascript:enableEditDelete();"></td>
 <td><%=map.get("BookName")%></td><td><%=map.get("AuthorName")%></td><td><%=map.get("BookCost")%></td>
 </tr>
 <%}%>
 </table>
 </p>
 <p>
 <table><tr>
 <td><input type="submit" name="actionMethod" value="AddBook" /></td>
 <td><input type="submit" name="actionMethod" id="editbutton" value="EditBook" disabled="true" /></td>
 <td><input type="submit" name="actionMethod" id="deletebutton" value="DeleteBook" disabled="true" onclick="return checkDelete();" /></td>
 </tr></table>
 </form>
 </p>
 <script>
 function checkDelete(){
 return confirm("Are u sure to delete this book..?");
 }
 function enableEditDelete(){
 document.getElementById('editbutton').disabled=false;
 document.getElementById('deletebutton').disabled=false;
 }
 </script>
 </body>
 </html>
 

addbook.jsp
Web page used to add a new book to the app store.

 <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
 <html>
 <body>
 <p><b>Struts Example - Simple Book Store App</b></p>
 <b>Add Book</b>
 <html:form>
 <table style="background-color:#82CAFA;">
 <tr><td>Book Name</td><td><html:text property="bookName" value=""/></td></tr>
 <tr><td>Author Name</td><td><html:text property="authorName" value=""/></td></tr>
 <tr><td>Book Cost</td><td><html:text property="bookCost" value=""/></td></tr>
 </table>
 </p>
 <p>
 <table><tr>
 <td><input type="submit" name="actionMethod" value="SaveBook" /></td>
 </tr></table>
 </html:form>
 </p>
 </body>
 </html>
 


editbook.jsp

In this page, used HTML tag lib, form bean class(BookForm) will take care of filling the form input elements.

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
 <html>
 <body>
 <p><b>Struts Example - Simple Book Store App</b></p>
 <b>Edit Book</b>
 <html:form>
 <table style="background-color:#82CAFA;">
 <tr><td>Book Id</td><td><html:text property="bookId" disabled="true"/></td></tr>
 <tr><td>Book Name</td><td><html:text property="bookName"/></td></tr>
 <tr><td>Author Name</td><td><html:text property="authorName"/></td></tr>
 <tr><td>Book Cost</td><td><html:text property="bookCost"/></td></tr>
 </table>
 </p>
 <p>
 <table><tr>
 <td><input type="submit" name="actionMethod" value="UpdateBook" /></td>
 </tr></table>
 </html:form>
 </p>
 </body>
 </html>
 

Note:

  • All the jsp files should present under directory apache-tomcat-6.0.29\webapps\examples\jsp\books.
  • Compile all the java files, and place the created class files to apache-tomcat-6.0.29\webapps\examples\WEB-INF\classes

All the codes specified in this blog will compile & work perfectly without any issues. Just download and try it. It’s very easy to learn and build applications in Struts.

Sample Output of Book Store Apps.

Available Books in Store

Add Book Web Page

Add Book

Edit Book Web Page

Edit Book