Iterator Design Pattern in Java

Iterator Design Pattern in Java

Iterator pattern is a behavioral object design pattern. Iterator pattern allows for the traversal through the elements in a grouping of objects via a standardized interface defines the actions or methods that can be performed. These actions or methods able to traverse the objects, remove or add Object according to project needs. So keeping in mind about the pattern just we need to apply on top of our business logic's. 

If we look at Java widely used Iterator interface which used to iterate through elements in various Java collections. We can write our own iterator by implementing java.util.Iterator. This interface features the hasNext(), next(), and remove() methods. Lets take simple example of book stall which contains list of books with these few following information's like,

Book Name
Author
Price

Based on above example lets create Book class which holds the book details


public class Book {

 private String name;
 private String author;
 private int price;
 
 public Book(String name, String author, int price) {
  this.name = name;
  this.author = author;
  this.price = price;
 }
 public String getName() {
  return name;
 }
 public String getAuthor() {
  return author;
 }
 public int getPrice() {
  return price;
 }

 @Override
 public String toString() {
  return "----------\n\nBook Name : "+name+" \nAuthor    : "+author+"\nPrice     : Rs."+price; 
 } 
}




Next lets create Store class which contains list of various books and list actions like add books, removing, listing etc., can be performed. 


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

public class Store {
 
 List<Book> bookList = new ArrayList<Book>();
 
 public void addBook(Book item) {
  bookList.add(item);
 }

 public Iterator<Book> iterator() {
  return new BooksIterator();
 }

 class BooksIterator implements Iterator<Book> {
  int bookId = 0;

  @Override
  public boolean hasNext() {
   if (bookId >= bookList.size()) {
    return false;
   } else {
    return true;
   }
  }

  @Override
  public Book next() {
   return bookList.get(bookId++);
  }

  @Override
  public void remove() {
   bookList.remove(--bookId);
  }
 } 
}


Next lets implement the main class which feeds list of books into Store and iterates. For sample lets add 4 books and will test.


import java.util.Iterator;

public class BookStore {
 
 public static void main(String[] args) {
  Book b1 = new Book("Lightning", "Dean Koontz", 500);
  Book b2 = new Book("Roma: The Novel of Ancient Rome", "Steven Saylor", 452);
  Book b3 = new Book("Humility", "Andrew Murray", 334);
  Book b4 = new Book("Meditations", "Marcus Aurelius, Martin Hammond", 635);
  
  Store store = new Store();
  store.addBook(b1);
  store.addBook(b2);
  store.addBook(b3);
  store.addBook(b4);
  
  System.out.println("Display list of books in store");
  Iterator<Book> iterator = store.iterator();
  while (iterator.hasNext()) {
   Book item = iterator.next();
   System.out.println(item.toString());
   
   //Removing "Humility" from the book store list
   if(item.getName().equals("Humility")){
    iterator.remove();
   }
  }
  
  System.out.println("\n\n\nDisplay list of books in store after removing 'Humility' book");
  iterator = store.iterator();
  while (iterator.hasNext()) {
   Book item = iterator.next();
   System.out.println(item.toString());
  }
 }
}


OUTPUT:


Display list of books in store
----------

Book Name : Lightning 
Author    : Dean Koontz
Price     : Rs.500
----------

Book Name : Roma: The Novel of Ancient Rome 
Author    : Steven Saylor
Price     : Rs.452
----------

Book Name : Humility 
Author    : Andrew Murray
Price     : Rs.334
----------

Book Name : Meditations 
Author    : Marcus Aurelius, Martin Hammond
Price     : Rs.635



Display list of books in store after removing 'Humility' book
----------

Book Name : Lightning 
Author    : Dean Koontz
Price     : Rs.500
----------

Book Name : Roma: The Novel of Ancient Rome 
Author    : Steven Saylor
Price     : Rs.452
----------

Book Name : Meditations 
Author    : Marcus Aurelius, Martin Hammond
Price     : Rs.635

Java Scanner class

Scanner class in Java

Scanner class does same work as like String Tokenizer and Split() used to parse a string, pulling out data of different types. But its limit in usage and can't get array of strings delimited by a particular expression like in Split(). 

If we see about Scanner and BufferedReader classes used to read stream contents, Scanner class mainly used to parsing tokens from the contents of the stream. But BufferedReader just reads the stream and does not do any special parsing like Scanner. For parsing we can pass those BufferedReader objects to a scanner as the source of characters or string to parse. 

The other difference is BufferedReader is synchronized and Scanner is non-synchronized. Also from JDK 6 we have got 1 KB of character buffer for Scanner and 8 KB of character buffer for BufferedReader . 

