Wednesday, November 7, 2007

J2EE - Vinyl Handler Servlet

/*
The VinylHandler Servlet allows a user to add a Vinyl to the collection and lists their current collection in a tabular format. A Vinyl record contains:
1. Title
2. Artist
3. Genre
4. Year
5. Playing Time
When a new Vinyl is submitted via the JSP page, the Servlet creates a corresponding Vinyl object, which is added to the session and a java.util.List object contains all Vinyls in the session. Accordingly, the table of existing Vinyls are then built by retrieving all Vinyl objects from the session and generating HTML for each Vinyl, while following the MVC (“Model 2”) architecture. Additionally, allowing all individual Vinyls to be deleted and modified from the list. The modification UI is provided using a separate JSP page.

Next, a new “generate report” feature was added, which provides a read-only printer-friendly view of the Vinyls currently in the collection. The generate report button is on the same page as the one allowing the user to add a Vinyl. The Servlet generates and returns an XML file in the HttpServletResponse, following the correct media (MIME) type. The XML also contains a processing instruction so that the browser will apply the xslt stylesheet Vinyls.xsl.

Next, an option to sort lists by genre, artist, year, or none (order added) was added, before generating a report. The JSP page defines a new page for editing a single Vinyl and uses the bean tag syntax to access the active Vinyl object from the session. It then sets the values of appropriate form controls according to the current values of the Vinyl, again, using bean tag syntax. An update button is provided that submits the form back to the controller Servlet.

Finally, the list of Vinyls are stored in the database where the application acquires a DataSource via JNDI in the Servlet.
*/

