RSS

Composite Pattern

I recently gave a presentation on Composite Pattern. I had used this pattern earlier in my life without knowing that its name is ‘Composite Pattern’. Learning what you have already implemented becomes easy and I believe that you absorb more out of it.

I referred Gang of Four and Head First Design Pattern books for preparing the presentation. Head First has a very good explanation of using Iterator Pattern with the Composite Pattern and Gang of Four cover mostly most of the issues you can come across while implementing this pattern. I also developed code to demonstrate the usage of the pattern. Sometimes reading code gives more information as compared to the text.

I am sharing the presentation we made. If you have any questions then leave me a comment and I will answer it.

Link to Download Presentation: Composite Pattern

 
Leave a comment

Posted by on September 30, 2011 in Uncategorized

 

Tags:

Piggydb Review

Internet has given us many options to gain knowledge about anything which we like. This helps researchers, students, business people, management gurus and many others to gather information.  It’s a general practice that we keep on accumulating data but find it hard to organize it.

Piggydb is a free web notebook application which solves the intricacy of organizing knowledge. It structures the data in the form of fragments where each fragment is a piece of information. You can build a network of knowledge fragments based on their tags and relationship between them can be changed at any point of time. You can even embed an information fragment into another.

Let’s talk about the most important features that Piggydb incorporates.

-          Structural Knowledge:  Piggydb gives a new dimension in the field of consolidating and structuring knowledge. It’s not an input and search application but on the other hand it aims to structure the knowledge in a continuous fashion. The knowledge fragments are interrelated based on tags assigned to them and are very flexible to change. You can even create a hierarchy of tags which can be used when adding new fragments.

-          Can be used from one person to small group: It supports both individual and collaborative knowledge organizing. Adding a new user is as easy as adding a text fragment. The application can also be configured to allow unauthenticated users to view but not delete or edit knowledge fragments. Doing this only requires a minor change in a property file.

-          Text Search: It is possible to search for fragments by keywords. The fetched results are shown and matched keywords are highlighted. This is the feature which is used at a maximum level.

-          User Defined Filters: You can create new Filters and save them so that you don’t have to repeat the search again when needed. The names of the filters can also be changed. The filter work on tags. Building a filter is as easy as to put the tags in the category of Classified by all of or Not classified by any of.

Beside these standard features, Piggydb comes with “Export” option. Using this option you can export the complete database as a single file. It also comes with an inbuilt image viewer. Moreover you can use System Information option to get the information about number of fragments, relations, tags and filters.

Why is Piggydb famous?

Piggydb is famous because it is a wonderful application which has introduced a radical idea of structuring information.

Piggydb puts the user in first place to decide how his information is going to be structured unlike other internet structured knowledge applications like Wikipedia, twitter etc.

Piggydb is adept to handle large numbers of tags and large amounts of information. It also allows user to create his hierarchies of concepts.

Piggydb allows tags to inherit the functions of their parent tags, in addition to of their own functions.

Polls:


 
Leave a comment

Posted by on September 11, 2010 in Software Review

 

Some Questions on Collections

1. What is the difference between a List and a Set?
List allows duplicates and maintains the order in which the elements were inserted on the other hand a Set doesn’t allow duplicates and no order is maintained.

2. Tell me some ways to make a synchronized list.
You can use Vector or can use a method provided in Collections class. Collections.SynchronizedList(List list) which returns a synchronized list.

3. What method should the key class of Hashmap override?
The class used as a Key must override equals() and hashCode() methods.

4. What is the key difference between Enumeration and Iterator?
Iterator has a remove() method while Enumeration doesn’t. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, whereas using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used whenever we want to make Collection objects as Read-only.

5. What is the difference between Vector and ArrayList?
Vector is synchronized whereas ArrayList is not.

6. Can a List contain heterogeneous objects?
Yes a List can contain heterogeneous objects. It also depends upon the type declaration of the List. From Java 1.5 onwards use

 List<Object> list = new ArrayList<Object>(); 

to declare a hetrogenous list.

7. How do I sort the Elements in a Collection?
You can use Collections.sort method to sort the elements.

 
1 Comment

Posted by on September 11, 2010 in Java, Java Collections

 

Sorting List in Java

Sorting Lists in Java is a common task. For this Java provides Comparators and Comparables. These are Interfaces which are required to be implemented for sorting purpose. For the demonstration we will consider one at a time. sort method of Collections class in used to sort. This method is overloaded one takes List as its parameter and other takes List and Comparator as its arguments.

Sorting using Comparable Interface:

This Interface has a method compareTo. It compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. In the code provided below the Person class implements Comparable Interface.

package com.sample.beans;

import java.util.Date;

/**
 * @author hgupta
 *
 */
public class Person implements Comparable<Person> {

	/** used for name of the Person **/
	private String name;
	
	/** used for home address of the Person **/
	private String address;
	
	/** used for Date of Birth **/
	private Date dateOfBirth;
	
	/** used for phone number **/
	private Integer phoneNumber;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the address
	 */
	public String getAddress() {
		return address;
	}

