Java Collection Framework : List


This material was first published by  Code Explosion | Code that explodes convention

Java collection framework is very common to every java programmer, again for the beginner, I’m going to share my ideas about it.  It’s really helpful to manage object easily. Java collection framework is more likely array, but difference is, Collections can  dynamically change their size. Today I’m going to write only about the List.

List:

The java.util.List interface is a subtype of the java.util.Collection interface. It represents an order list of objects. User can access the elements of list in a specific order or by and integer index. List allows to insert duplicate elements. Interestingly you can insert null object even in a list.
As it is an interface, there of course it has implementation. ArrayList, LinkedList, Vector, Stack are the implementation of List. All List types support basic operation like adding object, removing objects, accessing objects and iterating through the List.

There are also List implementation in java.util.concurrent package. Concurrency is the part of parallel programming, immutability, threads, executor frameworks etc. We better discuss this part later.

How to create list instance:

Creating list instance is too easy.

package org.codexplo.blog.list;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import java.util.Vector;

public class ListInstance {
public static void main(String[] args) {
List listA = new ArrayList();
List listB = new LinkedList();
List listC = new Vector();
List listD = new Stack();
}
}

Adding and accessing Elements
To add element, you need to call its add() methods. This method is inherited from java.util.Collection interface.
There are two overload method in list.

boolean add(E e);
void add(int index, E element);

The first one add elements t0 the end of the list and return true if the list is changed as a result of the call otherwise false.

and the second one add element at the specified position in the list. If any element is already in that position, it shifts the elements concurrently to the next.

package org.codexplo.blog.list;

import java.util.ArrayList;
import java.util.List;

public class AddingAndAccessingList {
public static void main(String[] args) {
List list = new ArrayList();

list.add("a");
list.add("b");
list.add("c");

list.add(0, "abcd");

System.out.println(list.get(0));
System.out.println(list.get(1));
}
}

The first three add() calls add a string instance to the end of the list. The last  add() call adds the element at the beginning of the list and rest of elements are shifted.

you can access elements using get method. you need to specify the index of the element.

Again you can access elements via Iterator.

package org.codexplo.blog.list;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class AddingAndAccessingList {
public static void main(String[] args) {
List list = new ArrayList();

list.add("a");
list.add("b");
list.add("c");

list.add(0, "abcd");

// via get() method
String a = (String) list.get(0);// need to type cast as I used generic
// type List
String b = (String) list.get(0);

// via iterator
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
String string = (String) iterator.next();

}
}
}

Removing Elements

You can remove element in two ways.

boolean remove(Object o);
E remove(int index);

The first method removes the first occurrence of the specified element from the list. If the list does not contain the element, it is unchanged. More precisely it removes the element with lowest index if the element exist. Returns true if the list contained the specified element.

The second method removes element at the specified position in the list. It shift any subsequent elements to the left concurrently and return the element that was removed from the list.

package org.codexplo.blog.list;

import java.util.*;

public class RemoveListObject {
public static void main(String[] args) {
List list = new ArrayList();

list.add("a");
list.add("b");
list.add("c");
list.add("d");

list.remove("a");

list.remove(2);
}
}

These are the basic operation of the list. But there are some more methods available in List interface. Some of them are given shortly.

int size();

Returns the number of element in the list. int size(); If the list contains more than Integer.Max_Value elements, it returns Integer.Max_Value meaning if the list contain more than 2147483642, it will return 2147483647 because we know an int can can have, 2^31-1.

boolean isEmpty();

returns true if the list contains no element otherwise false.

boolean contains(Object o);

returns true the list contains the specified element.

Iterator<E> iterator();

Returns an iterator over the elements in the list in proper sequence.

Object[] toArray();

Returns an array containing all of the elements in the list in proper sequence (from first to last element).

void clear();

Removes all of the elements from this list (optional operation).

int indexOf(Object o);

Returns the index of the first occurrence of the specified element in the list, or -1 if this list does not contain the element.

int lastIndexOf(Object o);

Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

List subList(int fromIndex, int toIndex);

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

if you want to remove a subset of elements from the list, you can use following way.

list.subList(from, to).clear();

it will remove elements of the range specified.

Optimized technique.

The performance of different implementation of List is different. The choice of using list implementation depends on specific operation. As I said earlier, all list type support all basic operation, so which one to choose since all the list implementation support these basic operation? Here choice depends on the performance and requirement options.

The requirement operation could be –
1. Thread safety
2. Size of collection
3. Type of operation (adding, removing , accessing or iterating)

If you want your collection to be thread safe then Vector or Stack must be used because both have synchronized methods. ArrayList and LinkedList are not thread safe. Stack is mean fo LIFO (last in, first out) operation. If thread safety is not your concern, you can use ArrayList or LinkedList. From the performance point of view the ArrayList gives better gives better performance when accessing and iterating object whereas LinkedList gives better performance when adding and removing objects.

The initial size for ArrayList and Vector is 10. ArrayList increase its capacity by half approximately whenever its capacity reaches maximum(10) but vector increase its capacity by double whenever its capacity reaches maximum.