@SuppressWarnings("unchecked")
public class VinylHandler extends HttpServlet {
// -----------------------------------------------------------------------------
private DataSource dataSource;
// -----------------------------------------------------------------------------
/**
* Initializes VinylHandler, loads the database driver and establishes a connection.
* @param conf servlet configuration
* @Override
*/
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup("java:comp/env");
dataSource = (DataSource)envCtx.lookup("jdbc/MyCDDB");
} catch (NamingException e) {e.printStackTrace();}
} // End init().
// -----------------------------------------------------------------------------
/**
* Grabs a connection from the pool.
* @return dataSource A connection to the database.
* @throws SQLException
*/
private Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
// -----------------------------------------------------------------------------
/**
* Processes requests for both HTTP GET and POST methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection connection = null; Statement statement = null;
HttpSession session = request.getSession();
if(session == null){response.sendRedirect("error.html");}
ArrayList vinylList = (ArrayList)session.getAttribute("vintlList");
if (vinylList == null) {
vinylList = new ArrayList();
session.setAttribute("vintlList", vinylList);
} // End if.
// An XML serializer.
LSSerializer writer = null;
// The DOM document.
Document document = null;
// Instantiate a vinyl object.
Vinyl record = null;
// Query.
String query = null;
// ID.
Integer vinylID = null;
System.out.println("--------------------------------------------------------I am here!!!!!!!!!!!!!!!!!!!!!");
// Retrieve the action parameter.
String action = request.getParameter("action");
// -----------------------------------------------------------------------------
if (action.equals("LOGIN")) {
// Retrieve the username.
String username = request.getParameter("username");
System.out.println("--------------------------------------------------------Test: The username is " + username);
// Place a reference to this user in the session.
session.setAttribute("username", username);
// Retrieve remaining login info.
String password = request.getParameter("password");
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
try{
// Establish a connection to the database.
connection = getConnection();
// Create a statement for executing queries.
statement = connection.createStatement();
// Enter user into the database.
/* NOTE: No check is performed to see if the user currently exists or
whether the info was entered correctly */
query = "INSERT INTO Flewwelling_UserTable VALUES ('" + username + "', '"
+ password + "', '"
+ firstname + "', '"
+ lastname + "')";
statement.executeUpdate(query);
// Close connection.
connection.close();
} catch(SQLException sqle) {System.err.println("Error with connection: " + sqle);
} finally {
if (connection != null)
try {connection.close();} catch (SQLException e) {}
}
// -----------------------------------------------------------------------------
// ADD vinyl to the collection.
} else if (action.equals("ADD")) {
// Increment the vinyl id.
vinylID = (Integer)session.getAttribute("vinylID");
// Determine if new session.
if(vinylID != null){
// Increment the vinylID.
vinylID++;
// Store the vinyl id for this session.
session.setAttribute("vinylID", vinylID);
}
// Retrieve the record.
record = getVinyl(request);
// Add first record to the list.
vinylList.add(record);
// Retrieve the new vinylID.
vinylID = (Integer)record.getID();
// Store the vinyl id for this session.
session.setAttribute("vinylID", vinylID);
System.out.println("----------------------------------------------------Test: The vinylID for ADD is " + vinylID);

try{
// Establish a connection to the database.
connection = getConnection();
// Create a statement for executing queries.
statement = connection.createStatement();
// Retrieve the username.
String user = (String)session.getAttribute("username");
// Insert record into the database.
query = "INSERT INTO Flewwelling_VinylTable VALUES ('" + user + "', '"
+ record.getID() + "', '"
+ record.getTitle() + "', '"
+ record.getArtist() + "', '"
+ record.getGenre() + "', '"
+ record.getYear() + "', '"
+ record.getDuration() + "')";
statement.executeUpdate(query);
// Close connection.
connection.close();
} catch(SQLException sqle) {System.err.println("Error with connection: " + sqle);
} finally {
if (connection != null)
try {connection.close();} catch (SQLException e) {}
}
// -----------------------------------------------------------------------------
// Delete vinyl from the collection.
} else if (action.equals("DELETE")) {
// Retrieve the delete index param.
String delete = request.getParameter("delindex");
// Convert to an integer used as an index to access the record in the list.
int d = (new Integer(delete)).intValue();
//Retrieve the record before deletion.
record = vinylList.get(d);
// Remove Vinyl.
vinylList.remove(d);
try {
// Establish a connection to the database.
connection = getConnection();
// Create a statement for executing queries.
statement = connection.createStatement();
// Retrieve the username for the session.
String user = (String)session.getAttribute("username");
// Delete the specified record from the database.
query = "DELETE FROM Flewwelling_VinylTable WHERE UserID = '" + user + "' and VinylID = '"
+ record.getID() + "'and Title = '"
+ record.getTitle() + "' and Artist = '"
+ record.getArtist() + "' and Genre = '"
+ record.getGenre() + "' and Year = '"
+ record.getYear() + "' and Duration = '"
+ record.getDuration() + "'";
statement.executeUpdate(query);
// Close connection.
connection.close();
} catch(SQLException sqle) {System.err.println("Error with connection: " + sqle);
} finally {
if (connection != null)
try {connection.close();} catch (SQLException e) {}
}
// -----------------------------------------------------------------------------
// Modify vinyl entry.
} else if (action.equals("EDIT")) {
// Retrieve edit index param.
String edit = request.getParameter("editindex");
// Convert to an integer used as an index to access the record in the list.
int index = (new Integer(edit)).intValue();
// Retrieve the specified record.
record = vinylList.get(index);
// Place a reference to this Vinyl object in the session.
session.setAttribute("record", record);
// Forward request to Modify.jsp.
String url = "/Modify.jsp";
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(request, response);
return;
// -----------------------------------------------------------------------------
// Update the vinyl in the collection.
} else if (action.equals("UPDATE")) {
// Retrieve modify index param.
String update = request.getParameter("modindex");
// Convert to an integer used as an index to access the record in the list.
int pointer = (new Integer(update)).intValue();
// Retrieve the vinyl id.
//vinylID = (Integer)request.getSession().getAttribute("vinylID");
System.out.println("----------------------------------------------------Test: The vinylID for UPDATE is " + vinylID);
// Retrieve the modified record.
record = getVinyl(request);
System.out.println("----------------------------------------------------Updated record: " +record.getTitle()+" "+record.getArtist()+" "+record.getGenre()+" "+record.getYear()+" "+record.getDuration());
// Replace the modified record with the exisiting one.
vinylList.set(pointer, record);
// Retrieve the old record.
Vinyl oldRecord = (Vinyl)session.getAttribute("record");
System.out.println("----------------------------------------------------Unmodified record: " +oldRecord.getTitle()+" "+oldRecord.getArtist()+" "+oldRecord.getGenre()+" "+oldRecord.getYear()+" "+oldRecord.getDuration());
try {
// Establish a connection to the database.
connection = getConnection();
// Create a statement for executing queries.
statement = connection.createStatement();
// Retrieve the username.
String user = (String)session.getAttribute("username");
// Modify the specified record.
query = "UPDATE Flewwelling_VinylTable SET UserID = '" + user + "', VinylID = '"
+ oldRecord.getID() + "', Title = '"
+ record.getTitle() + "', Artist = '"
+ record.getArtist() + "', Genre = '"
+ record.getGenre() + "', Year = '"
+ record.getYear() + "', Duration = '"
+ record.getDuration() + "' WHERE UserID = '"
+ user + "' and VinylID = '"
+ oldRecord.getID() + "' and Title = '"
+ oldRecord.getTitle() + "' and Artist = '"
+ oldRecord.getArtist() + "' and Genre = '"
+ oldRecord.getGenre() + "' and Year = '"
+ oldRecord.getYear() + "' and Duration = '"
+ oldRecord.getDuration() + "'";
statement.executeUpdate(query);
// Close connection.
connection.close();
} catch(SQLException sqle) {System.err.println("Error with connection: " + sqle);
} finally {
if (connection != null)
try {connection.close();} catch (SQLException e) {}
}
// -----------------------------------------------------------------------------
// Generate the collection.
} else if (action.equals("GENERATE")) {
try {
// Get an instance of the DOMImplementation registry.
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
// Get a DOM level 3 implementation.
DOMImplementation domImplementation = registry.getDOMImplementation("XML 3.0");
if (domImplementation == null) { // can't proceed -- config error
throw new RuntimeException ("No DOM 3.0 implementation found in classpath");
}
// Get an XML serializer.
if (domImplementation.hasFeature ("LS", "3.0")) {
writer = ((DOMImplementationLS) domImplementation.getFeature ("LS", "3.0")).createLSSerializer ();
} else { // can't proceed -- config error
throw new RuntimeException ("DOM implementation does not support serialization");
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
domImplementation = db.getDOMImplementation();

String qualifiedName = "cdlist";
String publicId = "-//j2ee dalcte//cd list//EN";
String systemId = "CDList.dtd";

// Create the DocumentType using DOMImplementation.createDocumentType.
DocumentType documentType = domImplementation.createDocumentType(qualifiedName, publicId, systemId);
// Create the Document, passing the DocumentType object to the DOMImplementation.createDocument method.
document = domImplementation.createDocument(null, documentType.getName(), null);
} catch (ClassNotFoundException ce) {
throw new RuntimeException (ce);
} catch (InstantiationException ie) {
throw new RuntimeException (ie);
} catch (IllegalAccessException ie) {
throw new RuntimeException (ie);
}catch(ParserConfigurationException pce) {System.out.println("Error while trying to instantiate DocumentBuilder " + pce);}
// Perform processing instruction.
ProcessingInstruction myPI = document.createProcessingInstruction("xml-stylesheet","type=\"text/xml\" href=\"CDs.xsl\"");
// Create root element - cdList.
Element cdlist = document.getDocumentElement();
// Insert before.
document.insertBefore(myPI, cdlist);
// -----------------------------------------------------------------------------
// Determine the desired sorting order and insert the order as an attribute in the root element.
String sortorder = request.getParameter("sortorder");
if(sortorder != null){
if(sortorder.equals("artist"))
{
System.out.println("----------sortby artist----------");
}
else if (sortorder.equals("genre")){System.out.println("----------sortby genre----------");}
else if (sortorder.equals("year")){System.out.println("----------sortby year----------");}
else {System.out.println("----------sortby order added----------");}
}
else{System.out.println("----------Note: No sorting order!----------");}
cdlist.setAttribute("sortorder", sortorder);
// -----------------------------------------------------------------------------
// Instantiate an iterator which points to the vinyl list.
Iterator it = vinylList.iterator();
while(it.hasNext()){
Vinyl cdz = (Vinyl)it.next();
Element cdElement = createCDElement(document, cdz);
cdlist.appendChild(cdElement);
} // End while.

// Set content type.
response.setContentType("text/xml");
// Serialize document to a String.
String str = writer.writeToString(document);
OutputStream out = response.getOutputStream () ;

PrintWriter pw = new PrintWriter(out);
pw.print(str);
pw.flush();
return;
} // End GENERATE.
// -----------------------------------------------------------------------------
String url = "/VinylInterface.jsp";
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(request, response);
} // End processRequest().
/**
* Returns a Vinyl object.
* @param request Servlet request.
* @param id The id of the specified record.
* @return record A Vinyl object.
*/
private Vinyl getVinyl(HttpServletRequest request) {
Integer index = 0;
Integer vinylID = (Integer)request.getSession().getAttribute("vinylID");
System.out.println("--------------------------------------------------------The id for getVinyl() " + vinylID);
if (vinylID == null){
// Retrieve the username for this session.
String s = (String)request.getSession().getAttribute("username");
System.out.println("----------------------------------------------------The username for this session is " + s);
// Call getTableIndex() to retrieve the index and determine if user already exists in the database.
index = getTableIndex(s);
// Increment the index.
index++;
} else { index = vinylID; }

// Create a new Vinyl Instance.
Vinyl record = new Vinyl(index,
request.getParameter("title"),
request.getParameter("artist"),
request.getParameter("genre"),
request.getParameter("year"),
request.getParameter("duration"));
// Return the Vinyl.
return record;
} // End getVinyl().

/**
* Returns the max index in the list for the specified user.
* @param UserId The username of the specified user.
* @return result The greatest index(VinylID) in the list for the specified user.
*/
private Integer getTableIndex(String UserID){
Integer result = 0;
try {
// Establish a connection to the database.
Connection connection = getConnection();
// Create a statement for executing queries.
Statement statement = connection.createStatement();
// query.
String query = "SELECT VinylID FROM Flewwelling_VinylTable WHERE UserID = '" + UserID + "'";
ResultSet rs = statement.executeQuery(query);

if(rs.last()){
if(rs.getString("VinylID") == null){return new Integer(0);}
result = new Integer(rs.getString("VinylID"));
}
// Close connection.
connection.close();

} catch(SQLException e) {System.err.println("Unable to get max index: " + e.getMessage());
result = null;
}
return result;
}