Use Scanner if need to parse the file or use BufferedReader just to read the file. 

Next we will see simple example of parsing CSV file using Scanner class.

training.csv


1,Java Basics,4 weeks,INR 3000,
2,Oracle,5 weeks,INR 4500,
3,ASP.NET,6 weeks,INR 5000,
4,EJP,3 weeks,INR 4000,
5,Hibernate,4 weeks,INR 2000,
6,Spring,8 weeks,INR 6000,


TrainingBean.java


public class TrainingBean {

 private int id;
 private String course;
 private String duration;
 private String fees;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getCourse() {
  return course;
 }
 public void setCourse(String course) {
  this.course = course;
 }
 public String getDuration() {
  return duration;
 }
 public void setDuration(String duration) {
  this.duration = duration;
 }
 public String getFees() {
  return fees;
 }
 public void setFees(String fees) {
  this.fees = fees;
 }
 
 @Override
 public String toString() {
  return "ID:"+id+"\t Course:"+course+"\t Duration:"+duration+"\t Fees:"+fees;
 }
}


ScannerTest.java


public class ScannerTest {

 public static void main(String[] args) throws FileNotFoundException {

  ArrayList<TrainingBean> trainingList = parseTrainingDetails("D://training.csv");

  displayTrainingDetails(trainingList);
 }

 public static ArrayList<TrainingBean> parseTrainingDetails(String file) {
  ArrayList<TrainingBean> list = new ArrayList<TrainingBean>();
  try {
   Scanner scan = new Scanner(new File(file));
   scan.useDelimiter(",");
   int i = 1;
   TrainingBean bean = new TrainingBean();
   while (scan.hasNext()) {
    String value = scan.next().trim();
    if (value.length() == 0)
     break;
    if (i == 1) {
     bean.setId(Integer.parseInt(value));
    } else if (i == 2) {
     bean.setCourse(value);
    } else if (i == 3) {
     bean.setDuration(value);
    } else if (i == 4) {
     bean.setFees(value);
     i = 0;
     list.add(bean);
     bean = new TrainingBean();
    }
    i++;
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
  return list;
 }

 public static void displayTrainingDetails(ArrayList<TrainingBean> list) {
  for (TrainingBean trainingBean : list) {
   System.out.println(trainingBean.toString());
  }
 }
}



OUTPUT:


ID:1  Course:Java Basics Duration:4 weeks  Fees:INR 3000
ID:2  Course:Oracle  Duration:5 weeks  Fees:INR 4500
ID:3  Course:ASP.NET  Duration:6 weeks  Fees:INR 5000
ID:4  Course:EJP  Duration:3 weeks  Fees:INR 4000
ID:5  Course:Hibernate Duration:4 weeks  Fees:INR 2000
ID:6  Course:Spring  Duration:8 weeks  Fees:INR 6000




Avoid direct JSP access from client browser

 
Any files inside direct context folder can be accessible through client browser, but if same files if we place under WEB-INF folder then we can't access those files from client browser. So this way we can avoid direct call or access to specific JSP files from client browser. 
To access those JSP files we need configuration in web.xml (deployment descriptor) as similar to servlet. Lets see simple deployment descriptor for configuring JSP files along with sample JSP file.

JSP File (jspinside.jsp)


<html>
 <head>
  <title>Java Discover</title>
 </head>
 <body>
  <h1>Hello Java Discover :-)</h1>
 </body>
</html>




Deployment Descriptor (web.xml)


<web-app>
 <servlet>
   <servlet-name>JSPTest</servlet-name>
   <jsp-file>/WEB-INF/jspinside.jsp</jsp-file>   
 </servlet>
  
 <servlet-mapping>
   <servlet-name>JSPTest</servlet-name>
   <url-pattern>/jsptest.do</url-pattern>
 </servlet-mapping>
</web-app>




Folder Structure:


<context_name>
      -><WEB-INF>
             -><classes>
             -><lib>
             ->jspinside.jsp
             ->web.xml


Once complete deploy and test with below url

URL : http://localhost:8080/jsptest/jsptest.do


OUTPUT:



Insertion sort in Java

As like earlier tutorial Bubble sort, in this tutorial we will see about Insertion sort in Java with simple example. Unlike the other sorting algorithm insertion sort passes through the array only once.
Basically insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. Each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain. Below sample image will explain about how Insertion sort algorithm works.
Insertion sort example in Java
Now lets see simple insertion sort in java.


public class InsertionSort {