LinkedList gives good performance when adding elements at the end and beginning but it is worse when adding objects at middle because it needs to scan the node whenever it needs to add an object.

Iterating collection using all three types of classes ,ArrayList ,Vector and LinkedList gives similar performance.

Key Points:
1. Use ArrayList with proper initialization if you don’t want thread safe for the collection whenever you add/remove/access objects at end and middle of collection.
2. Use Vector with proper initialization if you want thread safe for the collection whenever you add/remove/access objects at end and middle of collection.
3. Use LinkedList if you don’t want thread safe for the collection whenever you add/remove/access objects at beginning of collection.
4. Use synchronized LinkedList if you want thread safe for the collection whenever you add/remove/access objects at beginning of collection.

Let us make our application fly


Yes, today I’m with an interesting design pattern that is flyweight pattern. Here we are going to make our application fly and this is the motivation. We will make your application ready for fly, so it’s needed to make sure that our application has very little weight.

Let us think for an application which is going to draw 10000 lines for different colors. So we need 1000 line objects right?

Let us assume, creating a line object takes 100 milliseconds. So for 10000 lines, we need 1000000 milliseconds that mean we need 1000 seconds and it’s kind of huge. So first let us make a demo application.

Let us create a class named Line.

</p>
<p>import java.awt.Color;<br />
import java.awt.Graphics;</p>
<p>public class Line {<br />
private Color color;</p>
<p>public Line(Color color) {<br />
this.color = color;<br />
try {<br />
Thread.sleep(100);<br />
} catch (InterruptedException e) {<br />
e.printStackTrace();<br />
}<br />
}<br />
public void draw(Graphics g, int x1, int y1, int x2, int y2) {<br />
g.setColor(color);<br />
g.drawLine(x1, y1, x2, y2);<br />
}<br />
}<br />

Here I used Thread.sleep(100) as we have assumed that every line will take 100 milliseconds to be instantiated.

And now let us create a Demo:

Flyweight pattern Demo

Flyweight pattern Demo

So this is our application and it takes approximately 16 minutes that is very huge time.
Now I will make this application in a way so that it can fly. So it’s needed to be created so fast like within a seconds.
Here I’m going to use a design pattern that is called flyweight pattern.
So first let us make an interface named Line.

</p>
<p>import java.awt.Graphics;</p>
<p>public interface Line {</p>
<p>public void draw(Graphics g, int x1, int y1, int x2, int y2);<br />
}

Now let us make a concrete class implementing this interface.

</p>
<p>import java.awt.Color;<br />
import java.awt.Graphics;</p>
<p>public class MyLine implements Line {<br />
private Color color;</p>
<p>public MyLine(Color color) {<br />
this.color = color;<br />
try {<br />
Thread.sleep(100);<br />
} catch (InterruptedException e) {<br />
e.printStackTrace();<br />
}<br />
}</p>
<p>@Override<br />
public void draw(Graphics g, int x1, int y1, int x2, int y2) {<br />
g.setColor(color);<br />
g.drawLine(x1, y1, x2, y2);<br />
}<br />
}

Now let us make Factory class that is named MyLineFactory.

<br />
import java.awt.Color;<br />
import java.util.HashMap;</p>
<p>public class MyLineFactory {<br />
private static MyLineFactory myLineFactory;<br />
private static HashMap lineByColor;</p>
<p>private MyLineFactory() {<br />
lineByColor = new HashMap();<br />
}</p>
<p>public static MyLineFactory getMyLineFactory() {<br />
if (myLineFactory == null) {<br />
myLineFactory = new MyLineFactory();<br />
}<br />
return myLineFactory;<br />
}</p>
<p>public Line getLine(Color color) {<br />
if (lineByColor.containsKey(color)) {<br />
return (Line) lineByColor.get(color);<br />
} else {<br />
Line line = new MyLine(color);<br />
lineByColor.put(color, line);<br />
return line;<br />
}<br />
}<br />
}

This MyLineFactory itself implements two design pattern, they are Singleton pattern and Factory Pattern.

Now if we make a demo, I have calculated that it takes approximately 1200 milliseconds only.
So it’s better approach right?

Now let me define what actually Flyweight pattern.  According to Gang of Four Design pattern book, it

Facilitates the reuse of many fine grained objects, making the utilization of large numbers of objects more efficient.

Now let me tell you my understanding.
I have already told you that, we need to make your application very light weighted. So there should be a way. And that is reusing an object again and again.

In this application, we have drawn 10000 line objects with 5 colors. So the probability of the same color in the 10000 line is 2000. For example, there will be 2000 red colored line. So if we create an object of red color, and reuse it 2000 times, then for 5 colors, we can make our application with only 5 line objects instead of 10000 line objects.