/**
* Builds the DOMTREE and returns a Vinyl element.
* @param document The document.
* @param cdz A vinyl object.
* @return cd A Vinyl element.
*/
private Element createCDElement(Document document, Vinyl cdz){
Element cd = document.createElement("cd");
Element title = document.createElement("title");
title.appendChild(document.createTextNode(cdz.getTitle()));
cd.appendChild(title);

Element artist = document.createElement("artist");
artist.appendChild(document.createTextNode(cdz.getArtist()));
cd.appendChild(artist);

Element genre = document.createElement("genre");
genre.appendChild(document.createTextNode(cdz.getGenre()));
cd.appendChild(genre);

Element year = document.createElement("year");
year.appendChild(document.createTextNode(cdz.getYear()));
cd.appendChild(year);

Element duration = document.createElement("duration");
duration.appendChild(document.createTextNode(cdz.getDuration()));
cd.appendChild(duration);

return cd;
} //End createCDElement.
// -----------------------------------------------------------------------------
//
/**
* Handles the HTTP GET method.
* @param request servlet request
* @param response servlet response
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*/
@Override
public String getServletInfo() {
return "Short description";
}
//

} // End VinylHandler.

J2EE - Vinyl Object

// -----------------------------------------------------------------------------
package myVinylCollection;
// -----------------------------------------------------------------------------
import java.util.*;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
// -----------------------------------------------------------------------------
/**
* A Vinyl record. Individual tracks are not represented.

*/

public class Vinyl implements java.io.Serializable {
private String title, artist, genre, year, duration;
private int id;
/**
* Creates a new Vinyl object, with the given values.
*@param title the Vinyl title
*@param artist the artist/creator of the Vinyl content
*@param genre a categorization of the content
*@param year the year the content was first published
*@param duration the total duration of the recording
*/
public Vinyl (int id, String title, String artist, String genre, String year, String duration) {
this.id = id; this.title = title; this.artist = artist; this.genre = genre; this.year = year; this.duration = duration;
}
/**
* Creates a new, uninitialized Vinyl object.
*/
public Vinyl () {
title = artist = genre = year = duration = "UNDEFINED";
id = -1;
}

// JavaBean interface
// defines RW properties: title, artist, genre, year, duration
public String getTitle () { return title; }
public void setTitle (String newTitle) { title = newTitle; }

public String getArtist () { return artist; }
public void setArtist (String newArtist) { artist = newArtist; }

public String getGenre () { return genre; }
public void setGenre (String newGenre) { genre = newGenre; }

public String getYear () { return year; }
public void setYear (String newYear) { year = newYear; }

public String getDuration () { return duration; }
public void setDuration (String newDuration) { duration = newDuration; }

public int getID () { return id; }
public void setID (int newID) { id = newID; }

}

Monday, October 22, 2007

Java Handy Quick Reference

/************************************************************************
* *
* Reserved Words: *
* *
* Java: *
* abstract else long switch *
* boolean extends native synchronized *
* break final new this *
* byte finally null throw *
* case float package throws *
* catch for private transient *
* char if protected try *
* class implements public void *
* continue import return volatile *
* default instanceof short while *
* do int static *
* double interface super *
* *
* Reserved but not supported: *
* const goto *
* *
* C Not Used: *
* auto extern sizeof union *
* entry register struct unsigned *
* enum signed typedef *
* *
* C++ Not Used: *
* delete friend inline operator *
* *
************************************************************************/

/************************************************************************
* *
* Core Java Classes: *
* *
* java.applet java.rmi *
* java.awt java.rmi.dgc *
* java.awt.datatransfer java.rmi.registry *
* java.awt.event java.rmi.server *
* java.awt.image java.security *
* java.beans java.security.acl *
* java.io java.security.interfaces *
* java.lang java.sql *
* java.lang.reflect java.text *
* java.math java.util *
* java.net java.util.zip *
* *
* #java.awt.color #java.beans.beancontext *
* #java.awt.dnd #java.lang.ref *
* #java.awt.font #java.rmi.activation *
* #java.awt.geom #java.security.cert *
* #java.awt.im #java.security.spec *
* #java.awt.image.renderable #java.util.jar *
* #java.awt.print *
* *
* #javax.accessibility #javax.swing.plaf.multi *
* #javax.swing #javax.swing.table *
* #javax.swing.border #javax.swing.text *
* #javax.swing.colorchooser #javax.swing.text.html *
* #javax.swing.event #javax.swing.html.parser *
* #javax.swing.filechooser #javax.swing.text.rtf *
* #javax.swing.plaf #javax.swing.tree *
* #javax.swing.plaf.basic #javax.swing.undo *
* #javax.swing.plaf.metal *
* *
* #org.omg.CORBA #org.omg.CORBA.portable *
* #org.omg.CORBA.DynAnyPackage #org.omg.CORBA.TypeCodePackage *
* #org.omg.CORBA.ORBPackage #org.omg.CosNaming *
* #org.omg.CosNaming.NamingContextPackage *
* *
************************************************************************/

// pointer, struct, enum, and union not supported in java
// global variables and functions not supported in java

/************************************************************************
* *
* Documentation Comments: *
* *
************************************************************************/
/**
*
* @author document the author of the code
* @deprecated indicates the class/method has been superceeded with a new form
* @exception document the exceptions that can be thrown and the circumstances
* (@link) insert an inline link
* @param describes the parameters for a method
* @return describes the value returned for a method
* @see cross reference another part of code or url address
* @serial comment for default serializable field
* @serialData description for sequences and types of data
* @serialField description for serial fields
* @since add a since heading to docs
* @throws same as @exception
* @version document the current version of the code
*
* HTML tags can be interspersed in the comments, except H1 and H2
* Use javadoc to extract the documentation comments
*
*/

/************************************************************************
* *
* Package Definition: *
* *
************************************************************************/
package Test.Chris; // SET ClassPath=e:\java (package is in e:\java\Test\Chris\*.java)

/************************************************************************
* *
* Import References: *
* *
************************************************************************/
import java.awt.event.*; // allow simple access to classes within package without full name

/************************************************************************
* *
* Classes: *
* *
************************************************************************/
public class Syntax {

/*********************************************************************
* *
* Properties: *
* *
*********************************************************************/
// instance variables (properties) default to 0, false, or null
static final double PI = 3.14; // constant - final means var can't be modified
static int objcount = 0; // one variable shared by all instances of the class
int xpack; // visible to any class in same package (no access attribute)
public int xpub; // visible to any class anywhere
private int xpriv; // not visible outside of current class
protected int xprot; // visible to any class in same package or from any subclass anywhere
// private protected int xprivprot; // visible only to subclass
Square xd = new Square(2.0); // objects can be allocated outside of methods

{ // initialization code block - after super constructor
xpack = 1;
System.out.println("init");
}

static { // static initialization block - at time the class is first loaded
objcount = 0;
System.out.println("Static init");
}

/*********************************************************************
* *
* Application Entry Point: *
* *
*********************************************************************/
public static void main(String[] args) {

// stream io
System.out.println("Hello World!");
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}

// make an instance of this class
Syntax syntax_obj = new Syntax();

syntax_obj = null;

// try a different constructor
syntax_obj = new Syntax("Hello");
}

