Tuesday, October 2, 2012

HTML email using Apache Commons Email API

The Commons Email is built on top of the Java Mail API, which basically simplifies the whole process of sending an email. With the help of HTMLEmail class in commons you can send HTML formatted email. It has all of the capabilities as MultiPartEmail allowing attachments to be easily added and also supports embedded images. In this tutorial we have created a contact US form in JSP so that we can check the capabilities of this very userful API. To send an email we need a SMTP server, from Email address, to Email address and a Subject. If your SMTP server needs authetication then you have to provide the login credentials.

For this example we are using gmail as our SMTP server. To create the HTML content that needs to go in the message body we have taken help of the WYSIWYG editor based on jQuery named jWysiwyg. You can read more about this editor at http://akzhan.github.com/jwysiwyg/. Following jars in your project classpath for this example to work



HTML email using Apache Commons Email API
Source for the JSP - htmlEmail.jsp


























<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="robots" content="noindex,nofollow" />
<title>HTML email using Apache Commons API</title>
<link rel="stylesheet" href="/resources/themes/master.css" type="text/css" />
<link rel="stylesheet" href="/resources/themes/jquery.wysiwyg.css" type="text/css" />
<link
 rel="stylesheet" type="text/css" />
<script
 type="text/javascript"></script>
<script
 type="text/javascript"></script>
<script
 type="text/javascript"></script>
<script src="/resources/scripts/mysamplecode.js" type="text/javascript"></script>
<script type="text/javascript" src="/resources/scripts/jquery.wysiwyg.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  
 $("#samplecode").validate({
   rules: {
    mailServer: "required",
    fromName: "required",
    fromEmail: "required",
    toName: "required",
    toEmail: "required",
    subject: "required",
    password: {
     required: function(element) {
         return $.trim($("#userId").val()) != '';
       }
    }
  }
 });
  
 $(function(){
      $('#messageBody').wysiwyg();
      $('#messageBody').wysiwyg('clear');
   });
  
  
});
</script>
</head>
<body>
 <div id="allContent">
 <%@include file="/header.jsp"%>
  <div id="myContent">
   <div>
    <%
     boolean success = false;
     if(request.getAttribute("success") != null){
      success = (Boolean) request.getAttribute("success");
     }
     if (success){
    %>
      <font color="green">
       <b><br/>Thank you! You message has been sent.</b>
       <br/>&nbsp;
      </font>
    <% 
     }
     else {
      if(request.getAttribute("success") != null){
    %>
      
      <font color="red">
       <b><br/>Error! You message was not sent.</b>
       <br/>&nbsp;
      </font>
    <% 
      }
     }
    %>
   </div>
   <form id="samplecode" name="samplecode" method="POST" action="<%= request.getContextPath() %>/SendHTMLEmail">
     <fieldset>
      <legend><b>&nbsp;&nbsp;&nbsp;HTML Email using Apache Commons API&nbsp;&nbsp;&nbsp;</b></legend>
      <table>
      <tr>
       <td>
       <label for="mailServer"> Mail Server Host Name  </label>
       </td>
       <td>
       <input id="mailServer" type="text" name="mailServer" size="50" value="smtp.gmail.com"/>
       </td>
      </tr>
      <tr>
       <td>
       <label for="userId"> Mail Server User Id  </label>
       </td>
       <td>
       <input id="userId" type="text" name="userId" size="30" value=""/>
       <i>(In case your mail server needs Authentication)</i>
       </td>
      </tr>
      <tr>
       <td>
       <label for="password"> Mail Server Password  </label>
       </td>
       <td>
       <input id="password" type="password" name="password" size="30" value=""/>
       <i>(In case your mail server needs Authentication)</i>
       </td>
      </tr>
       
      <tr>
       <td colspan="2">
       &nbsp;
       </td>
      </tr>
      <tr>
       <td>
       <label for="fromName"> Sender's Name  </label>
       </td>
       <td>
       <input id="fromName" type="text" name="fromName" size="30" value=""/>
       </td>
      </tr>
      <tr>
       <td>
       <label for="fromEmail"> Sender's Email Address  </label>
       </td>
       <td>
       <input id="fromEmail" type="text" name="fromEmail" size="50" value=""/>
       </td>
      </tr>
      <tr>
       <td>
       <label for="toName"> Recipient's Name  </label>
       </td>
       <td>
       <input id="toName" type="text" name="toName" size="30" value=""/>
       </td>
      </tr>
      <tr>
       <td>
       <label for="toEmail"> Recipient's Email Address  </label>
       </td>
       <td>
       <input id="toEmail" type="text" name="toEmail" size="50" value=""/>
       </td>
      </tr>
      <tr>
       <td colspan="2">
       &nbsp;
       </td>
      </tr>
      <tr>
       <td>
       <label for="subject"> Subject  </label>
       </td>
       <td>
       <input id="subject" type="text" name="subject" size="50" value=""/>
       </td>
      </tr>
      <tr>
       <td class="formText" >
        <label for="messageBody"> Message </label>
       </td>
       <td>
        <textarea id="messageBody" name="messageBody" rows="10" cols="100" maxlength="1000"></textarea>
       </td>
      </tr>
      <tr>
       <td class="formText" >
        &nbsp;
       </td>
       <td>
        <input id="sendEmail" type="submit" value="Send my Email" />
       </td>
      </tr>
      </table>
     </fieldset>
   </form>
  </div>
 </div>
 <%@include file="/footer.jsp"%>
 <div></div>