So to implement flyweight pattern we need 4 participants. They are –
Flyweight: It’s an interface that defines the main behavior. In our application we created an interface named Line and it contains a method named draw.
Concrete Flyweight:  it’s a class that is going to implement the flyweight interface. In your application, it is MyLine.
Flyweight Factory: This is very important part. Here we use two major design patterns, singleton and Factory Pattern. In this class we will have an object pool.   The object pool holds flyweight objects with a key. Whenever we need an object, we search it in the object pool. If the object is available here in the object pool, we will take it; otherwise we will create one and push into the object pool so that whenever we need this object again, we can get it from it.
Client: And here we are going to do our rest of work.

Source Code: Here you will get two version of source code, one using flyweight and another non flyweight version.

Click This Link

Reference:

http://java.dzone.com/articles/design-patterns-flyweight
http://www.javaworld.com/javaworld/jw-07-2003/jw-0725-designpatterns.html?page=1
http://cnx.org/content/m26103/latest/

You have no right to miss it


Today Im gonna share with a magnificent video with you and you have no right to miss it. Lets have a byte.

Its a Shell-sort with Hungarian  folk dance and its Created at Sapientia University, Tirgu Mures (Marosvásárhely), Romania.
Directed by Kátai Zoltán and Tóth László.
In cooperation with “Maros Művészegyüttes”, Tirgu Mures (Marosvásárhely), Romania.
Choreographer: Füzesi Albert.

Better approch of String manipulation: StrignBuilder or StringBuffer


String is an immutable object, once constructed they cannot be changed anymore.That means, whenever you “change” the value of a String, you create a new object basically and make that variable reference this new object. Appending a String to another existing one is the same kind of deal and here old object is always dropped.

So for manipulating string means there is more to copy and more garbage is produced that is less performing.

So when we need to manipulate string, it  is better to use SrtringBuffer or StringBuilder.

StringBuilder and StringBuilder are mutable object. So when I/O gets large, we should use StringBuilder and StringBuilder.

Both of them are basically same. The difference between them is, StringBuilder is not thread safe, in others words, its methods are not synchronized. So it is recommended to use StringBuilder instead of StringBuffer whenever possible, because StringBuilder will run faster.

Linux commands- and my everyday life


ls – directory and file listing
ls -al  formatted listing with hidden files
cd [directory_name] change directory to directory_name
cd goto home
pwd – present working directory
mkdir [directory_name] create a directory directory_name
rm [file_name] delete file_name
rm -r [directory_name] delete directory directory_name
rm -r [file_name] forcefully delete file file_name
rm -f [directory_name] forcefully delte directory directory_name
cp [file_1] [file_2] copy file_1 to file_2
mv [file_1] [file_2] rename or move file_1 to file_2
touch [file_name] create or update file_name
cat > [file_name] standard input into file_name
less [file_name] read file_name

chmod 777  [file_name] permission to read, write execute for all
chomod 755 [file_name] permission rwx for owrner, rx for group and world

ssh [user_name]@[host_name] – connect to host as user
ssh -p [port] [user_name]@[host_name] – connect to host on port as user

whereis [application_name] show possible location for application_name
locate [file_name] show possible location for file file_name

ping [host_name] ping to a host
whois [domain_name] get information for a domain

Ctrl +C halts the current command
Ctrl + Z stop the current command,
Ctrl + L clear the terminal texts

Web programming with Java, Spring framework, part 3 (via Welcome to my awesome blog)


Web programming with Java, Spring framework, part 3 SimpleForm Controller Guys today I wanna show you a form processing system in spring framework. This is fairly simple and easy. So First let us write a controller and name it FormController and we need to extend SimpleFormController. package com.rokon.web; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http. … Read More

via Welcome to my awesome blog

Web programming with Java, Spring framework, part 3


SimpleForm Controller

Guys today I wanna show you a form processing system in spring framework. This is fairly simple and easy.
So First let us write a controller and name it FormController and we need to extend SimpleFormController.

package com.rokon.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.ui.ModelMap;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.rokon.db.User;
import com.rokon.service.UserService;

@SuppressWarnings( { "deprecation" })
public class FormController extends SimpleFormController {
 private UserService userService;

 private ModelMap modelMap = new ModelMap();

 public void setUserService(UserService userService) {
 this.userService = userService;
 }

 public FormController() {
 setCommandClass(User.class);
 setCommandName("user");
 }

 @Override
 protected Map referenceData(HttpServletRequest request) throws Exception {

 List list = userService.getCountryList();

 HttpSession session = request.getSession();
 session.setAttribute("list", list);

 return modelMap;
 }

 @Override
 protected ModelAndView onSubmit(HttpServletRequest request,
 HttpServletResponse response, Object command, BindException errors)
 throws Exception {
 User user = (User) command;

 ModelAndView mv = new ModelAndView("formSuccess");
 mv.addObject("user", user);
 return mv;
 }
}

Generally a form is associated with a particular domain. here we have a domain class that is User.  In
Spring domain class is called command object . So here we set the command object using setCommandClass() method and
we need set a name of the command object. and here using setCommandName() we set a name of the command object that is user.
and we have done these with constructor. command name is need when we are gonna access this object in our jsp page using simple user.[an_attritubes_of_user_class]

