Saturday, August 18, 2012

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.

Sunday, April 15, 2012

how ro get unread mails from gmail using java

/*
 *  This is the code for read the unread mails from your mail account.
 *  Requirements:
 *      JDK 1.5 and above
 *      Jar:mail.jar
 *
 */
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;

public class MailReader {
    Folder inbox;

    // Constructor of the calss.
    public MailReader() {
        /*   Set the mail properties  */
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
        try {
            /*   Create the session and get the store for read the mail. */
            Session session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("imaps");
            store.connect("imap.gmail.com", "xxxxxxxxx@gmail.com ", "xxxxxxxxx");

            /*   Mention the folder name which you want to read. */
            inbox = store.getFolder("Inbox");
            System.out.println("No of Unread Messages : "
                    + inbox.getUnreadMessageCount());

            /* Open the inbox using store. */
            inbox.open(Folder.READ_ONLY);

            /*   Get the messages which is unread in the Inbox */
            Message messages[] = inbox.search(new FlagTerm(
                    new Flags(Flag.SEEN), false));

            /* Use a suitable FetchProfile    */
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.CONTENT_INFO);
            inbox.fetch(messages, fp);

            try {
                printAllMessages(messages);
                inbox.close(true);
                store.close();
            } catch (Exception ex) {
                System.out.println("Exception arise at the time of read mail");
                ex.printStackTrace();
            }
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (MessagingException e) {
            e.printStackTrace();
            System.exit(2);
        }
    }

    public void printAllMessages(Message[] msgs) throws Exception {
        for (int i = 0; i < msgs.length; i++) {
            System.out.println("MESSAGE #" + (i + 1) + ":");
            printEnvelope(msgs[i]);
        }
    }

    /* &nbsp; Print the envelope(FromAddress,ReceivedDate,Subject)&nbsp; */
    public void printEnvelope(Message message) throws Exception {
        Address[] a;
        // FROM
        if ((a = message.getFrom()) != null) {
            for (int j = 0; j < a.length; j++) {
                System.out.println("FROM: " + a[j].toString());
            }
        }
        // TO
        if ((a = message.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < a.length; j++) {
                System.out.println("TO: " + a[j].toString());
            }
        }
        String subject = message.getSubject();
        Date receivedDate = message.getReceivedDate();
        String content = message.getContent().toString();
        System.out.println("Subject : " + subject);
        System.out.println("Received Date : " + receivedDate.toString());
        //System.out.println("Content : " + content);
        getContent(message);
    }

    public void getContent(Message msg) {
        try {
            String contentType = msg.getContentType();
            //System.out.println("Content Type : " + contentType);
            Multipart mp = (Multipart) msg.getContent();
            int count = mp.getCount();
            System.out.println("count--->"+count);
            for (int i = 0; i < count-1; i++) {
                dumpPart(mp.getBodyPart(i));
            }
        } catch (Exception ex) {
            System.out.println("Exception arise at get Content");
            ex.printStackTrace();
        }
    }

    public void dumpPart(Part p) throws Exception {
        // Dump input stream ..
        InputStream is = p.getInputStream();
        // If "is" is not already buffered, wrap a BufferedInputStream
        // around it.
        if (!(is instanceof BufferedInputStream)) {
            is = new BufferedInputStream(is);
        }
        int c;
        System.out.println("Message : ");
        while ((c = is.read()) != -1) {
            System.out.write(c);
        }
    }

}




Write this code in ur servlet:

MailReader mr=new MailReader();


how to send SMS using javamail

String username = "my mobile number"
String password = "my way2sms password"
String smtphost = "site3.way2sms.com";  
 String from = "my mobile number@site3.way2sms.com";
 String to = "receiver mobile number@site3.way2sms.com";
 String body = "Hello SMS World!"
Transport myTransport = null; 
         try { Properties props = System.getProperties(); 
          props.put("mail.smtp.auth", "true");
               Session mailSession = Session.getDefaultInstance(props, null); 
Message msg = new MimeMessage(mailSession); 
msg.setFrom(new InternetAddress(from));
 InternetAddress[] address = {new InternetAddress(to)}; msg.setRecipients(Message.RecipientType.TO, address);  
 msg.setText(body); msg.setSentDate(new Date());   
myTransport = mailSession.getTransport("smtp"); 
myTransport.connect(smtphost, username, password);
 msg.saveChanges();
 myTransport.sendMessage(msg, msg.getAllRecipients()); 
myTransport.close(); 
out.print("sent"); 
} catch (Exception e) { e.printStackTrace(); }



