vmassol 01/03/27 09:42:35
Added: j2eeunit/src/ant/org/apache/commons/j2eeunit/ant
ResinRun.java RunServerTestsTask.java
StartServerHelper.java StartServerTask.java
StopServerHelper.java StopServerTask.java
j2eeunit/src/framework/servlet22/org/apache/commons/j2eeunit/server
HttpServletRequestWrapper.java
RequestDispatcherWrapper.java
ServletConfigWrapper.java
ServletContextWrapper.java
j2eeunit/src/framework/servlet23/org/apache/commons/j2eeunit/server
HttpServletRequestWrapper.java
RequestDispatcherWrapper.java
ServletConfigWrapper.java
ServletContextWrapper.java
j2eeunit/src/framework/share/org/apache/commons/j2eeunit
JspTestCase.java ServiceDefinition.java
ServiceEnumeration.java ServletTestCase.java
ServletTestRequest.java ServletTestResult.java
ServletURL.java overview.html package.html
j2eeunit/src/framework/share/org/apache/commons/j2eeunit/client
AbstractHttpClient.java
AssertionFailedErrorWrapper.java
HttpClientHelper.java JspHttpClient.java
ServletExceptionWrapper.java ServletHttpClient.java
j2eeunit/src/framework/share/org/apache/commons/j2eeunit/server
CallerHelper.java JspImplicitObjects.java
JspTestCaller.java ServletImplicitObjects.java
ServletTestCaller.java ServletTestRedirector.java
j2eeunit/src/framework/share/org/apache/commons/j2eeunit/util
AssertUtils.java ClientCookie.java
j2eeunit/src license.apl
j2eeunit/src/sample/servlet22/org/apache/commons/j2eeunit/sample/unit
TestServletTestCaseSpecific.java
j2eeunit/src/sample/servlet23/org/apache/commons/j2eeunit/sample/unit
TestServletTestCaseSpecific.java
j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample
SampleServlet.java SampleServletConfig.java
TestSampleServlet.java TestSampleServletConfig.java
j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/unit
TestJspTestCase.java TestServletTestCase1.java
TestServletTestCase1_ExceptionNotSerializable.java
TestServletTestCase1_ExceptionSerializable.java
TestServletTestCase1_InterceptorServletTestCase.java
TestServletTestCase2.java TestServletTestCase3.java
TestServletTestCase4.java
j2eeunit/src/test/share/org/apache/commons/j2eeunit
TestAll.java
j2eeunit/src/test/share/org/apache/commons/j2eeunit/util
TestAssertUtils.java
Removed: j2eeunit/src license.gpl
j2eeunit/src/ant/j2eeunit/ant ResinRun.java
RunServerTestsTask.java StartServerHelper.java
StartServerTask.java StopServerHelper.java
StopServerTask.java
j2eeunit/src/framework/servlet22/j2eeunit/server
HttpServletRequestWrapper.java
RequestDispatcherWrapper.java
ServletConfigWrapper.java
ServletContextWrapper.java
j2eeunit/src/framework/servlet23/j2eeunit/server
HttpServletRequestWrapper.java
RequestDispatcherWrapper.java
ServletConfigWrapper.java
ServletContextWrapper.java
j2eeunit/src/framework/share/j2eeunit JspTestCase.java
ServiceDefinition.java ServiceEnumeration.java
ServletTestCase.java ServletTestRequest.java
ServletTestResult.java ServletURL.java
overview.html package.html
j2eeunit/src/framework/share/j2eeunit/client
AbstractHttpClient.java
AssertionFailedErrorWrapper.java
HttpClientHelper.java JspHttpClient.java
ServletExceptionWrapper.java ServletHttpClient.java
j2eeunit/src/framework/share/j2eeunit/server
CallerHelper.java JspImplicitObjects.java
JspTestCaller.java ServletImplicitObjects.java
ServletTestCaller.java ServletTestRedirector.java
j2eeunit/src/framework/share/j2eeunit/util AssertUtils.java
ClientCookie.java
j2eeunit/src/sample/servlet22/j2eeunit/sample/unit
TestServletTestCaseSpecific.java
j2eeunit/src/sample/servlet23/j2eeunit/sample/unit
TestServletTestCaseSpecific.java
j2eeunit/src/sample/share/j2eeunit/sample SampleServlet.java
SampleServletConfig.java TestSampleServlet.java
TestSampleServletConfig.java
j2eeunit/src/sample/share/j2eeunit/sample/unit
TestJspTestCase.java TestServletTestCase1.java
TestServletTestCase1_ExceptionNotSerializable.java
TestServletTestCase1_ExceptionSerializable.java
TestServletTestCase1_InterceptorServletTestCase.java
TestServletTestCase2.java TestServletTestCase3.java
TestServletTestCase4.java
j2eeunit/src/test/share/j2eeunit TestAll.java
j2eeunit/src/test/share/j2eeunit/util TestAssertUtils.java
Log:
changed license from GPL to APL + changed copyrights from Vincent Massol to Apache
Software Foundation + changed packages from j2eeunit.* to org.apache.commons.j2eeunit.*
Revision Changes Path
1.1
jakarta-commons-sandbox/j2eeunit/src/ant/org/apache/commons/j2eeunit/ant/ResinRun.java
Index: ResinRun.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.ant;
import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
/**
* Starts/stop Resin by setting up a listener socket.
*/
public class ResinRun extends Thread
{
private Object m_Server;
private int m_Port = 7777;
public static void main(String[] args)
{
ResinRun run = new ResinRun();
// Look for a -start or -stop flag
boolean isStart = true;
Vector newArgs = new Vector();
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("-start")) {
isStart = true;
} else if (args[i].equalsIgnoreCase("-stop")) {
isStart = false;
} else if (args[i].equalsIgnoreCase("-port")) {
run.m_Port = Integer.parseInt(args[i+1]);
i++;
} else {
newArgs.add(args[i]);
}
}
if (isStart) {
String[] strArgs = new String[0];
run.startResin((String[])newArgs.toArray(strArgs));
} else {
run.stopResin();
}
}
private void startResin(String[] args)
{
if (m_Server == null) {
try {
Class resinClass =
Class.forName("com.caucho.server.http.ResinServer");
Constructor constructor = resinClass.getConstructor(new Class[] {
args.getClass(), boolean.class });
m_Server = constructor.newInstance(new Object[] { args, new
Boolean(true) });
Method initMethod = resinClass.getMethod("init", new Class[] {
boolean.class });
initMethod.invoke(m_Server, new Object[] { new Boolean(true) } );
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error starting Resin");
}
}
// Set up listener socket for listening to request to stop Resin
new Thread(this).start();
}
private void stopResin()
{
// Open socket connection
Socket clientSocket = null;
try {
clientSocket = new Socket("127.0.0.1", m_Port);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error opening socket tp 127.0.0.1 on port ["
+ m_Port + "]");
} finally {
try {
if (clientSocket != null) {
clientSocket.close();
}
} catch (IOException e) {
throw new RuntimeException("Cannot close client socket");
}
}
}
public void run()
{
ServerSocket serverSocket = setUpListenerSocket();
// Accept a client socket connection
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
throw new RuntimeException("Error accepting connection for server socket
[" + serverSocket + "]");
} finally {
// Stop server socket
try {
serverSocket.close();
} catch (IOException e) {
throw new RuntimeException("Cannot close server socket [" +
serverSocket + "]");
}
}
// Stop Resin server
if (m_Server != null) {
try {
Method closeMethod = m_Server.getClass().getMethod("close", null);
closeMethod.invoke(m_Server, null);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Cannot stop Resin server");
}
}
// Stop server socket
try {
serverSocket.close();
} catch (IOException e) {
throw new RuntimeException("Cannot close server socket [" + serverSocket
+ "]");
}
}
private ServerSocket setUpListenerSocket()
{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(m_Port);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Error setting up the Resin listener socket");
}
return serverSocket;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/ant/org/apache/commons/j2eeunit/ant/RunServerTestsTask.java
Index: RunServerTestsTask.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.ant;
import java.net.*;
import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;
/**
*
* @version @version@
*/
public class RunServerTestsTask extends Task
{
private String m_TestTarget;
/**
*
*/
private StartServerHelper m_StartHelper;
/**
*
*/
private StopServerHelper m_StopHelper;
public void init()
{
m_StartHelper = new StartServerHelper(this);
m_StopHelper = new StopServerHelper(this);
}
/**
* Executes the task.
*/
public void execute() throws BuildException
{
try {
callStart();
callTests();
} finally {
// Make sure we stop the server
callStop();
}
}
/**
* Call the start server task
*/
private void callStart()
{
m_StartHelper.execute();
}
/**
* Call the stop server task
*/
private void callStop()
{
m_StopHelper.execute();
}
/**
* Call the run tests target
*/
private void callTests()
{
CallTarget callee;
callee = (CallTarget)project.createTask("antcall");
callee.setOwningTarget(target);
callee.setTaskName(getTaskName());
callee.setLocation(location);
callee.init();
callee.setTarget(m_TestTarget);
callee.execute();
}
/**
* Sets the target to call to start the server.
*
* @param theStartTarget the Ant target to call
*/
public void setStartTarget(String theStartTarget)
{
m_StartHelper.setStartTarget(theStartTarget);
}
/**
* Sets the target to call to stop the server.
*
* @param theStopTarget the Ant target to call
*/
public void setStopTarget(String theStopTarget)
{
m_StopHelper.setStopTarget(theStopTarget);
}
/**
* Sets the URL to call for testing if the server is running.
*
* @param theTestURL the test URL to ping
*/
public void setTestURL(String theTestURL)
{
m_StartHelper.setTestURL(theTestURL);
m_StopHelper.setTestURL(theTestURL);
}
/**
* Sets the target to call to run the tests.
*
* @param theTerstTarget the Ant target to call
*/
public void setTestTarget(String theTestTarget)
{
m_TestTarget = theTestTarget;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/ant/org/apache/commons/j2eeunit/ant/StartServerHelper.java
Index: StartServerHelper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.ant;
import java.net.*;
import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;
/**
* A helper class for an Ant Task that does the following :
* <ul>
* <li>create a java thread,</li>
* <li>start another Ant target in that thread. This target must be a
* blocking target that starts a web server/servlet engine,</li>
* <li>wait for that server to be started. This is done by continuously
* trying to call a URL.</li>
* </ul>.
*
* @version @version@
*/
public class StartServerHelper implements Runnable
{
/**
* The URL that is continuously pinged to verify if the server is running.
*/
private URL m_TestURL;
/**
* The Ant target name that will start the web server/servlet engine.
*/
private String m_StartTarget;
/**
* The tasks that wraps around this helper class
*/
private Task m_Task;
/**
*
*/
public StartServerHelper(Task theTask)
{
m_Task = theTask;
}
/**
* Executes the task.
*/
public void execute() throws BuildException
{
// Verify that a test URL has been specified
if (m_TestURL == null) {
throw new BuildException("A testURL attribute must be specified");
}
// Verify that a start target has been specified
if (m_StartTarget == null) {
throw new BuildException("A startTarget Ant target name must be
specified");
}
// Call the target that starts the server, in another thread. The called
// target must be blocking.
Thread thread = new Thread(this);
thread.start();
// Wait a few ms more (just to make sur the servlet engine is
// ready to accept connections)
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new BuildException("Interruption during sleep", e);
}
// Continuously try calling the test URL until it succeeds
while (true) {
try {
HttpURLConnection connection =
(HttpURLConnection)m_TestURL.openConnection();
connection.connect();
connection.disconnect();
} catch (IOException e) {
try {
Thread.sleep(500);
} catch (InterruptedException ee) {
throw new BuildException("Interruption during sleep", ee);
}
continue;
}
break;
}
// Wait a few ms more (just to be sure !)
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new BuildException("Interruption during sleep", e);
}
// We're done ... Ant will continue processing other tasks
}
/**
* The thread that calls the Ant target that starts the web server/servlet
* engine. Must be a blocking target.
*/
public void run()
{
// Call the Ant target using the "antcall" task.
CallTarget callee;
callee = (CallTarget)(m_Task.getProject().createTask("antcall"));
callee.setOwningTarget(m_Task.getOwningTarget());
callee.setTaskName(m_Task.getTaskName());
callee.setLocation(m_Task.getLocation());
callee.init();
callee.setTarget(m_StartTarget);
callee.execute();
// Should never reach this point as the target is blocking, unless the
// server is stopped.
}
/**
* @param theTestURL the test URL to ping
*/
public void setTestURL(String theTestURL)
{
try {
m_TestURL = new URL(theTestURL);
} catch (MalformedURLException e) {
throw new BuildException("Bad URL [" + theTestURL + "]", e);
}
}
/**
* @param theStartTarget the Ant target to call
*/
public void setStartTarget(String theStartTarget)
{
m_StartTarget = theStartTarget;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/ant/org/apache/commons/j2eeunit/ant/StartServerTask.java
Index: StartServerTask.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.ant;
import java.net.*;
import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;
/**
* An Ant Task that does the following :
* <ul>
* <li>create a java thread,</li>
* <li>start another Ant target in that thread. This target must be a
* blocking target that starts a web server/servlet engine,</li>
* <li>wait for that server to be started. This is done by continuously
* trying to call a URL.</li>
* </ul>.
*
* @version @version@
*/
public class StartServerTask extends Task
{
/**
* Helper class
*/
private StartServerHelper m_Helper;
/**
* Initialization
*/
public void init()
{
m_Helper = new StartServerHelper(this);
}
/**
* Executes the task.
*/
public void execute() throws BuildException
{
m_Helper.execute();
}
/**
* Ant will automatically call this method when the "testURL" attribute
* of our task is used.
*
* @param theTestURL the test URL to ping
*/
public void setTestURL(String theTestURL)
{
m_Helper.setTestURL(theTestURL);
}
/**
* Ant will automatically call this method when the "startTarget" attribute
* of our task is used.
*
* @param theStartTarget the Ant target to call
*/
public void setStartTarget(String theStartTarget)
{
m_Helper.setStartTarget(theStartTarget);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/ant/org/apache/commons/j2eeunit/ant/StopServerHelper.java
Index: StopServerHelper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.ant;
import java.net.*;
import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;
/**
* A helper class for an Ant task that does the following : stop a running
* server by calling an Ant target to stop it in another thread and wait for
* the servlet engine to be stopped by trying to continously connect to a test
* URL. If it succeeds it means the server is not stopped yet !
*
* @version @version@
*/
public class StopServerHelper implements Runnable
{
/**
* The URL that is continuously pinged to verify if the server is stopped
*/
private URL m_TestURL;
/**
* The Ant target name that will stop the web server/servlet engine.
*/
private String m_StopTarget;
/**
* The tasks that wraps around this helper class
*/
private Task m_Task;
/**
*
*/
public StopServerHelper(Task theTask)
{
m_Task = theTask;
}
/**
* Executes the task.
*/
public void execute() throws BuildException
{
// Verify that a test URL has been specified
if (m_TestURL == null) {
throw new BuildException("A testURL attribute must be specified");
}
// Verify that a stop target has been specified
if (m_StopTarget == null) {
throw new BuildException("A stopTarget Ant target name must be
specified");
}
// Call the target that stops the server, in another thread.
Thread thread = new Thread(this);
thread.start();
// Wait a few ms more (just to make sure)
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new BuildException("Interruption during sleep", e);
}
// Continuously try calling the test URL until it fails
while (true) {
try {
HttpURLConnection connection =
(HttpURLConnection)m_TestURL.openConnection();
connection.connect();
connection.disconnect();
} catch (IOException e) {
break;
}
try {
Thread.sleep(500);
} catch (InterruptedException ee) {
throw new BuildException("Interruption during sleep", ee);
}
}
// Wait a few ms more (just to be sure !)
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new BuildException("Interruption during sleep", e);
}
m_Task.log("Server stopped !");
// We're done ... Ant will continue processing other tasks
}
/**
* The thread that calls the Ant target that stops the web server/servlet
* engine.
*/
public void run()
{
// Call the Ant target using the "antcall" task.
CallTarget callee;
callee = (CallTarget)(m_Task.getProject().createTask("antcall"));
callee.setOwningTarget(m_Task.getOwningTarget());
callee.setTaskName(m_Task.getTaskName());
callee.setLocation(m_Task.getLocation());
callee.init();
callee.setTarget(m_StopTarget);
callee.execute();
}
/**
* @param theTestURL the test URL to ping
*/
public void setTestURL(String theTestURL)
{
try {
m_TestURL = new URL(theTestURL);
} catch (MalformedURLException e) {
throw new BuildException("Bad URL [" + theTestURL + "]", e);
}
}
/**
* @param theStopTarget the Ant target to call
*/
public void setStopTarget(String theStopTarget)
{
m_StopTarget = theStopTarget;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/ant/org/apache/commons/j2eeunit/ant/StopServerTask.java
Index: StopServerTask.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.ant;
import java.net.*;
import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;
/**
* Call an Ant stop target in another thread and wait for the servlet engine
* to be stopped by trying to continously connect to a test URL. If it succeeds
*it means the server is not stopped yet !
*
* @version @version@
*/
public class StopServerTask extends Task
{
/**
* Helper class
*/
private StopServerHelper m_Helper;
/**
* Initialization
*/
public void init()
{
m_Helper = new StopServerHelper(this);
}
/**
* Executes the task.
*/
public void execute() throws BuildException
{
m_Helper.execute();
}
/**
* Ant will automatically call this method when the "testURL" attribute
* of our task is used.
*
* @param theTestURL the test URL to ping
*/
public void setTestURL(String theTestURL)
{
m_Helper.setTestURL(theTestURL);
}
/**
* Ant will automatically call this method when the "stopTarget" attribute
* of our task is used.
*
* @param theStopTarget the Ant target to call
*/
public void setStopTarget(String theStopTarget)
{
m_Helper.setStopTarget(theStopTarget);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/servlet22/org/apache/commons/j2eeunit/server/HttpServletRequestWrapper.java
Index: HttpServletRequestWrapper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import java.util.*;
import java.io.*;
import java.security.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.j2eeunit.*;
/**
* Encapsulation class for the Servlet 2.2 API <code>HttpServletRequest</code>.
* This is an implementation that delegates all the call to the
* <code>HttpServletRequest</code> object passed in the constructor except for
* some overridden methods which are use to simulate a URL. This is to be able to
* simulate any URL that would have been used to call the test method : if this
* was not done, the URL that would be returned (by calling the
* <code>getRequestURI()</code> method or others alike) would be the URL of the
* server redirector servlet or JSP and not a URL that the test case want to
* simulate.
*
* @version @version@
*/
public class HttpServletRequestWrapper implements HttpServletRequest
{
/**
* The real HTTP request
*/
private HttpServletRequest m_Request;
/**
* The URL to simulate
*/
private ServletURL m_URL;
/**
* Construct an <code>HttpServletRequest</code> instance that delegates
* it's method calls to the request object passed as parameter and that
* uses the URL passed as parameter to simulate a URL from which the request
* would come from.
*
* @param theRequest the real HTTP request
* @param theURL the URL to simulate or <code>null</code> if none
*/
public HttpServletRequestWrapper(HttpServletRequest theRequest, ServletURL
theURL)
{
m_Request = theRequest;
m_URL = theURL;
}
public HttpServletRequest getOriginalRequest()
{
return m_Request;
}
public boolean isRequestedSessionIdFromURL()
{
return m_Request.isRequestedSessionIdFromURL();
}
public Enumeration getLocales()
{
return m_Request.getLocales();
}
public String getHeader(String theName)
{
return m_Request.getHeader(theName);
}
/**
* @return the context path from the simulated URL or the real context path
* if a simulation URL has not been defined.
*/
public String getContextPath()
{
if (m_URL != null) {
return m_URL.getContextPath();
}
return m_Request.getContextPath();
}
public String getScheme()
{
return m_Request.getScheme();
}
/**
* @return the path info from the simulated URL or the real path info
* if a simulation URL has not been defined.
*/
public String getPathInfo()
{
if (m_URL != null) {
return m_URL.getPathInfo();
}
return m_Request.getPathInfo();
}
public String getAuthType()
{
return m_Request.getAuthType();
}
/**
* @return the server name from the simulated URL or the real server name
* if a simulation URL has not been defined.
*/
public String getServerName()
{
if (m_URL != null) {
return m_URL.getURL().getHost();
}
return m_Request.getServerName();
}
public String getRealPath(String thePath)
{
return m_Request.getRealPath(thePath);
}
public HttpSession getSession()
{
return m_Request.getSession();
}
public HttpSession getSession(boolean isCreate)
{
return m_Request.getSession(isCreate);
}
public String getRemoteHost()
{
return m_Request.getRemoteHost();
}
public Enumeration getHeaderNames()
{
return m_Request.getHeaderNames();
}
public boolean isUserInRole(String theRole)
{
return m_Request.isUserInRole(theRole);
}
/**
* @return the server port number from the simulated URL or the real server
* port number if a simulation URL has not been defined. If not
* port is defined, then port 80 is returned.
*/
public int getServerPort()
{
if (m_URL != null) {
if (m_URL.getURL().getPort() == -1) {
return 80;
}
return m_URL.getURL().getPort();
}
return m_Request.getServerPort();
}
public BufferedReader getReader() throws IOException
{
return m_Request.getReader();
}
public int getContentLength()
{
return m_Request.getContentLength();
}
/**
* @return the URI from the simulated URL or the real URI
* if a simulation URL has not been defined.
*/
public String getRequestURI()
{
if (m_URL != null) {
return m_URL.getURL().getFile();
}
return m_Request.getRequestURI();
}
public String[] getParameterValues(String theName)
{
return m_Request.getParameterValues(theName);
}
public boolean isRequestedSessionIdFromUrl()
{
return m_Request.isRequestedSessionIdFromUrl();
}
public String getContentType()
{
return m_Request.getContentType();
}
public Locale getLocale()
{
return m_Request.getLocale();
}
public void removeAttribute(String theName)
{
m_Request.removeAttribute(theName);
}
public String getParameter(String theName)
{
return m_Request.getParameter(theName);
}
/**
* @return the servlet path from the simulated URL or the real servlet path
* if a simulation URL has not been defined.
*/
public String getServletPath()
{
if (m_URL != null) {
return m_URL.getServletPath();
}
return m_Request.getServletPath();
}
public boolean isRequestedSessionIdFromCookie()
{
return m_Request.isRequestedSessionIdFromCookie();
}
public ServletInputStream getInputStream() throws IOException
{
return m_Request.getInputStream();
}
public Principal getUserPrincipal()
{
return m_Request.getUserPrincipal();
}
public boolean isSecure()
{
return m_Request.isSecure();
}
public String getPathTranslated()
{
return m_Request.getPathTranslated();
}
public String getRemoteAddr()
{
return m_Request.getRemoteAddr();
}
public String getCharacterEncoding()
{
return m_Request.getCharacterEncoding();
}
public Enumeration getParameterNames()
{
return m_Request.getParameterNames();
}
public String getMethod()
{
return m_Request.getMethod();
}
public void setAttribute(String theName, Object theAttribute)
{
m_Request.setAttribute(theName, theAttribute);
}
public Object getAttribute(String theName)
{
return m_Request.getAttribute(theName);
}
public int getIntHeader(String theName)
{
return m_Request.getIntHeader(theName);
}
public boolean isRequestedSessionIdValid()
{
return m_Request.isRequestedSessionIdValid();
}
/**
* @return the query string from the simulated URL or the real query
* string if a simulation URL has not been defined.
*/
public String getQueryString()
{
if (m_URL != null) {
return m_URL.getQueryString();
}
return m_Request.getQueryString();
}
public long getDateHeader(String theName)
{
return m_Request.getDateHeader(theName);
}
public Enumeration getAttributeNames()
{
return m_Request.getAttributeNames();
}
public String getRemoteUser()
{
return m_Request.getRemoteUser();
}
public String getProtocol()
{
return m_Request.getProtocol();
}
public Enumeration getHeaders(String theName)
{
return m_Request.getHeaders(theName);
}
public String getRequestedSessionId()
{
return m_Request.getRequestedSessionId();
}
public RequestDispatcher getRequestDispatcher(String thePath)
{
return m_Request.getRequestDispatcher(thePath);
}
public Cookie[] getCookies()
{
return m_Request.getCookies();
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/servlet22/org/apache/commons/j2eeunit/server/RequestDispatcherWrapper.java
Index: RequestDispatcherWrapper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Wrapper around <code>RequestDispatcher</code> which overrides the
* <code>forward()</code> and <code>include</code> methods to use the original
* HTTP request object instead of the simulated one used by J2EEUnit.
*
* @version @version@
*/
public class RequestDispatcherWrapper implements RequestDispatcher
{
/**
* The original request dispatcher object
*/
private RequestDispatcher m_OriginalDispatcher;
/**
* @param theOriginalDispatcher the original request dispatcher object
*/
public RequestDispatcherWrapper(RequestDispatcher theOriginalDispatcher)
{
m_OriginalDispatcher = theOriginalDispatcher;
}
/**
* Call the original <code>RequestDispatcher</code> <code>forward()</code>
* method but with the original HTTP request (not the simulation one which
* would make the servlet engine choke !).
*
* @param theRequest the simulation HTTP request
* @param theResponse the original HTTP response
*/
public void forward(ServletRequest theRequest, ServletResponse theResponse)
throws IOException, ServletException
{
HttpServletRequestWrapper request = (HttpServletRequestWrapper)theRequest;
m_OriginalDispatcher.forward(request.getOriginalRequest(), theResponse);
}
/**
* Call the original <code>RequestDispatcher</code> <code>include()</code>
* method but with the original HTTP request (not the simulation one which
* would make the servlet engine choke !).
*
* @param theRequest the simulation HTTP request
* @param theResponse the original HTTP response
*/
public void include(ServletRequest theRequest, ServletResponse theResponse)
throws IOException, ServletException
{
HttpServletRequestWrapper request = (HttpServletRequestWrapper)theRequest;
m_OriginalDispatcher.include(request.getOriginalRequest(), theResponse);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/servlet22/org/apache/commons/j2eeunit/server/ServletConfigWrapper.java
Index: ServletConfigWrapper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import java.util.*;
import java.io.*;
import java.security.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Wrapper around <code>ServletConfig</code> which overrides the
* <code>getServletContext()</code> method to return our own wrapper around
* <code>ServletContext</code>.
*
* @version @version@
* @see ServletContext
*/
public class ServletConfigWrapper implements ServletConfig
{
/**
* The original servlet config object
*/
private ServletConfig m_OriginalConfig;
/**
* List of parameters set using the <code>setInitParameter()</code> method.
*/
private Hashtable m_InitParameters;
/**
* Simulated name of the servlet
*/
private String m_ServletName;
/**
* @param theOriginalConfig the original servlet config object
*/
public ServletConfigWrapper(ServletConfig theOriginalConfig)
{
m_OriginalConfig = theOriginalConfig;
m_InitParameters = new Hashtable();
}
/**
* Sets a parameter as if it were set in the <code>web.xml</code> file.
*
* @param theName the parameter's name
* @param theValue the parameter's value
*/
public void setInitParameter(String theName, String theValue)
{
m_InitParameters.put(theName, theValue);
}
/**
* Sets the servlet name. That will be the value returned by the
* <code>getServletName()</code> method.
*
* @param theServletName the servlet's name
*/
public void setServletName(String theServletName)
{
m_ServletName = theServletName;
}
//--Overridden methods -----------------------------------------------------
/**
* @return our own wrapped servlet context object
*/
public ServletContext getServletContext()
{
return new ServletContextWrapper(m_OriginalConfig.getServletContext());
}
/**
* @param theName the name of the parameter's value to return
* @return the value of the parameter, looking for it first in the list of
* parameters set using the <code>setInitParameter()</code> method
* and then in those set in <code>web.xml</code>.
*/
public String getInitParameter(String theName)
{
// Look first in the list of parameters set using the
// setInitParameter() method.
String value = (String)m_InitParameters.get(theName);
if (value == null) {
value = m_OriginalConfig.getInitParameter(theName);
}
return value;
}
/**
* @return the union of the parameters defined in the Redirector
* <code>web.xml</code> file and the one set using the
* <code>setInitParameter()</code> method.
*/
public Enumeration getInitParameterNames()
{
Vector names = new Vector();
Enumeration enum = m_InitParameters.keys();
while (enum.hasMoreElements()) {
String value = (String)enum.nextElement();
names.add(value);
}
enum = m_OriginalConfig.getInitParameterNames();
while (enum.hasMoreElements()) {
String value = (String)enum.nextElement();
names.add(value);
}
return names.elements();
}
/**
* @return the simulated servlet's name if defined or the redirector
* servlet's name
*/
public String getServletName()
{
if (m_ServletName != null) {
return m_ServletName;
}
return m_OriginalConfig.getServletName();
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/servlet22/org/apache/commons/j2eeunit/server/ServletContextWrapper.java
Index: ServletContextWrapper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import java.util.*;
import java.io.*;
import java.security.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Wrapper around <code>ServletContext</code> which overrides the
* <code>getRequestDispatcher()</code> method to return our own wrapper around
* <code>RequestDispatcher</code>.
*
* @version @version@
* @see RequestDispatcherWrapper
*/
public class ServletContextWrapper implements ServletContext
{
/**
* The original servlet context object
*/
private ServletContext m_OriginalContext;
/**
* @param theOriginalContext the original servlet context object
*/
public ServletContextWrapper(ServletContext theOriginalContext)
{
m_OriginalContext = theOriginalContext;
}
public String getMimeType(String theFilename)
{
return m_OriginalContext.getMimeType(theFilename);
}
public URL getResource(String thePath) throws MalformedURLException
{
return m_OriginalContext.getResource(thePath);
}
public InputStream getResourceAsStream(String thePath)
{
return m_OriginalContext.getResourceAsStream(thePath);
}
/**
* @return our request dispatcher wrapper
*/
public RequestDispatcher getRequestDispatcher(String thePath)
{
RequestDispatcher dispatcher = new RequestDispatcherWrapper(
m_OriginalContext.getRequestDispatcher(thePath));
return dispatcher;
}
public RequestDispatcher getNamedDispatcher(String theName)
{
RequestDispatcher dispatcher = new RequestDispatcherWrapper(
m_OriginalContext.getNamedDispatcher(theName));
return dispatcher;
}
public String getRealPath(String thePath)
{
return m_OriginalContext.getRealPath(thePath);
}
/**
* @return our servlet context wrapper
*/
public ServletContext getContext(String theUripath)
{
ServletContext context = new ServletContextWrapper(
m_OriginalContext.getContext(theUripath));
return context;
}
public String getServerInfo()
{
return m_OriginalContext.getServerInfo();
}
public String getInitParameter(String theName)
{
return m_OriginalContext.getInitParameter(theName);
}
public Enumeration getInitParameterNames()
{
return m_OriginalContext.getInitParameterNames();
}
public Object getAttribute(String theName)
{
return m_OriginalContext.getAttribute(theName);
}
public Enumeration getAttributeNames()
{
return m_OriginalContext.getAttributeNames();
}
public void setAttribute(String theName, Object theAttribute)
{
m_OriginalContext.setAttribute(theName, theAttribute);
}
public void removeAttribute(String theName)
{
m_OriginalContext.removeAttribute(theName);
}
public int getMajorVersion()
{
return m_OriginalContext.getMajorVersion();
}
public int getMinorVersion()
{
return m_OriginalContext.getMinorVersion();
}
public void log(String theMessage)
{
m_OriginalContext.log(theMessage);
}
public void log(String theMessage, Throwable theCause)
{
m_OriginalContext.log(theMessage, theCause);
}
// deprecated methods
public Servlet getServlet(String theName) throws ServletException
{
return m_OriginalContext.getServlet(theName);
}
public Enumeration getServlets()
{
return m_OriginalContext.getServlets();
}
public Enumeration getServletNames()
{
return m_OriginalContext.getServletNames();
}
public void log(Exception theException, String theMessage)
{
m_OriginalContext.log(theException, theMessage);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/servlet23/org/apache/commons/j2eeunit/server/HttpServletRequestWrapper.java
Index: HttpServletRequestWrapper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import java.util.*;
import java.io.*;
import java.security.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.j2eeunit.*;
/**
* Encapsulation class for the Servlet 2.3 API <code>HttpServletRequest</code>.
* This is an implementation that delegates all the call to the
* <code>HttpServletRequest</code> object passed in the constructor except for
* some overiden methods which are use to simulate a URL. This is to be able to
* simulate any URL that would have been used to call the test method : if this
* was not done, the URL that would be returned (by calling the
* <code>getRequestURI()</code> method or others alike) would be the URL of the
* J2EEUnit redirector servlet and not a URL that the test case want to simulate.
*
* @version @version@
*/
public class HttpServletRequestWrapper implements HttpServletRequest
{
/**
* The real HTTP request
*/
private HttpServletRequest m_Request;
/**
* The URL to simulate
*/
private ServletURL m_URL;
/**
* Construct an <code>HttpServletRequest</code> instance that delegates
* it's method calls to the request object passed as parameter and that
* uses the URL passed as parameter to simulate a URL from which the request
* would come from.
*
* @param theRequest the real HTTP request
* @param theURL the URL to simulate or <code>null</code> if none
*/
public HttpServletRequestWrapper(HttpServletRequest theRequest, ServletURL
theURL)
{
m_Request = theRequest;
m_URL = theURL;
}
public HttpServletRequest getOriginalRequest()
{
return m_Request;
}
public boolean isUserInRole(String theRole)
{
return m_Request.isUserInRole(theRole);
}
public boolean isRequestedSessionIdValid()
{
return m_Request.isRequestedSessionIdValid();
}
public boolean isRequestedSessionIdFromUrl()
{
return m_Request.isRequestedSessionIdFromUrl();
}
public boolean isRequestedSessionIdFromURL()
{
return m_Request.isRequestedSessionIdFromURL();
}
public boolean isRequestedSessionIdFromCookie()
{
return m_Request.isRequestedSessionIdFromCookie();
}
public Principal getUserPrincipal()
{
return m_Request.getUserPrincipal();
}
public HttpSession getSession(boolean isCreate)
{
return m_Request.getSession(isCreate);
}
public HttpSession getSession()
{
return m_Request.getSession();
}
/**
* @return the servlet path from the simulated URL or the real servlet path
* if a simulation URL has not been defined.
*/
public String getServletPath()
{
if (m_URL != null) {
return m_URL.getServletPath();
}
return m_Request.getServletPath();
}
public String getRequestedSessionId()
{
return m_Request.getRequestedSessionId();
}
public StringBuffer getRequestURL()
{
return m_Request.getRequestURL();
}
/**
* @return the URI from the simulated URL or the real URI
* if a simulation URL has not been defined.
*/
public String getRequestURI()
{
if (m_URL != null) {
return m_URL.getURL().getFile();
}
return m_Request.getRequestURI();
}
public String getRemoteUser()
{
return m_Request.getRemoteUser();
}
/**
* @return the query string from the simulated URL or the real query
* string if a simulation URL has not been defined.
*/
public String getQueryString()
{
if (m_URL != null) {
return m_URL.getQueryString();
}
return m_Request.getQueryString();
}
public String getPathTranslated()
{
return m_Request.getPathTranslated();
}
/**
* @return the path info from the simulated URL or the real path info
* if a simulation URL has not been defined.
*/
public String getPathInfo()
{
if (m_URL != null) {
return m_URL.getPathInfo();
}
return m_Request.getPathInfo();
}
public String getMethod()
{
return m_Request.getMethod();
}
public int getIntHeader(String theName)
{
return m_Request.getIntHeader(theName);
}
public Enumeration getHeaders(String theName)
{
return m_Request.getHeaders(theName);
}
public Enumeration getHeaderNames()
{
return m_Request.getHeaderNames();
}
public String getHeader(String theName)
{
return m_Request.getHeader(theName);
}
public long getDateHeader(String theName)
{
return m_Request.getDateHeader(theName);
}
public Cookie[] getCookies()
{
return m_Request.getCookies();
}
/**
* @return the context path from the simulated URL or the real context path
* if a simulation URL has not been defined.
*/
public String getContextPath()
{
if (m_URL != null) {
return m_URL.getContextPath();
}
return m_Request.getContextPath();
}
public String getAuthType()
{
return m_Request.getAuthType();
}
public void setCharacterEncoding(String env) throws UnsupportedEncodingException
{
m_Request.setCharacterEncoding(env);
}
public void setAttribute(String theName, Object theAttribute)
{
m_Request.setAttribute(theName, theAttribute);
}
public void removeAttribute(String theName)
{
m_Request.removeAttribute(theName);
}
public boolean isSecure()
{
return m_Request.isSecure();
}
/**
* @return the server port number from the simulated URL or the real server
* port number if a simulation URL has not been defined. If not
* port is defined, then port 80 is returned.
*/
public int getServerPort()
{
if (m_URL != null) {
if (m_URL.getURL().getPort() == -1) {
return 80;
}
return m_URL.getURL().getPort();
}
return m_Request.getServerPort();
}
/**
* @return the server name from the simulated URL or the real server name
* if a simulation URL has not been defined.
*/
public String getServerName()
{
if (m_URL != null) {
return m_URL.getURL().getHost();
}
return m_Request.getServerName();
}
public String getScheme()
{
return m_Request.getScheme();
}
public RequestDispatcher getRequestDispatcher(String thePath)
{
return m_Request.getRequestDispatcher(thePath);
}
public String getRemoteHost()
{
return m_Request.getRemoteHost();
}
public String getRemoteAddr()
{
return m_Request.getRemoteAddr();
}
public String getRealPath(String thePath)
{
return m_Request.getRealPath(thePath);
}
public BufferedReader getReader() throws IOException
{
return m_Request.getReader();
}
public String getProtocol()
{
return m_Request.getProtocol();
}
public String[] getParameterValues(String theName)
{
return m_Request.getParameterValues(theName);
}
public Enumeration getParameterNames()
{
return m_Request.getParameterNames();
}
public Map getParameterMap()
{
return m_Request.getParameterMap();
}
public String getParameter(String theName)
{
return m_Request.getParameter(theName);
}
public Enumeration getLocales()
{
return m_Request.getLocales();
}
public Locale getLocale()
{
return m_Request.getLocale();
}
public ServletInputStream getInputStream() throws IOException
{
return m_Request.getInputStream();
}
public String getContentType()
{
return m_Request.getContentType();
}
public int getContentLength()
{
return m_Request.getContentLength();
}
public String getCharacterEncoding()
{
return m_Request.getCharacterEncoding();
}
public Enumeration getAttributeNames()
{
return m_Request.getAttributeNames();
}
public Object getAttribute(String theName)
{
return m_Request.getAttribute(theName);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/servlet23/org/apache/commons/j2eeunit/server/RequestDispatcherWrapper.java
Index: RequestDispatcherWrapper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Wrapper around <code>RequestDispatcher</code> which overrides the
* <code>forward()</code> and <code>include</code> methods to use the original
* HTTP request object instead of the simulated one used by J2EEUnit.
*
* @version @version@
*/
public class RequestDispatcherWrapper implements RequestDispatcher
{
/**
* The original request dispatcher object
*/
private RequestDispatcher m_OriginalDispatcher;
/**
* @param theOriginalDispatcher the original request dispatcher object
*/
public RequestDispatcherWrapper(RequestDispatcher theOriginalDispatcher)
{
m_OriginalDispatcher = theOriginalDispatcher;
}
/**
* Call the original <code>RequestDispatcher</code> <code>forward()</code>
* method but with the original HTTP request (not the simulation one which
* would make the servlet engine choke !).
*
* @param theRequest the simulation HTTP request
* @param theResponse the original HTTP response
*/
public void forward(ServletRequest theRequest, ServletResponse theResponse)
throws IOException, ServletException
{
HttpServletRequestWrapper request = (HttpServletRequestWrapper)theRequest;
m_OriginalDispatcher.forward(request.getOriginalRequest(), theResponse);
}
/**
* Call the original <code>RequestDispatcher</code> <code>include()</code>
* method but with the original HTTP request (not the simulation one which
* would make the servlet engine choke !).
*
* @param theRequest the simulation HTTP request
* @param theResponse the original HTTP response
*/
public void include(ServletRequest theRequest, ServletResponse theResponse)
throws IOException, ServletException
{
HttpServletRequestWrapper request = (HttpServletRequestWrapper)theRequest;
m_OriginalDispatcher.include(request.getOriginalRequest(), theResponse);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/servlet23/org/apache/commons/j2eeunit/server/ServletConfigWrapper.java
Index: ServletConfigWrapper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import java.util.*;
import java.io.*;
import java.security.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Wrapper around <code>ServletConfig</code> which overrides the
* <code>getServletContext()</code> method to return our own wrapper around
* <code>ServletContext</code>.
*
* @version @version@
* @see ServletContext
*/
public class ServletConfigWrapper implements ServletConfig
{
/**
* The original servlet config object
*/
private ServletConfig m_OriginalConfig;
/**
* List of parameters set using the <code>setInitParameter()</code> method.
*/
private Hashtable m_InitParameters;
/**
* Simulated name of the servlet
*/
private String m_ServletName;
/**
* @param theOriginalConfig the original servlet config object
*/
public ServletConfigWrapper(ServletConfig theOriginalConfig)
{
m_OriginalConfig = theOriginalConfig;
m_InitParameters = new Hashtable();
}
/**
* Sets a parameter as if it were set in the <code>web.xml</code> file.
*
* @param theName the parameter's name
* @param theValue the parameter's value
*/
public void setInitParameter(String theName, String theValue)
{
m_InitParameters.put(theName, theValue);
}
/**
* Sets the servlet name. That will be the value returned by the
* <code>getServletName()</code> method.
*
* @param theServletName the servlet's name
*/
public void setServletName(String theServletName)
{
m_ServletName = theServletName;
}
//--Overridden methods -----------------------------------------------------
/**
* @return the simulated servlet's name if defined or the redirector
* servlet's name
*/
public String getServletName()
{
if (m_ServletName != null) {
return m_ServletName;
}
return m_OriginalConfig.getServletName();
}
/**
* @return our own wrapped servlet context object
*/
public ServletContext getServletContext()
{
return new ServletContextWrapper(m_OriginalConfig.getServletContext());
}
/**
* @return the union of the parameters defined in the Redirector
* <code>web.xml</code> file and the one set using the
* <code>setInitParameter()</code> method.
*/
public Enumeration getInitParameterNames()
{
Vector names = new Vector();
Enumeration enum = m_InitParameters.keys();
while (enum.hasMoreElements()) {
String value = (String)enum.nextElement();
names.add(value);
}
enum = m_OriginalConfig.getInitParameterNames();
while (enum.hasMoreElements()) {
String value = (String)enum.nextElement();
names.add(value);
}
return names.elements();
}
/**
* @param theName the name of the parameter's value to return
* @return the value of the parameter, looking for it first in the list of
* parameters set using the <code>setInitParameter()</code> method
* and then in those set in <code>web.xml</code>.
*/
public String getInitParameter(String theName)
{
// Look first in the list of parameters set using the
// setInitParameter() method.
String value = (String)m_InitParameters.get(theName);
if (value == null) {
value = m_OriginalConfig.getInitParameter(theName);
}
return value;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/servlet23/org/apache/commons/j2eeunit/server/ServletContextWrapper.java
Index: ServletContextWrapper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import java.util.*;
import java.io.*;
import java.security.*;
import java.net.*;
import java.lang.reflect.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Wrapper around <code>ServletContext</code> which overrides the
* <code>getRequestDispatcher()</code> method to return our own wrapper around
* <code>RequestDispatcher</code>.
*
* @version @version@
* @see RequestDispatcherWrapper
*/
public class ServletContextWrapper implements ServletContext
{
/**
* The original servlet context object
*/
private ServletContext m_OriginalContext;
/**
* @param theOriginalContext the original servlet context object
*/
public ServletContextWrapper(ServletContext theOriginalContext)
{
m_OriginalContext = theOriginalContext;
}
public void setAttribute(String theName, Object theAttribute)
{
m_OriginalContext.setAttribute(theName, theAttribute);
}
public void removeAttribute(String theName)
{
m_OriginalContext.removeAttribute(theName);
}
public void log(String theMessage, Throwable theCause)
{
m_OriginalContext.log(theMessage, theCause);
}
public void log(String theMessage)
{
m_OriginalContext.log(theMessage);
}
public void log(Exception theException, String theMessage)
{
m_OriginalContext.log(theException, theMessage);
}
public Enumeration getServlets()
{
return m_OriginalContext.getServlets();
}
public Enumeration getServletNames()
{
return m_OriginalContext.getServletNames();
}
public String getServletContextName()
{
return m_OriginalContext.getServletContextName();
}
public Servlet getServlet(String theName) throws ServletException
{
return m_OriginalContext.getServlet(theName);
}
public String getServerInfo()
{
return m_OriginalContext.getServerInfo();
}
public Set getResourcePaths()
{
Set returnSet;
// Use reflection because newest Servlet API 2.3 changes removed this
// method
try {
Method method =
m_OriginalContext.getClass().getMethod("getResourcePaths", null);
if (method != null) {
returnSet = (Set)method.invoke(m_OriginalContext, null);
} else {
throw new RuntimeException("Method ServletContext.getResourcePaths()
no longer supported by your servlet engine !");
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error getting/calling method
getResourcePaths()");
}
return returnSet;
}
/**
* Added to support the changes of the Jakarta Servlet API 2.3 of the
* 17/03/2001 (in anticipation of the upcoming draft of Servlet 2.3). Kept
* the method without parameters for servlet engines that do have upgraded
* yet to the new signature.
*/
public Set getResourcePaths(String thePath)
{
Set returnSet;
// Check if the method exist (for servlet engines that do not have
// upgraded yet)
try {
Method method =
m_OriginalContext.getClass().getMethod("getResourcePaths", new Class[] { String.class
});
if (method != null) {
returnSet = (Set)method.invoke(m_OriginalContext, new Object[] {
thePath });
} else {
throw new RuntimeException("Method
ServletContext.getResourcePaths(String path) not supported yet by your servlet engine
!");
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error getting/calling method
getResourcePaths(String path)");
}
return returnSet;
}
public InputStream getResourceAsStream(String thePath)
{
return m_OriginalContext.getResourceAsStream(thePath);
}
public URL getResource(String thePath) throws MalformedURLException
{
return m_OriginalContext.getResource(thePath);
}
/**
* @return our request dispatcher wrapper
*/
public RequestDispatcher getRequestDispatcher(String thePath)
{
RequestDispatcher dispatcher = new RequestDispatcherWrapper(
m_OriginalContext.getRequestDispatcher(thePath));
return dispatcher;
}
public String getRealPath(String thePath)
{
return m_OriginalContext.getRealPath(thePath);
}
/**
* @return our request dispatcher wrapper
*/
public RequestDispatcher getNamedDispatcher(String theName)
{
RequestDispatcher dispatcher = new RequestDispatcherWrapper(
m_OriginalContext.getNamedDispatcher(theName));
return dispatcher;
}
public int getMinorVersion()
{
return m_OriginalContext.getMinorVersion();
}
public String getMimeType(String theFilename)
{
return m_OriginalContext.getMimeType(theFilename);
}
public int getMajorVersion()
{
return m_OriginalContext.getMajorVersion();
}
public Enumeration getInitParameterNames()
{
return m_OriginalContext.getInitParameterNames();
}
public String getInitParameter(String theName)
{
return m_OriginalContext.getInitParameter(theName);
}
/**
* @return our servlet context wrapper
*/
public ServletContext getContext(String theUripath)
{
ServletContext context = new ServletContextWrapper(
m_OriginalContext.getContext(theUripath));
return context;
}
public Enumeration getAttributeNames()
{
return m_OriginalContext.getAttributeNames();
}
public Object getAttribute(String theName)
{
return m_OriginalContext.getAttribute(theName);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/JspTestCase.java
Index: JspTestCase.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit;
import javax.servlet.jsp.*;
import org.apache.commons.j2eeunit.client.*;
/**
* Test classes that need access to valid JSP implicit objects (such as the
* page context, the output jsp writer, the HTTP request, ...) must subclass
* this class. It also provides support for <code>beginXXX</code> and
* <code>endXXX()</code> methods.
*
* @version @version@
*/
public class JspTestCase extends ServletTestCase
{
/**
* Valid <code>PageContext</code> object that you can access from
* the <code>testXXX()</code>, <code>setUp</code> and <code>tearDown()</code>
* methods. If you try to access it from either the
* <code>beginXXX()</code> or <code>endXXX()</code> methods it will
* have the <code>null</code> value.
*/
public PageContext pageContext;
/**
* Valid <code>JspWriter</code> object that you can access from
* the <code>testXXX()</code>, <code>setUp</code> and <code>tearDown()</code>
* methods. If you try to access it from either the
* <code>beginXXX()</code> or <code>endXXX()</code> methods it will
* have the <code>null</code> value.
*/
public JspWriter out;
/**
* Constructs a JUnit test case with the given name.
*
* @param theName the name of the test case
*/
public JspTestCase(String theName)
{
super(theName);
}
/**
* Runs a test case. This method is overriden from the JUnit
* <code>TestCase</code> class in order to seamlessly call the
* J2EEUnit redirection servlet.
*/
protected void runTest() throws Throwable
{
runGenericTest(new JspHttpClient());
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/ServiceDefinition.java
Index: ServiceDefinition.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit;
/**
* Constants that define HTTP parameters required for defining a service that
* is performed by the <code>ServletTestRedirector</code> servlet.
*/
public class ServiceDefinition
{
/**
* Name of the parameter in the HTTP request that represents the name of the
* Test class to call. The name is voluntarily long so that it will not clash
* with a user-defined parameter.
*/
public final static String CLASS_NAME_PARAM = "ServletTestRedirector_TestClass";
/**
* Name of the parameter in the HTTP request that represents the name of the
* Test method to call. The name is voluntarily long so that it will not clash
* with a user-defined parameter.
*/
public final static String METHOD_NAME_PARAM =
"ServletTestRedirector_TestMethod";
/**
* Name of the parameter in the HTTP request that specify if a session
* should be automatically created for the user or not.
*/
public final static String AUTOSESSION_NAME_PARAM =
"ServletTestRedirector_AutomaticSession";
/**
* Name of the parameter in the HTTP request that specify the service asked
* to the Redirector Servlet. It can be either to ask the Redirector Servlet
* to call the test method or to ask the Redirector Servlet to return the
* result of the last test.
*
* @see ServiceEnumeration
*/
public final static String SERVICE_NAME_PARAM = "ServletTestRedirector_Service";
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/ServiceEnumeration.java
Index: ServiceEnumeration.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit;
/**
* List of valid services that the <code>ServletTestRedirector</code> can perform.
*/
public class ServiceEnumeration
{
/**
* Call test method Service.
*/
public static final ServiceEnumeration CALL_TEST_SERVICE = new
ServiceEnumeration("CALL_TEST");
/**
* Get the previous test results Service.
*/
public static final ServiceEnumeration GET_RESULTS_SERVICE = new
ServiceEnumeration("GET_RESULTS");
/**
* The service's name
*/
private String m_Name;
public ServiceEnumeration(String theServiceName)
{
m_Name = theServiceName;
}
/**
* Compares a string representing the name of the service with the Service
enumerated type.
* @return true if the string corresponds to the current Service
*/
public boolean equals(String theString)
{
return theString.equals(m_Name);
}
/**
* @return the Service's name
*/
public String toString()
{
return m_Name;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/ServletTestCase.java
Index: ServletTestCase.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit;
import java.lang.reflect.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.client.*;
import org.apache.commons.j2eeunit.server.*;
/**
* Test classes that need access to valid Servlet implicit objects (such as the
* the HTTP request, the HTTP response, the servlet config, ...) must subclass
* this class. It also provides support for <code>beginXXX</code> and
* <code>endXXX()</code> methods.
*
* @version @version@
*/
public class ServletTestCase extends TestCase
{
/**
* The prefix of a test method.
*/
protected final static String TEST_METHOD_PREFIX = "test";
/**
* The prefix of a begin test method.
*/
protected final static String BEGIN_METHOD_PREFIX = "begin";
/**
* The prefix of an end test method.
*/
protected final static String END_METHOD_PREFIX = "end";
/**
* Valid <code>HttpServletRequest</code> object that you can access from
* the <code>testXXX()</code>, <code>setUp</code> and <code>tearDown()</code>
* methods. If you try to access it from either the
* <code>beginXXX()</code> or <code>endXXX()</code> methods it will
* have the <code>null</code> value.
*/
public org.apache.commons.j2eeunit.server.HttpServletRequestWrapper request;
/**
* Valid <code>HttpServletResponse</code> object that you can access from
* the <code>testXXX()</code>, <code>setUp</code> and <code>tearDown()</code>
* methods. If you try to access it from either the
* <code>beginXXX()</code> or <code>endXXX()</code> methods it will
* have the <code>null</code> value.
*/
public HttpServletResponse response;
/**
* Valid <code>HttpSession</code> object that you can access from
* the <code>testXXX()</code>, <code>setUp</code> and <code>tearDown()</code>
* methods. If you try to access it from either the
* <code>beginXXX()</code> or <code>endXXX()</code> methods it will
* have the <code>null</code> value.
*/
public HttpSession session;
/**
* Valid <code>ServletConfig</code> object that you can access from
* the <code>testXXX()</code>, <code>setUp</code> and <code>tearDown()</code>
* methods. If you try to access it from either the
* <code>beginXXX()</code> or <code>endXXX()</code> methods it will
* have the <code>null</code> value.
*/
public ServletConfigWrapper config;
/**
* The name of the current test method being executed. This name is valid
* both on the client side and on the server side, meaning you can call it
* from a <code>testXXX()</code>, <code>setUp()</code> or
* <code>tearDown()</code> method, as well as from <code>beginXXX()</code>
* and <code>endXXX()</code> methods.
*/
public String currentTestMethod;
/**
* Constructs a JUnit test case with the given name.
*
* @param theName the name of the test case
*/
public ServletTestCase(String theName)
{
super(theName);
currentTestMethod = name();
}
/**
* @return the name of the test method to call without the
* TEST_METHOD_PREFIX prefix
*/
private String getBaseMethodName()
{
// Sanity check
if (!name().startsWith(TEST_METHOD_PREFIX)) {
// qqq throw new InvalidMethodNameException
throw new RuntimeException("bad name [" + name() + "]. It should start
with [" + TEST_METHOD_PREFIX + "].");
}
return name().substring(TEST_METHOD_PREFIX.length());
}
/**
* @return the name of the test begin method to call that initialize the
* test by initializing the <code>ServletTestRequest</code> object
* for the test case.
*/
protected String getBeginMethodName()
{
return BEGIN_METHOD_PREFIX + getBaseMethodName();
}
/**
* @return the name of the test end method to call when the test has been
* run on the server. It can be used to verify returned headers,
* cookies, ...
*/
protected String getEndMethodName()
{
return END_METHOD_PREFIX + getBaseMethodName();
}
/**
* Call the test case begin method
*
* @param theRequest the <code>ServletTestRequest</code> object to
* pass to the begin method.
*/
protected void callBeginMethod(ServletTestRequest theRequest) throws Throwable
{
// First, verify if a begin method exist. If one is found, verify if
// it has the correct signature. If not, send a warning.
Method[] methods = getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(getBeginMethodName())) {
// Check return type
if (!methods[i].getReturnType().getName().equals("void")) {
fail("The begin method [" + methods[i].getName() +
"] should return void and not [" +
methods[i].getReturnType().getName() + "]");
}
// Check if method is public
if (!Modifier.isPublic(methods[i].getModifiers())) {
fail("Method [" + methods[i].getName() + "] should be declared
public");
}
// Check parameters
Class[] parameters = methods[i].getParameterTypes();
if ((parameters.length != 1) ||
(!parameters[0].equals(ServletTestRequest.class))) {
fail("The begin method [" + methods[i].getName() +
"] must accept a single parameter of type [" +
ServletTestRequest.class.getName() + "]");
}
try {
methods[i].invoke(this, new Object[] { theRequest });
} catch (InvocationTargetException e) {
e.fillInStackTrace();
throw e.getTargetException();
}
catch (IllegalAccessException e) {
e.fillInStackTrace();
throw e;
}
}
}
}
/**
* Call the test case end method
*
* @param theConnection the <code>HttpURLConnection</code> that was used
* to open the connection to the redirection servlet. The response
* codes, headers, cookies can be checked using the get methods of
* this object.
*/
protected void callEndMethod(HttpURLConnection theConnection) throws Throwable
{
// First, verify if an end method exist. If one is found, verify if
// it has the correct signature. If not, send a warning.
Method[] methods = getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(getEndMethodName())) {
// Check return type
if (!methods[i].getReturnType().getName().equals("void")) {
fail("The end method [" + methods[i].getName() +
"] should return void and not [" +
methods[i].getReturnType().getName() + "]");
}
// Check if method is public
if (!Modifier.isPublic(methods[i].getModifiers())) {
fail("Method [" + methods[i].getName() + "] should be declared
public");
}
// Check parameters
Class[] parameters = methods[i].getParameterTypes();
if ((parameters.length != 1) ||
(!parameters[0].equals(HttpURLConnection.class))) {
fail("The end method [" + methods[i].getName() +
"] must accept a single parameter of type [" +
HttpURLConnection.class.getName() + "]");
}
try {
methods[i].invoke(this, new Object[] { theConnection });
} catch (InvocationTargetException e) {
e.fillInStackTrace();
throw e.getTargetException();
}
catch (IllegalAccessException e) {
e.fillInStackTrace();
throw e;
}
}
}
}
/**
* Runs the bare test sequence. This method is overridden from the
* JUnit <code>TestCase</code> class in order to prevent the latter
* to call the <code>setUp()</code> and <code>tearDown()</code> methods
* which, in our case, need to be ran in the servlet engine by the
* servlet redirector class.
*
* @exception Throwable if any exception is thrown
*/
public void runBare() throws Throwable
{
runTest();
}
/**
* Runs a test case. This method is overriden from the JUnit
* <code>TestCase</code> class in order to seamlessly call the
* J2EEUnit redirection servlet.
*/
protected void runTest() throws Throwable
{
runGenericTest(new ServletHttpClient());
}
protected void runGenericTest(AbstractHttpClient theHttpClient) throws Throwable
{
// Call the begin method to fill the request object
ServletTestRequest request = new ServletTestRequest();
callBeginMethod(request);
// Add the class name, the method name, the URL to simulate and
// automatic session creation flag to the request
request.addParameter(ServiceDefinition.CLASS_NAME_PARAM,
this.getClass().getName());
request.addParameter(ServiceDefinition.METHOD_NAME_PARAM, name());
request.addParameter(ServiceDefinition.AUTOSESSION_NAME_PARAM,
new Boolean(request.getAutomaticSession()).toString());
// Add the simulated URL (if one has been defined)
if (request.getURL() != null) {
request.getURL().saveToRequest(request);
}
// Open the HTTP connection to the servlet redirector
// and manage errors that could be returned in the
// HTTP response.
HttpURLConnection connection = theHttpClient.doTest(request);
// Call the end method
callEndMethod(connection);
// Close the intput stream (just in the case the user has not done it
// in it's endXXX method (or if he has no endXXX method) ....
connection.getInputStream().close();
//connection.disconnect();
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/ServletTestRequest.java
Index: ServletTestRequest.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit;
import java.util.*;
/**
* Contains all HTTP request data for a test case. It is the data that
* will be sent to the server redirector and that will be available to the test
* methods through the <code>HttpServletRequest</code> object.
* <br><br>
* Namely, it is :
* <ul>
* <li>Request parameters that the test case can retrieve using
* <code>HttpServletRequest.getParameters()</code>,</li>
* <li>Cookies that the test case can retrieve using
* <code>HttpServletRequest.getCookies()</code>,</li>
* <li>HTTP headers that the test case can retrieve using the
* <code>HttpServletRequest.getHeader(), getHeaders(),
* ...</code> APIs,</li>
* <li>URL data the the test case can retrieve using
* <code>HttpServletRequest.getRequestURI(), ...</code></li>
* <li>Whether you want the server redirector to automatically create a
* session for you or not,</li>
* <li>Whether you want the HTTP connection to the server redirector to
* use a POST or GET method. Default is POST</li>
* </ul>
*
* @version @version@
*/
public class ServletTestRequest
{
/**
* The request parameters.
*/
private Hashtable m_Parameters = new Hashtable();
/**
* GET Method identifier.
*/
public static final String GET_METHOD = "GET";
/**
* POST Method identifier.
*/
public static final String POST_METHOD = "POST";
/**
* The Cookies
*/
private Hashtable m_Cookies = new Hashtable();
/**
* HTTP Headers.
*/
private Hashtable m_Headers = new Hashtable();
/**
* The URL to simulate
*/
private ServletURL m_URL;
/**
* Automatic session creation flag (default is true).
*/
private boolean m_isAutomaticSession = true;
/**
* The chosen method for posting data (GET or POST)
*/
private String m_Method = POST_METHOD;
/**
* @param theMethod the method to use to post data (GET or POST)
*/
public void setMethod(String theMethod)
{
if (theMethod.equalsIgnoreCase(GET_METHOD)) {
m_Method = GET_METHOD;
} else if (theMethod.equalsIgnoreCase(POST_METHOD)) {
m_Method = POST_METHOD;
}
}
/**
* @return the method to use for posting data to the server redirector.
*/
public String getMethod()
{
return m_Method;
}
/**
* @param isAutomaticSession whether the redirector servlet will automatically
* create the HTTP session or not. Default is true.
*/
public void setAutomaticSession(boolean isAutomaticSession)
{
m_isAutomaticSession = isAutomaticSession;
}
/**
* @return true if session will be automatically created for the user or
* false otherwise.
*/
public boolean getAutomaticSession()
{
return m_isAutomaticSession;
}
/**
* Sets the simulated URL. A URL is of the form :<br>
* <code><pre><b>
* URL = "http://" + serverName (including port) + requestURI ?
queryString<br>
* requestURI = contextPath + servletPath + pathInfo
* </b></pre></code>
* From the Servlet 2.2 specification :<br>
* <code><pre><ul><li><b>Context Path</b>: The path prefix associated with the
* ServletContext that this servlet is a part of. If this context is the
* default context rooted at the base of the web server's URL namespace, this
* path will be an empty string. Otherwise, this path starts with a character
* but does not end with a character.</li>
* <li><b>Servlet Path</b>: The path section that directly corresponds to the
* mapping which activated this request. This path starts with a
character.</li>
* <li><b>PathInfo</b>: The part of the request path that is not part of the
* Context Path or the Servlet Path.</li></ul></pre></code>
*
* @param theServerName the server name (and port) in the URL to simulate,
* i.e. this is the name that will be returned by the
* <code>HttpServletRequest.getServerName()</code> and
* <code>HttpServletRequest.getServerPort()</code>.
* @param theContextPath the webapp context path in the URL to simulate,
* i.e. this is the name that will be returned by the
* <code>HttpServletRequest.getContextPath()</code>.
* Can be null. Format: "/" + name or an empty string
* for the default context.
* @param theServletPath the servlet path in the URL to simulate,
* i.e. this is the name that will be returned by the
* <code>HttpServletRequest.getServletPath()</code>.
* Can be null. Format : "/" + name.
* @param thePathInfo the path info in the URL to simulate, i.e. this is
* the name that will be returned by the
* <code>HttpServletRequest.getPathInfo()</code>. Can
* be null. Format : "/" + name.
* @param theQueryString the Query string in the URL to simulate, i.e. this
* is the string that will be returned by the
* <code>HttpServletResquest.getQueryString()</code>.
* Can be null.
*/
public void setURL(String theServerName, String theContextPath,
String theServletPath, String thePathInfo, String theQueryString)
{
m_URL = new ServletURL(theServerName, theContextPath,
theServletPath, thePathInfo, theQueryString);
}
/**
* @return the simulated URL
*/
public ServletURL getURL()
{
return m_URL;
}
/**
* Adds a parameter to the request. It is possible to add several times the
* the same parameter name (the same as for the <code>HttpServletRequest</code>).
*
* @param theName the parameter's name
* @param theValue the parameter's value
*/
public void addParameter(String theName, String theValue)
{
// If there is already a parameter of the same name, add the
// new value to the Vector. If not, create a Vector an add it to the
// hashtable
if (m_Parameters.containsKey(theName)) {
Vector v = (Vector)m_Parameters.get(theName);
v.addElement(theValue);
} else {
Vector v = new Vector();
v.addElement(theValue);
m_Parameters.put(theName, v);
}
}
/**
* @return the parameter names
*/
public Enumeration getParameterNames()
{
return m_Parameters.keys();
}
/**
* Returns the first value corresponding to this parameter's name.
*
* @param theName the parameter's name
* @return the first value corresponding to this parameter's name or null if not
* found
*/
public String getParameter(String theName)
{
String[] values = getParameterValues(theName);
if (values != null) {
return values[0];
}
return null;
}
/**
* Returns all the values associated with this parameter's name.
*
* @param theName the parameter's name
* @return the values corresponding to this parameter's name or null if not
* found
*/
public String[] getParameterValues(String theName)
{
if (m_Parameters.containsKey(theName)) {
Vector v = (Vector)m_Parameters.get(theName);
Object[] objs = new Object[v.size()];
v.copyInto(objs);
String[] result = new String[objs.length];
for (int i = 0; i < objs.length; i++) {
result[i] = (String)objs[i];
}
return result;
}
return null;
}
/**
* Adds a cookie to the request.
*
* @param theName the cookie's name
* @param theValue the cookie's value
*/
public void addCookie(String theName, String theValue)
{
m_Cookies.put(theName, theValue);
}
/**
* @return the cookie names
*/
public Enumeration getCookieNames()
{
return m_Cookies.keys();
}
/**
* @param theName the cookie's name
* @return the value corresponding to this cookie's name or null if not
* found
*/
public String getCookieValue(String theName)
{
return (String)m_Cookies.get(theName);
}
/**
* Adds a header to the request.
*
* @param theName the header's name
* @param theValue the header's value
*/
public void addHeader(String theName, String theValue)
{
m_Headers.put(theName, theValue);
}
/**
* @return the header names
*/
public Enumeration getHeaderNames()
{
return m_Headers.keys();
}
/**
* @param theName the header's name
* @return the value corresponding to this header's name or null if not
* found
*/
public String getHeaderValue(String theName)
{
return (String)m_Headers.get(theName);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/ServletTestResult.java
Index: ServletTestResult.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit;
import java.io.*;
/**
* Represent the result of the execution of the Test class by the
* server redirector.If any exception was raised during the test, it
* is saved by this class.
*
* @version @version@
*/
public class ServletTestResult implements Serializable
{
/**
* Name of the exception class if an error occurred
*/
private String exceptionClassName;
/**
* Save the stack trace as text because otherwise it will not be
* transmitted back to the client (the stack trac field in the
* <code>Throwable</code> class is transient).
*/
private String exceptionStackTrace;
/**
* The exception message if an error occurred
*/
private String exceptionMessage;
/**
* Constructor to call when the test was ok and no error was raised.
*/
public ServletTestResult()
{
}
/**
* Constructor to call when an exception was raised during the test.
*
* @param theException the raised exception.
*/
public ServletTestResult(Throwable theException)
{
exceptionClassName = theException.getClass().getName();
exceptionMessage = theException.getMessage();
// Save the stack trace as text
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
theException.printStackTrace(pw);
exceptionStackTrace = sw.toString();
}
/**
* @return the exception class name if an exception was raised or
* <code>null</code> otherwise.
*/
public String getExceptionClassName()
{
return exceptionClassName;
}
/**
* @return the exception message if an exception was raised or
* <code>null</code> otherwise.
*/
public String getExceptionMessage()
{
return exceptionMessage;
}
/**
* @return true if an exception was raised during the test, false otherwise.
*/
public boolean hasException()
{
return (exceptionClassName != null);
}
/**
* @return the stack trace as a string
*/
public String getExceptionStackTrace()
{
return exceptionStackTrace;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/ServletURL.java
Index: ServletURL.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit;
import java.util.*;
import java.io.*;
import java.security.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import junit.framework.*;
/**
* Simulate an HTTP URL by breaking it into its different parts :<br>
* <code><pre><b>
* URL = "http://" + serverName (including port) + requestURI ?
queryString<br>
* requestURI = contextPath + servletPath + pathInfo
* </b></pre></code>
* From the Servlet 2.2 specification :<br>
* <code><pre><ul><li><b>Context Path</b>: The path prefix associated with the
* ServletContext that this servlet is a part of. If this context is the
* default context rooted at the base of the web server's URL namespace, this
* path will be an empty string. Otherwise, this path starts with a character
* but does not end with a character.</li>
* <li><b>Servlet Path</b>: The path section that directly corresponds to the
* mapping which activated this request. This path starts with a character.</li>
* <li><b>PathInfo</b>: The part of the request path that is not part of the
* Context Path or the Servlet Path.</li></ul></pre></code>
*
* @version @version@
*/
public class ServletURL
{
/**
* Name of the parameter in the HTTP request that represents the Server name
* in the URL to simulate. The name is voluntarily long so that it will not
* clash with a user-defined parameter.
*/
public final static String URL_SERVER_NAME_PARAM = "ServletTestCase_URL_Server";
/**
* Name of the parameter in the HTTP request that represents the context path
* in the URL to simulate. The name is voluntarily long so that it will not
* clash with a user-defined parameter.
*/
public final static String URL_CONTEXT_PATH_PARAM =
"ServletTestCase_URL_ContextPath";
/**
* Name of the parameter in the HTTP request that represents the Servlet
* Path in the URL to simulate. The name is voluntarily long so that it will not
* clash with a user-defined parameter.
*/
public final static String URL_SERVLET_PATH_PARAM =
"ServletTestCase_URL_ServletPath";
/**
* Name of the parameter in the HTTP request that represents the Path Info
* in the URL to simulate. The name is voluntarily long so that it will not
* clash with a user-defined parameter.
*/
public final static String URL_PATH_INFO_PARAM = "ServletTestCase_URL_PathInfo";
/**
* Name of the parameter in the HTTP request that represents the Query String
* in the URL to simulate. The name is voluntarily long so that it will not
* clash with a user-defined parameter.
*/
public final static String URL_QUERY_STRING_PARAM =
"ServletTestCase_URL_QueryString";
/**
* The server name to simulate (including port number)
*/
private String m_URL_ServerName;
/**
* The context path to simulate
*/
private String m_URL_ContextPath;
/**
* The servlet path to simulate
*/
private String m_URL_ServletPath;
/**
* The Path Info to simulate
*/
private String m_URL_PathInfo;
/**
* The Query string
*/
private String m_URL_QueryString;
/**
* The full URL (useful later because we can benefit from the all
* methods of the <code>URL</code> class.
*/
private URL m_FullURL;
/**
* Creates the URL to simulate.
*
* @param theServerName the server name (and port) in the URL to simulate,
* i.e. this is the name that will be returned by the
* <code>HttpServletRequest.getServerName()</code> and
* <code>HttpServletRequest.getServerPort()</code>.
* @param theContextPath the webapp context path in the URL to simulate,
* i.e. this is the name that will be returned by the
* <code>HttpServletRequest.getContextPath()</code>.
* Can be null. Format: "/" + name or an empty string
* for the default context.
* @param theServletPath the servlet path in the URL to simulate,
* i.e. this is the name that will be returned by the
* <code>HttpServletRequest.getServletPath()</code>.
* Can be null. Format : "/" + name.
* @param thePathInfo the path info in the URL to simulate, i.e. this is
* the name that will be returned by the
* <code>HttpServletRequest.getPathInfo()</code>. Can
* be null. Format : "/" + name.
* @param theQueryString the Query string in the URL to simulate, i.e. this
* is the string that will be returned by the
* <code>HttpServletResquest.getQueryString()</code>.
* Can be null.
*/
public ServletURL(String theServerName, String theContextPath, String
theServletPath,
String thePathInfo, String theQueryString)
{
if (theServerName == null) {
throw new AssertionFailedError("Bad URL. The server name cannot be
null");
}
m_URL_ServerName = theServerName;
m_URL_ContextPath = (theContextPath == null) ? "" : theContextPath;
m_URL_ServletPath = theServletPath;
m_URL_PathInfo = thePathInfo;
m_URL_QueryString = theQueryString;
// create a full URL
String fullURL = "http://" + m_URL_ServerName;
if (m_URL_ContextPath.length() != 0) {
fullURL = fullURL + m_URL_ContextPath;
}
if ((m_URL_ServletPath != null) && (m_URL_ServletPath.length() != 0)) {
fullURL = fullURL + m_URL_ServletPath;
}
if ((m_URL_PathInfo != null) && (m_URL_PathInfo.length() != 0)) {
fullURL = fullURL + m_URL_PathInfo;
}
try {
m_FullURL = new URL(fullURL);
} catch (MalformedURLException e) {
throw new AssertionFailedError("Bad URL [" + fullURL + "]");
}
}
/**
* @return the full URL as a <code>URL</code> object.
*/
public URL getURL()
{
return m_FullURL;
}
/**
* @return the simulated URL server name (including the port number)
*/
public String getServerName()
{
return m_URL_ServerName;
}
/**
* @return the simulated URL context path
*/
public String getContextPath()
{
return m_URL_ContextPath;
}
/**
* @return the simulated URL servlet path
*/
public String getServletPath()
{
return m_URL_ServletPath;
}
/**
* @return the simulated URL path info
*/
public String getPathInfo()
{
return m_URL_PathInfo;
}
/**
* @return the simulated Query String
*/
public String getQueryString()
{
return m_URL_QueryString;
}
/**
* Saves the current URL to a <code>ServletTestRequest</code> object.
*
* @param theRequest the object to which the current URL should be saved to
*/
public void saveToRequest(ServletTestRequest theRequest)
{
if (m_URL_ServerName != null) {
theRequest.addParameter(URL_SERVER_NAME_PARAM, getServerName());
}
if (m_URL_ContextPath != null) {
theRequest.addParameter(URL_CONTEXT_PATH_PARAM, getContextPath());
}
if (m_URL_ServletPath != null) {
theRequest.addParameter(URL_SERVLET_PATH_PARAM, getServletPath());
}
if (m_URL_PathInfo != null) {
theRequest.addParameter(URL_PATH_INFO_PARAM, getPathInfo());
}
if (m_URL_QueryString != null) {
theRequest.addParameter(URL_QUERY_STRING_PARAM, getQueryString());
}
}
/**
* Creates a <code>ServletURL</code> object by loading it's values from the
* HTTP request.
*
* @param theRequest the incoming HTTP request.
*/
public static ServletURL loadFromRequest(HttpServletRequest theRequest)
{
String serverName = theRequest.getParameter(URL_SERVER_NAME_PARAM);
String contextPath = theRequest.getParameter(URL_CONTEXT_PATH_PARAM);
String servletPath = theRequest.getParameter(URL_SERVLET_PATH_PARAM);
String pathInfo = theRequest.getParameter(URL_PATH_INFO_PARAM);
String queryString = theRequest.getParameter(URL_QUERY_STRING_PARAM);
if (serverName != null) {
return new ServletURL(serverName, contextPath, servletPath, pathInfo,
queryString);
}
return null;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/overview.html
Index: overview.html
===================================================================
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>J2EEUnit is a JUnit extension to unit test server-side java code. A server-
side java code is some code that is called either by a JSP or by a Servlet.
Server-side code is also code that may need to have access to valid
<code>HttpServletRequest</code>, <code>HttpServletResponse</code> and
<code>HttpSession</code> objects.</p>
<p>Go to <a href="http://j2eeunit.sourceforge.net">J2EEUnit web site</a> for all
documentation and tutorials for installing and running J2EEUnit</p>
</body>
</html>
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/package.html
Index: package.html
===================================================================
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>Base package for the J2EEUnit project. All the framework classes are located
under subpackages of this package.
</body>
</html>
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/client/AbstractHttpClient.java
Index: AbstractHttpClient.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.client;
import java.util.*;
import java.net.*;
import java.io.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
/**
* Abstract class that all HTTP clients to the server redirector must extend.
* It provides a common abstraction of the <code>doTest</code> method and
* provides the URL to the server redirector servlet or JSP.
*
* @version @version@
*/
public abstract class AbstractHttpClient
{
/**
* Default URL to call the <code>jspRedirector</code> JSP.
*/
protected final static String m_JspRedirectorURL =
PropertyResourceBundle.getBundle("j2eeunit").getString("j2eeunit.jspRedirectorURL");
/**
* Default URL to call the <code>ServletRedirector</code> servlet.
*/
protected final static String m_ServletRedirectorURL =
PropertyResourceBundle.getBundle("j2eeunit").getString("j2eeunit.servletRedirectorURL");
/**
* Calls the test method indirectly by calling the Redirector servlet and
* then open a second HTTP connection to retrieve the test results.
*
* @param theRequest the request containing all data to pass to the
* redirector servlet.
*
* @return the <code>HttpURLConnection</code> that contains the HTTP
* response when the test was called.
*
* @exception Throwable if an error occured in the test method or in the
* redirector servlet.
*/
public abstract HttpURLConnection doTest(ServletTestRequest theRequest) throws
Throwable;
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/client/AssertionFailedErrorWrapper.java
Index: AssertionFailedErrorWrapper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.client;
import java.io.*;
import junit.framework.*;
/**
* Same as <code>ServletExceptionWrapper</code> except that this exception class
* extends JUnit <code>AssertionFailedError</code> so that JUnit will
* print a different message in it's runner console.
*
* @version @version@
*/
public class AssertionFailedErrorWrapper extends AssertionFailedError
{
/**
* The stack trace that was sent back from the servlet redirector as a
* string.
*/
private String m_StackTrace;
/**
* The class name of the exception that was raised on the server side.
*/
private String m_ClassName;
/**
* Standard throwable constructor.
*
* @param theMessage the exception message
*/
public AssertionFailedErrorWrapper(String theMessage)
{
super(theMessage);
}
/**
* Standard throwable constructor.
*/
public AssertionFailedErrorWrapper()
{
super();
}
/**
* The constructor to use to simulate a real exception.
*
* @param theMessage the server exception message
* @param theClassName the server exception class name
* @param theStackTrace the server exception stack trace
*/
public AssertionFailedErrorWrapper(String theMessage, String theClassName,
String theStackTrace)
{
super(theMessage);
m_ClassName = theClassName;
m_StackTrace = theStackTrace;
}
/**
* Simulates a printing of a stack trace by printing the string stack trace
*
* @param thePs the stream to which to output the stack trace
*/
public void printStackTrace(PrintStream thePs)
{
if (m_StackTrace == null) {
thePs.print(getMessage());
} else {
thePs.print(m_StackTrace);
}
}
/**
* Simulates a printing of a stack trace by printing the string stack trace
*
* @param thePw the writer to which to output the stack trace
*/
public void printStackTrace(PrintWriter thePw)
{
if (m_StackTrace == null) {
thePw.print(getMessage());
} else {
thePw.print(m_StackTrace);
}
}
/**
* As all the server exceptions are wrapped into this
* <code>ServletExceptionWrapper</code> class, we need to be able to
* know the original server exception class.
*
* @param theClass the class to compare with the server exception class
*/
public boolean instanceOf(Class theClass)
{
if (m_ClassName == null) {
return false;
}
return theClass.getName().equals(m_ClassName);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/client/HttpClientHelper.java
Index: HttpClientHelper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.client;
import java.util.*;
import java.net.*;
import java.io.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
/**
* Helper class to open an HTTP connection to the server redirector and pass
* to it HTTP parameters, Cookies and HTTP headers.
*
* @version @version@
*/
class HttpClientHelper
{
/**
* The URL that will be used for the HTTP connection.
*/
private String m_URL;
/**
* @param theURL the URL that will be used for the HTTP connection.
*/
public HttpClientHelper(String theURL)
{
m_URL = theURL;
}
/**
* Add the parameters to the request using a GET method.
*
* @param theRequest the request containing all data to pass to the server
* redirector.
* @param theURL the URL used to connect to the server redirector.
* @return the new URL
*/
private URL addParametersUsingGet(ServletTestRequest theRequest, URL theURL)
throws Throwable
{
// If no parameters, then exit
if (!theRequest.getParameterNames().hasMoreElements()) {
return theURL;
}
StringBuffer queryString = new StringBuffer();
Enumeration keys = theRequest.getParameterNames();
if (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String[] values = theRequest.getParameterValues(key);
queryString.append(key);
queryString.append('=');
queryString.append(URLEncoder.encode(values[0]));
for (int i = 1; i < values.length; i++) {
queryString.append('&');
queryString.append(key);
queryString.append('=');
queryString.append(URLEncoder.encode(values[i]));
}
}
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String[] values = theRequest.getParameterValues(key);
for (int i = 0; i < values.length; i++) {
queryString.append('&');
queryString.append(key);
queryString.append('=');
queryString.append(URLEncoder.encode(values[i]));
}
}
String file;
if (theURL.toString().indexOf("?") > 0) {
file = theURL.getFile() + "&" + queryString.toString();
} else {
file = theURL.getFile() + "?" + queryString.toString();
}
return new URL(theURL.getProtocol(), theURL.getHost(),
theURL.getPort(), file);
}
/**
* Add the parameters to the request using a POST method.
*
* @param theRequest the request containing all data to pass to the server
* redirector.
* @param theConnection the HTTP connection
*/
private void addParametersUsingPost(ServletTestRequest theRequest, URLConnection
theConnection) throws Throwable
{
// If no parameters, then exit
if (!theRequest.getParameterNames().hasMoreElements()) {
return;
}
PrintWriter out;
try {
out = new PrintWriter(theConnection.getOutputStream());
} catch (ConnectException e) {
// Cannot connect to server, try to explain why ...
String reason = "Cannot connect to URL [" + theConnection.getURL() + "].
Reason : [" + e.getMessage() + "]\r\n";
reason += "Possible reasons :\r\n";
reason += "\t- The server is not running,\r\n";
reason += "\t- The server redirector is not correctly mapped in
web.xml,\r\n";
reason += "\t- Something else ... !";
throw new Exception(reason);
}
StringBuffer queryString = new StringBuffer();
Enumeration keys = theRequest.getParameterNames();
if (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String[] values = theRequest.getParameterValues(key);
queryString.append(key);
queryString.append('=');
queryString.append(URLEncoder.encode(values[0]));
for (int i = 1; i < values.length; i++) {
queryString.append('&');
queryString.append(key);
queryString.append('=');
queryString.append(URLEncoder.encode(values[i]));
}
}
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String[] values = theRequest.getParameterValues(key);
for (int i = 0; i < values.length; i++) {
queryString.append('&');
queryString.append(key);
queryString.append('=');
queryString.append(URLEncoder.encode(values[i]));
}
}
out.print(queryString.toString());
out.close();
}
/**
* Add the Cookies to the request.
*
* @param theRequest the request containing all data to pass to the server
* redirector.
* @param theConnection the HTTP connection
*/
private void addCookies(ServletTestRequest theRequest, URLConnection
theConnection)
{
// If no Cookies, then exit
if (!theRequest.getCookieNames().hasMoreElements()) {
return;
}
Enumeration keys = theRequest.getCookieNames();
StringBuffer cookieString = new StringBuffer();
// Format of a Cookie string is (according to RFC 2109) :
// cookie = "Cookie:" cookie-version
// 1*((";" | ",") cookie-value)
// cookie-value = NAME "=" VALUE [";" path] [";" domain]
// cookie-version = "$Version" "=" value
// NAME = attr
// VALUE = value
// path = "$Path" "=" value
// domain = "$Domain" "=" value
// Write the cookie version first
cookieString.append("$Version=1");
// Possible improvement here: to add support for :
// - path
// - domain
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = (String)theRequest.getCookieValue(key);
cookieString.append(';');
cookieString.append(URLEncoder.encode(key));
cookieString.append('=');
cookieString.append(URLEncoder.encode(value));
}
theConnection.setRequestProperty("Cookie", cookieString.toString());
}
/**
* Add the Headers to the request.
*
* @param theRequest the request containing all data to pass to the server
* redirector.
* @param theConnection the HTTP connection
*/
private void addHeaders(ServletTestRequest theRequest, URLConnection
theConnection)
{
Enumeration keys = theRequest.getHeaderNames();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = (String)theRequest.getHeaderValue(key);
theConnection.setRequestProperty(key, value);
}
}
/**
* Calls the Servlet Redirector.
*
* @param theRequest the request containing all data to pass to the
* server redirector.
*
* @exception Throwable if an unexpected error occured
*/
public HttpURLConnection connect(ServletTestRequest theRequest) throws Throwable
{
URL url = new URL(m_URL);
// If the method is GET, add the parameters to the URL
if (theRequest.getMethod().equals(theRequest.GET_METHOD)) {
url = addParametersUsingGet(theRequest, url);
}
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
// Choose the method that we will use to post data
if (theRequest.getMethod().equals(theRequest.POST_METHOD)) {
connection.setDoOutput(true);
} else {
connection.setDoOutput(false);
}
connection.setUseCaches(false);
// Add the other header fields
addHeaders(theRequest, connection);
// Add the cookies
addCookies(theRequest, connection);
// Add the POST parameters
if (theRequest.getMethod().equals(theRequest.POST_METHOD)) {
addParametersUsingPost(theRequest, connection);
}
// Open the connection and get the result
connection.connect();
return connection;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/client/JspHttpClient.java
Index: JspHttpClient.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.client;
import java.util.*;
import java.net.*;
import java.io.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
/**
* Manage the logic for calling a test method (which need access to JSP
* objects) located on the server side. First opens an HTTP connection to
* the redirector JSP (which in trun calls the test) and get the test results
* by opening a second HTTP connection but to the Servlet redirector (the tests
* were saved in the application context scope).
*
* @version @version@
*/
public class JspHttpClient extends AbstractHttpClient
{
/**
* Calls the test method indirectly by calling the Redirector JSP and
* then open a second HTTP connection to the Servlet Redirector to retrieve
* the test results.
*
* @param theRequest the request containing all data to pass to the
* redirector JSP.
*
* @return the <code>HttpURLConnection</code> object that contains the HTTP
* response when the test was called.
*
* @exception Throwable if an error occured in the test method or in the
* redirector servlet.
*/
public HttpURLConnection doTest(ServletTestRequest theRequest) throws Throwable
{
ServletTestResult result = null;
HttpURLConnection connection = null;
// Open the first connection to the redirector JSP
HttpClientHelper helper1 = new HttpClientHelper(m_JspRedirectorURL);
// Specify the service to call on the redirector side
theRequest.addParameter(ServiceDefinition.SERVICE_NAME_PARAM,
ServiceEnumeration.CALL_TEST_SERVICE.toString());
connection = helper1.connect(theRequest);
// Note: We need to get the input stream here to trigger the actual
// call to the servlet ... Don't know why exactly ... :(
connection.getInputStream();
// Open the second connection (to the Servlet redirector) to get the
// test results
HttpClientHelper helper2 = new HttpClientHelper(m_ServletRedirectorURL);
ServletTestRequest resultsRequest = new ServletTestRequest();
resultsRequest.addParameter(ServiceDefinition.SERVICE_NAME_PARAM,
ServiceEnumeration.GET_RESULTS_SERVICE.toString());
HttpURLConnection resultConnection = helper2.connect(resultsRequest);
// Read the results as a serialized object
ObjectInputStream ois = new
ObjectInputStream(resultConnection.getInputStream());
result = (ServletTestResult)ois.readObject();
ois.close();
// Check if the result object returned from the redirection servlet
// contains an error or not. If yes, we need to raise an exception
// for the JUnit framework to catch it.
if (result.hasException()) {
// Wrap the exception message and stack trace into a fake
// class that extends Throwable (i.e.
// <code>ServletExceptionWrapper</code>) with an overloaded
// <code>printStackTrace()</code> methods so that when JUnit calls
// this method it will print the stack trace that was set on the
// <code>Throwable</code> is transient and thus cannot be
// serialized !
throw new ServletExceptionWrapper(
result.getExceptionMessage(), result.getExceptionClassName(),
result.getExceptionStackTrace());
}
return connection;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/client/ServletExceptionWrapper.java
Index: ServletExceptionWrapper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.client;
import java.io.*;
/**
* Wrapper around a <code>Throwable</code> object. Whenever an exception occurs
* in a test case executed on the server side, the text of this exception
* along with the stack trace as a String are sent back in the HTTP response.
* This is because some exceptions are not serializable and because the stack
* trace is implemented as a <code>transient</code> variable by the JDK so it
* cannot be transported in the response. However, we need to send a real
* exception object to JUnit so that the exception stack trace will be printed
* in the JUnit console. This class does this by being a <code>Throwable</code>
* and overloading the <code>printStackTrace()</code> methods to print a
* text stack trace.
*
* @version @version@
*/
public class ServletExceptionWrapper extends Throwable
{
/**
* The stack trace that was sent back from the servlet redirector as a
* string.
*/
private String m_StackTrace;
/**
* The class name of the exception that was raised on the server side.
*/
private String m_ClassName;
/**
* Standard throwable constructor.
*
* @param theMessage the exception message
*/
public ServletExceptionWrapper(String theMessage)
{
super(theMessage);
}
/**
* Standard throwable constructor.
*/
public ServletExceptionWrapper()
{
super();
}
/**
* The constructor to use to simulate a real exception.
*
* @param theMessage the server exception message
* @param theClassName the server exception class name
* @param theStackTrace the server exception stack trace
*/
public ServletExceptionWrapper(String theMessage, String theClassName, String
theStackTrace)
{
super(theMessage);
m_ClassName = theClassName;
m_StackTrace = theStackTrace;
}
/**
* Simulates a printing of a stack trace by printing the string stack trace
*
* @param thePs the stream to which to output the stack trace
*/
public void printStackTrace(PrintStream thePs)
{
if (m_StackTrace == null) {
thePs.print(getMessage());
} else {
thePs.print(m_StackTrace);
}
}
/**
* Simulates a printing of a stack trace by printing the string stack trace
*
* @param thePw the writer to which to output the stack trace
*/
public void printStackTrace(PrintWriter thePw)
{
if (m_StackTrace == null) {
thePw.print(getMessage());
} else {
thePw.print(m_StackTrace);
}
}
/**
* As all the server exceptions are wrapped into this
* <code>ServletExceptionWrapper</code> class, we need to be able to
* know the original server exception class.
*
* @param theClass the class to compare with the server exception class
*/
public boolean instanceOf(Class theClass)
{
if (m_ClassName == null) {
return false;
}
return theClass.getName().equals(m_ClassName);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/client/ServletHttpClient.java
Index: ServletHttpClient.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.client;
import java.util.*;
import java.net.*;
import java.io.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
/**
* Manage the logic for calling a test method (which need access to Servlet
* objects) located on the server side. First opens an HTTP connection to
* the redirector servlet (which in trun calls the test) and get the test results
* by opening a second HTTP connection but to the redirector servlet (the tests
* were saved in the application context scope).
*
* @version @version@
*/
public class ServletHttpClient extends AbstractHttpClient
{
/**
* Calls the test method indirectly by calling the Redirector servlet and
* then open a second HTTP connection to retrieve the test results.
*
* @param theRequest the request containing all data to pass to the
* redirector servlet.
*
* @return the <code>HttpURLConnection</code> that contains the HTTP
* response when the test was called.
*
* @exception Throwable if an error occured in the test method or in the
* redirector servlet.
*/
public HttpURLConnection doTest(ServletTestRequest theRequest) throws Throwable
{
ServletTestResult result = null;
HttpURLConnection connection = null;
// Open the first connection to the redirector servlet
HttpClientHelper helper1 = new HttpClientHelper(m_ServletRedirectorURL);
// Specify the service to call on the redirector side
theRequest.addParameter(ServiceDefinition.SERVICE_NAME_PARAM,
ServiceEnumeration.CALL_TEST_SERVICE.toString());
connection = helper1.connect(theRequest);
// Note: We need to get the input stream here to trigger the actual
// call to the servlet ... Don't know why exactly ... :(
connection.getInputStream();
// Open the second connection to get the test results
HttpClientHelper helper2 = new HttpClientHelper(m_ServletRedirectorURL);
ServletTestRequest resultsRequest = new ServletTestRequest();
resultsRequest.addParameter(ServiceDefinition.SERVICE_NAME_PARAM,
ServiceEnumeration.GET_RESULTS_SERVICE.toString());
HttpURLConnection resultConnection = helper2.connect(resultsRequest);
// Read the results as a serialized object
ObjectInputStream ois = new
ObjectInputStream(resultConnection.getInputStream());
result = (ServletTestResult)ois.readObject();
ois.close();
// Check if the result object returned from the redirection servlet
// contains an error or not. If yes, we need to raise an exception
// for the JUnit framework to catch it.
if (result.hasException()) {
// Wrap the exception message and stack trace into a fake
// exception class with overloaded <code>printStackTrace()</code>
// methods so that when JUnit calls this method it will print the
// stack trace that was set on the server side.
// If the error was an AssertionFailedError then we use an instance
// of AssertionFailedErrorWrapper (so that JUnit recognize it is
// an AssertionFailedError exception and print it differently in
// it's runner console). Otherwise we use an instance of
// ServletExceptionWrapper.
if
(result.getExceptionClassName().equals("junit.framework.AssertionFailedError")) {
throw new AssertionFailedErrorWrapper(
result.getExceptionMessage(), result.getExceptionClassName(),
result.getExceptionStackTrace());
} else {
throw new ServletExceptionWrapper(
result.getExceptionMessage(), result.getExceptionClassName(),
result.getExceptionStackTrace());
}
}
return connection;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/server/CallerHelper.java
Index: CallerHelper.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.apache.commons.j2eeunit.*;
/**
* Helper class to call the <code>setUp()</code> and <code>tearDown()</code>
* methods of the class to test on the server side.
*
* @version @version@
*/
public class CallerHelper
{
/**
* Call the <code>setUp</code> method if it exists. The <code>setUp()</code>
* method is called for each test case.
*
* @param theTestCase the instance of the test case from which to call the
* <code>setUp()</code> method.
*/
public static void callSetUpMethod(ServletTestCase theTestCase) throws Throwable
{
// Get the method to call
Method method;
try {
method = theTestCase.getClass().getMethod("setUp", new Class[0]);
} catch (NoSuchMethodException e) {
// No set up method, do nothing
return;
}
// ... and call it !
try {
method.invoke(theTestCase, null);
} catch (IllegalAccessException e) {
throw new ServletException("Illegal access", e);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
/**
* Call the <code>tearDown</code> method if it exists. The
<code>tearDown()</code>
* method is called for each test case.
*
* @param theTestCase the instance of the test case from which to call the
* <code>tearDown()</code> method.
*/
public static void callTearDownMethod(ServletTestCase theTestCase) throws
Throwable
{
// Get the method to call
Method method;
try {
method = theTestCase.getClass().getMethod("tearDown", new Class[0]);
} catch (NoSuchMethodException e) {
// No tear down method, do nothing
return;
}
// ... and call it !
try {
method.invoke(theTestCase, null);
} catch (IllegalAccessException e) {
throw new ServletException("Illegal access", e);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/server/JspImplicitObjects.java
Index: JspImplicitObjects.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import javax.servlet.jsp.*;
/**
* Holder class that contains the instances of the implicit objects that will
* be accessible in the test classes (i.e. subclasses of
* <code>JspTestCase</code>).
*
* @version @version@
*/
public class JspImplicitObjects extends ServletImplicitObjects
{
/**
* Correspond to the JSP <code>pageContext</code> implicit object that is
* available in JSP pages.
*/
public PageContext m_PageContext;
/**
* Correspond to the JSP <code>out</code> implicit object that is
* available in JSP pages.
*/
public JspWriter m_JspWriter;
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/server/JspTestCaller.java
Index: JspTestCaller.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.apache.commons.j2eeunit.*;
/**
* Call the test method on the server side after assigning the JSP implicit
* objects using reflection.
*
* @version @version@
*/
public class JspTestCaller
{
/**
* Name of the attribute in the <code>application</code> scope that will
* hold the results of the test.
*/
private final static String TEST_RESULTS = "ServletTestRedirector_TestResults";
/**
* Call the method to test.
*
* @param theClassName the name of the test class to call
* @param theMethod the name of the test method to call
* @param theObjects the implicit objects that will be assigned by
* reflection to the test class.
*/
private void callTestMethod(String theClassName, String theMethod,
JspImplicitObjects theObjects) throws Throwable
{
// Get the class to call and build an instance of it.
Class testClass = null;
ServletTestCase testInstance = null;
try {
testClass = Class.forName(theClassName);
Constructor constructor = testClass.getConstructor(new Class[] {
String.class });
testInstance = (ServletTestCase)constructor.newInstance(new Object[] {
theMethod });
} catch (Exception e) {
throw new ServletException("Error instanciating class [" + theClassName
+ "]", e);
}
// Set the current method name field
Field methodField = testClass.getField("currentTestMethod");
methodField.set(testInstance, theMethod);
// Set the request field of the test case class
// Extract from the HTTP request the URL to simulate (if any)
ServletURL url = ServletURL.loadFromRequest(theObjects.m_Request);
Field requestField = testClass.getField("request");
requestField.set(testInstance, new
HttpServletRequestWrapper(theObjects.m_Request, url));
// Set the response field of the test case class
Field responseField = testClass.getField("response");
responseField.set(testInstance, theObjects.m_Response);
// Set the config field of the test case class
Field configField = testClass.getField("config");
configField.set(testInstance, new ServletConfigWrapper(theObjects.m_Config));
// Set the page context field of the test case class
Field pageContextField = testClass.getField("pageContext");
pageContextField.set(testInstance, theObjects.m_PageContext);
// Set the JSP writer field of the test case class
Field outField = testClass.getField("out");
outField.set(testInstance, theObjects.m_JspWriter);
// Set the session field of the test case class
// Get a valid session object if the auto session flag is on
// Get the autologin flag from the request
String autoSession =
theObjects.m_Request.getParameter(ServiceDefinition.AUTOSESSION_NAME_PARAM);
boolean isAutomaticSession = new Boolean(autoSession).booleanValue();
if (isAutomaticSession) {
theObjects.m_Session = theObjects.m_Request.getSession(true);
Field sessionField = testClass.getField("session");
sessionField.set(testInstance, theObjects.m_Session);
}
// Call the setUp() method
CallerHelper.callSetUpMethod(testInstance);
// Get the method to call
Method method;
try {
method = testClass.getMethod(theMethod, new Class[0]);
} catch (Exception e) {
throw new ServletException("Method " + theMethod + "() does not exist
for class [" + theClassName + "].", e);
}
// Call the test method
try {
method.invoke(testInstance, null);
} catch (IllegalAccessException e) {
throw new ServletException("Illegal access", e);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
// Call the tearDown() method
CallerHelper.callTearDownMethod(testInstance);
}
/**
* Calls a test method. The parameters needed to call this method are found
* in the HTTP request. Save the results in the <code>application</code>
* scope so that the Get Test Result service can find them.
*
* @param theObjects the implicit objects that will be assigned by
* reflection to the test class.
* @exception ServletException if an unexpected error occurred
*/
public void doTest(JspImplicitObjects theObjects) throws ServletException
{
ServletTestResult result = null;
try {
// Extract from the HTTP request the test class name and method to call.
String testClassName =
theObjects.m_Request.getParameter(ServiceDefinition.CLASS_NAME_PARAM);
if (testClassName == null) {
throw new ServletException("Missing parameter [" +
ServiceDefinition.CLASS_NAME_PARAM + "] in HTTP request.");
}
String methodName =
theObjects.m_Request.getParameter(ServiceDefinition.METHOD_NAME_PARAM);
if (methodName == null) {
throw new ServletException("Missing parameter [" +
ServiceDefinition.METHOD_NAME_PARAM + "] in HTTP request.");
}
// Extract from the HTTP request the URL to simulate (if any)
ServletURL url = ServletURL.loadFromRequest(theObjects.m_Request);
// Call the method to test
callTestMethod(testClassName, methodName, theObjects);
// Return an instance of <code>ServletTestResult</code> with a
// positive result.
result = new ServletTestResult();
} catch (Throwable e) {
// An error occurred, return an instance of
// <code>ServletTestResult</code> with an exception.
result = new ServletTestResult(e);
}
// Save the test result.
theObjects.m_Config.getServletContext().setAttribute(TEST_RESULTS, result);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/server/ServletImplicitObjects.java
Index: ServletImplicitObjects.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Holder class that contains the instances of the implicit objects that will
* be accessible in the test classes (i.e. subclasses of
* <code>ServletTestCase</code>).
*
* @version @version@
*/
public class ServletImplicitObjects
{
/**
* The HTTP request wrapper.
*/
public HttpServletRequest m_Request;
/**
* The original HTTP response object that is created by the servlet
* container.
*/
public HttpServletResponse m_Response;
/**
* The HTTP session object. Can be <code>null</code> if no automatic
* session creation has been asked by the user.
*/
public HttpSession m_Session;
/**
* The Servlet configuration object.
*/
public ServletConfig m_Config;
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/server/ServletTestCaller.java
Index: ServletTestCaller.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.j2eeunit.*;
/**
* Call the test method on the server side after assigning the servlet implicit
* objects using reflection and retri
*
* @version @version@
*/
public class ServletTestCaller
{
/**
* Name of the attribute in the <code>application</code> scope that will
* hold the results of the test.
*/
private final static String TEST_RESULTS = "ServletTestRedirector_TestResults";
/**
* Call the method to test.
*
* @param theClassName the name of the test class to call
* @param theMethod the name of the test method to call
* @param theObjects the implicit objects that will be assigned by
* reflection to the test class.
*/
private void callTestMethod(String theClassName, String theMethod,
ServletImplicitObjects theObjects) throws Throwable
{
// Get the class to call and build an instance of it.
Class testClass = null;
ServletTestCase testInstance = null;
try {
testClass = Class.forName(theClassName);
Constructor constructor = testClass.getConstructor(new Class[] {
String.class });
testInstance = (ServletTestCase)constructor.newInstance(new Object[] {
theMethod });
} catch (Exception e) {
throw new ServletException("Error instanciating class [" + theClassName
+ "]", e);
}
// Set the current method name field
Field methodField = testClass.getField("currentTestMethod");
methodField.set(testInstance, theMethod);
// Set the request field of the test case class
// Extract from the HTTP request the URL to simulate (if any)
ServletURL url = ServletURL.loadFromRequest(theObjects.m_Request);
Field requestField = testClass.getField("request");
requestField.set(testInstance, new
HttpServletRequestWrapper(theObjects.m_Request, url));
// Set the response field of the test case class
Field responseField = testClass.getField("response");
responseField.set(testInstance, theObjects.m_Response);
// Set the config field of the test case class
Field configField = testClass.getField("config");
configField.set(testInstance, new ServletConfigWrapper(theObjects.m_Config));
// Set the session field of the test case class
// Get a valid session object if the auto session flag is on
// Get the autologin flag from the request
String autoSession =
theObjects.m_Request.getParameter(ServiceDefinition.AUTOSESSION_NAME_PARAM);
boolean isAutomaticSession = new Boolean(autoSession).booleanValue();
if (isAutomaticSession) {
theObjects.m_Session = theObjects.m_Request.getSession(true);
Field sessionField = testClass.getField("session");
sessionField.set(testInstance, theObjects.m_Session);
}
// Call the setUp() method
CallerHelper.callSetUpMethod(testInstance);
// Get the method to call
Method method;
try {
method = testClass.getMethod(theMethod, new Class[0]);
} catch (Exception e) {
throw new ServletException("Method " + theMethod + "() does not exist
for class [" + theClassName + "].", e);
}
// Call the test method
try {
method.invoke(testInstance, null);
} catch (IllegalAccessException e) {
throw new ServletException("Illegal access", e);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
// Call the tearDown() method
CallerHelper.callTearDownMethod(testInstance);
}
/**
* Calls a test method. The parameters needed to call this method are found
* in the HTTP request. Save the results in the <code>application</code>
* scope so that the Get Test Result service can find them.
*
* @param theObjects the implicit objects that will be assigned by
* reflection to the test class.
* @exception ServletException if an unexpected error occurred
*/
public void doTest(ServletImplicitObjects theObjects) throws ServletException
{
ServletTestResult result = null;
try {
// Extract from the HTTP request the test class name and method to call.
String testClassName =
theObjects.m_Request.getParameter(ServiceDefinition.CLASS_NAME_PARAM);
if (testClassName == null) {
throw new ServletException("Missing parameter [" +
ServiceDefinition.CLASS_NAME_PARAM + "] in HTTP request.");
}
String methodName =
theObjects.m_Request.getParameter(ServiceDefinition.METHOD_NAME_PARAM);
if (methodName == null) {
throw new ServletException("Missing parameter [" +
ServiceDefinition.METHOD_NAME_PARAM + "] in HTTP request.");
}
// Call the method to test
callTestMethod(testClassName, methodName, theObjects);
// Return an instance of <code>ServletTestResult</code> with a
// positive result.
result = new ServletTestResult();
} catch (Throwable e) {
// An error occurred, return an instance of
// <code>ServletTestResult</code> with an exception.
result = new ServletTestResult(e);
}
// Save the test result.
theObjects.m_Config.getServletContext().setAttribute(TEST_RESULTS, result);
}
/**
* Return the last test results as a serialized object in the HTTP response.
*
* @param theObjects the implicit objects that will be assigned by
* reflection to the test class.
* @exception ServletException if an unexpected error occurred
*/
public void doGetResults(ServletImplicitObjects theObjects) throws
ServletException
{
ServletTestResult result =
(ServletTestResult)theObjects.m_Config.getServletContext().getAttribute(TEST_RESULTS);
if (result == null) {
throw new ServletException("No test results found in the application
scope");
}
// Write back the results as a serialized object to the outgoing stream.
try {
OutputStream os = theObjects.m_Response.getOutputStream();
// Write back the result object as a serialized object
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(result);
oos.flush();
oos.close();
} catch (IOException e) {
throw new ServletException("Error writing ServletTestResult instance to
output stream", e);
}
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/server/ServletTestRedirector.java
Index: ServletTestRedirector.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.server;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.j2eeunit.*;
/**
* Generic Servlet redirector that calls a test method on the server side.
*
* @version @version@
* @see ServletTestCaller
*/
public class ServletTestRedirector extends HttpServlet
{
/**
* Handle GET requests.
*
* @param theRequest the incoming HTTP client request
* @param theResponse the outgoing HTTP client request to send back.
*
* @exception ServletException if an error occurred when sending back
* the response to the client.
*/
public void doGet(HttpServletRequest theRequest, HttpServletResponse
theResponse) throws ServletException
{
// Same handling than for a POST
doPost(theRequest, theResponse);
}
/**
* Handle POST request. Extract from the HTTP request parameter, the
* Service to perform : call test method or return tests results.
*
* @param theRequest the incoming HTTP request.
* @param theResponse the outgoing HTTP response.
*
* @exception ServletException if an unexpected error occurred
*/
public void doPost(HttpServletRequest theRequest, HttpServletResponse
theResponse) throws ServletException
{
// Call the correct Service method
String serviceName =
theRequest.getParameter(ServiceDefinition.SERVICE_NAME_PARAM);
if (serviceName == null) {
throw new ServletException("Missing parameter [" +
ServiceDefinition.SERVICE_NAME_PARAM + "] in HTTP request.");
}
ServletTestCaller caller = new ServletTestCaller();
ServletImplicitObjects objects = new ServletImplicitObjects();
objects.m_Config = getServletConfig();
objects.m_Request = theRequest;
objects.m_Response = theResponse;
// Is it the call test method service ?
if (ServiceEnumeration.CALL_TEST_SERVICE.equals(serviceName)) {
caller.doTest(objects);
// Is it the get test results service ?
} else if (ServiceEnumeration.GET_RESULTS_SERVICE.equals(serviceName)) {
caller.doGetResults(objects);
} else {
throw new ServletException("Unknown service [" + serviceName +
"] in HTTP request.");
}
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/util/AssertUtils.java
Index: AssertUtils.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.util;
import java.net.*;
import java.util.*;
import java.io.*;
/**
* J2EEUnit utility classes to help assert returned results from server side
* code.
*
* @version @version@
*/
public class AssertUtils
{
/**
* @param theConnection the connection object used to connect to the server
* redirector.
* @return the servlet output stream bytes as a string.
*/
public static String getResponseAsString(HttpURLConnection theConnection) throws
IOException
{
StringBuffer sb = new StringBuffer();
BufferedReader input = new BufferedReader(new
InputStreamReader(theConnection.getInputStream()));
String str;
while (null != ((str = input.readLine()))) {
sb.append(str);
}
input.close ();
return sb.toString();
}
/**
* Extract the cookies from a HTTP connection.
*
* @param theConnection the HTTP connection from which to extract server
* returned cookies.
* @return a hashtable of <code>ClientCookie</code> objects.
*/
public static Hashtable getCookies(HttpURLConnection theConnection)
{
// We conform to the RFC 2109 :
//
// The syntax for the Set-Cookie response header is
//
// set-cookie = "Set-Cookie:" cookies
// cookies = 1#cookie
// cookie = NAME "=" VALUE *(";" cookie-av)
// NAME = attr
// VALUE = value
// cookie-av = "Comment" "=" value
// | "Domain" "=" value
// | "Max-Age" "=" value
// | "Path" "=" value
// | "Secure"
// | "Version" "=" 1*DIGIT
Hashtable cookies = new Hashtable();
// There can be several headers named "Set-Cookie", so loop through all
// the headers, looking for cookies
String headerName = theConnection.getHeaderFieldKey(0);
String headerValue = theConnection.getHeaderField(0);
for (int i = 1; (headerName != null) || (headerValue != null); i++) {
if ((headerName != null) && headerName.equals("Set-Cookie")) {
// Parse the cookie definition
Vector clientCookies = parseSetCookieHeader(headerValue);
if (clientCookies.isEmpty()) {
continue;
}
// Check if the cookie name already exist in the hashtable.
// If so, then add it to the vector of cookies for that name.
String name = ((ClientCookie)clientCookies.elementAt(0)).getName();
if (cookies.containsKey(name)) {
Vector cookieValues = (Vector)cookies.get(name);
cookieValues.addAll(clientCookies);
} else {
Vector cookieValues = new Vector();
cookieValues.addAll(clientCookies);
cookies.put(name, cookieValues);
}
}
headerName = theConnection.getHeaderFieldKey(i);
headerValue = theConnection.getHeaderField(i);
}
return cookies;
}
/**
* Parse a single "Set-Cookie" header.
*
* @return a vector og <code>ClientCookie</code> objects containing the
* parsed values from the "Set-Cookie" header.
*/
protected static Vector parseSetCookieHeader(String theHeaderValue)
{
String name;
String value;
String comment = null;
String path = null;
String domain = null;
long maxAge = 0;
boolean isSecure = false;
float version = 1;
Vector cookies = new Vector();
// Find all cookies, they are comma-separated
StringTokenizer stCookies = new StringTokenizer(theHeaderValue, ",");
while (stCookies.hasMoreTokens()) {
String singleCookie = stCookies.nextToken();
singleCookie = singleCookie.trim();
// Parse a single cookie
// Extract cookie values, they are semi-colon separated
StringTokenizer stParams = new StringTokenizer(singleCookie, ";");
// The first parameter is always NAME = VALUE
String param = stParams.nextToken();
param = param.trim();
int pos = param.indexOf("=");
if (pos < 0) {
System.err.println("Bad 'Set-Cookie' syntax, missing '=' [" + param
+ "]");
continue;
}
name = param.substring(0, pos).trim();
value = param.substring(pos + 1).trim();
while (stParams.hasMoreTokens()) {
param = stParams.nextToken();
param = param.trim();
String left;
String right;
// Tokenize on "="
pos = param.indexOf("=");
if (pos < 0) {
left = param;
right = "";
} else {
left = param.substring(0, pos).trim();
right = param.substring(pos + 1).trim();
}
// Is it a comment ?
if (left.equalsIgnoreCase("comment")) {
comment = right;
} else if (left.equalsIgnoreCase("domain")) {
domain = right;
} else if (left.equalsIgnoreCase("max-age")) {
maxAge = Long.parseLong(right);
} else if (left.equalsIgnoreCase("path")) {
path = right;
} else if (left.equalsIgnoreCase("secure")) {
isSecure = true;
} else if (left.equalsIgnoreCase("version")) {
version = Float.parseFloat(right);
} else {
System.err.println("Bad 'Set-Cookie' syntax, bad name [" + param
+ "]");
continue;
}
}
// Create the client cookie
ClientCookie cookie = new ClientCookie(name, value, comment,
domain, maxAge, path, isSecure, version);
cookies.add(cookie);
}
return cookies;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/framework/share/org/apache/commons/j2eeunit/util/ClientCookie.java
Index: ClientCookie.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.util;
/**
* Contains cookie information for cookies returned from the server to the
* client.
*
* @version @version@
*/
public class ClientCookie
{
/**
* The cookie's name.
*/
private String m_Name;
/**
* The cookie's value.
*/
private String m_Value;
/**
* The cookie's comment.
*/
private String m_Comment;
/**
* The cookie's domain.
*/
private String m_Domain;
/**
* The cookie's max age.
*/
private long m_MaxAge;
/**
* The cookie's path.
*/
private String m_Path;
/**
* Specify if the cookie is a secure cookie
*/
private boolean m_IsSecure;
/**
* The cookie's spec. version
*/
private float m_Version;
/**
* Construct a client cookie.
*
* @param theName the cookie's name
* @param theValue the cookie's value
* @param theComment the cookie's comment
* @param theDomain the cookie's domain
* @param theMaxAge the cookie's max age
* @param thePath the cookie's path
* @param isSecure true is the cookies is a secure cookie
* @param theVersion the cookie's version
*/
public ClientCookie(String theName, String theValue, String theComment,
String theDomain, long theMaxAge, String thePath, boolean isSecure, float
theVersion)
{
m_Comment = theComment;
m_Domain = theDomain;
m_IsSecure = isSecure;
m_MaxAge = theMaxAge;
m_Name = theName;
m_Path = thePath;
m_Value = theValue;
m_Version = theVersion;
}
/**
* @return the cookie's name
*/
public String getName()
{
return m_Name;
}
/**
* @return the cookie's value
*/
public String getValue()
{
return m_Value;
}
/**
* @return the cookie's comment
*/
public String getComment()
{
return m_Comment;
}
/**
* @return the cookie's domain
*/
public String getDomain()
{
return m_Domain;
}
/**
* @return the cookie's max age
*/
public long getMaxAge()
{
return m_MaxAge;
}
/**
* @return the cookie's path
*/
public String getPath()
{
return m_Path;
}
/**
* @return true if the cookie is a secure cookie
*/
public boolean isSecure()
{
return m_IsSecure;
}
/**
* @return the cookie's spec. version
*/
public float getVersion()
{
return m_Version;
}
}
1.1 jakarta-commons-sandbox/j2eeunit/src/license.apl
Index: license.apl
===================================================================
/*
* $Header: /home/cvs/jakarta-commons-sandbox/j2eeunit/src/license.apl,v 1.1
2001/03/27 17:42:08 vmassol Exp $
* $Revision: 1.1 $
* $Date: 2001/03/27 17:42:08 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/servlet22/org/apache/commons/j2eeunit/sample/unit/TestServletTestCaseSpecific.java
Index: TestServletTestCaseSpecific.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample.unit;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.io.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
/**
* J2EEUnit unit tests for testing <code>ServletTestCase</code>. These tests
* are specific to Servlet API 2.2 only.
*
* These tests should not really be part of the sample application functional
* tests as they are unit tests for J2EEUnit. However, they are unit tests that
* need a servlet environment running for their execution, so they have been
* package here for convenience. They can also be read by end-users to
* understand how J2EEUnit work.
*
* @version @version@
*/
public class TestServletTestCaseSpecific extends ServletTestCase
{
/**
* Defines the testcase name for JUnit.
*
* @param theName the testcase's name.
*/
public TestServletTestCaseSpecific(String theName)
{
super(theName);
}
/**
* Start the tests.
*
* @param theArgs the arguments. Not used
*/
public static void main(String[] theArgs)
{
junit.ui.TestRunner.main(new String[]
{TestServletTestCaseSpecific.class.getName()});
}
/**
* @return a test suite (<code>TestSuite</code>) that includes all methods
* starting with "test"
*/
public static Test suite()
{
// All methods starting with "test" will be executed in the test suite.
return new TestSuite();
}
// No specific tests for Servlet API 2.2 for the moment !
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/servlet23/org/apache/commons/j2eeunit/sample/unit/TestServletTestCaseSpecific.java
Index: TestServletTestCaseSpecific.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample.unit;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.io.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
/**
* J2EEUnit unit tests for testing <code>ServletTestCase</code>. These tests
* are specific to Servlet API 2.3 only.
*
* These tests should not really be part of the sample application functional
* tests as they are unit tests for J2EEUnit. However, they are unit tests that
* need a servlet environment running for their execution, so they have been
* package here for convenience. They can also be read by end-users to
* understand how J2EEUnit work.
*
* @version @version@
*/
public class TestServletTestCaseSpecific extends ServletTestCase
{
/**
* Defines the testcase name for JUnit.
*
* @param theName the testcase's name.
*/
public TestServletTestCaseSpecific(String theName)
{
super(theName);
}
/**
* Start the tests.
*
* @param theArgs the arguments. Not used
*/
public static void main(String[] theArgs)
{
junit.ui.TestRunner.main(new String[]
{TestServletTestCaseSpecific.class.getName()});
}
/**
* @return a test suite (<code>TestSuite</code>) that includes all methods
* starting with "test"
*/
public static Test suite()
{
// All methods starting with "test" will be executed in the test suite.
return new TestSuite();
}
// No specific tests for Servlet API 2.3 for the moment !
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/SampleServlet.java
Index: SampleServlet.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
/**
* Sample servlet that implement some very simple business logic. The goal is
* to provide functional tests for J2EEUnit, so we focus on providing as many
* different test cases as possible rather than implementing a meaningful
* business logic.
*
* @version @version@
*/
public class SampleServlet extends HttpServlet
{
/**
* Entry point for the servlet when a GET request is received. This will
* be used to verify that we can test for the servlet output stream in
* J2EEUnit test cases.
*
* @param theRequest the HTTP request
* @param theResponse the HTTP response
*/
public void doGet(HttpServletRequest theRequest, HttpServletResponse
theResponse) throws IOException
{
PrintWriter pw = theResponse.getWriter();
theResponse.setContentType("text/html");
pw.println("<html><head/><body>");
pw.println("A GET request");
pw.println("</body></html>");
}
/**
* Return the method used to send data from the client (POST or GET). This
* will be used to verify that we can simulate POST or GET methods from
* J2EEUnit. This simulates a method which would test the method to
* implement it's business logic.
*
* @param theRequest the HTTP request
* @return the method used to post data
*/
public String checkMethod(HttpServletRequest theRequest)
{
return theRequest.getMethod();
}
/**
* Set some variable in the HTTP session. It verifies that a session object
* has automatically been created by J2EEUnit prior to calling this method.
*
* @param theRequest the HTTP request
*/
public void setSessionVariable(HttpServletRequest theRequest)
{
HttpSession session = theRequest.getSession(false);
session.setAttribute("name_setSessionVariable", "value_setSessionVariable");
}
/**
* Set some attribute in the request.
*
* @param theRequest the HTTP request
*/
public void setRequestAttribute(HttpServletRequest theRequest)
{
theRequest.setAttribute("name_setRequestAttribute",
"value_setRequestAttribute");
}
/**
* Get some parameters from the HTTP request.
*
* @param theRequest the HTTP request
* @return a hashtable containing some parameters
*/
public Hashtable getRequestParameters(HttpServletRequest theRequest)
{
Hashtable params = new Hashtable();
params.put("param1", theRequest.getParameter("param1"));
params.put("param2", theRequest.getParameter("param2"));
return params;
}
/**
* Get a header from the request.
*
* @param theRequest the HTTP request
*/
public String getRequestHeader(HttpServletRequest theRequest)
{
return theRequest.getHeader("testheader");
}
/**
* @return the cookies sent in the HTTP request
*
* @param theRequest the HTTP request
*/
public Hashtable getRequestCookies(HttpServletRequest theRequest)
{
Hashtable allCookies = new Hashtable();
Cookie[] cookies = theRequest.getCookies();
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
allCookies.put(cookie.getName(), cookie.getValue());
}
return allCookies;
}
/**
* Set a header in the HTTP response. This is to verify that J2EEUnit tests
* can assert the returned headers.
*
* @param theResponse the HTTP response
*/
public void setResponseHeader(HttpServletResponse theResponse)
{
theResponse.setHeader("responseheader", "this is a response header");
}
/**
* Set a cookie for sending back to the client. This is to verify that
* it is possible with J2EEUnit to assert the cookies returned to the client
*
* @param theResponse the HTTP response
*/
public void setResponseCookie(HttpServletResponse theResponse)
{
Cookie cookie = new Cookie("responsecookie", "this is a response cookie");
cookie.setDomain("j2eeunit.sourceforge.net");
theResponse.addCookie(cookie);
}
/**
* Use a <code>RequestDispatcher</code> to forward to a JSP page. This is
* to verify that J2EEUnit supports asserting the result, even in the case
* of forwarding to another page.
*
* @param theRequest the HTTP request
* @param theResponse the HTTP response
* @param theConfig the servlet config object
*/
public void doForward(HttpServletRequest theRequest, HttpServletResponse
theResponse, ServletConfig theConfig) throws IOException, ServletException
{
RequestDispatcher rd =
theConfig.getServletContext().getRequestDispatcher("/test/test.jsp");
rd.forward(theRequest, theResponse);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/SampleServletConfig.java
Index: SampleServletConfig.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
/**
* Sample servlet to show how to unit test a servlet that makes calls to
* <code>getServletConfig()</code>, <code>getServletContext()</code>,
* <code>log()</code>, ... (i.e. methods inherited from
* <code>GenericServlet</code>).
*
* @version @version@
*/
public class SampleServletConfig extends HttpServlet
{
/**
* Simulate a method that calls <code>getServletConfig()</code>.
*
* @return some data retrieved from the servlet configuration.
*/
public String getConfigData()
{
return getServletConfig().getInitParameter("param1");
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/TestSampleServlet.java
Index: TestSampleServlet.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.io.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
import org.apache.commons.j2eeunit.util.*;
/**
* Tests of the <code>SampleServlet</code> servlet class.
*
* @version @version@
*/
public class TestSampleServlet extends ServletTestCase
{
/**
* Defines the testcase name for JUnit.
*
* @param theName the testcase's name.
*/
public TestSampleServlet(String theName)
{
super(theName);
}
/**
* Start the tests.
*
* @param theArgs the arguments. Not used
*/
public static void main(String[] theArgs)
{
junit.ui.TestRunner.main(new String[] {TestSampleServlet.class.getName()});
}
/**
* @return a test suite (<code>TestSuite</code>) that includes all methods
* starting with "test"
*/
public static Test suite()
{
// All methods starting with "test" will be executed in the test suite.
return new TestSuite(TestSampleServlet.class);
}
//-------------------------------------------------------------------------
/**
* Verify that we can assert the servlet output stream.
*/
public void testReadServletOutputStream() throws IOException
{
SampleServlet servlet = new SampleServlet();
servlet.doGet(request, response);
}
/**
* Verify that we can assert the servlet output stream.
*
* @param theConnection the HTTP connection that was used to call the
* server redirector. It contains the returned HTTP
* response.
*/
public void endReadServletOutputStream(HttpURLConnection theConnection) throws
IOException
{
assertEquals("<html><head/><body>A GET request</body></html>",
AssertUtils.getResponseAsString(theConnection));
}
//-------------------------------------------------------------------------
/**
* Verify that we can simulate a POST request to a servlet. Note that
* the POST method is the default method so we don't need to initialize
* any parameter in <code>beginPostMethod()</code>.
*/
public void testPostMethod()
{
SampleServlet servlet = new SampleServlet();
assertEquals("POST", servlet.checkMethod(request));
}
//-------------------------------------------------------------------------
/**
* Verify that we can simulate a GET request to a servlet.
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginGetMethod(ServletTestRequest theRequest)
{
theRequest.setMethod(ServletTestRequest.GET_METHOD);
}
/**
* Verify that we can simulate a GET request to a servlet
*/
public void testGetMethod()
{
SampleServlet servlet = new SampleServlet();
assertEquals("GET", servlet.checkMethod(request));
}
//-------------------------------------------------------------------------
/**
* Verify that by default the session implicit object is available and can
* be used.
*/
public void testSetAttribute()
{
SampleServlet servlet = new SampleServlet();
servlet.setSessionVariable(request);
assert(session != null);
assertEquals("value_setSessionVariable",
session.getAttribute("name_setSessionVariable"));
}
/**
* Verify that we can set an attribute in the request.
*/
public void testSetRequestAttribute()
{
SampleServlet servlet = new SampleServlet();
servlet.setRequestAttribute(request);
assertEquals("value_setRequestAttribute",
request.getAttribute("name_setRequestAttribute"));
}
//-------------------------------------------------------------------------
/**
* Verify that we can simulate HTTP parameters in the HTTP request.
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginSendParams(ServletTestRequest theRequest)
{
theRequest.addParameter("param1", "value1");
theRequest.addParameter("param2", "value2");
}
/**
* Verify that we can send several parameters in the HTTP request.
*/
public void testSendParams()
{
SampleServlet servlet = new SampleServlet();
Hashtable params = servlet.getRequestParameters(request);
assert(params.get("param1") != null);
assert(params.get("param2") != null);
assertEquals("value1", params.get("param1"));
assertEquals("value2", params.get("param2"));
}
//-------------------------------------------------------------------------
/**
* Verify that we can simulate HTTP headers in the HTTP request.
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginSendHeader(ServletTestRequest theRequest)
{
theRequest.addHeader("testheader", "this is a header test");
}
/**
* Verify that we can simulate HTTP headers in the HTTP request.
*/
public void testSendHeader()
{
SampleServlet servlet = new SampleServlet();
String headerValue = servlet.getRequestHeader(request);
assertEquals("this is a header test", headerValue);
}
//-------------------------------------------------------------------------
/**
* Verify that we can simulate a single cookie sent in the HTTP request.
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginSendCookie(ServletTestRequest theRequest)
{
// Note: The cookie value that was chosen is a string without spaces
// because there is a problem with Resin 1.2.1 which does not support
// quoted cookies. It has been fixed since the 15/12/2000 release of
// Resin.
theRequest.addCookie("testcookie", "thisisacookie");
}
/**
* Verify that we can simulate a single cookie sent in the HTTP request.
*/
public void testSendCookie()
{
SampleServlet servlet = new SampleServlet();
Hashtable cookies = servlet.getRequestCookies(request);
assert(cookies.get("testcookie") != null);
assertEquals("thisisacookie", cookies.get("testcookie"));
}
/**
* Verify that we can simulate multiple cookies sent in the HTTP request.
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginSendMultipleCookies(ServletTestRequest theRequest)
{
theRequest.addCookie("testcookie1", "cookie1");
theRequest.addCookie("testcookie2", "cookie2");
}
/**
* Verify that we can simulate multiple cookies sent in the HTTP request.
*/
public void testSendMultipleCookies()
{
SampleServlet servlet = new SampleServlet();
Hashtable cookies = servlet.getRequestCookies(request);
assert(cookies.get("testcookie1") != null);
assertEquals("cookie1", cookies.get("testcookie1"));
assert(cookies.get("testcookie2") != null);
assertEquals("cookie2", cookies.get("testcookie2"));
}
//-------------------------------------------------------------------------
/**
* Verify that it is possible to send back a header and verify it on the
* client side.
*/
public void testReceiveHeader()
{
SampleServlet servlet = new SampleServlet();
servlet.setResponseHeader(response);
}
/**
* Verify that it is possible to send back a header and verify it on the
* client side.
*
* @param theConnection the HTTP connection that was used to call the
* server redirector. It contains the returned HTTP
* response.
*/
public void endReceiveHeader(HttpURLConnection theConnection)
{
assertEquals("this is a response header",
theConnection.getHeaderField("responseheader"));
}
//-------------------------------------------------------------------------
/**
* Test that it is possible to send back a Cookie and verify it on the
* client side.
*/
public void testReceiveCookie()
{
SampleServlet servlet = new SampleServlet();
servlet.setResponseCookie(response);
}
/**
* Test that it is possible to send back a Cookie and verify it on the
* client side.
*
* @param theConnection the HTTP connection that was used to call the
* server redirector. It contains the returned HTTP
* response.
*/
public void endReceiveCookie(HttpURLConnection theConnection)
{
Hashtable cookies = AssertUtils.getCookies(theConnection);
Vector list = (Vector)cookies.get("responsecookie");
assert(list.size() == 1);
ClientCookie cookie = (ClientCookie)list.elementAt(0);
assertEquals("responsecookie", cookie.getName());
assertEquals("this is a response cookie", cookie.getValue());
assertEquals("j2eeunit.sourceforge.net", cookie.getDomain());
}
//-------------------------------------------------------------------------
/**
* Verify that we can use a <code>RequestDispatcher</code> in the class to
* test and compare the result sent to the output stream on the client side.
*/
public void testRequestDispatcher() throws Exception
{
SampleServlet servlet = new SampleServlet();
servlet.doForward(request, response, config);
}
/**
* Verify that we can use a <code>RequestDispatcher</code> in the class to
* test and compare the result sent to the output stream on the client side.
*
* @param theConnection the HTTP connection that was used to call the
* server redirector. It contains the returned HTTP
* response.
*/
public void endRequestDispatcher(HttpURLConnection theConnection) throws
IOException
{
StringBuffer sb = new StringBuffer();
BufferedReader input = new BufferedReader(new
InputStreamReader(theConnection.getInputStream()));
String str;
while (null != ((str = input.readLine()))) {
sb.append(str);
}
input.close ();
// We cannot test what is exactly returned by the called JSP between
// different Servlet engine return different text ! For example some
// return the JSP comment, other do not, ...
// Thus, we only test for a match of "Hello !"
assert(sb.toString().indexOf("Hello !") > 0);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/TestSampleServletConfig.java
Index: TestSampleServletConfig.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.io.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
import org.apache.commons.j2eeunit.util.*;
/**
* Tests of the <code>SampleServletConfig</code> servlet class. This to show
* how servlet methods that makes calls to <code>getServletConfig()</code>,
* <code>getServletContext()</code>, <code>log()</code>, ... (i.e. methods that
* have been inherited from <code>GenericServlet</code>) can be unit-tested
* with J2EEUnit.
*
* @version @version@
*/
public class TestSampleServletConfig extends ServletTestCase
{
/**
* Defines the testcase name for JUnit.
*
* @param theName the testcase's name.
*/
public TestSampleServletConfig(String theName)
{
super(theName);
}
/**
* Start the tests.
*
* @param theArgs the arguments. Not used
*/
public static void main(String[] theArgs)
{
junit.ui.TestRunner.main(new String[]
{TestSampleServletConfig.class.getName()});
}
/**
* @return a test suite (<code>TestSuite</code>) that includes all methods
* starting with "test"
*/
public static Test suite()
{
// All methods starting with "test" will be executed in the test suite.
return new TestSuite(TestSampleServletConfig.class);
}
/**
* Verify that we can unit test a servlet that makes calls to
* <code>getServletConfig()</code>, <code>getServletContext()</code>,
* <code>log()</code>, ... (i.e. methods inherited from
* <code>GenericServlet</code>).
*
* @see TestSampleServletConfig_Helper
*/
public void testServletConfig() throws ServletException
{
SampleServletConfig servlet = new SampleServletConfig();
// VERY IMPORTANT : Call the init() method in order to initialize the
// Servlet ServletConfig object.
servlet.init(config);
assertEquals("value1 used for testing", servlet.getConfigData());
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/unit/TestJspTestCase.java
Index: TestJspTestCase.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample.unit;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.io.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
/**
* J2EEUnit unit tests for testing <code>JspTestCase</code>.
*
* These tests should not really be part of the sample application functional
* tests as they are unit tests for J2EEUnit. However, they are unit tests that
* need a servlet environment running for their execution, so they have been
* package here for convenience. They can also be read by end-users to
* understand how J2EEUnit work.
*
* @version @version@
*/
public class TestJspTestCase extends JspTestCase
{
/**
* Defines the testcase name for JUnit.
*
* @param theName the testcase's name.
*/
public TestJspTestCase(String theName)
{
super(theName);
}
/**
* Start the tests.
*
* @param theArgs the arguments. Not used
*/
public static void main(String[] theArgs)
{
junit.ui.TestRunner.main(new String[] {TestJspTestCase.class.getName()});
}
/**
* @return a test suite (<code>TestSuite</code>) that includes all methods
* starting with "test"
*/
public static Test suite()
{
// All methods starting with "test" will be executed in the test suite.
return new TestSuite(TestJspTestCase.class);
}
//-------------------------------------------------------------------------
/**
* Verify that we write some text to the output Jsp writer.
*/
public void testOut() throws IOException
{
out.print("some text sent back using out");
}
/**
* Verify that we write some text to the output Jsp writer.
*
* @param theConnection the HTTP connection that was used to call the
* server redirector. It contains the returned HTTP
* response.
*/
public void endOut(HttpURLConnection theConnection) throws IOException
{
StringBuffer sb = new StringBuffer();
BufferedReader input = new BufferedReader(new
InputStreamReader(theConnection.getInputStream()));
String str;
while (null != ((str = input.readLine()))) {
sb.append(str);
}
input.close ();
assertEquals("some text sent back using out", sb.toString());
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/unit/TestServletTestCase1.java
Index: TestServletTestCase1.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample.unit;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.io.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
/**
* J2EEUnit unit tests for testing exception handling of
* <code>ServletTestCase</code>.
*
* These tests should not really be part of the sample application functional
* tests as they are unit tests for J2EEUnit. However, they are unit tests that
* need a servlet environment running for their execution, so they have been
* package here for convenience. They can also be read by end-users to
* understand how J2EEUnit work.
* <br><br>
* Note : This class extends
* <code>TestServletTestCase1_InterceptorServletTestCase</code> (which itself
* extends <code>ServletTestCase</code>) because we need to be able to verify
* exception handling in our unit test cases so we must not let these exceptions
* get through to JUnit (otherwise the test will appear as failed).
*
* @version @version@
*/
public class TestServletTestCase1 extends
TestServletTestCase1_InterceptorServletTestCase
{
/**
* Defines the testcase name for JUnit.
*
* @param theName the testcase's name.
*/
public TestServletTestCase1(String theName)
{
super(theName);
}
/**
* Start the tests.
*
* @param theArgs the arguments. Not used
*/
public static void main(String[] theArgs)
{
junit.ui.TestRunner.main(new String[]
{TestServletTestCase1.class.getName()});
}
/**
* @return a test suite (<code>TestSuite</code>) that includes all methods
* starting with "test"
*/
public static Test suite()
{
// All methods starting with "test" will be executed in the test suite.
return new TestSuite(TestServletTestCase1.class);
}
//-------------------------------------------------------------------------
/**
* Raises an <code>AssertionFailedError</code> exception. The exception is
* caught in
* <code>TestServletTestCase_InterceptorServletTestCase.runTest()</code>.
* This is to verify that <code>AssertionFailedError</code> raised on the
* server side are properly propagated on the client side.
*/
public void testAssertionFailedError()
{
throw new AssertionFailedError("test assertion failed error");
}
//-------------------------------------------------------------------------
/**
* Raises a non serializable exception. The exception is
* caught in
* <code>TestServletTestCase_InterceptorServletTestCase.runTest()</code>.
* This is to verify that non serializable exceptions raised on the
* server side are properly propagated on the client side.
*
* @exception TestServletTestCaseHelper_ExceptionNotSerializable the non
* serializable exception to thow
*/
public void testExceptionNotSerializable()
throws TestServletTestCase1_ExceptionNotSerializable
{
throw new TestServletTestCase1_ExceptionNotSerializable("test non
serializable exception");
}
//-------------------------------------------------------------------------
/**
* Raises a serializable exception. The exception is
* caught in
* <code>TestServletTestCase_InterceptorServletTestCase.runTest()</code>.
* This is to verify that serializable exceptions raised on the
* server side are properly propagated on the client side.
*
* @exception TestServletTestCaseHelper_ExceptionSerializable the
* serializable exception to throw
*/
public void testExceptionSerializable()
throws TestServletTestCase1_ExceptionSerializable
{
throw new TestServletTestCase1_ExceptionSerializable("test serializable
exception");
}
//-------------------------------------------------------------------------
/**
* Test that when a begin method for a given test does not have the correct
* return type (i.e. void), a <code>AssertionFailedError</code> exception
* is returned.
* Note: the assert is done in the
* <code>TestServletTestCase1_InterceptorServletTestCase</code> class.
*/
public String beginBeginMethodBadReturnType(ServletTestRequest theRequest)
{
// Return anything
return "";
}
/**
* Test that when a begin method for a given test does not have the correct
* return type (i.e. void), a <code>AssertionFailedError</code> exception
* is returned.
* Note: the assert is done in the
* <code>TestServletTestCase1_InterceptorServletTestCase</code> class.
*/
public void testBeginMethodBadReturnType()
{
// This method only exist so that a test exist and thus the begin
// method for that test will be called.
}
//-------------------------------------------------------------------------
/**
* Test that when a begin method for a given test is not declared public
* a <code>AssertionFailedError</code> exception is returned.
* Note: the assert is done in the
* <code>TestServletTestCase1_InterceptorServletTestCase</code> class.
*/
private void beginBeginMethodNotPublic(ServletTestRequest theRequest)
{
}
/**
* Test that when a begin method for a given test is not declared public
* a <code>AssertionFailedError</code> exception is returned.
* Note: the assert is done in the
* <code>TestServletTestCase1_InterceptorServletTestCase</code> class.
*/
public void testBeginMethodNotPublic()
{
}
//-------------------------------------------------------------------------
/**
* Test that when a begin method for a given test has the wrong type of
* parameters, a <code>AssertionFailedError</code> exception is returned.
* Note: the assert is done in the
* <code>TestServletTestCase1_InterceptorServletTestCase</code> class.
*/
public void beginBeginMethodBadParams(String theDummy)
{
}
/**
* Test that when a begin method for a given test has the wrong type of
* parameters, a <code>AssertionFailedError</code> exception is returned.
* Note: the assert is done in the
* <code>TestServletTestCase1_InterceptorServletTestCase</code> class.
*/
public void testBeginMethodBadParams()
{
}
//-------------------------------------------------------------------------
/**
* Test that when an end method for a given test does not have the correct
* return type (i.e. void), a <code>AssertionFailedError</code> exception
* is returned.
* Note: the assert is done in the
* <code>TestServletTestCase1_InterceptorServletTestCase</code> class.
*/
public void testEndMethodBadReturnType()
{
// This method only exist so that a test exist and thus the end
// method for that test will be called.
}
/**
* Test that when an end method for a given test does not have the correct
* return type (i.e. void), a <code>AssertionFailedError</code> exception
* is returned.
* Note: the assert is done in the
* <code>TestServletTestCase1_InterceptorServletTestCase</code> class.
*/
public String endEndMethodBadReturnType(HttpURLConnection theConnection)
{
// Return anything
return "";
}
//-------------------------------------------------------------------------
/**
* Test that when an end method for a given test is not declared public
* a <code>AssertionFailedError</code> exception is returned.
* Note: the assert is done in the
* <code>TestServletTestCase1_InterceptorServletTestCase</code> class.
*/
public void testEndMethodNotPublic()
{
}
/**
* Test that when an end method for a given test is not declared public
* a <code>AssertionFailedError</code> exception is returned.
* Note: the assert is done in the
* <code>TestServletTestCase1_InterceptorServletTestCase</code> class.
*/
private void endEndMethodNotPublic(HttpURLConnection theConnection)
{
}
//-------------------------------------------------------------------------
/**
* Test that when an end method for a given test has the wrong type of
* parameters, a <code>AssertionFailedError</code> exception is returned.
* Note: the assert is done in the
* <code>TestServletTestCase1_InterceptorServletTestCase</code> class.
*/
public void testEndMethodBadParams()
{
}
/**
* Test that when an end method for a given test has the wrong type of
* parameters, a <code>AssertionFailedError</code> exception is returned.
* Note: the assert is done in the
* <code>TestServletTestCase1_InterceptorServletTestCase</code> class.
*/
public void endEndMethodBadParams(String theDummy)
{
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/unit/TestServletTestCase1_ExceptionNotSerializable.java
Index: TestServletTestCase1_ExceptionNotSerializable.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample.unit;
/**
* Used by <code>TestServletTestCase1</code> to test the case where
* a non serializable exception is returned by a test method.
*
* @version @version@
* @see TestServletTestCase1
*/
public class TestServletTestCase1_ExceptionNotSerializable extends Exception
{
/**
* @param theMessage the exception message
*/
public TestServletTestCase1_ExceptionNotSerializable(String theMessage)
{
super(theMessage);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/unit/TestServletTestCase1_ExceptionSerializable.java
Index: TestServletTestCase1_ExceptionSerializable.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample.unit;
import java.io.*;
/**
* Used by <code>TestServletTestCase1</code> to test the case where
* a serializable exception is raised by a test method.
*
* @version @version@
* @see TestServletTestCase1
*/
public class TestServletTestCase1_ExceptionSerializable extends Exception implements
Serializable
{
/**
* @param theMessage the exception message.
*/
public TestServletTestCase1_ExceptionSerializable(String theMessage)
{
super(theMessage);
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/unit/TestServletTestCase1_InterceptorServletTestCase.java
Index: TestServletTestCase1_InterceptorServletTestCase.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample.unit;
import junit.framework.*;
import org.apache.commons.j2eeunit.client.*;
import org.apache.commons.j2eeunit.*;
/**
* Helper class for the <code>TestServletTestCase1</code> tests. It is used to
* intercept exceptions. Indeed, in order to verify excpetion handling in our
* unit test cases we must not let these exceptions get through to JUnit
* (otherwise the test will appear as failed).
*
* @version @version@
* @see TestServletTestCase1
*/
public class TestServletTestCase1_InterceptorServletTestCase extends ServletTestCase
{
/**
* Constructs a test case with the given name.
*
* @param theName the name of the test case
*/
public TestServletTestCase1_InterceptorServletTestCase(String theName)
{
super(theName);
}
/**
* Intercepts running test cases to check for normal exceptions.
*/
protected void runTest() throws Throwable
{
try {
super.runTest();
} catch (AssertionFailedErrorWrapper e) {
// If the test case is "testAssertionFailedError" and the exception
// is of type AssertionFailedError and contains the text
// "test assertion failed error", then the test is ok.
if (name().equals("testAssertionFailedError")) {
if (e.instanceOf(AssertionFailedError.class)) {
assertEquals("test assertion failed error", e.getMessage());
return;
}
}
} catch (ServletExceptionWrapper e) {
// If the test case is "testExceptionNotSerializable" and the exception
// is of type TestServletTestCaseHelper1_ExceptionNotSerializable
// and contains the text "test non serializable exception", then
// the test is ok.
if (name().equals("testExceptionNotSerializable")) {
if
(e.instanceOf(TestServletTestCase1_ExceptionNotSerializable.class)) {
assertEquals("test non serializable exception", e.getMessage());
return;
}
}
// If the test case is "testExceptionSerializable" and the exception
// is of type TestServletTestCaseHelper1_ExceptionSerializable
// and contains the text "test serializable exception", then
// the test is ok.
if (name().equals("testExceptionSerializable")) {
assert(e.instanceOf(TestServletTestCase1_ExceptionSerializable.class));
assertEquals("test serializable exception", e.getMessage());
return;
}
throw e;
} catch (Throwable e) {
// Test that when a begin method for a given test does not have the
correct
// return type (i.e. void), a <code>AssertionFailedError</code> exception
// is returned.
if (name().equals("testBeginMethodBadReturnType")) {
if (e instanceof AssertionFailedError) {
assertEquals("The begin method [beginBeginMethodBadReturnType]
should return void and not [java.lang.String]",
e.getMessage());
return;
}
}
// Test that when a begin method for a given test is not declared public
// a <code>AssertionFailedError</code> exception is returned.
// Note: the assert is done in the
// <code>TestServletTestCase_InterceptorServletTestCase</code> class.
if (name().equals("testBeginMethodNotPublic")) {
if (e instanceof AssertionFailedError) {
assertEquals("Method [beginBeginMethodNotPublic] should be
declared public",
e.getMessage());
return;
}
}
// Test that when a begin method for a given test has the wrong
// type of parameters, a <code>AssertionFailedError</code> exception
// is returned.
if (name().equals("testBeginMethodBadParams")) {
if (e instanceof AssertionFailedError) {
assertEquals("The begin method [beginBeginMethodBadParams] must
accept a single parameter of type [org.apache.commons.j2eeunit.ServletTestRequest]",
e.getMessage());
return;
}
}
// Test that when an end method for a given test does not have the
correct
// return type (i.e. void), a <code>AssertionFailedError</code> exception
// is returned.
if (name().equals("testEndMethodBadReturnType")) {
if (e instanceof AssertionFailedError) {
assertEquals("The end method [endEndMethodBadReturnType] should
return void and not [java.lang.String]",
e.getMessage());
return;
}
}
// Test that when an end method for a given test is not declared public
// a <code>AssertionFailedError</code> exception is returned.
// Note: the assert is done in the
// <code>TestServletTestCase_InterceptorServletTestCase</code> class.
if (name().equals("testEndMethodNotPublic")) {
if (e instanceof AssertionFailedError) {
assertEquals("Method [endEndMethodNotPublic] should be declared
public",
e.getMessage());
return;
}
}
// Test that when an end method for a given test has the wrong
// type of parameters, a <code>AssertionFailedError</code> exception
// is returned.
if (name().equals("testEndMethodBadParams")) {
if (e instanceof AssertionFailedError) {
assertEquals("The end method [endEndMethodBadParams] must accept
a single parameter of type [java.net.HttpURLConnection]",
e.getMessage());
return;
}
}
throw e;
}
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/unit/TestServletTestCase2.java
Index: TestServletTestCase2.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample.unit;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.io.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
/**
* Some J2EEUnit unit tests for testing <code>ServletTestCase</code>.
*
* These tests should not really be part of the sample application functional
* tests as they are unit tests for J2EEUnit. However, they are unit tests that
* need a servlet environment running for their execution, so they have been
* package here for convenience. They can also be read by end-users to
* understand how J2EEUnit work.
*
* @version @version@
*/
public class TestServletTestCase2 extends ServletTestCase
{
/**
* Defines the testcase name for JUnit.
*
* @param theName the testcase's name.
*/
public TestServletTestCase2(String theName)
{
super(theName);
}
/**
* Start the tests.
*
* @param theArgs the arguments. Not used
*/
public static void main(String[] theArgs)
{
junit.ui.TestRunner.main(new String[]
{TestServletTestCase2.class.getName()});
}
/**
* @return a test suite (<code>TestSuite</code>) that includes all methods
* starting with "test"
*/
public static Test suite()
{
// All methods starting with "test" will be executed in the test suite.
return new TestSuite(TestServletTestCase2.class);
}
//-------------------------------------------------------------------------
/**
* Verify that it is possible to ask for no automatic session creation in
* the <code>beginXXX()</code> method.
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginNoAutomaticSessionCreation(ServletTestRequest theRequest)
{
theRequest.setAutomaticSession(false);
}
/**
* Verify that it is possible to ask for no automatic session creation in
* the <code>beginXXX()</code> method.
*/
public void testNoAutomaticSessionCreation()
{
assert("A valid session has been found when no session should exist",
session == null);
}
//-------------------------------------------------------------------------
/**
* Verify that multi value parameters can be sent in the
* <code>beingXXX()</code> method to the server redirector.
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginMultiValueParameters(ServletTestRequest theRequest)
{
theRequest.addParameter("multivalue", "value 1");
theRequest.addParameter("multivalue", "value 2");
}
/**
* Verify that multi value parameters can be sent in the
* <code>beingXXX()</code> method to the server redirector.
*/
public void testMultiValueParameters()
{
String[] values = request.getParameterValues("multivalue");
if (values[0].equals("value 1")) {
assertEquals("value 2", values[1]);
} else if (values[0].equals("value 2")) {
assertEquals("value 1", values[1]);
} else {
fail("Shoud have returned a vector with the values \"value 1\" and
\"value 2\"");
}
}
//-------------------------------------------------------------------------
/**
* Verify that it is possible to write to the servlet output stream.
*/
public void testWriteOutputStream() throws IOException
{
PrintWriter pw = response.getWriter();
pw.println("should not result in an error");
}
/**
* Verify that it is possible to write to the servlet output stream.
*
* @param theConnection the HTTP connection that was used to call the
* server redirector. It contains the returned HTTP
* response.
*/
public void endWriteOutputStream(HttpURLConnection theConnection) throws
IOException
{
DataInputStream dis = new DataInputStream(theConnection.getInputStream());
assertEquals("should not result in an error", dis.readLine());
}
//-------------------------------------------------------------------------
/**
* Verify that we can add parameters to the config list of parameters
* programatically, without having to define them in <code>web.xml</code>.
*/
public void testSetConfigParameter()
{
config.setInitParameter("testparam", "test value");
assertEquals("test value", config.getInitParameter("testparam"));
boolean found = false;
Enumeration enum = config.getInitParameterNames();
while(enum.hasMoreElements()) {
String name = (String)enum.nextElement();
if (name.equals("testparam")) {
found = true;
break;
}
}
assert("[testparam] not found in parameter names", found);
}
//-------------------------------------------------------------------------
/**
* Verify that we can override the
* <code>ServletConfig.getServletName()</code> method.
*/
public void testGetServletName()
{
config.setServletName("MyServlet");
assertEquals("MyServlet", config.getServletName());
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/unit/TestServletTestCase3.java
Index: TestServletTestCase3.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample.unit;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.io.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
/**
* J2EEUnit unit tests for verifying that <code>setUp()</code> and
* <code>tearDown()</code> methods are called and can access implicit objects
* in <code>ServletTestCase</code>.
*
* These tests should not really be part of the sample application functional
* tests as they are unit tests for J2EEUnit. However, they are unit tests that
* need a servlet environment running for their execution, so they have been
* package here for convenience. They can also be read by end-users to
* understand how J2EEUnit work.
*
* @version @version@
*/
public class TestServletTestCase3 extends ServletTestCase
{
/**
* Defines the testcase name for JUnit.
*
* @param theName the testcase's name.
*/
public TestServletTestCase3(String theName)
{
super(theName);
}
/**
* Start the tests.
*
* @param theArgs the arguments. Not used
*/
public static void main(String[] theArgs)
{
junit.ui.TestRunner.main(new String[]
{TestServletTestCase3.class.getName()});
}
/**
* @return a test suite (<code>TestSuite</code>) that includes all methods
* starting with "test"
*/
public static Test suite()
{
// All methods starting with "test" will be executed in the test suite.
return new TestSuite(TestServletTestCase3.class);
}
//-------------------------------------------------------------------------
/**
* Put a value in the session to verify that this method is called prior
* to the test, and that it can access servlet implicit objects.
*/
public void setUp()
{
session.putValue("setUpFlag", "a setUp test flag");
}
/**
* Verify that <code>setUp()</code> has been called and that it put a
* value in the session object.
*/
public void testSetUp()
{
assertEquals("a setUp test flag", session.getValue("setUpFlag"));
}
//-------------------------------------------------------------------------
/**
* Set an HTTP response header to verify that this method is called after
* the test, and that it can access servlet implicit objects.
*/
public void tearDown()
{
response.setHeader("teardownheader", "tear down header");
}
/**
* Verify that <code>tearDown()</code> has been called and that it created
* an HTTP reponse header.
*/
public void testTearDown()
{
}
/**
* Verify that <code>tearDown()</code> has been called and that it created
* an HTTP reponse header.
*
* @param theConnection the HTTP connection that was used to call the
* server redirector. It contains the returned HTTP
* response.
*/
public void endTearDown(HttpURLConnection theConnection)
{
assertEquals("tear down header",
theConnection.getHeaderField("teardownheader"));
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/sample/share/org/apache/commons/j2eeunit/sample/unit/TestServletTestCase4.java
Index: TestServletTestCase4.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.sample.unit;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import junit.framework.*;
import org.apache.commons.j2eeunit.*;
/**
* J2EEUnit unit tests for testing simulation URL for
* <code>ServletTestCase</code>.
*
* These tests should not really be part of the sample application functional
* tests as they are unit tests for J2EEUnit. However, they are unit tests that
* need a servlet environment running for their execution, so they have been
* package here for convenience. They can also be read by end-users to
* understand how J2EEUnit work.
*
* @version @version@
*/
public class TestServletTestCase4 extends ServletTestCase
{
/**
* Defines the testcase name for JUnit.
*
* @param theName the testcase's name.
*/
public TestServletTestCase4(String theName)
{
super(theName);
}
/**
* Start the tests.
*
* @param theArgs the arguments. Not used
*/
public static void main(String[] theArgs)
{
junit.ui.TestRunner.main(new String[]
{TestServletTestCase4.class.getName()});
}
/**
* @return a test suite (<code>TestSuite</code>) that includes all methods
* starting with "test"
*/
public static Test suite()
{
// All methods starting with "test" will be executed in the test suite.
return new TestSuite(TestServletTestCase4.class);
}
//-------------------------------------------------------------------------
/**
* Verify that we can simulate the basic parts of the URL : server name,
* default server port of 80, no servlet context, URI.
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginSimulatedURLBasics(ServletTestRequest theRequest)
{
theRequest.setURL("j2eeunit.sourceforge.net", null, "/test/test.jsp", null,
null);
}
/**
* Verify that we can simulate the basic parts of the URL : server name,
* default server port of 80, no servlet context, servlet path.
*/
public void testSimulatedURLBasics()
{
// Verify URI
assertEquals("/test/test.jsp", request.getRequestURI());
// Verify server name
assertEquals("j2eeunit.sourceforge.net", request.getServerName());
// Returns 80 when no port is specified
assertEquals(80, request.getServerPort());
// Return "" when no context path is defined
assertEquals("", request.getContextPath());
}
//-------------------------------------------------------------------------
/**
* Verify that we can simulate different parts of the URL.
* Set 1 of test values (taken from Sun's Servlet API spec)
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginSimulatedURL1(ServletTestRequest theRequest)
{
theRequest.setURL("j2eeunit.sourceforge.net", "/mywebapp", "/test/test.jsp",
null, null);
}
/**
* Verify that we can simulate different parts of the URL.
* Set 1 of test values (taken from Sun's Servlet API spec)
*/
public void testSimulatedURL1()
{
assertEquals("/mywebapp/test/test.jsp", request.getRequestURI());
assertEquals("j2eeunit.sourceforge.net", request.getServerName());
assertEquals(80, request.getServerPort());
assertEquals("/mywebapp", request.getContextPath());
}
//-------------------------------------------------------------------------
/**
* Verify that we can simulate different parts of the URL.
* Set 2 of test values (taken from Sun's Servlet API spec)
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginSimulatedURL2(ServletTestRequest theRequest)
{
theRequest.setURL("j2eeunit.sourceforge.net", "/catalog", "/lawn",
"/index.html", null);
}
/**
* Verify that we can simulate different parts of the URL.
* Set 2 of test values (taken from Sun's Servlet API spec)
*/
public void testSimulatedURL2()
{
assertEquals("j2eeunit.sourceforge.net", request.getServerName());
assertEquals("/catalog/lawn/index.html", request.getRequestURI());
assertEquals(80, request.getServerPort());
assertEquals("/catalog", request.getContextPath());
assertEquals("/lawn", request.getServletPath());
assertEquals("/index.html", request.getPathInfo());
}
//-------------------------------------------------------------------------
/**
* Verify that we can simulate different parts of the URL.
* Set 3 of test values (taken from Sun's Servlet API spec)
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginSimulatedURL3(ServletTestRequest theRequest)
{
theRequest.setURL("j2eeunit.sourceforge.net", "/catalog", "/garden",
"/implements/", null);
}
/**
* Verify that we can simulate different parts of the URL.
* Set 3 of test values (taken from Sun's Servlet API spec)
*/
public void testSimulatedURL3()
{
assertEquals("j2eeunit.sourceforge.net", request.getServerName());
assertEquals("/catalog/garden/implements/", request.getRequestURI());
assertEquals(80, request.getServerPort());
assertEquals("/catalog", request.getContextPath());
assertEquals("/garden", request.getServletPath());
assertEquals("/implements/", request.getPathInfo());
}
//-------------------------------------------------------------------------
/**
* Verify that we can simulate different parts of the URL.
* Set 4 of test values (taken from Sun's Servlet API spec)
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginSimulatedURL4(ServletTestRequest theRequest)
{
theRequest.setURL("j2eeunit.sourceforge.net", "/catalog",
"/help/feedback.jsp", null, null);
}
/**
* Verify that we can simulate different parts of the URL.
* Set 4 of test values (taken from Sun's Servlet API spec)
*/
public void testSimulatedURL4()
{
assertEquals("j2eeunit.sourceforge.net", request.getServerName());
assertEquals("/catalog/help/feedback.jsp", request.getRequestURI());
assertEquals(80, request.getServerPort());
assertEquals("/catalog", request.getContextPath());
assertEquals("/help/feedback.jsp", request.getServletPath());
assert(request.getPathInfo() == null);
}
//-------------------------------------------------------------------------
/**
* Verify that we can simulate different parts of the URL.
* Set 5 of test values (taken from Sun's Servlet API spec)
*
* @param theRequest the request object that serves to initialize the
* HTTP connection to the server redirector.
*/
public void beginSimulatedURL5(ServletTestRequest theRequest)
{
theRequest.setURL("j2eeunit.sourceforge.net", "/catalog",
"/help/feedback.jsp", null, "PARAM1=param1&PARAM2=param2");
}
/**
* Verify that we can simulate different parts of the URL.
* Set 5 of test values (taken from Sun's Servlet API spec)
*/
public void testSimulatedURL5()
{
assertEquals("j2eeunit.sourceforge.net", request.getServerName());
assertEquals("/catalog/help/feedback.jsp", request.getRequestURI());
assertEquals(80, request.getServerPort());
assertEquals("/catalog", request.getContextPath());
assertEquals("/help/feedback.jsp", request.getServletPath());
assert(request.getPathInfo() == null);
assertEquals("PARAM1=param1&PARAM2=param2", request.getQueryString());
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/test/share/org/apache/commons/j2eeunit/TestAll.java
Index: TestAll.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit;
import junit.framework.*;
/**
* Run all the unit tests of J2EEUnit that do not need a servlet
* environment to run. These other tests will be exercised in the sample
* application.
*
* @version @version@
*/
public class TestAll extends TestCase
{
/**
* Defines the testcase name for JUnit.
*
* @param theName the testcase's name.
*/
public TestAll(String theName)
{
super(theName);
}
/**
* Start the tests.
*
* @param theArgs the arguments. Not used
*/
public static void main(String[] theArgs)
{
junit.ui.TestRunner.main(new String[] {TestAll.class.getName()});
}
/**
* @return a test suite (<code>TestSuite</code>) that includes all methods
* starting with "test"
*/
public static Test suite()
{
TestSuite suite = new TestSuite("J2EEUnit unit tests not needing servlet
engine");
suite.addTest(org.apache.commons.j2eeunit.util.TestAssertUtils.suite());
return suite;
}
}
1.1
jakarta-commons-sandbox/j2eeunit/src/test/share/org/apache/commons/j2eeunit/util/TestAssertUtils.java
Index: TestAssertUtils.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.j2eeunit.util;
import java.util.*;
import junit.framework.*;
/**
* Unit tests of the <code>AssertUtils</code> class.
*
* @version @version@
*/
public class TestAssertUtils extends TestCase
{
/**
* Defines the testcase name for JUnit.
*
* @param theName the testcase's name.
*/
public TestAssertUtils(String theName)
{
super(theName);
}
/**
* Start the tests.
*
* @param theArgs the arguments. Not used
*/
public static void main(String[] theArgs)
{
junit.ui.TestRunner.main(new String[] {TestAssertUtils.class.getName()});
}
/**
* @return a test suite (<code>TestSuite</code>) that includes all methods
* starting with "test"
*/
public static Test suite()
{
// All methods starting with "test" will be executed in the test suite.
return new TestSuite(TestAssertUtils.class);
}
public void testParseSetCookieHeader1()
{
Vector cookies =
AssertUtils.parseSetCookieHeader("testcookie=value;Domain=j2eeunit.sourceforge.net");
assert(cookies.size() == 1);
ClientCookie cookie = (ClientCookie)cookies.elementAt(0);
assertEquals("testcookie", cookie.getName());
assertEquals("value", cookie.getValue());
assertEquals("j2eeunit.sourceforge.net", cookie.getDomain());
assert(cookie.getComment() == null);
assert(cookie.getMaxAge() == 0);
assert(cookie.getPath() == null);
assert(cookie.isSecure() == false);
assert(cookie.getVersion() == 1);
}
public void testParseSetCookieHeader2()
{
Vector cookies = AssertUtils.parseSetCookieHeader("testcookie=value;
domain=j2eeunit.sourceforge.net");
assert(cookies.size() == 1);
ClientCookie cookie = (ClientCookie)cookies.elementAt(0);
assertEquals("testcookie", cookie.getName());
assertEquals("value", cookie.getValue());
assertEquals("j2eeunit.sourceforge.net", cookie.getDomain());
assert(cookie.getComment() == null);
assert(cookie.getMaxAge() == 0);
assert(cookie.getPath() == null);
assert(cookie.isSecure() == false);
assert(cookie.getVersion() == 1);
}
}