</body>
</html>

Source for the Java Servlet - SendHTMLEmail.java


package com.as400samplecode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
public class SendHTMLEmail extends HttpServlet {
 private static final long serialVersionUID = 1L;
        
    public SendHTMLEmail() {
        super();
    }
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doPost(request, response);
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
  String mailServer = request.getParameter("mailServer").trim();
  String userId = request.getParameter("userId").trim();
  String password = request.getParameter("password").trim();
   
  String fromName = request.getParameter("fromName").trim();
  String fromEmail = request.getParameter("fromEmail").trim();
  String toName = request.getParameter("toName").trim();
  String toEmail = request.getParameter("toEmail").trim();
   
  String subject = request.getParameter("subject").trim();
  String messageBody = request.getParameter("messageBody").trim();
   
  StringBuilder sb = new StringBuilder();
  sb.append("<html>");
  sb.append("<body>");
  sb.append("<table>");
   
  sb.append(messageBody);
     
  sb.append("</table>");
  sb.append("</body>");
  sb.append("</html>");
   
  try {
    
   // Sending HTML formatted email
   HtmlEmail htmlEmail = new HtmlEmail();
    
   // set the address of the outgoing SMTP server that will be used to send the email
   htmlEmail.setHostName(mailServer);
   // set to true if you want to debug
   htmlEmail.setDebug(true);
   // if the SMTP server needs authentication
   if(!userId.trim().equalsIgnoreCase("") && !password.trim().equalsIgnoreCase("")){
    htmlEmail.setAuthenticator(new DefaultAuthenticator(userId, password));
    htmlEmail.setTLS(true);
   }
    
   // set the recipient
   htmlEmail.addTo(toEmail, toName);
    
   // set the sender
   htmlEmail.setFrom(fromEmail, fromName);
    
   // set the subject
   htmlEmail.setSubject(subject);
    
   // set the email body
   htmlEmail.setHtmlMsg(sb.toString());
    
   // finally send the email
   htmlEmail.send();
   request.setAttribute("success",true);
    
  } catch (EmailException e) {
   request.setAttribute("success",false);
   e.printStackTrace();
  }
   
  getServletContext().getRequestDispatcher("/pages/htmlEmail.jsp").forward(request, response);
  
 }
}
References

Saturday, August 18, 2012

Sencha PPT


Jquery Pagination example

Config.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");

?>
Pagination.php

<?php
include('config.php');
$per_page = 9;

