Wednesday, August 31, 2011

Java Interview Questions - 59

Q: What are implicit objects? List them?

A: Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below

  • request
  • response
  • pageContext
  • session
  • application
  • out
  • config
  • page
  • exception

Get Java Runtime

    /*
    Get Java Runtime Example
    This get java runtime examples shows how to get the runtime
    in which the java application is running. Runtime allows us
    to interface with the environment in which the current
    application is running.
    */
    
    package org.best.example;
    public class GetJavaRuntime {
    
    public static void main(String args[])
    {
    /*
    * Current runtime can be obtained using getRuntime method
    * of Runtime class.
    *
    * getRuntime method is a static method. Application can not
    * create instance of this class.
    */
    
    Runtime runtime = Runtime.getRuntime();
    
    }
    }
    
    /*
    Output of this program would be,
    Current java runtime obtained!
    */

Tuesday, August 30, 2011

Get Available Processors using Java Runtime

    /*
    Get Available Processors using Java Runtime Example
    This Java example shows how to get number of processors
    available to current Java Virtual Machine (JVM).
    */
   
    package org.best.example;

    public class GetAvailableProcessors {
    
    public static void main(String args[])
    {
    /*
    * get current Java Runtime using getRuntime()
    * method of Runtime class.
    */
    Runtime runtime = Runtime.getRuntime();
    
    /*
    * use availableProcessors method to determine
    * how many processors are available to the Java Virtual
    * Machine (JVM).
    */
    
    int numberOfProcessors = runtime.availableProcessors();
    
    System.out.println(numberOfProcessors + " processor available to JVM");
    }
    }
    
    /*
    Typical output of this program would be,
    1 processor available to JVM
    */

Java Interview Questions - 58

Q: What is a Scriptlet?
A: A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can 1.Declare variables or methods to use later in the file (see also Declaration).

2.Write expressions valid in the page scripting language (see also Expression).

3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.

Monday, August 29, 2011

Java Interview Questions - 57

Q: What is a Declaration?
A: A declaration declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.

<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>

Equalizer

package org.best.example;

import java.rmi.RemoteException;

public interface Equalizer extends javax.ejb.EJBObject {
  public String getTimeOfHit() throws RemoteException;
}

Sunday, August 28, 2011

Java Interview Questions - 56

Q: What is a Expression?
A: An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression

Equalizer home

package org.best.example;

import java.rmi.RemoteException;
import javax.ejb.CreateException;

import com.ack.j2ee.ejb.session.Equalizer;

public interface EqualizerHome extends javax.ejb.EJBHome {
  public Equalizer create() throws CreateException, RemoteException;
}

Saturday, August 27, 2011

Java Interview Questions - 55

Q: What is a Hidden Comment?
A: A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.

You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<%-- comment --%>

Examples
<%@ page language="java" %>
<html>
<head><title>A Hidden Comment </title></head>
<body>
<%-- This comment will not be visible to the colent in the page source --%>
</body>
</html>

Equalizer Session Bean

package org.best.example;

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.RemoveException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

/**
 *
 <session>
 <display-name>Equalizer</display-name>
 ...
 <ejb-ref>
 <description>one the top CIA informers</description>
 <ejb-ref-name>cia/grass</ejb-ref-name>
 <ejb-ref-type>Session</ejb-ref-type>
 <home>com.ack.j2ee.ejb.session.EqualizerHome</home>
 <remote>com.ack.j2ee.ejb.session.Equalizer</remote>
 <ejb-link>Equalizer</ejb-link>
 </ejb-ref>
 </session>
 */

public class EqualizerBean implements SessionBean {
  private SessionContext sessionContext;

  public String getTimeOfHit() throws RemoteException {
    Informer informer = null;
    try {
      InitialContext ctx = new InitialContext();

      // note that by making the Informer session bean an ejb link,
      // it can be accessed from within its naming environment,
      // that is 'java:comp/env' by using the name specified
      // within its deployment descriptor, that is 'cia/grass'
      Object ejbObject = ctx.lookup( "java:comp/env/cia/grass" );

      // then its business as usual once we have the ejbObject
      InformerHome home = (InformerHome) PortableRemoteObject.
          narrow( ejbObject, InformerHome.class );
      informer = home.create();
      return "Assassination Time: " + informer.getTheTime();
    }
    catch( NamingException nex ) {
      throw new EJBException( "cannot find informer", nex );
    }
    catch( CreateException cex ) {
      throw new EJBException( "problem getting informed", cex );
    }
    finally {
      if( informer != null ) {
        try {
          informer.remove();
        }
        catch( RemoveException rex ) {
          throw new EJBException( "problem getting rid of informer", rex );
        }
      }
    }
  }