/*********************************************************************
* *
* Constructors: *
* *
*********************************************************************/
Syntax() {
// constructors do not return a value and have the same name as the class
// exercise();

Java_lang x0 = new Java_lang();
x0.exercise();

Java_lang_reflect x1 = new Java_lang_reflect();
x1.exercise();

Java_math x2 = new Java_math();
x2.exercise();

Test.Chris.Java_io x3 = new Test.Chris.Java_io();
x3.exercise();

Test.Chris.Java_util x4 = new Test.Chris.Java_util();
x4.exercise();

Test.Chris.Java_util_zip x5 = new Test.Chris.Java_util_zip();
x5.exercise();

Test.Chris.Java_text x6 = new Test.Chris.Java_text();
x6.exercise();

//Test.Chris.Java_sql x7 = new Test.Chris.Java_sql();
//x7.exercise();

//Test.Chris.Java_net x8 = new Test.Chris.Java_net();
//x8.exercise();

//Test.Chris.Java_security x9 = new Test.Chris.Java_security();
//x9.exercise();

InnerClass x10 = new InnerClass();

OuterClass x11 = new OuterClass();
}

Syntax(String s) {
Java_awt x12 = new Java_awt();
x12.exercise();
System.exit(0); // awt leaves some stranded threads
}

/*********************************************************************
* *
* Finalize: *
* *
*********************************************************************/
protected void finalize() {
// finalize called after object goes out of scope and the garbage collection is performed (useless!)
System.out.println("finalize");
try {
super.finalize(); // should call super finalize since it is not chained like constructors
} catch(Throwable e) {
}
}

/*********************************************************************
* *
* Exercise: *
* *
*********************************************************************/
public void exercise() {
int i;
double x;

types();
operators();
flow();
arrays();
i = factorial(5);
i = max(5, 3);
x = max(5.0, 3.0);
exceptions();
}

/*********************************************************************
* *
* Primitive Variable Types: *
* *
*********************************************************************/
private void types() { // local variables are not automatically initialized
byte a; // 8-bit signed
short b; // 16-bit signed
int c; // 32-bit signed
long d; // 64-bit signed
char e; // 16-bit unicode
boolean f; // true|false
float x; // 32-bit ieee
double y; // 64-bit ieee

{
int z = 3; // variable scope is limited to block in which it is declared
}

int i = 0; // initialize when declared
int j = i - 1; // autoinit may contain expressions

a = 1; // int constant
b = 07; // octal notation
c = 0xF; // hex notation
d = 2L; // long constant
e = 'a'; // character constant
f = true; // boolean constant
x = 3;
x = 4.0F; // float constant
y = 4.0E2; // scientific notation

x = 9.99F;
x = -9.99F;
y = 1.0;
y = 2.0;
y = 3.0;
y = 4.0;
y = 5.0;
y = 6.0;
y = 7.0;
y = 8.0;
y = 9.0;
y = 10.0;
y = 20.0;
y = 100.0;
y = 9.99;

e = '\001'; // octal ascii code
e = '\u0001'; // hex unicode character (www.unicode.com)
e = '\b'; // backspace
e = '\f'; // form feed
e = '\n'; // new line
e = '\r'; // carriage return
e = '\t'; // tab
e = '\''; // single quote
e = '\"'; // double qoute
e = '\\'; // backslash

// java does less auto-casting than C++
a += 1; // combined operators not require cast
a = (byte)(a + 1); // all byte/short math is done in int - plus (+) autocasts to int
a = (byte)b;
a = (byte)c;
a = (byte)d;
a = (byte)e;
a = (byte)x;
a = (byte)y;

b = a;
b = (short)(b + 1);
b = (short)c;
b = (short)d;
b = (short)e;
b = (short)x;
b = (short)y;

c = a;
c = b;
c = (c + 1);
c = (int)d;
c = e;
c = (int)x; // truncation on the floating point numbers
c = (int)y;

d = a;
d = b;
d = c;
d = d;
d = e;
d = (long)x;
d = (long)y;

e = (char)a;
e = (char)b;
e = (char)c;
e = (char)d;
e = (char)(e + 1);
e = (char)x;
e = (char)y;

f = !false; // can't cast other types to or from boolean type

x = a;
x = b;
x = c;
x = d;
x = e;
x = (x + 1);
x = (float)y;

y = a;
y = b;
y = c;
y = d;
y = e;
y = x;
y = y + 1;
}

/*********************************************************************
* *
* Operators: *
* [] array subscript >= greater than or equal *
* . class member == equal *
* ! logical not != not equal *
* ~ one's complement & bitwise and / logical and*
* + unary plus ^ bitwise xor *
* - unary minus | bitwise or *
* ++ increment && logical and *
* -- decrement || logical or *
* (type) type cast ?: conditional if?then:else *
* new new = assign *
* * multiply *= compound assign *
* / divide /= *
* % modulus %= *
* + add += *
* - subtract -= *
* << left shift &= *
* >> right shift ^= *
* >>> |= *
* instanceof <<= *
* < less than >>= *
* <= less than or equal >>>= *
* > greater than , comma *
* *
*********************************************************************/
private void operators() {
boolean b;
int i;
int j;
byte k = 10;
float x;
String s = "Test";

i = 1; // simple asignment: i = 1;
i = j = 3; // compound assignment: j = 3; i = j;
i = (j = 1) + 2; // parenthesis precedence: j = 1; i = j + 2;

i = 3 + 2; // add: i = 5;
i = (3) % (2); // mod: i = 2;

x = (int)3.14; // cast operator: i = 3;
x = 2 / 3; // integer divide: x = 0
k = (byte)-k; // unary plus/minus always converts byte/short/char to an int

i = ++j; // pre-increment: j = j + 1; i = j;
i = --j; // pre-decrement: j = j - 1; i = j;
i = j++; // post-increment: i = j; j = j + 1;
i = j--; // post-increment: i = j; j = j - 1;

// compound assignment operators - always does autocast
i += j; // i = i + j;
i -= j; // i = i - j;
i *= j; // i = i * j;
i /= j; // i = i / j;
i %= j; // i = i % j;
i <<= j; // i = i << j;
i >>= j; // i = i >> j;
i >>>= j; // i = i >>> j;
i &= j; // i = i & j;
i ^= j; // i = i ^ j;
i |= j; // i = i | j;

// only boolean var may receive boolean op result
b = (i == 0); // equal
b = (i < j); // less than
b = (i <= j); // less than or equal
b = (i > j); // greater than
b = (i >= j); // greater than or equal
b = (i != j); // not equal

b = !b; // not operator
b = ((i > 0) && (i < j)); // logical and
b = ((i > 0) || (i < j)); // logical or
b = ((i > 0) & (i < j)); // logical and - always perform both tests
b = ((i > 0) | (i < j)); // logical or - always perform both tests

i = j & 1; // bitwise and
i = j ^ 1; // bitwise xor
i = j | 1; // bitwise or

b = (s instanceof String); // test if object is an instance of a class (null returns false)
}

/*********************************************************************
* *
* Flow Control: *
* *
*********************************************************************/
private boolean flow() {
int i = 10;
int j = 10;
boolean b = true;

if (b) { // if then else
j = 1;
} else {
j = 2;
}

while (i != 0) { // while loop
i = i - 1;
if (b) continue;
break;
}

do { // do while loop
i = i + 1;
if (b) continue;
break;
} while (i < 10);

for (i = 0; i < 4; i++) { // for loop - comma operator allowed in initialize and increment
j = j + 1; // variables can be scoped within loop
if (b) continue; // if conditional expression omitted evaluates to true
break;
}

switch (i) { // switch case - expression type must be byte/char/short/int
case 0:
j = 1;
break;
default:
j = 3;
break;
}

Outer: // break outer
{
i = i - 1;
if (b) {
break Outer;
}
j = j - 1;
}

return(true); // exit function with return value
}

/*********************************************************************
* *
* Arrays: *
* *
*********************************************************************/
private void arrays() {
int i;
int[] a; // can also be declared as: int a[];
int[] b = new int[20];
int[][] c;
int[][] d = new int[10][20];
int[] primes = {2, 3, 5, 7, 11, 13, 17,};

a = new int[10];
System.arraycopy(primes, 0, a, 0, 2);

for (i = 0; i < a.length; i++) a[i] = i;

d = new int[10][]; // multidimensional arrays do not have to be rectangular
for (i = 0; i < d.length; i++) d[i] = new int[i+1];
}

/*********************************************************************
* *
* Methods: *
* *
*********************************************************************/
private int factorial(int n) { // methods must always specify a return value (can be void)
if (n == 1) {
return (1);
} else {
return (n * factorial(n-1));
}
}

static int sfactorial(int n) { // static methods belong to class - can be called with no instance
if (n == 1) { // i = Syntax.sfactorial(n);
return (1); // static methods are implicitly final - no override allowed
} else {
return (n * sfactorial(n-1));
}
}

/*********************************************************************
* *
* Method Overloading: *
* *
*********************************************************************/
private int max(int a, int b) { // method overloading is resolved at compile time
if (a >= b) { // method of derived class always overrides - no matter how accessed
return a; // all function parameters are passed by value
} else {
return b;
}
}

private double max(double a, double b) {
if (a >= b) {
return a;
} else {
return b;
}
}

/*********************************************************************
* *
* Exceptions: *
* *
*********************************************************************/
private void exceptions(){
int i = 10;
int[] a = new int[10];

// all standard exceptions are covered by two direct subclasses of Throwable
// - Error: catastrophic errors that usually have no recovery
// - Exception: must catch or register throws (except for subclasses of RuntimeException)

try {
a[i] = i;
} catch (IndexOutOfBoundsException e) {
} catch (Exception e) { // catch order should be from lowest subclass to highest superclass
//System.out.println(e.toString());
} finally { // this block will always be executed even when no exception
}

try { // methods that register throws require catch or register
throwMe();
} catch (Exception e) {
//System.out.println(e.toString());
} catch (Throwable e) {
//System.out.println(e.toString());
}

try { // can also be used to perform operations if return executed
return;
} finally { // break/continue/return/throw statement will cause forget of branch
}
}

// if registered exceptions are not caught they must be registered as throws
private void throwMe() throws java.io.FileNotFoundException, ChrisException {
try {
java.io.InputStream ios = new java.io.FileInputStream("Syntax.java");
} catch (java.io.FileNotFoundException e) {
throw e; // exception can be rethrown - pass it up to calling method
}
throw new ChrisException("User Defined Exception");
}

// user defined exception
class ChrisException extends Throwable {
ChrisException() {
}

ChrisException(String s) {
super(s);
}
}


/*********************************************************************
* *
* Inner Classes: *
* *
*********************************************************************/
public class InnerClass {
int a; // static vars not allowed in inner classes
public int b;
private int c;

InnerClass() {
InnerInnerClass xa = new InnerInnerClass();

// anonymous class - extends class - no constructors allowed
Object xb = new Object() {
public String toString() {
System.out.println("Hello Anonynomous");
return super.toString();
}
};

xb.toString();
}

public class InnerInnerClass {
int a;
public int b;
private int c;

InnerInnerClass() {
a = 0;
}
}
}
}

/************************************************************************
* *
* Outer Classes: *
* *
************************************************************************/
class OuterClass { // outer class can not be declared public
static final double PI = 3.14;
static int objcount = 0;
int xpack;
public int xpub;
private int xpriv;
protected int xprot;

OuterClass() {
int i;
double x;
String s;

XShape x1;
XShape x2;
XShape x3;
XShape x4;
XShape x5;
XRectangle xa;
Convert xb;

x1 = new XRectangle(3.0, 4.0);
x2 = new Square(3.0);
x3 = new Triangle(1.0, 2.0, 3.0);
x4 = new Circle(4.0);
x5 = new EquilateralTriangle(5.0);

xa = (XRectangle)x2; // polymorphism - base class object can point to any derived class
x2 = xa; // assigning object to super class does not require casting

x = x1.area(); // appropriate method for the subclass instance is called
i = x2.sides; // superclass variables can only access variables and methods
s = x3.toString(); // that exist at the superclass level of the variable

xb = (Convert)x4; // polymorphism - interface var can point to any class that implements
x = xb.inchToMM();

//System.out.println(x1.toString() + " " + x2.toString() + " " + x3.toString() + " " +
// x4.toString() + " " + x5.toString());
}

// inner class objects outside of class can be created only in context of the top level class
OuterClass(String s) {
Syntax xa = new Syntax();
Syntax.InnerClass xb = xa.new InnerClass();
Syntax.InnerClass.InnerInnerClass xc = xb.new InnerInnerClass();
}
}

/************************************************************************
* *
* SubClasses: *
* *
************************************************************************/
abstract class XShape { // abstract class can not be alocated - serves as subclass template
String name;
int sides = 0; // subclasses inherit all fields and methods not defined as private

XShape(int sides) {
this.sides = sides;
}

abstract double area(); // abstract requires all subclasses to define this method

abstract double perimeter();

public String toString() { // override the inherited Object method
return name;
}
}

class XRectangle extends XShape { // extends identifies this as a subclass of the specified superclass
double length = 1.0; // subclass inherits all members of superclass that are not private
double width = 1.0;

XRectangle(double length, double width) {
super(4); // constructors of base class not inherited - but can be called
name = "XRectangle";
this.length = length;
this.width = width;
}

XRectangle() {
this(2, 4); // this or super constructor must be first statement in constructor
}

double area() { // define abstract method
return length * width;
}

double perimeter() {
return 2 * length * width;
}
}

final class Square extends XRectangle { // final class prevents any further subclassing
double length;

Square(double length) {
super(length, length);
name = "Square";
this.length = length;
super.length = length; // accessing shadowed variables allowed through super
((XRectangle)this).length = length; // accessing shadowed variables allowed through casting
double x = super.area(); // accessing overridden method allowed through super
x = ((XRectangle)this).area(); // casting does not provide access to the overridden method
}

double area() { // override base class method - perimeter function is inherited
return super.area(); // overriding method cannot be less accessible than overridden method
} // throws clause of overriding method must match overridden method
}

class Triangle extends XShape {
double[] side = new double[3];
double base;
double height;

Triangle(double a, double b, double c) {
super(3);
name = "Triangle";
side[0] = a;
side[1] = b;
side[2] = c;
base = a;
height = 1.0;
}

double area() {
return 0.5 * base * height;
}

double perimeter() {
return (side[0] + side[1] + side[2]);
}
}

/************************************************************************
* *
* Interfaces: *
* *
************************************************************************/
interface Factors { // an interface is a collection of constants and abstract methods
double PI = 3.14; // constants in interface are always public, static and final
double PISQUARE = Math.pow(PI, 2);
double INCH_TO_MM = 25.4;
}

interface Convert { // access can be specified as public or package (not specified)
double inchToMM(); // methods in interface are always abstract and public
}

interface MoreConvert extends Convert { // interfaces can be extended similar to classes
double MMToInch();
}

class Circle extends XShape implements Factors, MoreConvert { // multiple interfaces may be implemented
double radius;

Circle(double radius) {
super(0);
name = "Circle";
this.radius = radius;
}

double area() { // abstract methods required from superclass
return PI * PI * radius;
}

public double perimeter() { // override superclass method
return 2 * PI * radius;
}

public double inchToMM() { // abstract method for interface
return (perimeter() * INCH_TO_MM);
}

public double MMToInch() {
return radius * (1 / INCH_TO_MM);
}
}

class EquilateralTriangle extends Triangle implements Factors, Convert {
EquilateralTriangle(double a) {
super(a, a, a);
name = "EquilateralTriangle";
}

double area() {
return 0.5;
}

public double inchToMM() { // abstract method for interface
return 3 * side[0] * INCH_TO_MM;
}
}

/************************************************************************
* *
* Link Lists: *
* *
************************************************************************/
class LinkList {
LinkList prev;
LinkList next;

LinkList() {
prev = null;
next = null;
}

LinkList(LinkList x) {
x.prev = x;
x.next = null;
x.prev.next = this;
}
}
--------------------------------------------------------------------------------

Chris Rathman / ChrisRath@aol.com

Thursday, September 27, 2007

Abstract classes and Interfaces FAQs

What is an Interface?
A Java Interface can contain only method declarations and/or public static final constants, which doesn't contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present in the Interface. Also Interfaces have the ability to extend from other Interfaces(multiple Inheritance) and cannot be instantiated with the new operator.

What is an Abstract Class (ABC)?
Abstract class must be extended/subclassed in order to be implemented (useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated. i.e. A Vehicle class would be an ABC, while its subclasses Car, Truck, FourWheeler, Spacecraft, etc are specific implementations.

What are the similarities between an ABC and an Interface?
•There is no difference between a fully abstract class (all methods declared as abstract and all fields are public static final) and an Interface.
•Neither an ABC nor an Interface can be instantiated.

What are the main differences between an ABC and an Interface?
•An Interface can only contain public members, whereas an ABC can contain private as well as protected members.
•All variables in an Interface are by default, public static final, while an ABC can have instance variables.
•A class that implements an Interface must implement all methods defined in that Interface, while a class extending an ABC need not implement any of the methods defined in an ABC.

When is an Interface preferred over an ABC?
Interfaces are preferred in situations when all its properties need to be implemented by subclasses.

When is an ABC preferred over an Interface?
Abstract classes are preferred in situations when some general methods should be implemented and specialization behavior should be implemented by subclasses.

When should you tend towards an ABC or towards an Interface?
If the various objects are all of the same kind, and share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an Interface.

What is the down side to an ABC and an Interface?
The downside to an Interface is; if you want to add a new feature (method) in its contract, then you MUST implement the method in all of the classes which implement that Interface. However, in the case of an ABC, the method can be simply implemented in the ABC and the same can be called by its subclass.

Why should you separate Interfaces from implementation?
Interfaces are the company’s most valuable resources – they’re expensive.

Can Interfaces be used to describe the “peripheral abilities” of a class?
Yes, Interfaces are often used to describe the peripheral abilities of a class, and not its central identity. i.e. An Automobile class might implement the Paint interface, which could apply to many otherwise totally unrelated objects.

What must a class do to implement an Interface?
The class must provide all the methods in the interface and identify the interface in its implements clause.

What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.

How to define an Interface?
In Java an Interface defines the methods but does not implement them and can include constants. A class that implements Interface is bound to implement all the methods defined in Interface.

Example of Interface:

public interface SampleInterface{
public void sampleFunction();
public int SAMPLE_CONSTANT = 1;
}

How to define an ABC?
An ABC serves as a template. An ABC must be extended/subclassed for it to be implemented. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated. An ABC is a class that provides some general functionality but leaves specific implementation to its inheriting classes.

Example of an ABC:

abstract class SampleABC{
protected String name;
public String getName() {
return name;
}
public abstract void sampleFunction();
}

Explain in your own words the "bottom line" benefits of the use of an interface.
The interface makes it possible for a method in one class to invoke methods on objects of other classes, without the requirement to know the true class of those objects, provided that those objects are all instantiated from classes that implement one or more specified interfaces. In other words, objects of classes that implement specified interfaces can be passed into methods of other objects as the generic type Object, and the methods of the other objects can invoke methods on the incoming objects by first casting them as the interface type.

Wednesday, September 26, 2007

Java Design Patterns

Java is associated with a number of Design Patterns, which are subdivided into three groups, creational, structural, and behaviour. Below is a list of all patterns in Java and a brief description of each. Throughout the next few weeks I will provide coded examples for each individual pattern. Stay tuned!

Creational Patterns
Abstract Factory - Various methods to make various objects various ways.
Builder - Make and return one object various ways.
Factory Method – Methods to make and return components of one object various ways.
Prototype - Make new objects by cloning the objects which you set as prototypes.
Singleton - A class distributes the only instance of itself.

Structural Patterns
Adapter - A class extends another class and takes in an object, and makes the taken object behave like the extended class.
Bridge - An abstraction and implementation are in different class hierarchies.
Composite - Assemble groups of objects with the same signature.
Decorator - One class takes in another class, both of which extend the same abstract class, and adds functionality.
Façade - One class has a method that performs a complex process calling several other classes.
Flyweight - The reusable and variable parts of a class are broken into two classes to save resources.
Proxy - One class controls the creation of and access to objects in another class.

Behaviour Patterns
Chain of Responsibility - A method called in one class can move up a series to find an object that can properly execute the method.
Command - An object encapsulates everything needed to execute a method in another object.
Interpreter- Define a macro language and syntax, parsing input into objects which perform the correct opertaions.
Iterator - One object can traverse all of the elements of another object.
Mediator - An object distributes communication between two or more objects.
Memento - One object stores another objects state.
Observer - An object notifies other object(s) if it changes.
State - An object appears to change its` class when the class it passes calls through to switches itself for a related class.
Strategy - An object controls which of a family of methods is called. Each method is in its` own class that extends a common base class.
Template - An abstract class defines various methods, and has one non-overridden method which calls the various methods.
Visitor - One or more related classes have the same method, which calls a method specific for themselves in another class.

J2EE - FAQs

What is J2EE?
J2EE is an environment for developing and deploying enterprise applications.The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications.

What is a Servlet?
A Servlet is a Java object that is based on Servlet framework and extends the functionality of a web server, being responsible for creating dynamic contents.

Which tier do Servlet and JSP components belong to?
Servlet and JSP are web tier components that run in a web tier container.

What roles do Servlet and JSP play?
• receive client requests (HTTP)
• perform business logic
• return responses to clients

What are the advantages of Servlet Technology?
• Abundant third-party tools and web servers support Servlet
• Access to an entire family of Java APIs
• Reliable, reusability, scalability
• Platform and server independent
• Secure
• Automatic reloading of Servlets

What is JSP Technology?
• Enables separation of business logic (Java Beans or custom tags) from presentation (HTML or XML/XSLT)
• Extensible via custom tags
• Builds on Servlet technology

What advantage does JSP have over Servlet technology? What is the downside to Servlet?
The downside to Servlet is that the presentation (HTML pages) has to be generated as part of the Servlet Java code, i.e. using printf statements, therefore whenever changes are made to the presentation, the Java code has to be changed and recompiled, redeployed. This in turn results in a maintenance problem of your application along with making web-page prototyping very difficult.

What is JSP page?
A text-based document capable of returning dynamic content to a client browser, which contains both Static (HTML, XML) and Dynamic content (programming code, JavaBeans, custom tags).

When to use Servlet over JSP?
• Extend the functionality of a Web server such as supporting a new file format
• Generate objects that do not contain HTML (graphics or charts)
• Avoid returning HTML directly from your Servlets whenever possible

Should I use Servlet or JSP?
In practice Servlets and JSP are used together via MVC (Model, View, Controller) architecture. Servlet handles Controller while JSP handles View. Servlet is good for controlling functionality while JSP is good for handling presentation logic.

What is a request?
Information that is sent from a client to a server. The information consists of (1) who made the request (2) user-entered data and (3) HTTP header entries.

What is a response?
Information that is sent to a client from a server. The information consists of static text (HTML, plain) or binary(image) data. It also contains HTTP response headers and cookies which are used to maintain session state.

What does the HTTP request contain?
It contains a header, a method(Get, Post, Put, Header) and request data.

What does the Get request contain?
User entered information is appended to the URL in a query string and can only send limited amount of data. i.e. ../servlet/ViewCourse?FirstName=Tom&LastName=Flewwelling

What does the Post request contain?
User entered information is sent as data (not appended to the URL). Any amount of data can be sent.

Servlet Interfaces and classes

List the interfaces and classes associated with Servlet.
Classes: HttpSession, GenericServlet, HttpServlet
Interfaces: Servlet, ServletRequest, HttpServletRequest, ServletResponse, HttpServletResponse

Servlet Life-Cycle

What controls the life cycle of a Servlet?
The container.

Explain the life cycle of a Servlet.
The init() gets called once a Servlet instance is created. The service() gets called every time there comes a new request. The service() calls doGet() and doPost() for incoming HTTP requests. Finally the destroy() is called to remove the Servlet instance.

What classes are Servlet defined in?
javax.servlet.GenericServlet or javax.servlet.HttpServlet.

Is the service() abstract? If so explain.
Yes, the service() is abstract and GenericServlet is thus abstract class. Therefore the service() of the GenericServlet class has to be implemented by a subclass – HTTPServlet class.

What role does the init() play?
Invoked once when the Servlet is instantiated and performs any set-up. i.e. Setting up a data base connection.

What role does the destroy() play?
Invoked before Servlet instance is removed and performs any clean up. i.e. Closing a database connection.

How are user entered parameters via the browser accessed?
They are accessed via getParameter().

How are init parameters via the web.xml deployment descriptor file accessed?
They are accessed via getInitParameter().

What kind of requests and responses does the service() receive?
It receives generic requests and responses. i.e. service(ServletRequest request, ServletResponse response).

What kind of requests and responses do the doGet() and doPost() receive?
They receive HTTP requests and responses. i.e. doGet(HTTPServletRequest request, HTTPServletResponse response), doPost(HTTPServletRequest request, HTTPServletResponse response).

Note: The doGet() and doPost() methods of HTTPServlet class are invoked from concrete implementation of service() method in the HTTPServlet class.

What are 5 things you want to do in doGet() and doPost() methods?
1.Extract client sent info such as user-entered parameter values that were sent as query string.
2.Set and get attributes to and from scope objects.
3.Perform some business logic or access the database.
4.Optionally include or forward your request to other web components.
5.Populate HTTP response message and then send it to client.

What are the typical steps to follow when creating a HTTP response?
1.Fill HTTP response headers with content type.
2.Set properties such as buffer size.
3.Get an output stream object from the response object and the write body contents to the output stream.

What are Scope Objects?
Scope Objects enable sharing information among collaborating web components (Servlet & JSP) via attributes(name/object pairs) maintained in Scope Objects.

What methods are used to access the attributes maintain in the Scope Objects?
getAttribute() & setAttribute()

Name 4 different types of Scope Objects: Class
Web context: Accessible from Web components within a Web context
Session: Accessible from Web components handling a request that belongs to the session
Request: Accessible from Web components handling the request
Page: Accessible from JSP page that creates the object

Web Context

How is a web context object represented?
A web context object is represented by ServletContext object. There is one ServletContext object per web application.

What is ServletContext used for?
It is used by servlets to:
• Set and get context-wide (application-wide) object-valued attributes
• Get request dispatcher
• Access Web content-wide initialization parameters set in the web.xml file
• Access Web resources associated with the Web context
• Log
• Access other misc. info

How do you access ServletContext object?
Call getServletContext() from within your servlet code and filter. Also, the ServletContext is located in ServletConfig object, which the Web server provides to a servlet when the servlet is initialized.

Session (Http Session)

Why is HTTPSession important?
It’s a mechanism employed to maintain client state across a series of requests from a same user over some period of time. i.e. Online shopping cart. Since HTTP is stateless, the HttpSession maintains client state in the form of attributes and the attributes remain in the session scope.

How do you get HTTPSession object in your Servlet code?
By an HTTPRequest object that is passed to your servlet object as an input parameter of Service() or getSession().

Servlet Request (HttpServletRequest)

What is a Servlet Request?
It contains data passed from client to server and implements ServletRequest.

How do you get client sent(user-entered) parameters?
By HTTP GET and HTTP POST.
HTTP GET: The name and value pairs of the parameters are sent as appendix to the URL.
HTTP POST: The name and value pairs of the parameters are sent as user data.

How to extract the values of the parameters?
getParameter() from the ServletRequest interface.

How are object/values attributes set?
The Servlet container itself can set attributes to make available custom information about a request. Or the Servlet set application-specific attribute. i.e. void setAttribute(java.lang.String name, java.lang.Object o)

How can Servlets get client information from the request?
String request.getRemoteAddr(); - get client’s IP address
String request.getRemoteHost(); - get client’s host name

How to obtain Server information?
String request.getServerName(); i.e. www.sun.com
int request.getServerPort(); i.e. Port number 8080

How to determine if the line is secure (if HTTPS)?
boolean isSecure()

HTTPServletRequest

What is HTTP Servlet Request?
It contains data passed from HTTP client to HTTP Servlet that is created by Servlet container and passed to Servlet as a parameter of doGet() or doPost().

What does a HTTP Request URL contain?
http://[host]:[port]/[request path]?[query string]

What do HTTP Request Headers do?
They Accept, Accept-Encoding and Authorize.

HTTPServletResponse

What is a Servlet Response?
It contains data passed from the Servlet to the client. And all Servlet responses implement ServletResponse Java Interface, which contains methods for retrieving an output stream, indicating content type, indicating whether to buffer output or not, for setting localization information.
Status Code in HTTPResponse

Why do we need HTTP response status code?
• To forward a client to another page.
• Indicate resources are missing.
• Instruct browser to use cached copy.

List some common Status Codes?
• 200(SC_OK) Success and documents follows – default for all Servlets.
• 204(SC_No_CONTENT) Success but no response body
• 301(SC_MOVED_PERMANENTLY) The document moved permanently (indicated in Location header)

Header in HTTPResponse

Why HTTP Response Headers?
To name a few:
• Give forwarding location
• Specify cookies
• Supply the page modification date
• Instruct the browser to reload the page after a designated interval
• Give the file size so that persistent HTTP connections can be used
• Designate the type of document being generated

Body in HTTPResponse

What are the key points to writing a response Reader?
A Servlet almost always return a response body which could be either a PrintWriter or a ServletOutputStream.

Overview

What are the 4 main J2EE application parts?
Client-tier components run on the client machine.
Web-tier components run on the J2EE server.
Business-tier components run on the J2EE server.
Enterprise information system (EIS)-tier software runs on the EIS server.

What do Enterprise JavaBeans components contain?
Enterprise JavaBeans components contains Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.

Are JavaBeans J2EE components?
No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture.

Is HTML page a web component?
No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either.

What can be considered as a web component?
J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.

What is the container?
Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.

What are container services?
A container is a runtime support of a system-level entity. Containers provide components with services such as:

lifecycle management
security
deployment
threading

What is deployment descriptor?
A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a components deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly.

What is the EAR file?
An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.

What is JAXP?
JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations.

What is Java Naming and Directory Service?
The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS.

What is Struts?
A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.

<----------------------------------------EJB----------------------------------->

The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes?
The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintainence is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer.

What is Hibernate?
Hibernate is a powerful, high performance object/relational persistence and query service. Hibernate lets you develop persistent classes following object-oriented idiom - including association, inheritance, polymorphism, composition, and collections. Hibernate allows you to express queries in its own portable SQL extension (HQL), as well as in native SQL, or with an object-oriented Criteria and Example API.

What are Struts?
The "Struts" framework tends to mainly focus on the web tier.

What is Spring Framework?
The Spring Framework tends to mainly focus on the Enterprise tier while providing support and integrating well with the Struts framework.

The "Struts" framework is no doubt a good framework to enhance the ability of the web tier, but the biggest drawback is the fact that it caters only to the web tier and leaves most of the Enterprise tier or middle tier to the fancy of the application architects. The Application architects need to provide an additional framework to deal with the enterprise tier and make sure that the new framework integrates well with the Struts framework. Spring tries to alleviate this problem by providing a comprehensive framework, which includes an MVC framework, an AOP integration framework, a JDBC integration framework, and an EJB integration framework

AWT and Swing FAQs

What does AWT stand for?
AWT stands for Abstract Window ToolKit. AWT enables programmers to develop Java applications with GUI components, such as windows, and buttons.

Pointers regarding Swing.
•100% Java implementation of components
•Pluggable Look & Feel
•Lightweight components
•Uses Model View Control (MVC) Architecture

What is the difference between AWT and Swing?
AWT is heavy-weight components, but Swing is light-weight components. AWT is OS dependent because it uses native components, but Swing components are OS independent. We can change the look and feel in Swing which is not possible in AWT. Swing takes less memory compared to AWT. For drawing AWT uses screen rendering where Swing uses double buffering.

What is a “heavyweight” component?
A heavyweight component is one that is associated with its own native screen resource (commonly known as a peer).

What is a “lightweight” component?
A lightweight component is one that “borrows” the native screen resources of an ancestor (which means it has no native resources of its own – peerless).

Just what is a button really?
It is simply a wrapper class inheriting from JComponent that holds the DefaultButtonModel object, some view data (such as the button label and icons), and a BasicButtonUI object that is responsible for the button views.

Why won’t the JVM terminate when all application windows are closed?
The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit() to terminate the JVM.

Which Swing methods are thread-safe?
The only thread-safe methods are repaint(), revalidate(), and invalidate().

What class is at the top of the AWT event hierarchy?
java.awt.AWTEvent.

What does “heavy weight components” mean?
Heavy weight components like Abstract Window Toolkit (AWT) depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component.

Name the container classes which use Border Layout as their default layout?
Window, Frame and Dialog classes.

Name Container classes.
Window, Frame, Dialog, FileDialog, Panel, Applet, and ScrollPane.

What is the difference between the paint() and repaint() methods?
The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

Which package has light weight components?
javax.Swing package contains light weight components. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.

What is JFC?
JFC stands for Java Foundation Classes. The Java Foundation Classes (JFC) are a set of Java class libraries provided as part of Java 2 Platform, Standard Edition (J2SE) to support building graphics user interface (GUI) and graphics functionality for client applications that will run on popular platforms such as Microsoft Windows, Linux, and Mac OSX.

What is an event?
Changing the state of an object is an event.

What is an Event Handler?
An Event Handler is part of a program which tells the program how to act in response to a specific event.

What is a layout manager?
A layout manager is an object used to organize components in a container.

Which container classes use BorderLayout manager as their default layout?
Window, Frame and Dialog classes.

Which container classes use FlowLayout manager as their default layout?
Panel and Applet classes.

What method of the Container class is used to set the position and size of the component?
The setBounds() method.

What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout. For example, setLayout(new FlowLayout()); will set the layout as FlowLayout.

How are the elements of different layouts organized?
A layout manager is an object that is used to organize components in a container. The different layouts available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.

FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.

BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container.

CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards.

GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.

GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements may be different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

Which Container method is used to cause a container to be laid out and redisplayed?
validate()

Name Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.

What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is just a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the component to display normally.

How can a GUI component handle its own events?
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

What are peerless components?
The peerless components are called light-weight components.

What is the purpose of the enableEvents() method?
The enableEvents() method is used to enable an event for a particular component. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.