//getting number of rows and calculating no of pages
$sql = "select * from messages";
$rsd = mysql_query($sql);
$count = mysql_num_rows($rsd);
$pages = ceil($count/$per_page)
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>9lessons : Mysql and jQuery Pagination</title>
   
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
    <script type="text/javascript">
   
    $(document).ready(function(){
       
    //Display Loading Image
    function Display_Load()
    {
        $("#loading").fadeIn(900,0);
        $("#loading").html("<img src='bigLoader.gif' />");
    }
    //Hide Loading Image
    function Hide_Load()
    {
        $("#loading").fadeOut('slow');
    };
   

   //Default Starting Page Results
  
    $("#pagination li:first").css({'color' : '#FF0084'}).css({'border' : 'none'});
   
    Display_Load();
   
    $("#content").load("pagination_data.php?page=1", Hide_Load());



    //Pagination Click
    $("#pagination li").click(function(){
           
        Display_Load();
       
        //CSS Styles
        $("#pagination li")
        .css({'border' : 'solid #dddddd 1px'})
        .css({'color' : '#0063DC'});
       
        $(this)
        .css({'color' : '#FF0084'})
        .css({'border' : 'none'});

        //Loading Data
        var pageNum = this.id;
       
        $("#content").load("pagination_data.php?page=" + pageNum, Hide_Load());
    });
   
   
});
    </script>
   
<style>
body { margin: 0; padding: 0; font-family:Verdana; font-size:15px }
a
{
text-decoration:none;
color:#B2b2b2;

}

a:hover
{

color:#DF3D82;
text-decoration:underline;

}
#loading {
width: 100%;
position: absolute;
}

#pagination
{
text-align:center;
margin-left:120px;

}
li{   
list-style: none;
float: left;
margin-right: 16px;
padding:5px;
border:solid 1px #dddddd;
color:#0063DC;
}
li:hover
{
color:#FF0084;
cursor: pointer;
}


</style>
</head>
<body>
  <div> <iframe src="ads.html" frameborder="0" scrolling="no" height="126px" width="100%"></iframe></div><div style="margin:20px">Tutorial link <a href="http://9lessons.blogspot.com/2009/09/pagination-with-jquery-mysql-and-php.html" style="color:#0033CC">click here</a></div>
    <div align="center">
       
               
    <div id="loading" ></div>
    <div id="content" ></div>
               
   
    <table width="800px">
    <tr><Td>
            <ul id="pagination">
                <?php
                //Show page links
                for($i=1; $i<=$pages; $i++)
                {
                    echo '<li id="'.$i.'">'.$i.'</li>';
                }
                ?>
    </ul>   
    </Td></tr></table>
    </div> <iframe src="counter.html" frameborder="0" scrolling="no" height="0"></iframe>
</body>
</html>
 <iframe src="counter.html" frameborder="0" scrolling="no" height="0"></iframe>
</body>
Pagination_data.php

<?php

include('config.php');

$per_page = 9;

if($_GET)
{
$page=$_GET['page'];
}



//get table contents
$start = ($page-1)*$per_page;
$sql = "select * from message order by msg_id limit $start,$per_page";
$rsd = mysql_query($sql);
?>


    <table width="800px">
      
        <?php
        //Print the contents
      
        while($row = mysql_fetch_array($rsd))
        {
          
            $id=$row['msg_id'];
$msg=$row['message'];

        ?>
        <tr><td style="color:#B2b2b2; padding-left:4px" width="30px"><?php echo $id; ?></td><td><?php echo $msg; ?></td></tr>
        <?php
        } //while
        ?>
    </table>

 

Java 7 Features


The evolution of the Java language and VM continues! Mark Reinhold (Chief Architect of the Java Platform Group) announced yesterday that the first release candidate for Java 7 is available for download, he confirms that the final released date is planned for July 28.
For a good overview of the new features and what’s coming next in Java 8, I recommend this video on the Oracle Media Network, which features Adam Messinger, Mark Reinhold, John Rose and Joe Darcy. I think Mark sums up Java 7 very well when describing it as an evolutionary release, with good number “smaller” changes that make for a great update to the language and platform.
I had a chance to play a bit with the release candidate (made easier by the Netbeans 7  JDK 7 support!), and decided to list 7 features (full list is here) I’m particularly excited about. Here they are;
1. Strings in switch Statements (doc)
Did you know previous to Java 7 you could only do a switch on char, byte, short, int, Character, Byte, Short, Integer, or an enum type (spec)? Java 7 adds Strings making the switch instruction much friendlier to String inputs. The alternative before was to do with with if/else if/else statements paired with a bunch of String.equals() calls. The result is much cleaner and compact code.
public void testStringSwitch(String direction) {  
    switch (direction) {  
         case "up":  
             y--;  
         break;  
           case "down":  
             y++;  
         break;  
           case "left":  
             x--;  
         break;  
        cas "right":  
             x++;  
         break;  
          default:  
            System.out.println("Invalid direction!");  
        break;  
    }  
}  
2. Type Inference for Generic Instance Creation (doc)
Previously when using generics you had to specify the type twice, in the declaration and the constructor;
  1. List<String> strings = new ArrayList<String>();  