  public void ejbCreate() throws CreateException {
  }

  public void ejbRemove() {
  }

  public void ejbActivate() {
  }

  public void ejbPassivate() {
  }

  public void setSessionContext( SessionContext sessionContext ) {
    this.sessionContext = sessionContext;
  }

}

Friday, August 26, 2011

Accessing session items

package org.best.example;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AccessingSessionItems extends HttpServlet {
  public void goGet( HttpServletRequest req, HttpServletResponse res )
      throws ServletException, IOException {
    res.setContentType( "text/html" );
    PrintWriter pw = res.getWriter();
    pw.println( "<HTML><BODY>" );

    HttpSession theSession = req.getSession();

    // get a named item out of the session
    Object obj = theSession.getAttribute( "power" );
    pw.println( "<BR>" + obj );

    // get all the items out of the session
    Enumeration attributeNames = theSession.getAttributeNames();
    while( attributeNames.hasMoreElements() ) {
      String attributeName = (String) attributeNames.nextElement();
      obj = theSession.getAttribute( attributeName );
      pw.println( "<BR>" + attributeName + " = " + obj );
    }

    pw.println( "</BODY></HTML>" );
  }
}

Java Interview Questions - 54

Q: What is a output comment?
A: A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser. JSP Syntax
<!-- comment [ <%= expression %> ] -->

Example 1
<!-- This is a commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->

Displays in the page source:
<!-- This is a commnet sent to client on January 24, 2004 -->

Thursday, August 25, 2011

Java Interview Questions - 53

Q: What is the difference between ServletContext and ServletConfig?
A: ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized

ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.

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 );
  }
}

Sunday, August 21, 2011

Java Mail session from a servlet

package org.best.example;

import java.io.IOException;
import java.io.PrintWriter;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * configure a resource reference within the web.xml file
 * that is a container managed javamail session object
 *
 <web-app>
 ...
 <resource-ref>
 <description>smtp mail out</description>
 <res-ref-name>mail/smtp</res-ref-name>
 <res-type>javax.mail.Session</res-type>
 <res-auth>CONTAINER</res-auth>
 </resource-ref>
 </web-app>
 *
 * and use your vendor specific xml file to map the
 * resource name to the jndi name, eg for weblogic
 *
 <weblogic-web-app>
 ...
 <reference-descriptor>
 <resource-description>
 <res-ref-name>mail/smtp</res-ref-name>
 <jndi-name>mail/dailyplanet</jndi-name>
 </resource-description>
 ...
 </reference-descriptor>
 </weblogic-web-app>
 *
 *
 */

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

    try {
      // get hold of the JavaMail session
      Context ctx = new InitialContext();
      Session mailSession = (Session) ctx.lookup( "java:comp/env/mail/smtp" );

      // create a message
      Message msg = new MimeMessage( mailSession );
      msg.setSubject( "a servlet test email" );
      msg.setSentDate( new java.util.Date( System.currentTimeMillis() ) );
      msg.setText( "<h1>Hello You</h1>" );
      msg.addHeader( "Content-Type", "text/html" );
      msg.setFrom( new InternetAddress( "x@xxx" ) );
      msg.setRecipient( Message.RecipientType.TO,
                        new InternetAddress( "cleve" ) );

      // send it
      Transport.send( msg );

      // and provide feedback to the use
      pw.println( "message sent!" );
    }
    catch( Exception ex ) {
      // if we get a problem, log it
      log( "problem sending message", ex );

      // and send an error back to the client
      res.sendError( res.SC_INTERNAL_SERVER_ERROR, ex.getMessage() );
    }
  }
}

Java Interview Questions - 49

Q: Explain ServletContext.
A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.

Saturday, August 20, 2011

Java Interview Questions - 48

Q: What are the common mechanisms used for session tracking?
A: Cookies
SSL sessions
URL- rewriting

Java Servlet Buffering responses