	/**
	 * @param address the address to set
	 */
	public void setAddress(String address) {
		this.address = address;
	}

	/**
	 * @return the dateOfBirth
	 */
	public Date getDateOfBirth() {
		return dateOfBirth;
	}

	/**
	 * @param dateOfBirth the dateOfBirth to set
	 */
	public void setDateOfBirth(Date dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}

	/**
	 * @return the phoneNumber
	 */
	public Integer getPhoneNumber() {
		return phoneNumber;
	}

	/**
	 * @param phoneNumber the phoneNumber to set
	 */
	public void setPhoneNumber(Integer phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	@Override
	public int compareTo(Person o) {
		return this.getName().compareTo(o.getName());
	}
	
}

Here the Person class implements the Comparable Interface and so it has the method compareTo. Here in this example it uses String’s compareTo method to compare the String at the base. Depending upon the comparison it returns an int which can be –ve, +ve or 0. Here one concept to be mentioned is it only depends upon the sign of the number but not its magnitude.
Now we will also write a Comparator which will be used to sort the List of Person on the property named dateOfBirth which is of Date type.

package com.comparators;

import java.util.Comparator;

import com.sample.beans.Person;

/**
 * @author Himanshu
 *
 */
public class PersonDOBComparator implements Comparator<Person> {

	@Override
	public int compare(Person o1, Person o2) {
		return o1.getDateOfBirth().compareTo(o2.getDateOfBirth());
	}


}

The PersonDOBComparator implements the Comparator Interface. The method compare takes two arguments and compares them. Using Comparator is easy. If you have any final class whose code cannot be modified, at that stage you can write a comparator. Also if you have a functionality in which you have to sort the List on a number of properties then writing a comparator for each property is easy. Also there are some libraries available which provides comparator on the fly.
Let us sort a List containing Person’s Objects. For this we will make a CollectionSorter.java class which will sort and display the sorted results to the user.

package com.collection.sorting.examples;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;

import com.comparators.PersonDOBComparator;
import com.sample.beans.Person;

/**
 * @author hgupta
 *
 */
public class CollectionSorter {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CollectionSorterUtil collectionSorterUtil = new CollectionSorterUtil();
		ArrayList<Person> persons = collectionSorterUtil.getPersonsAsArrayList();
		System.out.println("Orignal List");
		displayPersons(persons);
		Collections.sort(collectionSorterUtil.getPersonsAsArrayList());//Line 1
		System.out.println("List Sorted By Name");
		displayPersons(persons);
		Collections.sort(collectionSorterUtil.getPersonsAsArrayList(), new PersonDOBComparator());// Line 2
		System.out.println("List Sorted By Date of Birth");
		displayPersons(persons);
	}

	private static void displayPersons(ArrayList<Person> persons){
		DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		System.out.println("----------------------------------------------------------");
		for(Person person:persons){
			System.out.print(person.getName());
			System.out.println(" " + dateFormat.format(person.getDateOfBirth()));
		}
		System.out.println("----------------------------------------------------------");
	}
}

This class uses another utility class named CollectionSorterUtil.java which populated the list used by CollectionSorter class. At Line 1 we have used Collections.sort(List list) method to sort the List. It uses the method compareTo which we provided in the Person class by implementing Comparable Interface. At Line 2 we have used a Comparator to sort it. This Comparator uses dateOfBirth to sort the List.

package com.collection.sorting.examples;

import java.util.ArrayList;
import java.util.Date;

import com.sample.beans.Person;

/**
 * @author hgupta
 *
 */
public class CollectionSorterUtil {

	/** ArrayList to store Persons Object**/
	ArrayList<Person> persons = new ArrayList<Person>();
	{
		populatePersons();
	}
	
	/**
	 * This method returns a collection of Person
	 * Objects.
	 * @return {@link ArrayList} Person
	 */
	public  ArrayList<Person> getPersonsAsArrayList(){
		return this.persons ;
	}
	