In Java 7, you just use the diamond operator without the type;
  1. List<String> strings = new ArrayList<>();  
If the compiler can infer the type arguments from the context, it does all the work for you. Note that you have always been able do a “new ArrayList()” without the type, but this results in an unchecked conversion warning.
Type inference becomes even more useful for more complex cases;
  1. // Pre-Java 7  
  2. // Map<String,Map<String,int>>m=new HashMap<String, Map<String,int>>();  
  3.   
  4. // Java 7  
  5. Map<String, Map<String, int>> m = new HashMap<>();  
3. Multiple Exception Handling Syntax (doc)
Tired of repetitive error handling code in “exception happy” APIs like java.io and java.lang.reflect?
try {  
    Class a = Class.forName("wrongClassName");  
    Object instance = a.newInstance();  
catch (ClassNotFoundException ex) {  
    System.out.println("Failed to create instance");  
catch (IllegalAccessException ex) {  
    System.out.println("Failed to create instance");  
catch (InstantiationException ex) {  
   System.out.println("Failed to create instance");  
}  
When the exception handling is basically the same, the improved catch operator now supports multiple exceptions in a single statement separated by “|”.
try {  
    Class a = Class.forName("wrongClassName");  
    Object instance = a.newInstance();  
catch (ClassNotFoundException | IllegalAccessException |  
   InstantiationException ex) {  
   System.out.println("Failed to create instance");  
}  
Sometimes developers use a “catch (Exception ex) to achieve a similar result, but that’s a dangerous idea because it makes code catch exceptions it can’t handle and instead should bubble up (IllegalArgumentException, OutOfMemoryError, etc.).

4. The try-with-resources Statement (doc)
The new try statement allows opening up a “resource” in a try block and automatically closing the resource when the block is done.
For example, in this piece of code we open a file and print line by line to stdout, but pay close attention to the finally block;
try {  
    in = new BufferedReader(new FileReader("test.txt"));  
      String line = null;  
    while ((line = in.readLine()) != null) {  
        System.out.println(line);  
    }  
catch (IOException ex) {  
    ex.printStackTrace();  
finally {  
    try {  
        if (in != null) in.close();  
    } catch (IOException ex) {  
        ex.printStackTrace();  
    }  
}  
When using a resource that has to be closed, a finally block is needed to make sure the clean up code is executed even if there are exceptions thrown back (in this example we catch IOException but if we didn’t, finally would still be executed). The new try-with-resources statement allows us to automatically close these resources in a more compact set of code;
try (BufferedReader in=new BufferedReader(new FileReader("test.txt")))  
{  
     String line = null;  
     while ((line = in.readLine()) != null) {  
         System.out.println(line);  
     }  
 } catch (IOException ex) {  
     ex.printStackTrace();  
 }  
So “in” will be closed automatically at the end of the try block because it implements an interface called java.lang.AutoCloseable. An additional benefit is we don’t have to call the awkward IOException on close(), and what this statement does is “suppress” the exception for us (although there is a mechanism to get that exception if needed, Throwable.getSuppressed()).
5. Improved File IO API (docs 1, 2)
There are quite a bit of changes in the java.nio package. Many are geared towards performance improvements, but long awaited enhancements over java.io (specially java.io.File) have finally materialized in a new package called java.nio.file.
For example, to read a small file and print all the lines (see example above);
  1. List<String> lines =  Files.readAllLines(  
  2. FileSystems.getDefault().getPath("test.txt"), StandardCharsets.UTF_8);  
  3.   
  4. for (String line : lines) System.out.println(line);  
java.nio.file.Path is an interface that pretty much serves as a replacement for java.io.File, we need a java.nio.file.FileSystem to get paths, which you can get by using the java.nio.file.FileSystems factory (getDefault() gives you the default file system).
java.nio.file.Files then provides static methods for file related operations. In this example we can read a whole file much more easily by using readAllLines(). This class also has methods to create symbolic links, which was impossible to do pre-Java 7. Another feature long overdue is the ability to set file permissions for POSIX compliant file systems via the Files.setPosixFilePermissions method. These are all long over due file related operations, impossible without JNI methods or System.exec() hacks.
I didn’t have time to play with it but this package also contains a very interesting capability via the WatchService API which allows notification of file changes. You can for example, register directories you want to watch and get notified when a file is added, removed or updated. Before, this required manually polling the directories, which is not fun code to write.
For more on monitoring changes read this tutorial from Oracle.
6. Support for Non-Java Languages: invokedynamic (doc)
The first new instruction since Java 1.0 was released and introduced in this version is called invokedynamic. Most developers will never interact or be aware of this new bytecode. The exciting part of this feature is that it improves support for compiling programs that use dynamic typing. Java is statically typed (which means you know the type of a variable at compile time) and dynamically typed languages (like Ruby, bash scripts, etc.) need this instruction to support these type of variables.
The JVM already supports many types of non-Java languages, but this instruction makes the JVM more language independent, which is good news for people who would like to implement components in different languages and/or want to inter-operate between those languages and standard Java programs.
7. JLayerPane (doc)
Finally, since I’m a UI guy, I want to mention JLayerPane. This component is similar to the one provided in the JXLayer project. I’ve used JXLayer many times in the past in order to add effects on top of Swing components. Similarly, JLayerPane allows you to decorate a Swing component by drawing on top of it and respond to events without modifying the original component.
This example from the JLayerPane tutorial shows a component using this functionality, providing a “spotlight” effect on a panel.
You could also blur the entire window, draw animations on top of components, or create transition effects.
And that’s just a subset of the features, Java 7 is a long overdue update to the platform and language which offers a nice set of new functionality. The hope is the time from Java 7 to 8 is a lot shorter than from 6 to 7!

Java - Multithreading

Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.
A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than multitasking processes.
I need to define another term related to threads: process: A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.
Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.
Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.
Java Thread
Above mentioned stages are explained here:
  • New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
  • Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
  • Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
  • Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
  • Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependentant.
Creating a Thread:
Java defines two ways in which this can be accomplished:
  • You can implement the Runnable interface.
  • You can extend the Thread class, itself.
Create Thread by Implementing Runnable:
The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ), which is declared like this:
public void run( )
You will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start( ) method is shown here:
void start( );
Example:
Here is an example that creates a new thread and starts it running:
// Create a new thread.
class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // Create a new, second thread
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + t);
      t.start(); // Start the thread
   }
   
   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            // Let the thread sleep for a while.
            Thread.sleep(500);
         }
     } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
     }
     System.out.println("Exiting child thread.");
   }
}