package org.best.example;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

    // create 32K buffer
    res.setBufferSize( 32 * 1024 );

    pw.println( "everything we send now is buffered " );
    pw.println( "at the server until we reach the " );
    pw.println( "buffer size limit or we do a flush!" );

    // check to see if anything has been sent to the client
    if( res.isCommitted() ) {
      pw.println( "<br>damned, something has been sent" );
    }
    else {
      // clear the buffer, so what has gone before is lost
      res.resetBuffer();

      pw.println( "we are going to clear this as well" );

      // clears buffer, status codes and headers
      res.reset();

      // we've blanked the ContentType header so lets add it back
      res.setContentType( "text/html" );

      pw.println( "<br>but we are going to see this" );
    }

    // send what we have now
    res.flushBuffer();

    pw.println( "<br>and this will get flushed at the end of the method" );
    pw.println( "<br>current response buffer size is: " + res.getBufferSize() );
  }
}

Friday, August 19, 2011

Java Questions - 47

Q: Explain the directory structure of a web application.
A: The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.

WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory

Servlet Basic Authentication

package org.best.example;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Securing a web application with basic HTTP authentication
 * has been reduced to a configuration within web.xml
 *
 * to test: http://localhost/ack/servlet/protected/footie/get_time
 *
 <web-app>
 <servlet>
 <servlet-name>footie_time</servlet-name>
 <servlet-class>com.ack.web.servlet.BasicAuthenticationWebResource</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>footie_time</servlet-name>
 <url-pattern>/protected/footie/get_time</url-pattern>
 </servlet-mapping>
 <security-constraint>
 <web-resource-collection>
 <web-resource-name>protected_zone</web-resource-name>
 <url-pattern>/protected/footie/*</url-pattern>
 <http-method>GET</http-method>
 <http-method>POST</http-method>
 <http-method>PUT</http-method>
 <http-method>DELETE</http-method>
 <http-method>HEAD</http-method>
 <http-method>OPTIONS</http-method>
 <http-method>TRACE</http-method>
 </web-resource-collection>
 <auth-constraint>
 <role-name>footie</role-name>
 </auth-constraint>
 <user-data-constraint>
 <transport-guarantee>NONE</transport-guarantee>
 </user-data-constraint>
 </security-constraint>
 <login-config>
 <auth-method>BASIC</auth-method>
 <realm-name>pure genius football club</realm-name>
 </login-config>
 <security-role>
 <description>the footie guys</description>
 <role-name>footie</role-name>
 </security-role>
 </web-app>
 *
 * finally we need to map from the 'footie' role name to the
 * security principal with the application server, in weblogic
 * we do the following within the supporting weblogic.xml file:
 *
 *
 <weblogic-web-app>
 <security-role-assignment>
 <role-name>footie</role-name>
 <principal-name>cleve</principal-name>
 </security-role-assignment>
 </weblogic-web-app>
 */
public class BasicAuthenticationWebResource extends HttpServlet {
  public void doGet( HttpServletRequest req, HttpServletResponse res )
      throws ServletException, IOException {
    res.setContentType( "text/html" );
    PrintWriter pw = res.getWriter();

    pw.println( "<strong>21:00 @ The Wandle Centre, Wandsworth</strong>" );
    pw.println( "<br>don't be late!" );

  }
}

Thursday, August 18, 2011

Java Questions - 46

Q: What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.

An included Servlet

package org.best.example;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AnIncludedServlet extends HttpServlet {

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

    /**
     * note that a servlet that has been included within another
     * servlet has access to both the original request uri, servlet
     * path, path info, context path and query string through the
     * HttpServletRequest object.
     *
     * However it also has access to these values that can be different
     * depending on how the servlet include was dispatched.  The servlet
     * engine gives you access to these though request attributes as
     * demonstrated before.
     */

    pw.println( "<h1>The Included Servlet</h1>" );
    pw.println( "<br>request uri: " +
                req.getAttribute( "javax.servlet.include.request_uri" ) );
    pw.println( "<br>context path: " +
                req.getAttribute( "javax.servlet.include.context_path" ) );
    pw.println( "<br>servlet path: " +
                req.getAttribute( "javax.servlet.include.servlet_path" ) );
    pw.println( "<br>path info: " +
                req.getAttribute( "javax.servlet.include.path_info" ) );
    pw.println( "<br>query string: " +
                req.getAttribute( "javax.servlet.include.query_string" ) );
  }
}

Wednesday, August 17, 2011

Java Interview Questions - 45