here is another method that is referenceData(). I will tell about it later.

you need to override a mathod to handle the form. So here we override onSubmit() method. It returns a ModelAndView object which
has the success page and model that is data.

so let us see the domain class

package com.rokon.db;

public class User {
 private String name;
 private String password;
 private String email;
 private String country;
 private String phone;

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getPassword() {
 return password;
 }

 public void setPassword(String password) {
 this.password = password;
 }

 public String getEmail() {
 return email;
 }

 public void setEmail(String email) {
 this.email = email;
 }

 public String getCountry() {
 return country;
 }

 public void setCountry(String country) {
 this.country = country;
 }

 public String getPhone() {
 return phone;
 }

 public void setPhone(String phone) {
 this.phone = phone;
 }
}

now let see our service interface

package com.rokon.service;

import java.util.List;

public interface UserService {
 public void addUser();
 public List getCountryList();
}

and the implementation is

package com.rokon.service;

import java.util.ArrayList;
import java.util.List;

public class UserServiceImpl implements UserService {

 @Override
 public void addUser() {
 System.out.println("User added successfully");
 // here actually we add user in database for simplicity we are avoiding
 // this part for now, may be we are gonna implement this later
 }

 @Override
 public List getCountryList() {

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

 list.add("Afghanistan");
 list.add("Albania");
 list.add("Algeria");
 list.add("American Samoa");
 list.add("Andorra");
 list.add("Angola");
 list.add("Anguilla");
 list.add("Antarctica");
 list.add("Antigua and Barbuda");
 list.add("Arctic Ocean");
 list.add("Argentina");
 list.add("Armenia");
 list.add("Aruba");
 list.add("Ashmore and Cartier Islands");
 list.add("Atlantic Ocean");
 list.add("Australia");
 list.add("Austria");
 list.add("Azerbaijan");
 list.add("");
 list.add("Bahamas");
 list.add("Bahrain");
 list.add("Baltic Sea");
 list.add("Baker Island");
 list.add("Bangladesh");
 list.add("Barbados");
 list.add("Bassas da India");
 list.add("Belarus");
 list.add("Belgium");
 list.add("Belize");
 list.add("Benin");
 list.add("Bermuda");
 list.add("Bhutan");
 list.add("Bolivia");
 list.add("Borneo");
 list.add("Bosnia and Herzegovina");
 list.add("Botswana");
 list.add("Bouvet Island");
 list.add("Brazil");
 list.add("British Virgin Islands");
 list.add("Brunei");
 list.add("Bulgaria");
 list.add("Burkina Faso");
 list.add("Burundi");
 list.add("");
 list.add("Cambodia");
 list.add("Cameroon");
 list.add("Canada");
 list.add("Cape Verde");
 list.add("Cayman Islands");
 list.add("Central African Republic");
 list.add("Chad");
 list.add("Chile");
 list.add("China");
 list.add("Christmas Island");
 list.add("Clipperton Island");
 list.add("Cocos Islands");
 list.add("Colombia");
 list.add("Comoros");
 list.add("Cook Islands");
 list.add("Coral Sea Islands");
 list.add("Costa Rica");
 list.add("Cote d'Ivoire");
 list.add("Croatia");
 list.add("Cuba");
 list.add("Cyprus");
 list.add("Czech Republic");
 list.add("");
 list.add("Democratic Republic of the Congo");
 list.add("Denmark");
 list.add("Djibouti");
 list.add("Dominica");
 list.add("Dominican Republic");
 list.add("");
 list.add("East Timor");
 list.add("Ecuador");
 list.add("Egypt");
 list.add("El Salvador");
 list.add("Equatorial Guinea");
 list.add("Eritrea");
 list.add("Estonia");
 list.add("Ethiopia");
 list.add("Europa Island");
 list.add("");
 list.add("Falkland Islands (Islas Malvinas)");
 list.add("Faroe Islands");
 list.add("Fiji");
 list.add("Finland");
 list.add("France");
 list.add("French Guiana");
 list.add("French Polynesia");
 list.add("French Southern and Antarctic Lands");
 list.add("");
 list.add("Gabon");
 list.add("Gambia");
 list.add("Gaza Strip");
 list.add("Georgia");
 list.add("Germany");
 list.add("Ghana");
 list.add("Gibraltar");
 list.add("Glorioso Islands");
 list.add("Greece");
 list.add("Greenland");
 list.add("Grenada");
 list.add("Guadeloupe");
 list.add("Guam");
 list.add("Guatemala");
 list.add("Guernsey");
 list.add("Guinea");
 list.add("Guinea-Bissau");
 list.add("Guyana");
 list.add("");
 list.add("Haiti");
 list.add("Heard Island and McDonald Islands");
 list.add("Honduras");
 list.add("Hong Kong");
 list.add("Howland Island");
 list.add("Hungary");
 list.add("");
 list.add("Iceland");
 list.add("India");
 list.add("Indian Ocean");
 list.add("Indonesia");
 list.add("Iran");
 list.add("Iraq");
 list.add("Ireland");
 list.add("Isle of Man");
 list.add("Israel");
 list.add("Italy");
 list.add("");
 list.add("Jamaica");
 list.add("Jan Mayen");
 list.add("Japan");
 list.add("Jarvis Island");
 list.add("Jersey");
 list.add("Johnston Atoll");
 list.add("Jordan");
 list.add("Juan de Nova Island");
 list.add("");
 list.add("Kazakhstan");
 list.add("Kenya");
 list.add("Kerguelen Archipelago");
 list.add("Kingman Reef");
 list.add("Kiribati");
 list.add("Kosovo");
 list.add("Kuwait");
 list.add("Kyrgyzstan");
 list.add("");
 list.add("Laos");
 list.add("Latvia");
 list.add("Lebanon");
 list.add("Lesotho");
 list.add("Liberia");
 list.add("Libya");
 list.add("Liechtenstein");
 list.add("Lithuania");
 list.add("Luxembourg");
 list.add("");
 list.add("Macau");
 list.add("Macedonia");
 list.add("Madagascar");
 list.add("Malawi");
 list.add("Malaysia");
 list.add("Maldives");
 list.add("Mali");
 list.add("Malta");
 list.add("Marshall Islands");
 list.add("Martinique");
 list.add("Mauritania");
 list.add("Mauritius");
 list.add("Mayotte");
 list.add("Mediterranean Sea");
 list.add("Mexico");
 list.add("Micronesia");
 list.add("Midway Islands");
 list.add("Moldova");
 list.add("Monaco");
 list.add("Mongolia");
 list.add("Montenegro");
 list.add("Montserrat");
 list.add("Morocco");
 list.add("Mozambique");
 list.add("Myanmar");
 list.add("");
 list.add("Namibia");
 list.add("Nauru");
 list.add("Navassa Island");
 list.add("Nepal");
 list.add("Netherlands");
 list.add("Netherlands Antilles");
 list.add("New Caledonia");
 list.add("New Zealand");
 list.add("Nicaragua");
 list.add("Niger");
 list.add("Nigeria");
 list.add("Niue");
 list.add("Norfolk Island");
 list.add("North Korea");
 list.add("North Sea");
 list.add("Northern Mariana Islands");
 list.add("Norway");
 list.add("");
 list.add("Oman");
 list.add("");
 list.add("Pacific Ocean");
 list.add("Pakistan");
 list.add("Palau");
 list.add("Palmyra Atoll");
 list.add("Panama");
 list.add("Papua New Guinea");
 list.add("Paracel Islands");
 list.add("Paraguay");
 list.add("Peru");
 list.add("Philippines");
 list.add("Pitcairn Islands");
 list.add("Poland");
 list.add("Portugal");
 list.add("Puerto Rico");
 list.add("");
 list.add("Qatar");
 list.add("");
 list.add("Republic of the Congo");
 list.add("Reunion");
 list.add("Romania");
 list.add("Ross Sea");
 list.add("Russia");
 list.add("Rwanda");
 list.add("");
 list.add("Saint Helena");
 list.add("Saint Kitts and Nevis");
 list.add("Saint Lucia");
 list.add("Saint Pierre and Miquelon");
 list.add("Saint Vincent and the Grenadines");
 list.add("Samoa");
 list.add("San Marino");
 list.add("Sao Tome and Principe");
 list.add("Saudi Arabia");
 list.add("Senegal");
 list.add("Serbia");
 list.add("Seychelles");
 list.add("Sierra Leone");
 list.add("Singapore");
 list.add("Slovakia");
 list.add("Slovenia");
 list.add("Solomon Islands");
 list.add("Somalia");
 list.add("South Africa");
 list.add("South Georgia and the South Sandwich Islands");
 list.add("South Korea");
 list.add("Southern Ocean");
 list.add("Spain");
 list.add("Spratly Islands");
 list.add("Sri Lanka");
 list.add("Sudan");
 list.add("Suriname");
 list.add("Svalbard");
 list.add("Swaziland");
 list.add("Sweden");
 list.add("Switzerland");
 list.add("Syria");
 list.add("");
 list.add("Taiwan");
 list.add("Tajikistan");
 list.add("Tanzania");
 list.add("Tasman Sea");
 list.add("Thailand");
 list.add("Togo");
 list.add("Tokelau");
 list.add("Tonga");
 list.add("Trinidad and Tobago");
 list.add("Tromelin Island");
 list.add("Tunisia");
 list.add("Turkey");
 list.add("Turkmenistan");
 list.add("Turks and Caicos Islands");
 list.add("Tuvalu");
 list.add("");
 list.add("Uganda");
 list.add("Ukraine");
 list.add("United Arab Emirates");
 list.add("United Kingdom");
 list.add("Uruguay");
 list.add("USA");
 list.add("Uzbekistan");
 list.add("");
 list.add("Vanuatu");
 list.add("Venezuela");
 list.add("Viet Nam");
 list.add("Virgin Islands");
 list.add("");
 list.add("Wake Island");
 list.add("Wallis and Futuna");
 list.add("West Bank");
 list.add("Western Sahara");
 list.add("");
 list.add("Yemen");
 list.add("");
 list.add("Zambia");
 list.add("Zimbabwe");

 return list;
 }

}