	private void populatePersons(){
		Person person = new Person();
		person.setName("Mark");
		person.setDateOfBirth(new Date("02/12/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Anthony");
		person.setDateOfBirth(new Date("02/30/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Zulia");
		person.setDateOfBirth(new Date("02/12/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Jenifer");
		person.setDateOfBirth(new Date("05/2/1988"));
		persons.add(person);
		
		person = new Person();
		person.setName("Jhon");
		person.setDateOfBirth(new Date("01/11/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Russels");
		person.setDateOfBirth(new Date("02/12/1980"));
		persons.add(person);
		
		person = new Person();
		person.setName("Erik");
		person.setDateOfBirth(new Date("05/25/1984"));
		persons.add(person);
		
		person = new Person();
		person.setName("Peter");
		person.setDateOfBirth(new Date("12/02/1997"));
		persons.add(person);
		
	}
	
}

After you run the CollectionSorter class you will see the following output in the console.

Orignal List
----------------------------------------------------------
Mark 02/12/1987
Anthony 03/02/1987
Zulia 02/12/1987
Jenifer 05/02/1988
Jhon 01/11/1987
Russels 02/12/1980
Erik 05/25/1984
Peter 12/02/1997
----------------------------------------------------------
List Sorted By Name
----------------------------------------------------------
Anthony 03/02/1987
Erik 05/25/1984
Jenifer 05/02/1988
Jhon 01/11/1987
Mark 02/12/1987
Peter 12/02/1997
Russels 02/12/1980
Zulia 02/12/1987
----------------------------------------------------------
List Sorted By Date of Birth
----------------------------------------------------------
Russels 02/12/1980
Erik 05/25/1984
Jhon 01/11/1987
Mark 02/12/1987
Zulia 02/12/1987
Anthony 03/02/1987
Jenifer 05/02/1988
Peter 12/02/1997
----------------------------------------------------------

 
Leave a comment

Posted by on September 10, 2010 in Java, Java Collections

 

Tags: , , ,

Installing Tomcat on Windows

Tomcat is an open source servlet and JSP container. It is very easy to install and use. Many Java developers around the world use it. It has got very strong community support and has evolved a lot.  This article gives stress on the installation process of tomcat. To install Tomcat follow the step given as under:

  1. Download the Tomcat from the URL: http://tomcat.apache.org/download-60.cgi . There are two types of files available to download. One is to download the zip file and extract it. Second one is .exe windows installer file to install it in your PC. Second approach is much easier and it will install the service also to start and stop the tomcat server.
  2. If you have downloaded the .exe file just run it by double clicking it and it will install tomcat on your PC. In case you have downloaded the Core version of it then unzip the file to a folder. After unzipping it you will see the following directories inside parent tomcat directory.
  3. tomcat home directory

  4. Deploying a web-application: If you want to deploy any web application put it in the directory named webapp. The application should be a valid web application so that it can be deployed successfully.
  5. Starting /Stopping the Server: Go to the bin directory and double click the startup.bat file to start the server. You will see some logs in the console which opens up when you click the startup file. To shut it down click the shutdown.bat.

Tomcat bin Directory

Tomcat Startup screen

The Console window will show you the log messages when it starts and stops. If you don’t want to stop the server by clicking shutdown.exe you can press CTRL+C in the console window. It will stop the server by itself.

 
Leave a comment

Posted by on September 10, 2010 in Java, Servers

 

Tags: , ,

Writing your First Hello World Program in JAVA

Before attempting to start programming in Java make sure that you have Java installed in your computer.
This example is simple and easy to understand. The program will print “Hello World” in the console.
To start open notepad and type the following code:


/**
 * This is a public class named HelloWorld.
 */
public class HelloWorld {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Hello World!!");
	}

}

1. Save this file by naming it HelloWorld.java. Make sure that the file name and the class name are same.
2. Open the command console and go to the parent directory where you have saved the HelloWorld.java file. Give the following command: javac HelloWorld.java and press Enter key. This will compile the HelloWorld file and make a class file of it. This file has the bytecode which will be executed by the JVM.

3. After that you can run your java program by running the following command:
C:\>java HelloWorld

This will give you output of “Hello World” in the console.
Source Code Explanation

You have complied and have seen your program run successfully. This all is good but it is also very important to understand how it works. The source code has three main components:

  • Comments
  • Class Declaration
  • Main method

Comments: The comments start from “/*” and end by “*/”. They are ignored by the compiler and are only useful for the programmers to improve readability of the code.  Java supports three types of comment types:

/* text */ Compiler completely ignores whatever comes between.

/** documentation */ These comments are called documentation comments and are also ignored by the compiler. The javadoc tool uses these comments to make automatically generated documentation.
// text: The compiler ignores everything from // to the end of the line.

Class Declaration: The following code declares a public class whose name is HelloWorld.

public class HelloWorld {
…………….
….
}

The class declaration uses the keyword class for its declaration and the code is written in between the opening and closing curly braces.

The main Method: The following code shows the main method. This method accepts a single argument: an array of elements of type String. Every Java Application must have this main method to run.  You can interchange the position of public and static keyword and doing this will not affect your code.

public static void main(String[] args) {
		System.out.println("Hello World!!");
	}

The code in this method is written between the curly braces.

The line System.out.println(“Hello World!!”); in this example uses System class to print the message “Hello World!!” to the console.

 
Leave a comment

Posted by on September 6, 2010 in Java

 

What are Servlets?

As seen from the top then Servlets are no different as compared to a Java class. They provide a component based way to design a web application. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. Servlets run entirely inside the Java Virtual Machine and so have access to the whole set of Java API. Also an application written using Servlets can be deployed in any container and it will work. Servlets are popular choice for building interactive Web applications. Third-party servlet containers are available for example Apache Web Server, Microsoft IIS, and others. Servlet containers are usually a component of Web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server, and others.

Servlets are not bound to any specific protocol and can be extended to design one of its own choice but commonly servlets designed to work with HTTP(Hyper Text Transfer Protocol) are used heavily. These Servlets are controlled by the container from their creation to collection by Garbage Collector.

 
Leave a comment

Posted by on July 7, 2010 in J2EE, Java

 

Tags: ,

 
Follow

Get every new post delivered to your Inbox.