Q: Explain the life cycle methods of a Servlet.
A: The javax.servlet.Servlet interface defines the three methods known as life-cycle method.

public void init(ServletConfig config) throws ServletException

public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException

public void destroy()

First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.

The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.

Accessing a data source from a servlet

package org.best.example;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * web.xml configuration part of the a data source
 *
 *  <web-app>
 ...
 <resource-ref>
 <description>the database for this app</description>
 <res-ref-name>jdbc/thedatabase</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>CONTAINER</res-auth>
 </resource-ref>
 ...
 </web-app>
 *
 * the vendor-specific mapping of the res-ref-name into their
 * own application server space, eg weblogic does the following
 * in a weblogic.xml file
 *
 <weblogic-web-app>
 ...
 <reference-descriptor>
 ...
 <resource-description>
 <res-ref-name>jdbc/thedatabase</res-ref-name>
 <jndi-name>jdbc/gangland</jndi-name>
 </resource-description>
 ...
 </reference-descriptor>
 ...
 </weblogic-web-app>
 */

public class AccessingADataSourceFromAServlet extends HttpServlet {

  public void init() {
    System.out.println( "### loading -> " + getServletName() + " at " +
                        new Date( System.currentTimeMillis() ).toString() );

  }

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

    Connection con = null;
    try {
      Context ctx = new InitialContext();
      DataSource ds = (DataSource) ctx.lookup( "java:comp/env/jdbc/thedatabase" );
      con = ds.getConnection();
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery( "select * from enemies" );
      while( rs.next() ) {
        pw.println( rs.getString( "name" ) + "<br>" );
      }
    }
    catch( Exception ex ) {
      log( "problem accessing database", ex );
      res.sendError( res.SC_INTERNAL_SERVER_ERROR, ex.getMessage() );
    }
    finally {
      if( con != null ) {
        try {
          con.close();
        }
        catch( SQLException ex ) {
          log( "problem closing connection", ex );
        }
      }
    }
  }
}

Tuesday, August 16, 2011

Remove all values from Java LinkedHashMap

package org.best.example;

    /*
      Remove all values from Java LinkedHashMap example
      This Java Example shows how to remove all values from LinkedHashMap object or empty
      LinkedHashMap or clear LinkedHashMap using clear method.
    */
    
    import java.util.LinkedHashMap;
    
    public class EmptyLinkedHashMapExample {
    
    public static void main(String[] args) {
    
    //create LinkedHashMap object
    LinkedHashMap lHashMap = new LinkedHashMap();
    
    //add key value pairs to LinkedHashMap
    lHashMap.put("1","One");
    lHashMap.put("2","Two");
    lHashMap.put("3","Three");
    
    /*
      To remove all values or clear LinkedHashMap use
      void clear method() of LinkedHashMap class. Clear method removes all
      key value pairs contained in LinkedHashMap.
      */
    
    lHashMap.clear();
    
    System.out.println("Total key value pairs in LinkedHashMap are : "
    + lHashMap.size());
    }
    }
    
    /*
    Output would be
    Total key value pairs in LinkedHashMap are : 0
    */

Java Questions - 44

Question: What do you understand by Synchronization?
Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}

Monday, August 15, 2011

Iterate through the values of Java LinkedHashMap

package org.best.example;

    /*
      Iterate through the values of Java LinkedHashMap example
      This Java Example shows how to iterate through the values contained in the
      LinkedHashMap object.
    */
    
    import java.util.Collection;
    import java.util.LinkedHashMap;
    import java.util.Iterator;
    
    public class IterateValuesOfLinkedHashMapExample {
    
    public static void main(String[] args) {
    
    //create LinkedHashMap object
    LinkedHashMap lHashMap = new LinkedHashMap();
    
    //add key value pairs to LinkedHashMap
    lHashMap.put("1","One");
    lHashMap.put("2","Two");
    lHashMap.put("3","Three");
    
    /*
      get Collection of values contained in LinkedHashMap using
      Collection values() method of LinkedHashMap class
      */
    Collection c = lHashMap.values();
    
    //obtain an Iterator for Collection
    Iterator itr = c.iterator();
    
    //iterate through LinkedHashMap values iterator
    while(itr.hasNext())
    System.out.println(itr.next());
    }
    }
    
    /*
    Output would be
    One
    Two
    Three
    */

Java Questions - 43

Question: Name the containers which uses Border Layout as their default layout?
Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog classes.