Monday, April 9, 2012

Thursday, April 5, 2012

JSP Elements


A JSP page can have two types of data:
  • Template Data: It is the static part of a jsp page. Anything that is copied as it is directly to the response by the JSP server is known as template data.
  • JSP Elements: It is the dynamic part of a jsp page. Anything that is translated and executed by the JSP server is known as JSP element.
There are three types of JSP elements:
Directive Elements: The directive elements, contains the information about the page itself that remains the same between requests for the page. The general directive syntax is:
<%@ directiveName attr1="value1" attr2="value2" %>
The directive name and all attribute names are case-sensitive and the attribute values can be enclosed with single quotes instead of double quotes.
Action Element: Action elements generally performs some action depending on the information required at when the JSP page is requested by a browser. An action can access parameters sent with the request in order to lookup the database.
The general syntax for the action elements is:
<action_name attribute=value ...>action_body</action_name>
<action_name attribute=value .../>
Scripting Element: A JSP element is an element that provides embedded Java statements. A JSP page can have three types of scripting elements:
  • Declaration Element: A JSP element provides the capability of inserting Java declaration statements into the Servlet class. Here is the syntax for the declaration element.
   <%! Java decalaration statements %>
  • Scriptlet Element: A JSP element provides the capability of embedding Java expressions to be evaluated as part of the service method of the Servlet class. An scripting element can be written in two ways:
  <% Java statements %>
  • Expression Element: A JSP element provides the capability of embedding Java expressions to be evaluated as part of the service method of the Servlet class. An expression element can be written in two ways: <% Java expressoins %>

Saturday, March 24, 2012

GlassFish and MyEclipse and Eclipse support...

For the time and energy I spent to install the Release candidate for Europa, I must admit that paying a few dollars for MyEclipse is definitely the right investment to do (although I am still missing a complete installer for Mac OSX, and a GlassFish/MyEclipse co-Bundle that would be installable in one shot).





I enjoyed the JSP editor (and renderer), as well as an extensive JavaScript support that should play well with our Ajax jMaki  components (that are also available for Eclipse).
There are still a few issues in the Java EE 5 support of MyEclipse (for example, one cannot create JPA entity beans in a Web Application, or no pure Java EE 5 Web Services support -Axis is the only supported stack-, or that the fact you need to touch files like web.xml or ejb-jar.xml or application.xml to trigger a redeployment for exploded directories -when these files are now optional in the latest Java EE 5 specification which is all about ease of development and replacement of those xml files into Java annotations)-, but all I can say is that for people who want an Eclipse based IDE to do Java EE 5 development (and target the GlassFish application server), MyEclipse is certainly a very good option and worth the investment. Very soon, MyEclipse will switch to Eclipse Europa platform and the latest good stuff from WTP 2.0.

Registering GlassFish in MyEclipse is very easy, and deployment of Java EE 5 applications to it is simple:


Having said that, for people who have the freedom to look at a solution which is not Eclipse based, NetBeans 5.5.1 and the coming NetBeans 6.0 are also offering advanced (and complete) Java EE 5 support, including JSF, JPA, Web Services and more. NetBeans also updates automatically the GlassFish specific descriptors when needed and transparently.

In conclusion, it is good to see that there is a wide range of tools targeting Java EE 5, and it's best implementation so far: GlassFish:-)


Link:
http://weblogs.java.net/blog/ludo/archive/2007/05/glassfish_and_m.html

Configure WebLogic in MyEclipse


Hi,
Please follow the steps to configure Weblogic in MyEclipse
 Before configuring in MyEclipse, first we need to configure the server and domain in Configuration Wizard
1) Go to Start ->  Bea Web Logic -> Configuration Wizard
This will open a configuration wizard for you
2) Select “Create a new WebLogic Configuration” and Click next
3) Select “Basic WebLogic Server Domain” and Click Next
4) Select “Express” and click next
5) Here, give username and password
6) click next -> next ->
7) By default, the domai name is mydomain , If you want you can change in the bottom right corner  “Configuration Name”
8) Select Create and It will create a domain for you.
9) You can see that in Start -> BEA Weblogic -> User Projects

 Steps to follow in MYEclipse