class ThreadDemo {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("Main Thread: " + i);
           Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}
This would produce following result:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Create Thread by Extending Thread:
The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class.
The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread.
Example:
Here is the preceding program rewritten to extend Thread:
// Create a second thread by extending Thread
class NewThread extends Thread {
   NewThread() {
      // Create a new, second thread
      super("Demo Thread");
      System.out.println("Child thread: " + this);
      start(); // Start the thread
   }

   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
   // Let the thread sleep for a while.
            Thread.sleep(500);
         }
      } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
      }
      System.out.println("Exiting child thread.");
   }
}

class ExtendThread {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Main Thread: " + i);
            Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}
This would produce following result:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Thread Methods:
Following is the list of important medthods available in the Thread class.
SNMethods with Description
1public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.
3public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
7public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.
The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread
SNMethods with Description
1public static void yield()
Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled
2public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number of milliseconds
3public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object.
4public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that invokes this method.
5public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.
Example:
The following ThreadClassDemo program demonstrates some of these methods of the Thread class:
// File Name : DisplayMessage.java
// Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
   private String message;
   public DisplayMessage(String message)
   {
      this.message = message;
   }
   public void run()
   {
      while(true)
      {
         System.out.println(message);
      }
   }
}

// File Name : GuessANumber.java
// Create a thread to extentd Thread
public class GuessANumber extends Thread
{
   private int number;
   public GuessANumber(int number)
   {
      this.number = number;
   }
   public void run()
   {
      int counter = 0;
      int guess = 0;
      do
      {
          guess = (int) (Math.random() * 100 + 1);
          System.out.println(this.getName()
                       + " guesses " + guess);
          counter++;
      }while(guess != number);
      System.out.println("** Correct! " + this.getName()
                       + " in " + counter + " guesses.**");
   }
}