Let’s now create the user registration form using the Spring form tags and name it form.jsp. To use the form tags you need to first import the Spring’s form tag library.

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!–<span class="hiddenSpellError" pre=""–>DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
<html>
<head>
<%@ taglib uri="http://www.springframework.org/tags/form&quot; prefix="form"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<span class="hiddenSuggestion" pre="">submit</span> this form

<style type="text/css">
.error {
color: red;
font: italic;
font-stretch: normal;
}
</style>

</head>
<body>
<h1>Hello user, submit your form</h1>
<form:form method="POST" commandName="user">
<table>
<tr>
<td>User Name:</td>
input path="name">
<td><form:errors path="name" cssClass="error"></form:errors></td>
</tr>

<tr>
Passworld:
<td><form:password path="password"></form:password></td>
<td><form:errors path="password" cssClass="error"></form:errors></td>
</tr>

<tr>
<td>Email:</td>
input path="email">
<td><form:errors path="email" cssClass="error"></form:errors></td>
</tr>

<tr>
<td>Country:</td>
<td><form:select path="country" >
<form:options items="${list}" />
</form:select></td>
</tr>

<tr>
<td>Phone:</td>
<td><form:input path="phone"></form:input></td>
<td><form:errors path="phone" cssClass="error"></form:errors></td>
</tr>