1)      Go to  Windows – > Preferences -> Select MyEclipse
2)      Expand that and select Application Servers – > WebLogic -> Weblogic 8
  1. Select on WebLogic 8.x and fill the following

      b) Select JDK and select jdk 1.4 from bea directory
     c) now you can start the server



How Spring MVC Works


In this we will see the request flow for the spring framework. We will also show you the request flow diagram illustrating the working of Spring MVC module.
The Spring MVC modules comes with the Spring Framework distribution. The Spring MVC modules of the Spring Framework well integrates with rest of the framework. This modules is also very extensible.
Spring MVC is based on the MVC design pattern. Here is the list of key classes of Spring MVC.
  • DispatcherServlet
    The DispatcherServlet is  configured in the web.xml file and required URL patterns are mapped to this Servlet. It works as the front controller and handle all the request from the user.
     
  • ModelAndView
    This class works as the holder for both Model and View in the Spring MVC.
     
  • SimpleFormController
    The SimpleFormController is the Concrete FormController implementation. It provides the configurable form and success views, and an onSubmit chain for convenient overriding. Automatically resubmits to the form view in case of validation errors, and renders the success view in case of a valid submission.
Simplified Spring MVC architecture diagram
Following diagram shows the simplified architecture of Spring MVC:
Spring MVC Architecture, Spring MVC request flow
Let's understand the sequences of the events happens when a request is received by the Spring MVC. Following events happens when DispatcherServlet receives are request:
  1.  The DispatcherServlet configured in web.xml file receives the request.
  2. The DispatcherServlet finds the appropriate Controller with the help of HandlerMapping and then invokes associated Controller.
  3. Then the Controller executes the logic business logic (if written by the programmer) and then returns ModeAndView object to the DispatcherServlet.
  4. The DispatcherServlet determines the view from the ModelAndView object.
  5. Then the DispatcherServlet passes the model object to the View.
  6.  The View is rendered and the Dispatcher Servlet sends the output to the Servlet container. Finally Servlet Container sends the result back to the user.
Request flow in Spring MVC
Spring MVC is request driven and DispatcherServlet handles the request from client and then dispatches the request to controllers. It tightly integrates with the Spring IoC container and allows the developers to use every features of Spring framework.
The following diagram illustrates the request flow in Spring MVC.
Spring MVC Request flow
Request handling steps in Spring MVC
  1. Client access some URL on the server.
  2. The Spring Front Controller (DispatcherServlet) intercepts the Request. After receiving the request it finds the appropriate Handler Mappings.
  3. The Handle Mappings maps the client request to appropriate Controller. In this process framework reads the configuration information from the configuration file or from the annotated controller list. Then DispatcherServlet dispatch the request to the appropriate Controller. The Handler Adapters involves in this process.
  4. Then the Controller processes the Client Request, it executes the logic defined in the Controller method and finally returns the ModelAndView object back to the Front Controller.
  5. Based on the values in the ModelAndView Controller resolves the actual view, which can be JSP, Velocity, FreeMaker, Jasper or any other configured view resolver.
  6. Then the selected view is rendered and output is generated in the form of HttpServletResponse. Finally Controller sends the response to the Servlet container, which sends the output to the user.
Controllers hierarchy in Spring MVC
In this we will will understand the controllers hierarchy in Spring MVC Module. The Spring MVC module provides a lot of flexibility to easily develop MVC based web applications. It provides many controllers that can be used to achieve different jobs.
Spring MVC module is based on the MVC design pattern. The main components involved are DispatcherServlet, Controller and Views. In Spring MVC DispatcherServlet plays very important role. It handles the user request and delegates it with Controller. Following diagram shows the very simplified architecture:

In this Spring MVC, DispatcherServlet works as the controller and it delegates the request to the Controller. Developers extends the abstract controller provided by the framework and writes the business logic there. The actual business related processing is done in the Controller.
 Spring MVC provides many abstract controllers, which is designed for specific tasks. Here is the list of anstract controllers that comes with the Spring MVC module:
  1. SimpleFormController
  2. AbstractController
  3. AbstractCommandController
  4. CancellableFormController
  5. AbstractCommandController
  6. MultiActionController
  7. ParameterizableViewController
  8. ServletForwardingController
  9. ServletWrappingController
  10. UrlFilenameViewController
  11. AbstractController
  12. AbstractCommandController
  13. SimpleFormController
  14. CancellableFormController.
Following diagram shows the Controllers hierarchy in Spring MVC:
Spring MVC Controller hierarchy
In the next sections we will be learning about all these controllers. We will also provide you the examples codes illustrating the usage of these controllers.

Friday, March 23, 2012

Spring PPT'S

Saturday, March 17, 2012

MVC 1 vs MVC2

MVC1 Vs MVC2:




Difference Between MVC 1 & MVC 2   
                                           
                    MVC  1     
                        MVC 2
MVC1 associates the presentation logic with the business logic.

MVC 2 isolates or disassociates the presentation logic from business logic

In MVC1, only one component is responsible for receiving request and sending response.
In MVC2, there is separate components for receiving and  sending response. i.e. Controller & View.In
MVC 1, business logic and presentation Logic is combined so web designer and web developer cant work simulateously.
Since both logics are separate that's why designer and developer can work together.
Doesn't support reusability of application components.
Reusability of components
In MVC 1, controller and model,both are JSP.
While controller is servlet and model is java class.
In MVC1 there is tight coupling between page and model as data access is usually done using Custom tag or through java bean call. 
In MVC2 architecture there is only one controller which receives all the request for the application and is responsible for taking appropriate action in response to each request.
Link:

Struts 1 vs Struts 2



FeatureStruts 1Struts 2
Action classesStruts 1 requires Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces.An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with a execute signature can be used as an Struts 2 Action object.
Threading ModelStruts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1 Actions and requires extra care to develop. Action resources must be thread-safe or synchronized.Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)
Servlet DependencyStruts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the executemethod when an Action is invoked.Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.
TestabilityA major hurdle to testing Struts 1 Actions is that theexecute method exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts 1.Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking methods. Dependency Injection support also makes testing simpler.
Harvesting InputStruts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since  other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. DynaBeans can used as an alternative to creating conventional ActionForm classes, but, here too, developers may be redescribing existing JavaBeans.Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties. The Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Rich object types, including business or domain objects, can be used as input/output objects. The ModelDriven feature simplifies taglb references to POJO input objects.
Expression LanguageStruts 1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support.Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
Binding values into viewsStruts 1 uses the standard JSP mechanism for binding objects into the page context for access.Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows reuse of views across a range of types which may have the same property name but different property types.
Type ConversionStruts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons-Beanutils for type conversion. Converters are per-class, and not configurable per instance.Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.
ValidationStruts 1 supports manual validation via a validatemethod on the ActionForm, or through an extension to the Commons Validator. Classes can have different validation contexts for the same class, but cannot chain to validations on sub-objects.Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.
Control Of Action ExecutionStruts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle.Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.

Friday, March 16, 2012

configure glassfish in myeclipse

http://glassfishplugins.java.net/eclipse34/index.html

What is the need to Override Hashcode() and equals() method


Although there are lots of materials are available on internet and API document about the necessity of the overriding the hashcode() and equals() method in Java but lots of new developers still not able to understand the necessity of hashcode() method.
In this article, I will try to explain step by step the need of overriding hashcode() method in Java.
Few Thump rules:
  • If two objects are same then they must return same value in hashcode() and equals() method whenever invoked.
  • It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.
JVM assigns unique hashcode value to each object when they are created in memory and if developers don’t override the hashcode method then there is no way the two object returns same hashcode value.
As the question comes in your mind that equals() method is used to compare objects that they are having same value or not but why should we override the hashcode method ?
The answer to the question is for the hash technique based data structures like HashMap and HashTable.
How Hashcode works in java
How Hashcode works in java
As you can see in above diagram that every object is placed in Hash bucket depending on the hashcode they have. It is not necessary that every different object must have different hashcode. hashcode is used to narrow the search result. When we try to insert any key in HashMap first it checks whether any other object present with same hashcode and if yes then it checks for the equals() method. If two objects are same then HashMap will not add that key instead it will replace the old value by new one.
What will happen if I don’t override the hashcode method?
Ans : If the object does not implement hashcode() method and used as key then we will not get the object back as shown in below code.

Add sharing buttons in web page


Code for Sharing buttons:

<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style addthis_32x32_style">
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_preferred_4"></a>
<a class="addthis_button_compact"></a>
<a class="addthis_counter addthis_bubble_style"></a>
</div>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4f62aeac3f8df2c1"></script>
<!-- AddThis Button END -->


Link:://www.addthis.com/get/sharing#.T2KuDsUqAxc