Thursday, August 25, 2011

Stop watch programme using Java Threads

package org.best.example;

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class Stopwatch extends JFrame implements ActionListener, Runnable
    {
     private long startTime;
     private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss.SSS");
     private final JButton startStopButton= new JButton("Start/stop");
     private Thread updater;
     private boolean isRunning= false;
     private final Runnable displayUpdater= new Runnable()
         {
         public void run()
             {
             displayElapsedTime(System.currentTimeMillis() - Stopwatch.this.startTime);
         }
     };
     public void actionPerformed(ActionEvent ae)
         {
         if(isRunning)
             {
             long elapsed= System.currentTimeMillis() - startTime;
             isRunning= false;
             try
                 {
                 updater.join();
                 // Wait for updater to finish
             }
             catch(InterruptedException ie) {}
             displayElapsedTime(elapsed);
             // Display the end-result
         }
         else
             {
             startTime= System.currentTimeMillis();
             isRunning= true;
             updater= new Thread(this);
             updater.start();
         }
     }
     private void displayElapsedTime(long elapsedTime)
         {
         startStopButton.setText(timerFormat.format(new java.util.Date(elapsedTime)));
     }
     public void run()
         {
         try
             {
             while(isRunning)
                 {
                 SwingUtilities.invokeAndWait(displayUpdater);
                 Thread.sleep(50);
             }
         }
         catch(java.lang.reflect.InvocationTargetException ite)
             {
             ite.printStackTrace(System.err);
             // Should never happen!
         }
         catch(InterruptedException ie) {}
         // Ignore and return!
     }
     public Stopwatch()
         {
         startStopButton.addActionListener(this);
         getContentPane().add(startStopButton);
         setSize(100,50);
         setVisible(true);
     }
     public static void main(String[] arg)
         {
         new Stopwatch().addWindowListener(new WindowAdapter()
             {
             public void windowClosing(WindowEvent e)
                 {
                 System.exit(0);
             }
         });
     }
}

Wednesday, August 24, 2011

Java Interview Questions - 52

Q: What is the difference between HttpServlet and GenericServlet?
A: A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
Both these classes are abstract.

Demonstrating the runnable interface

package org.best.example;
 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class RandomCharacters extends JApplet implements Runnable, ActionListener
 {
     private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
     private JLabel outputs[];
     private JCheckBox checkboxes[];
     private final static int SIZE = 3;

     private Thread threads[];
     private boolean suspended[];

     public void init()
     {
         outputs = new JLabel[ SIZE ];
         checkboxes = new JCheckBox[ SIZE ];
         threads = new Thread[ SIZE ];
         suspended = new boolean[ SIZE ];

         Container c = getContentPane();
         c.setLayout( new GridLayout( SIZE, 2, 5, 5 ) );

         for ( int i = 0; i < SIZE; i++ )
         {
             outputs[ i ] = new JLabel();
             outputs[ i ].setBackground( Color.green );
             outputs[ i ].setOpaque( true );
             c.add( outputs[ i ] );

             checkboxes[ i ] = new JCheckBox( "Suspended" );
             checkboxes[ i ].addActionListener( this );
             c.add( checkboxes[ i ] );
         }
    }

     public void start()
     {
         // create threads and start every time start is called
         for ( int i = 0; i < threads.length; i++ )
         {
             threads[ i ] = new Thread( this, "Thread " + (i + 1) );
             threads[ i ].start();
         }
     }

     public void run()
     {
         Thread currentThread = Thread.currentThread();
         int index = getIndex( currentThread );
         char displayChar;

         while ( threads[ index ] == currentThread )
         {
             // sleep from 0 to 1 second
             try
             {
                 Thread.sleep( (int) ( Math.random() * 1000 ) );

                 synchronized( this )
                 {
                     while ( suspended[ index ] && threads[ index ] == currentThread )
                     wait();
                 }
             }
             catch ( InterruptedException e )
             {
                 System.err.println( "sleep interrupted" );
             }

             displayChar = alphabet.charAt( (int) ( Math.random() * 26 ) );
             outputs[ index ].setText( currentThread.getName() +
             ": " + displayChar );
         }

         System.err.println( currentThread.getName() + " terminating" );
     }

     private int getIndex( Thread current )
     {
         for ( int i = 0; i < threads.length; i++ )
             if ( current == threads[ i ] )
                 return i;

         return -1;
     }

     public synchronized void stop()
     {
         // stop threads every time stop is called
         // as the user browses another Web page
         for ( int i = 0; i < threads.length; i++ )
             threads[ i ] = null;

         notifyAll();
     }

     public synchronized void actionPerformed( ActionEvent e )
     {
         for ( int i = 0; i < checkboxes.length; i++ )
         {
             if ( e.getSource() == checkboxes[ i ] )
             {
                 suspended[ i ] = !suspended[ i ];

                 outputs[ i ].setBackground( !suspended[ i ] ? Color.green : Color.red );

                 if ( !suspended[ i ] )
                 notify();

                 return;
             }
         }
     }
 }