<tr>
<td>
<input type="<span class=" />submit" value="Submit Form">
</td>
</tr>

</table>
</form:form>

</body>
</html>

See it carefully, here we path is mean the attributes that we used in the User class and here we used HTTP POST method.
now see carefully –

<tr>
<td>Country:</td>
<td><form:select path=”country” onchange=”submitForm()”>
<form:options items=”${list}” />
</form:select></td>
</tr>

form:options items =${list}
what does it mean?
let us see the getCountryList() method again in the service class implementation.
it returns a list of all country.  and now go to the referenceData() method in the FormController class.
here we call the method getCountryList() to get the list.
in the referenceData() method, we created a session object and push the the list in the session object so that we
can get in the form that is in our view.

now we need to create a validator class. validation means that in the form for example in email, we have to push the correct
format of email, other wise it wont let you submit the form.

here is the validator class

package com.rokon.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.rokon.db.User;

public class FormValdiator implements Validator{

 @Override
 public boolean supports(Class clazz) {
 return User.class.isAssignableFrom(clazz);
 }

 @Override
 public void validate(Object target, Errors error) {
 ValidationUtils.rejectIfEmptyOrWhitespace(error, "name", "name.required");
 ValidationUtils.rejectIfEmptyOrWhitespace(error, "email", "email.required");
 ValidationUtils.rejectIfEmptyOrWhitespace(error, "password", "password.required");
 ValidationUtils.rejectIfEmptyOrWhitespace(error, "phone", "phone.required");


 User user = (User) target;
 Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
 Matcher m = p.matcher(user.getEmail());

 //check  whether any match is found
 boolean matchFound = m.matches();
 if (!matchFound)
 {
 error.rejectValue("email", "email","Email is not valid");
 }
 }
}

here we have the error messages in a seperate properties file so we add the error code, it is called internationalization (i18n).
so we need to create it. Create a messages.properties file, and place it in the source folder.
the messages.properties contains

name.required = User Name is required
email.required = Email is required
email.invalid = Email is not valid
password.required = Password is required
country.required = Country is required
phone.required = Phone is required

now lets see the web.xml

xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 <display-name>submit form v2</display-name>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
 <servlet-name>form</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>form</servlet-name>
 <url-pattern>*.rok</url-pattern>
 </servlet-mapping>
</web-app>

and the bean configuration file that is form-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="viewResolver"

 p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
 <bean id="messageSource"

 p:basename="messages" />

 <bean id="formValidator">
 <bean id="formService"></bean>

 <bean name="/form.rok"
 p:validator-ref="formValidator" p:userService-ref="formService"
 p:formView="form" p:successView="formSuccess"></bean>

</beans>

we will be needing the success page,  name it userSuccess.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!–<span class="hiddenSpellError" pre=""–>DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Success  page</title>
</head>
<body>
<h1>Thank you for submitting information</h1>
<h2>You submitted  : </h2>
<table>
<tr>
<td>Name: </td><td>${user.name}</td>
</tr>
<tr>
<td>Email: </td><td>${user.email}</td>
</tr>
<tr>
<td>Country: </td><td>${user.country}</td>
</tr>
<tr>
<td>Phone: </td><td>${user.phone}</td>
</tr>
</table>

</body>
</html>

now open the index.jsp page
wirte there simply

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
<%response.sendRedirect(“form.rok”) ;%>