 public static void main(String[] args) {

  int values[] = { 5, 4, 8, 6, 9, 1, 7, 3, 2 };

  System.out.print("\nBefore sort : ");
  printArray(values);

  insertionSort(values);

  System.out.print("\nAfter sort : ");
  printArray(values);
 }

 private static void insertionSort(int[] array) {
  int i;
  for (int j = 1; j < array.length; j++) {
   int key = array[j];
   for (i = j - 1; (i >= 0) && (array[i] > key); i--) {
    array[i + 1] = array[i];
   }
   array[i + 1] = key;
  }
 }

 private static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
   System.out.print(array[i] + ", ");
  }
 }
}

OUTPUT:

Before sort : 5, 4, 8, 6, 9, 1, 7, 3, 2, 
After sort : 1, 2, 3, 4, 5, 6, 7, 8, 9, 




Bubble sort in Java

Bubble sort in java

Bubble sort is the simple sorting algorithm and same time has worst-case and average complexity. Bubble sort iterating down from first element to the last element in the array by comparing each pair of elements and switching elements if they meets our sorting condition. So lets see simple example in Java by using Bubble sort algorithm.



public class BubbleSort {

 public static void main(String[] args) {

  int values[] = { 5, 4, 8, 6, 9, 1, 7, 3, 2 };

  System.out.print("\nBefore sort : ");
  printArray(values);

  bubbleSort(values);

  System.out.print("\nAfter sort : ");
  printArray(values);
 }

 private static void bubbleSort(int[] array) {
  for (int i = 0; i < array.length - 1; i++) {
   for (int j = i + 1; j < array.length; j++) {
    if (array[i] > array[j]) {
     int tmp = array[i];
     array[i] = array[j];
     array[j] = tmp;
    }
   }
  }
 }

 private static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
   System.out.print(array[i] + ", ");
  }
 }
}


OUTPUT:


Before sort : 5, 4, 8, 6, 9, 1, 7, 3, 2, 
After sort : 1, 2, 3, 4, 5, 6, 7, 8, 9, 



Increase MySql database time wait

Viewing from dev.mysql.com site

In one of our earlier tutorials we have see about basic MySql commands and MySql connection sample code. In this tutorial we will see about increasing MySql default time wait of 8 hours.
For example in a rare condition we have an application which running socket connection between 2 server and communicates each other's data. But communication times are inconsistent and it can happen once in 1 hour or 2 hour once or even after 8 hours once. Lets assume in that case we having a open MySql database connection and whenever request comes it needs to preform its appropriate database activity. 
In that case if time wait goes more than 8 hours then MySql will disconnect all those database connections. So we need of more time wait from 8 hours to 10 or 15 hours or 1 days etc.,
So lets see how to change default MySql time wait option.

Before changing default time wait in MySql lets query for the current time wait which set in server.

mysql> show variables LIKE '%timeout%';
+----------------------------------+-------+
| Variable_name                    | Value |
+----------------------------------+-------+
| connect_timeout                 | 10    |
| delayed_insert_timeout       | 300   |
| innodb_lock_wait_timeout    | 50    |
| innodb_rollback_on_timeout | OFF   |
| interactive_timeout             | 28800 |
| net_read_timeout               | 30    |
| net_write_timeout              | 60    |
| slave_net_timeout              | 3600  |
| table_lock_wait_timeout     | 50    |
| wait_timeout                     | 28800 |
+----------------------------------+-------+

By above query we can get current MySql "wait_timeout" and "interactive_timeout" values as 28800(seconds equal to 8 hrs). Next we will see about changing those values from 8 hrs to 24 hrs. 

Under /etc edit my.cnf file with below details

# vi /etc/my.cnf 

[mysqld]
wait_timeout=86400
interactive_timeout=86400

NOTE: Suppose if my.cnf file not exist please create it. 

Once changed please restart MySql and check for the parameters has been updated or not.


mysql> show variables LIKE '%timeout%';

+------------------------------------+--------+
| Variable_name                      | Value  |
+------------------------------------+--------+
| connect_timeout                    | 10     | 
| delayed_insert_timeout          | 300    | 
| innodb_lock_wait_timeout       | 50     | 
| innodb_rollback_on_timeout    | OFF    | 
| interactive_timeout                | 86400  | 
| net_read_timeout                  | 30     | 
| net_write_timeout                 | 60     | 
| slave_net_timeout                 | 3600   | 
| table_lock_wait_timeout         | 50     | 
| wait_timeout                        | 86400  | 
+------------------------------------+--------+

From above table we can see timeout value got changed from 8 hrs to 24 hrs. 