Tuesday, August 23, 2011

Attachment receiver

package org.best.example;

import java.util.Iterator;
import javax.servlet.ServletException;
import javax.xml.messaging.JAXMServlet;
import javax.xml.messaging.ReqRespListener;
import javax.xml.soap.AttachmentPart;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;

/**
 * Servlet that accepts a SOAP message and looks through
 * its attachments before sending the SOAP part of the message
 * to the console and sending back a response
 *
 */
public class AttachmentReceiver extends JAXMServlet implements ReqRespListener {
  private MessageFactory fac;

  public void init() throws ServletException {
    try {
      fac = MessageFactory.newInstance();
    }
    catch( Exception ex ) {
      ex.printStackTrace();
      throw new ServletException( ex );
    }
  }

  // This is the application code for handling the message.. Once the
  // message is received the application can retrieve the soap part, the
  // attachment part if there are any, or any other information from the
  // message.

  public SOAPMessage onMessage( SOAPMessage message ) {
    System.out.println( "On message called in receiving servlet" );
    try {
      System.out.println( "\nMessage Received: " );
      System.out.println( "\n============ start ============\n" );

      // dump out attachments
      System.out.println( "Number of Attachments: " + message.countAttachments() );
      int i = 1;
      for( Iterator it = message.getAttachments(); it.hasNext(); i++ ) {
        AttachmentPart ap = (AttachmentPart) it.next();
        System.out.println( "Attachment #" + i + " content type : " +
                            ap.getContentType() );
      }

      // dump out the SOAP part of the message
      SOAPPart soapPart = message.getSOAPPart();
      System.out.println( "SOAP Part of Message:\n\n" + soapPart );
      System.out.println( "\n============ end ===========\n" );

      SOAPMessage msg = fac.createMessage();
      SOAPEnvelope env = msg.getSOAPPart().getEnvelope();

      env.getBody()
          .addChildElement( env.createName( "MessageResponse" ) )
          .addTextNode( "Right back at you" );
      return msg;
    }
    catch( Exception e ) {
      e.printStackTrace();
      return null;
    }
  }
}

Java Interview Questions - 51

Q: What is the difference between Difference between doGet() and doPost()?
A: A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.

Monday, August 22, 2011

Java Interview Questions - 50

Q: What is preinitialization of a servlet?
A: A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

Accessing Java Servlet JNDI environment variables

package org.best.example;

import java.io.IOException;
import java.io.PrintWriter;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * It is better to use environment variables within a J2EE
 * context for values that can be changed a deployment time
 * instead of Context attributes within the web.xml.  This
 * way you don't have to update the web.xml to change the
 * values.
 *
 *
 <env-entry>
 <description>the guy responsible for this site</description>
 <env-entry-name>webmaster</env-entry-name>
 <env-entry-value>x@xxx</env-entry-value>
 <env-entry-type>java.lang.String</env-entry-type>
 </env-entry>
 */
public class AccessingServletJndiEnvironmentVariables extends HttpServlet {

  public void doGet( HttpServletRequest req, HttpServletResponse res )
      throws ServletException, IOException {
    res.setContentType( "text/html" );
    PrintWriter pw = res.getWriter();

    String webMaster = null;
    try {
      // get a handle on the JNDI root context
      Context ctx = new InitialContext();

      // and access the environment variable for this web component
      webMaster = (String) ctx.lookup( "java:comp/env/webmaster" );
    }
    catch( NamingException ex ) {
      ex.printStackTrace();
    }

    pw.println( "the web master is -> " + webMaster );
  }
}