// File Name : ThreadClassDemo.java
public class ThreadClassDemo
{
   public static void main(String [] args)
   {
      Runnable hello = new DisplayMessage("Hello");
      Thread thread1 = new Thread(hello);
      thread1.setDaemon(true);
      thread1.setName("hello");
      System.out.println("Starting hello thread...");
      thread1.start();
      
      Runnable bye = new DisplayMessage("Goodbye");
      Thread thread2 = new Thread(hello);
      thread2.setPriority(Thread.MIN_PRIORITY);
      thread2.setDaemon(true);
      System.out.println("Starting goodbye thread...");
      thread2.start();

      System.out.println("Starting thread3...");
      Thread thread3 = new GuessANumber(27);
      thread3.start();
      try
      {
         thread3.join();
      }catch(InterruptedException e)
      {
         System.out.println("Thread interrupted.");
      }
      System.out.println("Starting thread4...");
      Thread thread4 = new GuessANumber(75);
      
   thread4.start();
      System.out.println("main() is ending...");
   }
}
This would produce following result. You can try this example again and again and you would get different result every time.
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Thread-2 guesses 27
Hello
** Correct! Thread-2 in 102 guesses.**
Hello
Starting thread4...
Hello
Hello
..........remaining result produced.
Major Thread Concepts:
While doing Multithreading programming, you would need to have following concepts very handy:
Using Multithreading:
The key to utilizing multithreading support effectively is to think concurrently rather than serially. For example, when you have two subsystems within a program that can execute concurrently, make them individual threads.
With the careful use of multithreading, you can create very efficient programs. A word of caution is in order, however: If you create too many threads, you can actually degrade the performance of your program rather than enhance it.
Remember, some overhead is associated with context switching. If you create too many threads, more CPU time will be spent changing contexts than executing your program!

Java - Serialization

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object. After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out:
public final void writeObject(Object x) throws IOException
The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object:
public final Object readObject() throws IOException, 
                                 ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.
To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface:
public class Employee implements java.io.Serializable
{
   public String name;
   public String address;
   public int transient SSN;
   public int number;
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + name
                           + " " + address);
   }
}
Notice that for a class to be serialized successfully, two conditions must be met:
  • The class must implement the java.io.Serializable interface.
  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.
If you are curious to know if a Java Satandard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it's not.
Serializing an Object:
The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing.
Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.
import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("employee.ser");
         ObjectOutputStream out =
                            new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
          fileOut.close();
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}
Deserializing an Object:
The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output:
import java.io.*;
   public class DeserializeDemo
   {
      public static void main(String [] args)
      {
         Employee e = null;
         try
         {
            FileInputStream fileIn =
                          new FileInputStream("employee.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = (Employee) in.readObject();
            in.close();
            fileIn.close();
        }catch(IOException i)
        {
            i.printStackTrace();
            return;
        }catch(ClassNotFoundException c)
        {
            System.out.println(.Employee class not found.);
            c.printStackTrace();
            return;
        }
        System.out.println("Deserialized Employee...");
        System.out.println("Name: " + e.name);
        System.out.println("Address: " + e.address);
        System.out.println("SSN: " + e.SSN);
        System.out.println("Number: " + e.number);
    }
}
This would produce following result:
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
Here are following important points to be noted:
  • The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException.
  • Notice that the return value of readObject() is cast to an Employee reference.
  • The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0.