Rich Dynamic Table using JQuery DataTable

 
When we see about recent Web Developments and role of HTML 5, AJAX, jQuery UI and other plugins into the world of Web made more and more changes which brings rich UI and sophisticated enhancements for the end users. At the same time we need to know that all end user machines should be with updates and latest software versions. 

We all may know that few months back Google has enhanced all its web products and asked all users to use browsers with latest version. And also by using AJAX we can get just piece of update information from server to client instead of requesting for complete web page. So it makes response as faster and less load to the web server. 

In recent web development world we can see lot and lot of plugins and tools to develop web application. As a plugin which I have came across is DataTable plugin which gives more functionality and rich UI for the developers with just few line of code. Lets assume few years back if we need to display a table in web page with 5 to 6 columns and with 1000 rows. So developer need to keep in mind like Pagination, each column sorting, search, records editing and finally giving rich UI and they need to write code for each functionality and need to integrate with those tables. 

But DataTable is one of the plugin which makes complete work into few integration steps. Now lets see simple example code as how to use DataTable. 

In below example if we see table we have created with id "javadiscover_table" and same id has been associated with dataTable in jQuery ready function. Thats it, remaining things are related to our custom requirement and we can add multiple properties like search feature enable/ disable, page counts, custom column sorting etc., Also here we have used jQuery UI for our rich table look.

You can download complete code and supporting js and css files in below link.

DataTable Example Code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">

<html>

 <head>
  <link rel="stylesheet" href="dtable.css"/>
  <link rel="stylesheet" href="jquery-ui-1.8.4.custom.css"/>
  <script type="text/javascript" charset="utf-8" src="jquery.js"></script>
  <script type="text/javascript" charset="utf-8" src="jquery.dataTables.js"></script>
  
  <script type="text/javascript" charset="utf-8">   

   jQuery( document ).ready(function( jQuery ) {
     $('#javadiscover_table').dataTable( {
      "sDom": '<"top"iflp<"clear">>',
      "aaSorting": [[ 4, "desc" ]], // Column sorting
      "bJQueryUI": true

     } );    
   });
   
  </script>
  
 </head>

 <body>
  <table cellpadding='0' cellspacing='0' border='0' class='display' id='javadiscover_table'>
   <thead>
    <tr>
     <th>Source</th>
     <th>Destination</th>
     <th>Type</th>
     <th>IP Address</th>
     <th>Start Time</th>
     <th>End Time</th>
    </tr>
   </thead>
   <tfoot>
    <tr>
     <th>Source</th>
     <th>Destination</th>
     <th>Type</th>
     <th>IP Address</th>
     <th>Start Time</th>
     <th>End Time</th>
    </tr>
   </tfoot>
   <tbody>
    <tr>
     <td>Raj</td>
     <td>Sundar</td>
     <td>Audio Call</td>
     <td>10.70.54.81</td>
     <td>2013-10-29 09:10:57</td>
     <td>2013-10-29 09:11:14</td>
    </tr>
    <tr>
     <td>David</td>
     <td>Anand</td>
     <td>Audio Call</td>
     <td>10.70.54.83</td>
     <td>2013-10-29 09:46:34</td>
     <td>2013-10-29 09:46:59</td>
    </tr>
    <tr>
     <td>Rex</td>
     <td>Bill</td>
     <td>Video Call</td>
     <td>10.70.54.40</td>
     <td>2013-10-29 10:09:18</td>
     <td>2013-10-29 10:09:30</td>
    </tr>
    <tr>
    <td>Alex</td>
     <td>Gates</td>
     <td>Video Call</td>
     <td>10.70.53.123</td>
     <td>2013-10-29 10:38:14</td>
     <td>2013-10-29 10:38:17</td>
    </tr>
    <tr>
     <td>Steve</td>
     <td>Ronald</td>
     <td>Audio Call</td>
     <td>10.70.53.221</td>
     <td>2013-10-29 10:38:30</td>
     <td>2013-10-29 10:39:13</td>
    </tr>
    <tr>
     <td>Jobs</td>
     <td>Zen</td>
     <td>Video Call</td>
     <td>10.70.54.190</td>
     <td>2013-10-29 10:50:52</td>
     <td>2013-10-29 10:51:22</td>
    </tr>
    <tr>
     <td>Tim</td>
     <td>Tony</td>
     <td>Audio Call</td>
     <td>10.70.54.194</td>
     <td>2013-10-29 10:52:04</td>
     <td>2013-10-29 10:53:12</td>
    </tr>
   </tbody>
  </table>
 </body>
</html>




OUTPUT: