
By Alexandre POLOZOFF
polozoff@us.ibm.com
IBM Software Group
AIM Services
Copyright @ 2001, IBM
Corporation
One benefit of unit testing is being able to get immediate feedback on the state of the code. JUnit does this job very well and integrates nicely into the VisualAge for Java environment. One aspect of J2EE programming involves writing servlets. But no obvious way exists to unit test them within the JUnit framework. This paper presents code examples on how to unit test servlets from within the VisualAge for Java environment utilizing the familiar JUnit test tool.
A servlet takes form input in a sequence of name and value pairs. Each name is a specific html form element tagname with an associated value. The servlet processes the data and produces a web page that is normally viewed through a browser. The servlet-under-test’s output should contain key words that readily identifys the success or failure of the servlet processing. Based on assertions of the key words the unit test succeeded or failed.
Downloadable jar file containing all the code described in this document is available at
http://www.alexandre.polozoff.com/papers/jars/ServletTester.jar
The Servlet Tester Project is a VisualAge for Java project that contains JUnit code to test servlets and the supporting socket layer code to perform http GET and POST requests. The ServletTest class below has two primary methods, getPage and postPage.
When testing within the VisualAge for Java WebSphere Test Environment you normally use the following parameters:
server = localhost
port = 8080
url = /servlet/com.yourpackage.name.NameOfServlet
The WebSphere Test Environment and the JUnit classpath must include the VisualAge for Java project containing the test case.
The getPage( ) method connects to a server, on a specified
port, and requests the URL. If any
parameters are passed in the HTTPForm object then those are appended to the
query.
The postPage( ) method connects to a server, on a specified port and requests the URL. The HTTPForm parameters are mandatory and are sent with the http POST request.
Both getPage and postPage methods return a string that contains the entire contents of the webpage (including HTTP header data). If the URL is not being fetched properly it is useful to examin the contents of the web page to see what error message the server is responding with.
Cookies are maintained within the scope of the ServletTest class and easily re-initialized.
This is the test servlet tested by our JUnit testing methodology.
doGet method
The sample servlet provided with this code.
First, the method loads up two cookies into the response.
Then it prints out one line of text that is used for the assertion test.
/*****************************************************************************
* Process incoming HTTP GET requests
*
* @param request Object that encapsulates
the request to the servlet
* @param response Object that encapsulates
the response from the servlet
*/
public
void doGet(
javax.servlet.http.HttpServletRequest
request,
javax.servlet.http.HttpServletResponse
response) {
response.setContentType("text/plain");
try {
// type the code for your useful
task here
javax.servlet.ServletOutputStream
out = response.getOutputStream();
javax.servlet.http.Cookie cookie =
new
javax.servlet.http.Cookie("testcookie1", "cookievalue1");
response.addCookie(cookie);
cookie = new
javax.servlet.http.Cookie("testcookie2", "value is 2");
response.addCookie(cookie);
out.println("Hello from the
World Wide Web.");
out.close();
} catch (Exception e) {
//
This will show up in logs when
// ncf.jvm.stdoutlog.enabled=true
in jvm.properties
System.out.println("Sample
Servlet failed: ");
e.printStackTrace();
}
}
doPost method
The method first reads the parameters submitted within the html form construct passed as part of the POST request.
Then the method prints out the values sent as form input and any cookies it received for the assertion test.
The doPost method in this exmple does not set any cookies.
/*****************************************************************************
*
Process incoming HTTP POST requests
*
*
@param request Object that encapsulates the request to the servlet
*
@param response Object that encapsulates the response from the servlet
*/
public
void doPost(
javax.servlet.http.HttpServletRequest
request,
javax.servlet.http.HttpServletResponse
response) {
response.setContentType("text/plain");
try {
String firstname = (String)
request.getParameter(FirstServlet.FIRST_NAME);
String lastname = (String) request.getParameter(FirstServlet.LAST_NAME);
String city = (String)
request.getParameter(FirstServlet.CITY);
// type the code for your useful
task here
javax.servlet.ServletOutputStream
out = response.getOutputStream();
javax.servlet.http.Cookie[] cookies
= request.getCookies();
for (int counter = 0;
counter<cookies.length; counter++)
out.println("cookie
#" + counter + " " + cookies[counter].getName() + " "
+ cookies[counter].getValue());
out.println("Hello from the
World Wide Web.");
out.print(FirstServlet.FIRST_NAME);
out.print("=");
out.println(firstname);
out.print(FirstServlet.LAST_NAME);
out.print("=");
out.println(lastname);
out.print(FirstServlet.CITY);
out.print("=");
out.println(city);
out.close();
} catch (Exception e) {
// This will show up in logs when
// ncf.jvm.stdoutlog.enabled=true
in jvm.properties
System.out.println("Sample
Servlet failed: ");
e.printStackTrace();
}
}
Normally, the catch block of the doPost method uses RequestDispatcher.forward( ) to send the user to an error page.
This class contains the test case that is run against the servlet. The testFirstServlet method performs the actual test of the servlet. A programmatic way to test a servlet by testing the existence (or lack thereof) of known keywords in the servlet’s output.

Cookie autonomy within the testFirstServlet method to other ServletTest methods is maintained by setting the instance variable cookies to a new Hashtable. Initializing the instance variable cookies ensures that the session starts with a clean slate with no cookies in the requests. Likewise, the cookies Hashtable can be loaded with cookies. The Hashtable key is simply an Integer and the value is the cookie string expected in the HTTP header (a name/value pair as counter=123).
The lifecycle of an individual textXYZ method should be as follows:

The method first does a GET request of the servlet page with no parameters passed (i.e. no HTTPForm input) and any cookies in the instance variable cookies are sent with the GET request (in our case the hashtable is empty so no cookies are sent). The page contents from the web server are returned as a string by the getPage method. Any cookies returned by the web server are parsed and stored in the instance variable cookies.
Then the method performs a POST request after setting up the appropriate form parameters into the HTTPForm object and any cookies in the instance variable cookies are sent with the POST request. The page contents are returned as a string by the postPage method. The string is indexOf’d to find specific strings we are expecting the servlet to produce (see the FirstServlet’s doPost method). Any cookies returned by the web server are parsed and stored in the instance variable cookies.
Cookies are not cumulative. The getPage and postPage methods destroy all previous cookies before reading the response from the web server. This ensures that old cookies are not carried forward in subsequent requests.
The assertions in the testFirstServlet method assert that the page contents produced by the servlet are the expected contents. If, for example, the servlet processed the city and changed Chicago to New York then the servlet testFirstServlet method would fail.
FirstServlet also prints out the value of the cookies received in the doPost() method. The assertions in the testFirstServlet method checks that the cookie names are in the page produced.
Debugging Tips
The Visual Age for Java console receives all the output of the servlet testing class. If the System.out.println statements are left inside the getPage and postPage methods then you can view the textual output of the web server.
The web server should respond with the first line as “200 ok” and this means that the page was delivered without error. Any other code return points to a problem with the servlet or JSP being invoked and you need to debug it before the output can be asserted.
One handy technique with a non-working servlet is to rename the original servlet from MyServlet to MyServletOld. Then create a new base servlet that does very little except process the doGet, doPost, init and service methods. Once the new servlet is working copy one method at a time from the original MyServletOld and test the new servlet. Eventually, by deduction, you’ll find the method that is causing the servlet to not execute.
package com.ibm.demo.servlet.test;
import junit.extensions.*;
import junit.framework.*;
import java.net.*;
import java.io.*;
import java.util.*;
/**
* Insert the type's description here.
* Creation date: (4/26/2001 8:35:34 AM)
* @author: Alexandre Polozoff
*/
public class ServletTest extends TestCase {
private java.util.Hashtable cookies = null;
public final static java.lang.String SET_COOKIE = "Set-Cookie:";
/**
* ServletTest constructor comment.
* @param arg1 java.lang.String
*/
public ServletTest(String arg1) {
super(arg1);
}
/**
* Insert the method's description here.
* Creation date: (4/30/2001 10:09:30 AM)
* @return java.util.Hashtable
*/
public java.util.Hashtable getCookies() {
return cookies;
}
/**
* Send an http GET request to a URL
*
* Creation date: (4/26/2001 8:38:44 AM)
* @return java.io.BufferedReader
* @param url java.lang.String should be format "localhost/servlet/pageToGetServlet"
* @param port int port to connect to (8080 for WTE, 80 for regular web server)
* @param formParameters Clause the form parameters to be sent, if any
* @exception java.net.SocketException The exception description. Socket error loading page
*/
public String getPage(
String server,
String pageurl,
int port,
HTTPForm formParameters)
throws
java.net.SocketException,
java.net.UnknownHostException,
IOException,
ServerErrorException {
Integer bufferSize = new Integer(1024);
String builtURL = null;
try {
if (formParameters.getSize() > 0)
builtURL =
pageurl
+ "?"
+ java.net.URLEncoder.encode(formParameters.elementsAsFormString());
} catch (NullPointerException e) {
builtURL = pageurl;
}
builtURL = builtURL;
Socket aSocket = new Socket(server, port);
BufferedReader inStream = null;
StringBuffer sb = null;
try {
aSocket.setSoTimeout(10 * 1000);
aSocket.setReceiveBufferSize(bufferSize.intValue());
InetAddress host = aSocket.getInetAddress();
System.out.println("connected to " + host);
BufferedOutputStream outStream =
new BufferedOutputStream(aSocket.getOutputStream());
StringBuffer getSB = new StringBuffer("GET ");
getSB.append(builtURL);
getSB.append(" HTTP/1.1");
try {
if (!cookies.isEmpty()) {
Enumeration enumeration = cookies.elements();
while (enumeration.hasMoreElements()) {
String cookieString = (String)enumeration.nextElement();
getSB.append("\r\nCookie: ");
getSB.append(cookieString);
}
}
} catch (NullPointerException npe) { /* no action necessary */ }
getSB.append("\r\n\r\n");
String get = getSB.toString();
System.out.println("sending HTTP GET request\n\r" + get);
outStream.write(get.getBytes(), 0, get.length());
outStream.flush();
System.out.println("GET request sent");
System.out.println("reading from BufferedReader");
inStream = new BufferedReader(new InputStreamReader(aSocket.getInputStream()));
sb = getResponse(inStream);
} finally {
aSocket.close();
}
return sb.toString();
}
/**
* Send an http GET request to a URL
*
* Creation date: (4/26/2001 8:38:44 AM)
* @return java.io.BufferedReader
* @param url java.lang.String should be format "localhost/servlet/pageToGetServlet" or "www.aon.com/servlet/pageToGetServlet"
* @param formParameters Clause the form parameters to be sent, if any
* @exception java.net.SocketException The exception description. Socket error loading page
*/
public String getPage(
String server,
String url,
HTTPForm formParameters)
throws
java.net.SocketException,
java.net.UnknownHostException,
IOException,
ServerErrorException {
return getPage(server, url, 80, formParameters);
}
/**
* Insert the method's description here.
* Creation date: (4/30/2001 1:46:39 PM)
* @return java.lang.StringBuffer
* @param inStream java.io.BufferedReader
*/
public StringBuffer getResponse(BufferedReader inStream)
throws IOException, ServerErrorException
{
StringBuffer sb = new StringBuffer();
String lineIn = inStream.readLine();
String errorLine = lineIn;
this.cookies = new Hashtable();
int cookieCounter = 0;
boolean bTwoHundredOK = false;
while (lineIn != null) {
sb.append(lineIn);
if (!bTwoHundredOK)
if (lineIn.toUpperCase().indexOf("200 OK") != -1)
bTwoHundredOK = true;
// process cookies (if any)
int pos = lineIn.indexOf(SET_COOKIE);
if (pos != -1)
cookies.put(
new Integer(cookieCounter++),
lineIn.substring(pos + SET_COOKIE.length()));
System.out.println(lineIn);
lineIn = inStream.readLine();
}
if (!bTwoHundredOK)
throw new ServerErrorException(errorLine);
return sb;
}
/**
* Send an http POST request to a URL
*
* Creation date: (4/26/2001 8:38:44 AM)
* @return java.io.BufferedReader
* @param url java.lang.String should be format "localhost/servlet/pageToGetServlet"
* @param port int port to connect to (8080 for WTE, 80 for regular web server)
* @param formParameters Clause the form parameters to be sent, if any
* @exception java.net.SocketException The exception description. Socket error loading page
*/
public String postPage(
String server,
String pageurl,
int port,
HTTPForm formParameters)
throws
java.net.SocketException,
java.net.UnknownHostException,
IOException,
ServerErrorException {
Integer bufferSize = new Integer(1024);
Socket aSocket = new Socket(server, port);
BufferedReader inStream = null;
StringBuffer sb = null;
try {
aSocket.setSoTimeout(10 * 1000);
aSocket.setReceiveBufferSize(bufferSize.intValue());
InetAddress host = aSocket.getInetAddress();
System.out.println("connected to " + host);
BufferedOutputStream outStream =
new BufferedOutputStream(aSocket.getOutputStream());
StringBuffer cookieSB = null;
try {
if (!cookies.isEmpty()) {
cookieSB = new StringBuffer("\r\nCookie: ");
Enumeration enumeration = cookies.elements();
while (enumeration.hasMoreElements()) {
String cookieString = (String) enumeration.nextElement();
cookieSB.append(cookieString);
cookieSB.append(";");
}
}
} catch (NullPointerException npe) { /* no action necessary */
}
String formdata = null;
String cookieString = "";
if (!cookies.isEmpty()) cookieString = cookieSB.toString();
formdata = formParameters.elementsAsFormString();
String get =
"POST "
+ pageurl
+ " HTTP/1.1 "
+ cookieString
+"\r\nContent-type: application/x-www-form-urlencoded\r\nContent-length: "
+ formdata.length()
+ "\r\n\r\n"
+ formdata
+ "\r\n\r\n";
System.out.println("sending HTTP POST request\n\r" + get);
outStream.write(get.getBytes(), 0, get.length());
outStream.flush();
System.out.println("POST request sent");
System.out.println("reading from BufferedReader");
inStream = new BufferedReader(new InputStreamReader(aSocket.getInputStream()));
sb = getResponse(inStream);
} finally {
aSocket.close();
}
return sb.toString();
}
/**
* Send an http POST request to a URL
*
* Creation date: (4/26/2001 8:38:44 AM)
* @return java.io.BufferedReader
* @param url java.lang.String should be format "localhost/servlet/pageToGetServlet" or "www.aon.com/servlet/pageToGetServlet"
* @param formParameters Clause the form parameters to be sent, if any
* @exception java.net.SocketException The exception description. Socket error loading page
*/
public String postPage(
String server,
String url,
HTTPForm formParameters)
throws
java.net.SocketException,
java.net.UnknownHostException,
IOException,
ServerErrorException,
NullPointerException {
return postPage(server, url, 80, formParameters);
}
/**
* Insert the method's description here.
* Creation date: (4/30/2001 10:09:30 AM)
* @param newCookies java.util.Hashtable
*/
public void setCookies(java.util.Hashtable newCookies) {
cookies = newCookies;
}
/**
* Insert the method's description here.
* Creation date: (3/28/2001 3:49:36 PM)
*/
public static Test suite() {
return new TestSuite(ServletTest.class);
}
/**
* In WebSphere Studio, create a default servlet called FirstServlet with the wizard.
* Publish it to VAJ WTE.
*
* Creation date: (4/26/2001 10:31:09 AM)
*/
public void testFirstServlet() {
this.cookies = new Hashtable(); // clear out the cookies, if any exist
// http GET
// will also SET COOKIES
String url = "/servlet/com.ibm.demo.servlet.test.FirstServlet";
try {
String allText = getPage("localhost", url, 8080, null);
assert(allText.indexOf("Hello from the World Wide Web.")!= -1);
} catch (Exception e) {
fail(e.getMessage());
}
// http POST
// FirstServlet prints out cookie values if we properly pass them through to the post
try {
HTTPForm hf = new HTTPForm(3);
hf.addFormElement(FirstServlet.FIRST_NAME, "Alexandre (the 'Great)");
hf.addFormElement(FirstServlet.LAST_NAME, "Polozoff");
hf.addFormElement(FirstServlet.CITY, "Chicago");
String allText = postPage("localhost", url, 8080, hf);
assert(allText.indexOf(FirstServlet.FIRST_NAME)!= -1);
assert(allText.indexOf("Alexandre (the 'Great)")!= -1);
assert(allText.indexOf(FirstServlet.LAST_NAME)!= -1);
assert(allText.indexOf("Polozoff")!= -1);
assert(allText.indexOf(FirstServlet.CITY)!= -1);
assert(allText.indexOf("Chicago")!= -1);
assert(allText.indexOf("testcookie1") != -1);
assert(allText.indexOf("testcookie2") != -1);
} catch (Exception e) {
fail(e.getMessage());
}
}
}
Normally, a web server responds with the result “200 ok” to identify that no error occurred in servicing the requested page. But for a developer more often than not an error does occur. The ServletTester methods throw the ServerErrorException if “200 ok” is not returned by the web server. This results in the JUnit test case to fail.
Many times the JUnit assertion fails and the text of the assertion in the JUnit window appears as:
junit.framework.AssertionFailedError: HTTP/1.0 500 ok
java.lang.Throwable(java.lang.String)
java.lang.Error(java.lang.String)
junit.framework.AssertionFailedError(java.lang.String)
Error 500
means that the web server experienced an error directly related to running the
servlet or JSP file.
In the VisualAge for Java console, topmost pane click on the com.ibm.ivj.control.WebControlCenter.main()
WTE Control Center -> com.ibm.ivj.control.node.ServletEngineRunner.main() line.
More likely than not a bunch of unhandled servlet exceptions are visible. This also means that the doGet or doPost methods of your servlet are not catching exceptions. It is good practise to have a try-catch block for the entire method as such:
doPost() {
try {
… servlet processing code …
requestDispatcher = RequestDispatcher……(GOOD_URL);
requestDispatcher.forward(request, response);
} catch (Exception e) {
… set up error variables …
requestDispatcher = RequestDispatcher……(ERROR_URL);
requestDispatcher.forward(request, response);
}
}
Another common assertion failure is:
junit.framework.AssertionFailedError: HTTP/1.0 404 ok
java.lang.Throwable(java.lang.String)
java.lang.Error(java.lang.String)
junit.framework.AssertionFailedError(java.lang.String)
This means that the requested page was not found. This means that the webserver could not specifically find either
Ø the
servlet you specified as the URL to the doGet or doPost methods
Ø the JSP page the servlet is chaining to in the RequestDispatcher.forward( ) or RequestDispatcher.include( ) statements.
Another common error that appears in the JUnit window is:
junit.framework.AssertionFailedError: Connection refused:
no further information
java.lang.Throwable(java.lang.String)
java.lang.Error(java.lang.String)
junit.framework.AssertionFailedError(java.lang.String)
Several reasons exist for the Connection being refused, among them:
Ø WebSphere
Test Enviornment not started
Ø Servlet
Engine not started
Ø Accessing the wrong port. For the WebSphere Test Environment the port must be 8080, for the normal WebSphere environment it is port 80.
An additional way to debug Connection refused is to attempt to bring up the same servlet or JSP page in a normal internet browser (such as Netscape or Internet Explorer). If the web server services the request and the servlet/JSP appears then there is some problem in the unit test code probably attempting to use the wrong port number.
This is a convenience class that easily allows multiple form elements to be passed to the getPage or postPage methods. The HTTPForm class is utilized as follows:
HTTPForm ht = new HTTPForm(x);
where the HTTPForm constructor takes an integer that defines the number of elements. Then each element is added to the form as:
ht.addFormElement(“form_input_label_name”, “form_input_value”);
passing the form element’s label name and its value for each form element that needs to be passed to the servlet.
package com.ibm.demo.servlet.test;
/**
* Insert the type's description here.
* Creation date: (4/26/2001 8:54:02 AM)
* @author: Alexandre Polozoff
*/
public class HTTPForm extends Clause {
/**
* HTTPForm constructor comment.
* @param initialCapacity int
*/
public HTTPForm(int initialCapacity) {
super(initialCapacity);
}
/**
* Insert the method's description here.
* Creation date: (5/1/2001 8:58:00 AM)
* @param elementName java.lang.String
* @param elementValue java.lang.String
*/
public void addFormElement(String elementName, String elementValue) throws IndexOutOfBoundsException {
int counter = 0;
for(counter = 1; this.get(counter) != null; counter++)
// do nothing
;
this.put(counter, new ClauseMember(elementName, elementValue));
}
/**
* Insert the method's description here.
* Creation date: (4/26/2001 9:08:01 AM)
* @return java.lang.String
*/
public String elementsAsFormString() {
int maxElements = this.getSize();
StringBuffer stringBuffer = new StringBuffer();
for (int counter=1; counter<=maxElements; counter++) {
if (counter>1)
stringBuffer.append("&");
ClauseMember cm = this.get(counter);
stringBuffer.append(cm.getColumnName());
stringBuffer.append("=");
switch (cm.getSyntax()) {
case ClauseMember.SYNTAX_INTEGER : {
stringBuffer.append(cm.getValue().intValue());
break;
}
case ClauseMember.SYNTAX_DOUBLE : {
stringBuffer.append(cm.getValue().doubleValue());
break;
}
case ClauseMember.SYNTAX_STRING : {
stringBuffer.append(cm.getValue().stringValue());
break;
}
} // switch statement
}
return stringBuffer.toString();
}
}
The classes that support the ServletTest class are Clause, ClauseMember and ClauseValue. These classes combine to allow the passing of multiple parameters to methods.
/**
* Insert the type's description here.
* Creation date: (4/7/2001 10:52:46 AM)
* @author: Alexandre Polozoff
*/
public
abstract class Clause {
private ClauseMember[] key;
private int size;
private int hashcode = -1;
/**
* Clause constructor comment.
*/
private
Clause() {
super();
}
/**
* Clause constructor comment.
*/
public
Clause(int initialCapacity) {
super();
size = initialCapacity + 1;
key = new ClauseMember[size];
}
/**
* Compares two objects for equality. Returns
a boolean that indicates
* whether this object is equivalent to the
specified object. This method
* is used when an object is stored in a
hashtable.
* @param obj the Object to compare with
* @return true if these Objects are equal;
false otherwise.
* @see java.util.Hashtable
*/
public
boolean equals(Object obj) {
// Insert code to compare the receiver
and obj here.
// This implementation forwards the
message to super. You may replace or
supplement this.
// NOTE: obj might be an instance of any
class
Clause c = (Clause)obj;
if (obj.hashCode() != this.hashCode())
return false;
int maxElements = this.getSize();
if (maxElements != c.getSize())
return false;
for (int counter=1; counter <=
maxElements; counter++) {
ClauseMember cm =
this.get(counter);
ClauseMember cm2 = c.get(counter);
int syntax = cm.getSyntax();
if (syntax != cm2.getSyntax())
return false;
if (syntax ==
ClauseMember.SYNTAX_INTEGER) {
if
(cm.getValue().intValue() != cm2.getValue().intValue())
return false;
} else
if (syntax == ClauseMember.SYNTAX_STRING)
{
if
(!cm.getValue().stringValue().equals(cm2.getValue().stringValue()))
return false;
} else
if (syntax ==
ClauseMember.SYNTAX_DOUBLE) {
if
(cm.getValue().doubleValue() != cm2.getValue().doubleValue())
return
false;
}
}
return true;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:18:05 AM)
* @return java.lang.Object
* @param index int
* @exception
java.lang.IndexOutOfBoundsException The exception description.
*/
public
ClauseMember get(int index) throws java.lang.IndexOutOfBoundsException {
return key[index];
}
/**
* Insert the method's description here.
* Creation date: (4/23/2001 2:10:44 PM)
* @return int
*/
final
private int getHashcode() {
return hashcode;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:19:01 AM)
* @return int
*/
public
int getSize() {
return size-1;
}
/**
* Generates a hash code for the receiver.
* This method is supported primarily for
* hash tables, such as those provided in
java.util.
* @return an integer hash code for the
receiver
* @see java.util.Hashtable
*/
public
int hashCode() {
// Insert code to generate a hash code
for the receiver here.
// This implementation forwards the
message to super. You may replace or
supplement this.
// NOTE: if two objects are equal
(equals(Object) returns true) they must have the same hash code
int returnValue = 0;
int maxElements = this.getSize();
for (int counter=1; counter <=
maxElements; counter++) {
ClauseMember cm =
this.get(counter);
returnValue += cm.hashCode();
}
return returnValue;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:17:27 AM)
* @param index int
* @param value org.omg.CORBA.Object
* @exception java.lang.IndexOutOfBoundsException
The exception description.
*/
public
void put(int index, ClauseMember value) throws
java.lang.IndexOutOfBoundsException {
key[index] = value;
}
/**
* Insert the method's description here.
* Creation date: (4/23/2001 2:10:44 PM)
* @param newHashcode int
*/
final
private void setHashcode(int newHashcode) {
hashcode = newHashcode;
}
/**
* Insert the method's description here.
* Creation date: (4/8/2001 4:41:11 PM)
* @param preparedStatement
java.sql.PreparedStatement
*/
public
void setPreparedStatement(java.sql.PreparedStatement preparedStatement)
throws
java.sql.SQLException
{
int maxElements = this.getSize();
for (int counter=1; counter <=
maxElements; counter++) {
ClauseMember cm =
this.get(counter);
int syntax = cm.getSyntax();
if (syntax ==
ClauseMember.SYNTAX_INTEGER) {
preparedStatement.setInt(counter,
cm.getValue().intValue());
} else
if (syntax ==
ClauseMember.SYNTAX_STRING) {
preparedStatement.setString(counter,
cm.getValue().stringValue());
} else
if (syntax ==
ClauseMember.SYNTAX_DOUBLE) {
preparedStatement.setDouble(counter,
cm.getValue().doubleValue());
}
else
if (syntax ==
ClauseMember.SYNTAX_DATE) {
preparedStatement.setDate(counter,
new java.sql.Date(cm.getValue().dateValue().getTime()));
}
}
}
}
/**
* Insert the type's description here.
* Creation date: (4/7/2001 10:39:23 AM)
* @author: Alexandre Polozoff
*/
public class ClauseMember {
public final static int SYNTAX_INTEGER = 0;
public final static int SYNTAX_DOUBLE = 1;
public final static int SYNTAX_STRING = 2;
public final static int SYNTAX_DATE = 3;
public final static int SYNTAX_TIME = 4;
public final static java.lang.String EQUALITY_EQUALS = "=";
public final static java.lang.String EQUALITY_LESSTHAN_EQUALS = "<=";
public final static java.lang.String EQUALITY_GREATERTHAN_EQUALS = ">=";
public final static java.lang.String EQUALITY_LESSTHAN = "<";
public final static java.lang.String EQUALITY_GREATERTHAN = ">";
private int syntax = 0;
private ClauseMemberValue value = null;
private java.lang.String columnName = null; // database column name
private java.lang.String equality = null;
private int hashcode = -1;
/**
* ClauseMember constructor comment.
*/
public ClauseMember() {
super();
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 10:41:43 AM)
* @param newDouble double
*/
public ClauseMember(double newDouble) {
setSyntax(SYNTAX_DOUBLE);
value = new ClauseMemberValue(newDouble);
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 10:41:43 AM)
* @param newDouble double
*/
public ClauseMember(int newInteger) {
setSyntax(SYNTAX_INTEGER);
value = new ClauseMemberValue(newInteger);
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 10:41:43 AM)
* @param newDouble double
*/
public ClauseMember(String newString) {
setSyntax(SYNTAX_STRING);
value = new ClauseMemberValue(newString);
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 10:41:43 AM)
* @param newDouble double
*/
public ClauseMember(String columnName, double newDouble) {
setSyntax(SYNTAX_DOUBLE);
setColumnName(columnName);
setEquality(ClauseMember.EQUALITY_EQUALS);
value = new ClauseMemberValue(newDouble);
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 10:41:43 AM)
* @param newDouble double
*/
public ClauseMember(String columnName, int newInteger) {
setSyntax(SYNTAX_INTEGER);
setColumnName(columnName);
setEquality(ClauseMember.EQUALITY_EQUALS);
value = new ClauseMemberValue(newInteger);
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 10:41:43 AM)
* @param newDouble double
*/
public ClauseMember(String columnName, int syntax, String newString) {
setSyntax(syntax);
setColumnName(columnName);
value = new ClauseMemberValue(newString);
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 10:41:43 AM)
* @param newDouble double
*/
public ClauseMember(String columnName, String newString) {
setSyntax(SYNTAX_STRING);
setColumnName(columnName);
setEquality(ClauseMember.EQUALITY_EQUALS);
value = new ClauseMemberValue(newString);
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 10:41:43 AM)
* @param newDouble double
*/
public ClauseMember(String columnName, String equalityIdentifier, double newDouble) {
setSyntax(SYNTAX_DOUBLE);
setColumnName(columnName);
setEquality(equalityIdentifier);
value = new ClauseMemberValue(newDouble);
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 10:41:43 AM)
* @param newDouble double
*/
public ClauseMember(String columnName, String equalityIdentifier, int newInteger) {
setSyntax(SYNTAX_INTEGER);
setColumnName(columnName);
setEquality(equalityIdentifier);
value = new ClauseMemberValue(newInteger);
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 10:41:43 AM)
* @param newDouble double
*/
public ClauseMember(String columnName, String equalityIdentifier, String newString) {
setSyntax(SYNTAX_STRING);
setColumnName(columnName);
setEquality(equalityIdentifier);
value = new ClauseMemberValue(newString);
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 10:41:43 AM)
* @param newDouble double
*/
public ClauseMember(String columnName, java.util.Date newDate) {
setSyntax(SYNTAX_DATE);
setColumnName(columnName);
setEquality(ClauseMember.EQUALITY_EQUALS);
value = new ClauseMemberValue(newDate);
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 10:41:43 AM)
* @param newDate date
*/
public ClauseMember(java.util.Date newDate) {
setSyntax(SYNTAX_DATE);
value = new ClauseMemberValue(newDate);
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 12:01:06 PM)
* @return java.lang.String
*/
public java.lang.String getColumnName() {
return columnName;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 12:04:39 PM)
* @return java.lang.String
*/
public java.lang.String getEquality() {
return equality;
}
/**
* Insert the method's description here.
* Creation date: (4/23/2001 2:06:48 PM)
* @param newHashcode int
*/
final private int getHashcode() {
return hashcode;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:34:06 AM)
*/
public int getSyntax() {
return syntax;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:34:06 AM)
*/
public ClauseMemberValue getValue() {
return value;
}
/**
* Insert the method's description here.
* Creation date: (4/23/2001 9:21:14 AM)
* @return int
*/
public int hashCode() {
if (this.getHashcode() != -1)
return getHashcode();
switch (this.getSyntax()) {
case SYNTAX_INTEGER :
{
setHashcode(this.getValue().intValue());
break;
}
case SYNTAX_DOUBLE :
{
Double doubleValue = new Double(this.getValue().doubleValue());
setHashcode(doubleValue.hashCode());
break;
}
case SYNTAX_STRING :
{
setHashcode(this.getValue().stringValue().hashCode());
break;
}
}
return this.getHashcode();
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 12:01:06 PM)
* @param newColumnName java.lang.String
*/
public void setColumnName(java.lang.String newColumnName) {
columnName = newColumnName;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 12:04:39 PM)
* @param newEquality java.lang.String
*/
public void setEquality(java.lang.String newEquality) {
equality = newEquality;
}
/**
* Insert the method's description here.
* Creation date: (4/23/2001 2:06:48 PM)
* @param newHashcode int
*/
final private void setHashcode(int newHashcode) {
hashcode = newHashcode;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:31:10 AM)
* @param newSyntax int
*/
public void setSyntax(int newSyntax) {
syntax = newSyntax;
}
}
/**
* Insert the type's description here.
* Creation date: (4/7/2001 11:24:57 AM)
* @author: Alexandre Polozoff
*/
public class ClauseMemberValue {
private double aDouble;
private java.lang.String string;
private int anInteger;
private java.util.Date aDate;
/**
* ClauseMemberValue constructor comment.
*/
public ClauseMemberValue() {
super();
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:25:49 AM)
* @param newDouble double
*/
public ClauseMemberValue(double newDouble) {
aDouble = newDouble;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:25:49 AM)
* @param newDouble double
*/
public ClauseMemberValue(int newInteger) {
anInteger = newInteger;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:25:49 AM)
* @param newDouble double
*/
public ClauseMemberValue(String newString) {
string = newString;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:25:49 AM)
* @param newDouble double
*/
public ClauseMemberValue(java.util.Date newDate) {
aDate = newDate;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:28:46 AM)
* @return java.lang.String
*/
public java.util.Date dateValue() {
return aDate;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:26:33 AM)
* @return java.lang.Double
*/
public double doubleValue() {
return aDouble;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:26:53 AM)
* @return java.lang.String
*/
public java.lang.String getString() {
return string;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:26:33 AM)
* @return java.lang.Double
*/
public int intValue() {
return anInteger;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:26:53 AM)
* @param newString java.lang.String
*/
public void setString(java.lang.String newString) {
string = newString;
}
/**
* Insert the method's description here.
* Creation date: (4/7/2001 11:28:46 AM)
* @return java.lang.String
*/
public String stringValue() {
return string;
}
}
May 2, 2001 – More on exception and identifying problems
May 1, 2001 – Rearranged text, more text added to HTTPForm.
Apr
30, 2001 – Added cookie support