By the way, we will be needing some libraries,

antlr-runtime-3.0.jar
commons-logging-1.0.4.jar
org.springframework.asm-3.0.0.M3.jar
org.springframework.beans-3.0.0.M3.jar
org.springframework.context.support-3.0.0.M3.jar
org.springframework.context-3.0.0.M3.jar
org.springframework.core-3.0.0.M3.jar
org.springframework.expression-3.0.0.M3.jar
org.springframework.web.servlet-3.0.0.M3.jar
org.springframework.web-3.0.0.M3.jar

get them from spring framework and place them into the lib folder in WEB-INF

let us see the structure of the project

output:

Cheers guys!!

And the war (including source) : http://www.box.net/shared/yca6nq23gc

observer pattern


I think we are matured enough in object oriented programming and we know how to define an object. An object has some behaviors and attributes and they can be changed anytime while performing their job. Let us assume that, there is an object and some other objects are dependent with it. So if this object is changed, it is a must to let know the others the state of the object. So here we are gonna discuss about dependency that an object has a dependency with others. Let us assume more simply.

One object register an event, and some others object want to know when an event occurs. This is the main concept and motivation of the observer pattern. This is kind of watching objects with others objects.

So let’s get a problem which can be solved with this pattern.Problem:

Problem:

Suppose there are some companies like IBM, Microsoft, Apple etc. These companies have their share price. There are some investors like Suzan, Sharif, Iqbal. They are interested about the share prices of the companies. The investors can register to the companies if they are interested to the share price of a specific company. The investors can unregister if they don’t feel interested any more to a specific company.

When the share price of a company changes, the registered investors are automatically informed about the changed price.

Write a code that shows the above features.

Let us analysis the problem. When anything is gonna change in the Company, we need to notify to the registered investor that something is changed. This is the main motivation. We can solve it with Observer pattern.

Let us think the object that is going to be observed is named subject and the objects are going to observe,  are called observers.

here main motivation is  the subject doesn’t need to know anything special about its observers. Instead, the subject simply allows observers to registered . When the subject generates an event, it simply passes it to each of its observers. Here if company changes its share prize, it will pass the information to its registered users.

So let us firs define two interface.

public interface CompanyObservable{
public void register(InvestorObserver invesotor);
public void unRegister(InvestorObserver investor);
public void changePrize(double prize);
public void notifyInvestors();
}

that means a company can register an new investor, unregister a investor, change it prize and notify its changes to the investors.


public interface InvestorObserver{
public void update(CompanyObservable company, Object o);
}

and an investor can be updated only.

Now lets get the implementation of the CompanyObservable.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Company implements CompanyObservable {

 private String name;
 private double sharePrize;
 private List listOfInvestors;

 public Company(String name, double sharedPrize) {
 this.name = name;
 this.sharePrize = sharedPrize;
 listOfInvestors = new ArrayList();
 }

 public Company() {
 listOfInvestors = new ArrayList();
 }

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public double getSharePrize() {
 return sharePrize;
 }

 public void setSharePrize(double sharePrize) {
 this.sharePrize = sharePrize;
 }

 @Override
 public void changePrize(double prize) {
 this.setSharePrize(prize);
 notifyInvestors();
 }

 @Override
 public void notifyInvestors() {
 Iterator<Investors> it = listOfInvestors.iterator();
 while (it.hasNext()) {
 Investors investors = (Investors) it.next();
 investors.update(this, this.getSharePrize());
 }
 }

 @Override
 public void register(InvestorObserver investor) {
 if (!listOfInvestors.contains(investor)) {
 listOfInvestors.add((Investors) investor);
 System.out.println(((Investors) investor).getName() +" is registered '"+this.getName()+"' successfully.");
 }else {
 System.out.println(((Investors)investor).getName()+" is already registered with "+this.getName()+".");
 }
 }

 @Override
 public void unRegister(InvestorObserver investor) {
 if (listOfInvestors.contains(investor)) {
 listOfInvestors.remove(investor);
 System.out.println(((Investors) investor).getName() +" is removed successfully");
 }else {
 System.out.println(((Investors) investor).getName()+" is already removed");
 }
 }
}

and implementation of the InvestorObserver

public class Investors implements InvestorObserver{
 private String name;

 public Investors(String name) {
 this.setName(name);
 }

 @Override
 public void update(CompanyObservable company, Object o) {
 System.out.println(((Company)company).getName()+" has now "+ o + " prize------>"+this.getName()+".");
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getName() {
 return name;
 }
}

now let us check that things are going fine.

public class MainClass {
 public static void main(String[] args) {
 // creating company
 Company ibm = new Company("IBM", 3000);
 Company microsoft = new Company("Microsoft", 3000);
 Company apple = new Company("Apple", 3000);

 // creating investors
 Investors suzan = new Investors("Suzan");
 Investors sharif = new Investors("Sharif");
 Investors iqbal = new Investors("Iqbal");

 //suzan registered with IBM and microsoft
 ibm.register(suzan);
 microsoft.register(suzan);

 // sharif registered with IBM, microsoft, apple
 ibm.register(sharif);
 microsoft.register(sharif);
 apple.register(sharif);

 //iqbal only registered with apple
 apple.register(iqbal);

 // now let us make some changes in company shareprize
 System.out.println();
 ibm.changePrize(400);
 microsoft.changePrize(900);
 apple.changePrize(1000);

 // now lets think iqbal unregistered from apple and register in ibm
 System.out.println();
 apple.unRegister(iqbal);
 ibm.register(iqbal);

 // now make some changes both the company apple and ibm
 // here iqbal will now get notification from ibm but not from apple
 System.out.println();
 apple.changePrize(400);
 ibm.changePrize(800);
 }
}

The output should be like

Suzan is registered ‘IBM’ successfully.
Suzan is registered ‘Microsoft’ successfully.
Sharif is registered ‘IBM’ successfully.
Sharif is registered ‘Microsoft’ successfully.
Sharif is registered ‘Apple’ successfully.
Iqbal is registered ‘Apple’ successfully.

IBM has now 400.0 prize——>Suzan.
IBM has now 400.0 prize——>Sharif.
Microsoft has now 900.0 prize——>Suzan.
Microsoft has now 900.0 prize——>Sharif.
Apple has now 1000.0 prize——>Sharif.
Apple has now 1000.0 prize——>Iqbal.

Iqbal is removed successfully
Iqbal is registered ‘IBM’ successfully.

Apple has now 400.0 prize——>Sharif.
IBM has now 800.0 prize——>Suzan.
IBM has now 800.0 prize——>Sharif.
IBM has now 800.0 prize——>Iqbal.

Source Code: CLICK THIS LINK

Beginners’ guide to PHP, part -2


Part one is available here.

We have already discussed  about different data types of php in part 1. This text will continue data types too and here I’m going to start with arrays.

Array:

Array is a very special data type. It is going to be strongly used in your Php programs. So let me sure that you are very much clear about it. First let me clear about what is an array actually. An array is a series of variable in a contiguous memory location and it is not necessarily important to be same type in Php. More generally you can imagine a class room full of students and every student has a unique identity that is their roll number, and we can find them calling roll number. So here series of variable are the students and the class room is an array.

So now let’s go having created a simple array to get an idea how this works.

We need to define an array using array(). Let’s see.

$my_array = array(1,3,4,5,6);

Here we define an array named my_array which has five elements and it is itself a variable.

So now question is how to retrieve the value from the array. It’s simple. We call them using index position as like calling roll number in class room. So let’s get an example.



You need to call an array element using a square bracket [] with the variable name and index number will be inside the square bracket.

$my_array = array(1,5,7,9,30,23);
echo $my_array[2];

If you run the program, it will print 7. Wait a minute. Let us go back in our array and look 7 is in the third position. One thing we need to keep in mind always that array index starts with zero. First index is zero, and second index is 1 and it will continue this way. So if we call first element of the array, we will write like

php echo $my_array[0];

Now go back to your browser and refresh it, it will print 1 as it is expected.

Now let me penetrate into more advance.

Let us define a new array. As I said before, array elements should not necessarily same time. An array can hold integer, string, even another array. Let’s see another example.

Here we define a my_new_array that contains an integer, two strings and anther array into it. Now let’s retrieve third value of the array.

It is simple. Just write

echo $my_new_array[2];

As I said before. Now if you write

echo $my_new_array[4];

It will print simply ‘Array’ that’s means it’s indicating it’s an array and it doesn’t give us the values inside it. So if we want to retrieve the value inside it, what we need to do is, we need to put another square bracket like

echo $my_new_array[4][2];

Now it will print 7.

Now we know how retrieve values from array. Now in the same we can put value inside the array. Let say, we instead of rokon, we want to have amit. So here we will simply reassign the value into the index of rokon. Write simply like-

$my_new_array[3] = "amit";

Now if you want to echo back the position write simply like –

echo $my_new_array[3];

What did you found? It echoed amit now.

Now let me say that, there are two types of array available in php. They are Indexed array and Associative array. We already talked about indexed array. Now let me introduce associative array.

Some time we may not be interested with order that is index but can be more interested what kind data we are dealing with. Let us remind our class room. We may not always interested to call student with roll no but something we may be more interested to call them by name. So here name is their label sometime it is called key. So if we call the key, the value will be retrieved. So let us define an array that holds the label or key of the value it holds instead of their position.

Here is an example of associative array.

$my_array = array("rayhan"=> 1, "mohaimin"=>2, "alim"=> 3, "anik"=>4);

Here rayhan is the kay and 1 is the value.

So we have an array, the first value of array is 1. So if we want to have the first value, we need not call it with index. We can call it simply by its key name that is its label.

echo $my_array["rayhan"];

It will print 1.

Again if we want to set a new value in the first elements of the array, we will do simply –

$my_array["rayhan"]= 5;

Oh this enough for today. Next will be available soon. Stay tuned.