httpunit-commit Mailing List for httpunit (Page 22)
Brought to you by:
russgold
You can subscribe to this list here.
| 2000 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(5) |
Sep
(31) |
Oct
(39) |
Nov
(18) |
Dec
(6) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2001 |
Jan
(8) |
Feb
(5) |
Mar
(8) |
Apr
(25) |
May
(20) |
Jun
(23) |
Jul
(28) |
Aug
(10) |
Sep
(3) |
Oct
(32) |
Nov
(61) |
Dec
(24) |
| 2002 |
Jan
(50) |
Feb
(34) |
Mar
(35) |
Apr
(3) |
May
(25) |
Jun
(25) |
Jul
(30) |
Aug
(146) |
Sep
(49) |
Oct
(156) |
Nov
(121) |
Dec
(54) |
| 2003 |
Jan
(12) |
Feb
(79) |
Mar
(88) |
Apr
(26) |
May
(67) |
Jun
(29) |
Jul
(8) |
Aug
(16) |
Sep
(20) |
Oct
(17) |
Nov
|
Dec
(5) |
| 2004 |
Jan
|
Feb
(40) |
Mar
(30) |
Apr
(5) |
May
|
Jun
(83) |
Jul
(34) |
Aug
(20) |
Sep
(44) |
Oct
(46) |
Nov
|
Dec
(14) |
| 2005 |
Jan
(4) |
Feb
|
Mar
(5) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(4) |
Oct
|
Nov
|
Dec
(1) |
| 2006 |
Jan
|
Feb
|
Mar
(26) |
Apr
(8) |
May
(2) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(5) |
Nov
|
Dec
|
| 2008 |
Jan
|
Feb
|
Mar
|
Apr
(36) |
May
(38) |
Jun
(1) |
Jul
(1) |
Aug
|
Sep
(4) |
Oct
|
Nov
(18) |
Dec
(4) |
| 2009 |
Jan
|
Feb
(2) |
Mar
(3) |
Apr
|
May
|
Jun
(2) |
Jul
|
Aug
(35) |
Sep
(1) |
Oct
|
Nov
|
Dec
(1) |
| 2010 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(3) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
| 2011 |
Jan
(9) |
Feb
|
Mar
|
Apr
(1) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
| 2012 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(21) |
Oct
(18) |
Nov
(1) |
Dec
|
|
From: Russell G. <rus...@us...> - 2004-03-02 11:13:53
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27879/test/com/meterware/servletunit Modified Files: HttpServletRequestTest.java RequestContextTest.java Log Message: support request body encoding in ServletUnit Index: HttpServletRequestTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/HttpServletRequestTest.java,v retrieving revision 1.19 retrieving revision 1.20 diff -u -r1.19 -r1.20 --- HttpServletRequestTest.java 26 Feb 2004 17:36:47 -0000 1.19 +++ HttpServletRequestTest.java 2 Mar 2004 10:54:15 -0000 1.20 @@ -34,6 +34,7 @@ import com.meterware.httpunit.GetMethodWebRequest; import com.meterware.httpunit.WebRequest; import com.meterware.httpunit.PutMethodWebRequest; +import com.meterware.httpunit.PostMethodWebRequest; import junit.framework.Test; import junit.framework.TestSuite; @@ -419,6 +420,28 @@ } + public void testSpecifiedCharEncoding() throws Exception { + String hebrewValue = "\u05d0\u05d1\u05d2\u05d3"; + String paramString = "param1=red¶m2=" + hebrewValue; + WebRequest wr = new PostMethodWebRequest( "http://localhost/simple" ); + wr.setHeaderField( "Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-8" ); + ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, new ServletUnitContext(), new Hashtable(), paramString.getBytes( "ISO-8859-8" ) ); + assertEquals( "param1 value", "red", request.getParameter( "param1") ); + assertEquals( "param2 value", hebrewValue, request.getParameter( "param2") ); + } + + + public void testSuppliedCharEncoding() throws Exception { + String hebrewValue = "\u05d0\u05d1\u05d2\u05d3"; + String paramString = "param1=red¶m2=" + hebrewValue; + WebRequest wr = new PostMethodWebRequest( "http://localhost/simple" ); + ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, new ServletUnitContext(), new Hashtable(), paramString.getBytes( "ISO-8859-8" ) ); + request.setCharacterEncoding( "ISO-8859-8" ); + assertEquals( "param1 value", "red", request.getParameter( "param1") ); + assertEquals( "param2 value", hebrewValue, request.getParameter( "param2") ); + } + + private final static byte[] NO_MESSAGE_BODY = new byte[0]; private final static ServletMetaData NULL_SERVLET_REQUEST = new ServletMetaData() { Index: RequestContextTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/RequestContextTest.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- RequestContextTest.java 13 Feb 2003 20:25:56 -0000 1.2 +++ RequestContextTest.java 2 Mar 2004 10:54:15 -0000 1.3 @@ -73,7 +73,7 @@ /** - * Verify parsing of a query string. + * Verify override of parent request parameters. */ public void testParameterOverride() throws Exception { HttpServletRequest request = new DummyHttpServletRequest( new URL( "http://localhost/basic?param=red¶m1=old¶m=blue" ) ); @@ -85,6 +85,33 @@ } + /** + * Verify parsing of message body parameters. + */ + public void testPostParameterParsing() throws Exception { + RequestContext rc = new RequestContext( new URL( "http://localhost/basic" )); + rc.setMessageBody( "param=red¶m1=old¶m=blue".getBytes() ); + assertMatchingSet( "parameter names", new String[] { "param", "param1" }, rc.getParameterNames() ); + assertMatchingSet( "param values", new String[] { "red", "blue" }, rc.getParameterValues( "param" ) ); + assertEquals( "param1 value", "old", ((String[]) rc.getParameterMap().get( "param1"))[0] ); + } + + + /** + * Verify parsing of message body parameters using a specified character encoding. + */ + public void testEncodedParameterParsing() throws Exception { + RequestContext rc = new RequestContext( new URL( "http://localhost/basic" )); + String hebrewValue = "\u05d0\u05d1\u05d2\u05d3"; + String paramString = "param=red¶m1=" + hebrewValue + "¶m=blue"; + rc.setMessageBody( paramString.getBytes( "iso-8859-8" ) ); + rc.setMessageEncoding( "iso-8859-8" ); + assertMatchingSet( "parameter names", new String[] { "param", "param1" }, rc.getParameterNames() ); + assertMatchingSet( "param values", new String[] { "red", "blue" }, rc.getParameterValues( "param" ) ); + assertEquals( "param1 value", hebrewValue, ((String[]) rc.getParameterMap().get( "param1"))[0] ); + } + + class DummyHttpServletRequest implements HttpServletRequest { private RequestContext _requestContext; |
|
From: Russell G. <rus...@us...> - 2004-03-02 11:13:49
|
Update of /cvsroot/httpunit/httpunit/doc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27879/doc Modified Files: release_notes.txt Log Message: support request body encoding in ServletUnit Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.324 retrieving revision 1.325 diff -u -r1.324 -r1.325 --- release_notes.txt 26 Feb 2004 17:36:46 -0000 1.324 +++ release_notes.txt 2 Mar 2004 10:54:14 -0000 1.325 @@ -13,6 +13,10 @@ Revision History: + 1-Mar-2004 + Problems fixed: + 1. ServletUnit now applies character encoding in interpreting post parameters + 26-Feb-2004 Additions: 1. Added support for filters |
|
From: Russell G. <rus...@us...> - 2004-03-02 11:11:14
|
Update of /cvsroot/httpunit/httpunit/site/com/meterware/website In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27263/site/com/meterware/website Modified Files: Site.java Log Message: update documentation Index: Site.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/site/com/meterware/website/Site.java,v retrieving revision 1.6 retrieving revision 1.7 diff -u -r1.6 -r1.7 --- Site.java 19 Jun 2003 01:26:17 -0000 1.6 +++ Site.java 2 Mar 2004 10:51:39 -0000 1.7 @@ -22,19 +22,12 @@ import com.meterware.website.*; import com.meterware.xml.DocumentSemantics; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.FactoryConfigurationError; - import org.xml.sax.SAXException; import org.w3c.dom.Document; import java.io.IOException; import java.io.File; import java.util.ArrayList; -import java.beans.IntrospectionException; -import java.lang.reflect.InvocationTargetException; -import java.text.ParseException; /** @@ -160,6 +153,8 @@ super.setLocation( getBugEntryURL() ); } else if (type.equalsIgnoreCase( "enhancements" )) { super.setLocation( getFeatureEntryURL() ); + } else if (type.equalsIgnoreCase( "donations" )) { + super.setLocation( "http://sourceforge.net/project/project_donations.php?group_id=" + _groupId ); } else if (type.equalsIgnoreCase( "cvs" )) { super.setLocation( "http://sourceforge.net/cvs/?group_id=" + _groupId ); } |
|
From: Russell G. <rus...@us...> - 2004-03-02 11:11:14
|
Update of /cvsroot/httpunit/httpunit/sitedocs/doc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27263/sitedocs/doc Modified Files: citations.xml faq.xml Log Message: update documentation Index: citations.xml =================================================================== RCS file: /cvsroot/httpunit/httpunit/sitedocs/doc/citations.xml,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- citations.xml 16 Jun 2003 01:31:45 -0000 1.2 +++ citations.xml 2 Mar 2004 10:51:39 -0000 1.3 @@ -13,14 +13,24 @@ </section> <section title="Articles"> - <citation name="Black Box Web Testing with HttpUnit" url="http://www.onjava.com/pub/a/onjava/2003/05/07/blackboxwebtest.html"> + <citation name="Build a Java Web App Using HttpUnit and the Test-driven Methodology, Part II" + url="http://www.devx.com/Java/Article/17991"> + 4 December 2003: Wellie Chao, DevX.com + </citation> + <citation name="Build a Java Web App Using HttpUnit and the Test-driven Methodology, Part I" + url="http://www.devx.com/Java/Article/17908"> + 25 November 2003: Wellie Chao, DevX.com + </citation> + <citation name="Black Box Web Testing with HttpUnit" + url="http://www.onjava.com/pub/a/onjava/2003/05/07/blackboxwebtest.html"> 7 May 2003: Giora Katz-Lichtenstein, ONJava.com </citation> <citation name="HttpUnit: A Civilized Way to Test Web Applications in WebSphere Studio" url="http://www7b.software.ibm.com/wsdd/library/techarticles/0303_bhogal/bhogal.html"> March 2003: Kulvir Singh Bhogal, IBM Software Services for WebSphere </citation> - <citation name="Test entire Web applications with HttpUnit" url="http://www.zdnet.com.au/builder/program/java/story/0,2000034779,20264830,00.htm"> + <citation name="Test entire Web applications with HttpUnit" + url="http://www.zdnet.com.au/builder/program/java/story/0,2000034779,20264830,00.htm"> 26 April 2002: Jamie Scheinblum, ZDNet Australia </citation> </section> @@ -42,4 +52,12 @@ Contains a simple example using HttpUnit and describes the API. Covers HttpUnit 1.4 </citation> </section> + + <section title="Blog Postings"> + <citation name="Testing Web Applications with HttpUnit (Don't worry, it's not boring!)" + url="http://fb2.hu/x10/Articles/HttpUnit.html"> + 22 February 2004: Balazs Fejes, 10x More Productive Blog! + </citation> + </section> + </citations> Index: faq.xml =================================================================== RCS file: /cvsroot/httpunit/httpunit/sitedocs/doc/faq.xml,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- faq.xml 12 Feb 2004 17:38:44 -0000 1.5 +++ faq.xml 2 Mar 2004 10:51:39 -0000 1.6 @@ -30,6 +30,29 @@ <answer><![CDATA[Yes. Call <a href="api/com/meterware/httpunit/WebClient.html#setProxyServer(java.lang.String, int)"> <code>WebClient.setProxyServer( host, port )</code></a>before sending your request.]]></answer> </faq> + <faq id="masquerade"> + <question>How can I handle certificates from a test machine?</question> + <answer><![CDATA[Often you will need to run your secure website - complete with certificates - from a test + server. Under most conditions, this will cause a validation problem, as the JSSE detects that the + certificate does not match the requested server. You can "trick" HttpUnit into accepting the certificate + as follows:<p> + Assume that your certificate is for your real machine at <code>realserver.domain.com</code> and your + test machine is at the IP address: 192.168.1.23. You want your tests to send requests to + <code>realserver.domain.com</code> (since that is what your certificates expect), but to actually + go to the test machine.<p> + First, create a <a href="api/com/meterware/httpunit/DNSListener.html"><code>DNSListener</code></a>: + <pre>DNSListener aListener = <b>new</b> DNSListener() { + <b>public</b> String getIpAddress( String hostName ) { + if (hostName.equals( "realserver.domain.com" )) <b>return</b> "192.168.1.23"; + <b>return</b> hostName; + } +};</pre>This listener substitutes the test IP address for the specified server name. Now specify this listener + for your client by calling + <a href="api/com/meterware/httpunit/ClientProperties.html#setDnsListener(com.meterware.httpunit.DNSListener)"> + <code>wc.getClientProperties().setDnsListener( aListener )</code></a>. + All subsequent requests will be rerouted as you specify, but the security layer should think it is coming + from the named server.]]></answer> + </faq> <faq id="charset"> <question>Why isn't HttpUnit handling my non-English pages?</question> <answer><![CDATA[When no Content-Type header is specified, HTML 1.1 says that the character set is to be taken as iso-8859-1. @@ -40,9 +63,9 @@ This setting will not apply to those pages for which the server specifies the character set.</p> <p>Non-English form handling is supported as well. Any parameter values entered into a form will be encoded as the same character set as the document containing the form. The server code will then have to handle those characters - appropriately. In Java, that would be converting them to Unicode with statements such as<blockquote><code> -String rawName = request.getParameter( "name" );<br> -String japaneseName = <b>new</b> String( name.getBytes("8859_1"), "EUC_JP" );</code></blockquote> + appropriately. In Java, that would be converting them to Unicode with statements such as + <pre>String rawName = request.getParameter( "name" ); +String japaneseName = <b>new</b> String( name.getBytes("8859_1"), "EUC_JP" );</pre> where the proper encoding should be substituted for "EUC_JP". The <code>getBytes</code> call is needed to extract the raw bytes from the parameter string.]]></answer> </faq> @@ -53,7 +76,7 @@ </faq> <faq id="rejected cookies"> <question>Why isn't HttpUnit seeing cookies from my site?</question> - <answer><![CDATA[According to the <a href="http://www.faqs.org/rfcs/rfc2965.html">Cookie specification>/a>, + <answer><![CDATA[According to the <a href="http://www.faqs.org/rfcs/rfc2965.html">Cookie specification</a>, sites may specify a domain and path to restrict the scope of their cookies. These specifications must follow certain rules, and the vast majority of sites do. Unfortunately, there are some popular sites (such as Yahoo.com) which do not. By default, HttpUnit is very strict about @@ -61,7 +84,7 @@ <a href="api/com/meterware/httpunit/cookies/CookieProperties.html">CookieProperties</a> class. If you suspect that this is happening, you can also register a <a href="api/com/meterware/httpunit/cookies/CookieListener.html">CookieListener</a> to watch for cookies - being rejected.]]</answer> + being rejected.]]></answer> </faq> </section> @@ -97,7 +120,7 @@ Unfortunately, it is then impossible to predict what, if any, response is relevant. The method therefore does not return WebResponse. In most cases, it is the main window of your browser that you care about and you can always obtain that by calling - <a href="api/com/meterware/httpunit/WebClient.html#getCurrentPage()"><code>client.getCurrentPage()</code></a>.]]</answer> + <a href="api/com/meterware/httpunit/WebClient.html#getCurrentPage()"><code>client.getCurrentPage()</code></a>.]]></answer> </faq> </section> @@ -111,6 +134,11 @@ <question>JavaScript is not being executed at all. Why not?</question> <answer>If you do not have the Rhino JAR (js.jar) in your classpath, JavaScript features do not work.</answer> </faq> + <faq id="disable scripting"> + <question>How do I turn off scripting for certain tests?</question> + <answer><![CDATA[If you call <a href="api/com/meterware/httpunit/HttpUnitOptions.html#setScriptingEnabled(boolean)"><code>HttpUnitOptions.setScriptingEnabled( false );</code></a> + JavaScript will not be interpreted.]]></answer> + </faq> <faq id="nofunction"> <question>My JavaScript works in a browser, but HttpUnit says "ReferenceError: ... is not defined"</question> <answer>This usually indicates that you are calling a function which contains statements that HttpUnit does not understand. @@ -119,9 +147,13 @@ </faq> <faq id="unsupported"> <question>How do I handle a page that uses JavaScript features that HttpUnit does not support?</question> - <answer><![CDATA[If you call<blockquote><code>HttpUnitOptions.setExceptionsThrownOnScriptError( false );</code></blockquote> + <answer><![CDATA[If you call + <a href="api/com/meterware/httpunit/HttpUnitOptions.html#setExceptionsThrownOnScriptError(boolean)"> + <code>HttpUnitOptions.setExceptionsThrownOnScriptError( false );</code></a> problems will be recorded but will not throw exceptions. You can see the list of problems detected by calling - <blockquote><code>HttpUnitOptions.getScriptErrorMessages();</code></blockquote>]]></answer> + <a href="api/com/meterware/httpunit/HttpUnitOptions.html#getScriptErrorMessages()"> + <code>HttpUnitOptions.getScriptErrorMessages();</code> + </a>]]></answer> </faq> <faq id="text"> <question>I called document.write() in my page, but getText() does not show the results! Why not?</question> |
|
From: Russell G. <rus...@us...> - 2004-03-02 11:11:13
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/cookies In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27263/src/com/meterware/httpunit/cookies Modified Files: CookieListener.java Log Message: update documentation Index: CookieListener.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/cookies/CookieListener.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- CookieListener.java 12 Feb 2004 13:03:24 -0000 1.2 +++ CookieListener.java 2 Mar 2004 10:51:39 -0000 1.3 @@ -1,5 +1,4 @@ package com.meterware.httpunit.cookies; - /******************************************************************************************************************** * $Id$ * @@ -20,6 +19,12 @@ * DEALINGS IN THE SOFTWARE. * *******************************************************************************************************************/ + +/** + * An interface for classes which can listen for cookies being rejected and the reason. + * + * @author <a href="mailto:rus...@ht...">Russell Gold</a> + */ public interface CookieListener { |
|
From: Russell G. <rus...@us...> - 2004-03-02 11:11:13
|
Update of /cvsroot/httpunit/httpunit/sitedocs In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27263/sitedocs Modified Files: site.xml Log Message: update documentation Index: site.xml =================================================================== RCS file: /cvsroot/httpunit/httpunit/sitedocs/site.xml,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- site.xml 18 May 2003 05:20:47 -0000 1.1 +++ site.xml 2 Mar 2004 10:51:39 -0000 1.2 @@ -1,6 +1,6 @@ <?xml version='1.0' ?> <site project="HttpUnit" group-id="6550" logo="doc/images/HttpUnit.jpg"> - <copyright owner="Russell Gold" dates="2000-2003"/> + <copyright owner="Russell Gold" dates="2000-2004"/> <page location="index.html" title="Home" mainPage="true"> <fragment source="sitedocs/welcome.html"/> @@ -51,4 +51,6 @@ <space/> <project-page type="bugs" item="Bug Database" /> <project-page type="enhancements" item="Feature Requests" /> + <space/> + <project-page type="donations" item="Support HttpUnit"/> </site> \ No newline at end of file |
|
From: Russell G. <rus...@us...> - 2004-02-29 15:43:30
|
Update of /cvsroot/httpunit/httpunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21092 Modified Files: build.xml Log Message: copy package-list to archive Index: build.xml =================================================================== RCS file: /cvsroot/httpunit/httpunit/build.xml,v retrieving revision 1.70 retrieving revision 1.71 diff -u -r1.70 -r1.71 --- build.xml 12 Feb 2004 13:03:23 -0000 1.70 +++ build.xml 29 Feb 2004 15:25:20 -0000 1.71 @@ -237,6 +237,7 @@ <exclude name="**/activation.jar"/> <exclude name="**/mailapi.jar" /> <include name="doc/**/*.*" /> + <include name="doc/api/package-list" /> </fileset> </copy> </target> |
|
From: Russell G. <rus...@us...> - 2004-02-26 17:52:42
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv12499/src/com/meterware/servletunit Modified Files: InvocationContext.java InvocationContextImpl.java ServletMetaData.java ServletUnitClient.java ServletUnitHttpRequest.java WebApplication.java Added Files: FilterConfigImpl.java FilterMetaData.java FilterUrlMap.java WebResourceConfiguration.java XMLUtils.java Log Message: Added support for Servlet 2.3 filters ***** Error reading new file[Errno 2] No such file or directory: 'FilterConfigImpl.java' ***** Error reading new file[Errno 2] No such file or directory: 'FilterMetaData.java' ***** Error reading new file[Errno 2] No such file or directory: 'FilterUrlMap.java' ***** Error reading new file[Errno 2] No such file or directory: 'WebResourceConfiguration.java' ***** Error reading new file[Errno 2] No such file or directory: 'XMLUtils.java' Index: InvocationContext.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/InvocationContext.java,v retrieving revision 1.7 retrieving revision 1.8 diff -u -r1.7 -r1.8 --- InvocationContext.java 13 Feb 2003 20:25:55 -0000 1.7 +++ InvocationContext.java 26 Feb 2004 17:36:47 -0000 1.8 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * - * Copyright (c) 2001-2003, Russell Gold + * Copyright (c) 2001-2004, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -23,9 +23,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.Servlet; -import javax.servlet.ServletException; -import javax.servlet.RequestDispatcher; +import javax.servlet.*; import java.io.IOException; @@ -39,20 +37,26 @@ /** - * Returns the request to be processed by the servlet. + * Returns the request to be processed by the servlet or filter. **/ HttpServletRequest getRequest(); /** - * Returns the response which the servlet should modify during its operation. + * Returns the response which the servlet or filter should modify during its operation. **/ HttpServletResponse getResponse(); /** + * Invokes the current servlet or filter. + */ + void service() throws ServletException, IOException; + + + /** * Returns the selected servlet, initialized to provide access to sessions - * and servlet context information. + * and servlet context information. Only valid to call if {@link #isFilterActive} returns false. **/ Servlet getServlet() throws ServletException; @@ -83,8 +87,40 @@ /** - * Removes the top request dispatcher from this context. + * Removes the top request dispatcher or filter from this context. */ void popRequest(); + + /** + * Returns true if the current context is a filter, rather than a servlet. + */ + boolean isFilterActive(); + + + /** + * Returns the current active filter object. Only valid to call if {@link #isFilterActive} returns true. + */ + Filter getFilter() throws ServletException; + + + /** + * Returns the current filter chain. Only valid to call if {@link #isFilterActive} returns true. + */ + FilterChain getFilterChain(); + + + /** + * Pushes the current filter onto the execution stack and switches to the next filter or the selected servlet. + * This can be used to simulate the effect of the {@link javax.servlet.FilterChain#doFilter doFilter} call. + * <br><b>Note:</b> this method specifies {@link ServletRequest} and {@link ServletResponse} because those are the + * types passed to {@link Filter#doFilter}; however, HttpUnit requires the objects to implement + * {@link HttpServletRequest} and {@link HttpServletResponse} because they will eventually be passed to an + * {@link javax.servlet.http.HttpServlet}. + * + * @param request the request to pass to the next filter. May be a wrapper. + * @param response the response object to pass to the next filter. May be a wrapper. + */ + void pushFilter( ServletRequest request, ServletResponse response ); + } Index: InvocationContextImpl.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/InvocationContextImpl.java,v retrieving revision 1.14 retrieving revision 1.15 diff -u -r1.14 -r1.15 --- InvocationContextImpl.java 17 Jun 2003 23:23:02 -0000 1.14 +++ InvocationContextImpl.java 26 Feb 2004 17:36:47 -0000 1.15 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2001-2003, Russell Gold +* Copyright (c) 2001-2004, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -31,9 +31,7 @@ import java.util.Stack; import java.util.StringTokenizer; -import javax.servlet.RequestDispatcher; -import javax.servlet.Servlet; -import javax.servlet.ServletException; +import javax.servlet.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; @@ -46,20 +44,35 @@ **/ class InvocationContextImpl implements InvocationContext { + private Stack _contextStack = new Stack(); + private URL _effectiveURL; + /** - * Returns the request to be processed by the servlet. + * Returns the request to be processed by the servlet or filter. **/ public HttpServletRequest getRequest() { - return _request; + return getContext().getRequest(); } /** - * Returns the response which the servlet should modify during its operation. + * Returns the response which the servlet or filter should modify during its operation. **/ public HttpServletResponse getResponse() { - return _response; + return getContext().getResponse(); + } + + + /** + * Invokes the current servlet or filter. + */ + public void service() throws ServletException, IOException { + if (isFilterActive()) { + getFilter().doFilter( getRequest(), getResponse(), getFilterChain() ); + } else { + getServlet().service( getRequest(), getResponse() ); + } } @@ -68,21 +81,7 @@ * and servlet context information. **/ public Servlet getServlet() throws ServletException { - if (_servlet == null) { - if (!_application.requiresAuthorization( _requestURL ) || userIsAuthorized() ) { - _servlet = _application.getServletRequest( _requestURL ).getServlet(); - } else if (_request.getRemoteUser() != null) { - throw new AccessDeniedException( _requestURL ); - } else if (_application.usesBasicAuthentication()) { - throw new BasicAuthenticationRequiredException( _application.getAuthenticationRealm() ); - } else if (_application.usesFormAuthentication()) { - _servlet = _application.getServletRequest( _application.getLoginURL() ).getServlet(); - ((ServletUnitHttpRequest) getRequest()).setOriginalURL( _requestURL ); - } else { - throw new IllegalStateException( "Authorization required but no authentication method defined" ); - } - } - return _servlet; + return getContext().getServlet(); } @@ -91,14 +90,15 @@ * only be invoked after all processing has been done to the servlet response. **/ public WebResponse getServletResponse() throws IOException { + if (_contextStack.size() != 1) throw new IllegalStateException( "Have not returned from all request dispatchers" ); if (_webResponse == null) { - HttpSession session = _request.getSession( /* create */ false ); + HttpSession session = getRequest().getSession( /* create */ false ); if (session != null && session.isNew()) { Cookie cookie = new Cookie( ServletUnitHttpSession.SESSION_COOKIE_NAME, session.getId() ); cookie.setPath( _application.getContextPath() ); - _response.addCookie( cookie ); + getResponse().addCookie( cookie ); } - _webResponse = new ServletUnitWebResponse( _client, _target, _requestURL, _response, _client.getExceptionsThrownOnErrorStatus() ); + _webResponse = new ServletUnitWebResponse( _client, _target, _effectiveURL, getResponse(), _client.getExceptionsThrownOnErrorStatus() ); } return _webResponse; } @@ -113,34 +113,53 @@ public void pushIncludeRequest( RequestDispatcher rd, HttpServletRequest request, HttpServletResponse response ) throws ServletException { - if (_servlet == null) throw new IllegalStateException( "Get the servlet for this context before pushing a request" ); - _request = DispatchedRequestWrapper.createIncludeRequestWrapper( request, rd ); - _servletStack.push( _servlet ); - _servlet = ((RequestDispatcherImpl) rd).getServletMetaData().getServlet(); + if (isFilterActive()) throw new IllegalStateException( "May not push an include request when no servlet is active" ); + _contextStack.push( new ExecutionContext( DispatchedRequestWrapper.createIncludeRequestWrapper( request, rd ), + response, ((RequestDispatcherImpl) rd).getServletMetaData() ) ); } public void pushForwardRequest( RequestDispatcher rd, HttpServletRequest request, HttpServletResponse response ) throws ServletException { - if (_servlet == null) throw new IllegalStateException( "Get the servlet for this context before pushing a request" ); - _request = DispatchedRequestWrapper.createForwardRequestWrapper( request, rd ); - _servletStack.push( _servlet ); - _servlet = ((RequestDispatcherImpl) rd).getServletMetaData().getServlet(); + if (isFilterActive()) throw new IllegalStateException( "May not push a forward request when no servlet is active" ); + _contextStack.push( new ExecutionContext( DispatchedRequestWrapper.createForwardRequestWrapper( request, rd ), + response, ((RequestDispatcherImpl) rd).getServletMetaData() ) ); } public void popRequest() { - if (!( _request instanceof DispatchedRequestWrapper)) throw new IllegalStateException( "May not pop the initial request" ); - _request = ((DispatchedRequestWrapper) _request).getBaseRequest(); - _servlet = (Servlet) _servletStack.pop(); + if (getContext().mayPopFilter()) { + getContext().popFilter(); + } else if (_contextStack.size() == 1) { + throw new IllegalStateException( "May not pop the initial request" ); + } else { + _contextStack.pop(); + } } - private boolean userIsAuthorized() { - String[] roles = _application.getPermittedRoles( _requestURL ); - for (int i = 0; i < roles.length; i++) { - if (_request.isUserInRole( roles[i] )) return true; - } - return false; + public boolean isFilterActive() { + return getContext().isFilterActive(); + } + + + public Filter getFilter() throws ServletException { + return getContext().getFilter(); + } + + + public FilterChain getFilterChain() { + return new FilterChain() { + public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse ) throws IOException, ServletException { + pushFilter( servletRequest, servletResponse ); + service(); + popRequest(); + } + }; + } + + + public void pushFilter( ServletRequest request, ServletResponse response ) { + getContext().pushFilter( request, response ); } @@ -161,20 +180,140 @@ InvocationContextImpl( ServletUnitClient client, ServletRunner runner, String target, WebRequest request, Dictionary clientHeaders, byte[] messageBody ) throws IOException, MalformedURLException { _client = client; _application = runner.getApplication(); - _requestURL = request.getURL(); _target = target; - final ServletUnitHttpRequest suhr = new ServletUnitHttpRequest( _application.getServletRequest( _requestURL ), request, runner.getContext(), - clientHeaders, messageBody ); - _request = suhr; + URL requestURL = request.getURL(); + final ServletUnitHttpRequest suhr = new ServletUnitHttpRequest( _application.getServletRequest( requestURL ), request, + runner.getContext(), clientHeaders, messageBody ); Cookie[] cookies = getCookies( clientHeaders ); for (int i = 0; i < cookies.length; i++) suhr.addCookie( cookies[i] ); if (_application.usesBasicAuthentication()) suhr.readBasicAuthentication(); else if (_application.usesFormAuthentication()) suhr.readFormAuthentication(); - HttpSession session = _request.getSession( /* create */ false ); + HttpSession session = suhr.getSession( /* create */ false ); if (session != null) ((ServletUnitHttpSession) session).access(); + + _effectiveURL = computeEffectiveUrl( suhr, requestURL ); + _contextStack.push( new ExecutionContext( suhr, new ServletUnitHttpResponse(), + _application.getServletRequest( _effectiveURL ) ) ); + } + + + + private URL computeEffectiveUrl( HttpServletRequest request, URL requestURL ) { + if (!_application.requiresAuthorization( requestURL ) || userIsAuthorized( request, requestURL ) ) { + return requestURL; + } else if (request.getRemoteUser() != null) { + throw new AccessDeniedException( requestURL ); + } else if (_application.usesBasicAuthentication()) { + throw new BasicAuthenticationRequiredException( _application.getAuthenticationRealm() ); + } else if (!_application.usesFormAuthentication()) { + throw new IllegalStateException( "Authorization required but no authentication method defined" ); + } else { + ((ServletUnitHttpSession) request.getSession()).setOriginalURL( requestURL ); + return _application.getLoginURL(); + } + } + + + private boolean userIsAuthorized( HttpServletRequest request, URL requestURL ) { + String[] roles = _application.getPermittedRoles( requestURL ); + for (int i = 0; i < roles.length; i++) { + if (request.isUserInRole( roles[i] )) return true; + } + return false; + } + + + + static class ExecutionContext { + + private HttpServletResponse _response; + private HttpServletRequest _request; + private ServletMetaData _metaData; + + private Stack _filterStack = new Stack(); + + + ExecutionContext( HttpServletRequest request, HttpServletResponse response, ServletMetaData metaData ) { + _request = request; + _response = response; + _metaData = metaData; + } + + + boolean isFilterActive() { + return getFilterIndex() < _metaData.getFilters().length; + } + + + Servlet getServlet() throws ServletException { + if (isFilterActive()) throw new IllegalStateException( "Current context is a filter - may not request servlet."); + return _metaData.getServlet(); + } + + + HttpServletResponse getResponse() { + return _filterStack.isEmpty() ? _response : ((FilterContext) _filterStack.lastElement()).getResponse(); + } + + + HttpServletRequest getRequest() { + return _filterStack.isEmpty() ? _request : ((FilterContext) _filterStack.lastElement()).getRequest(); + } + + + public Filter getFilter() throws ServletException { + if (!isFilterActive()) throw new IllegalStateException( "Current context is a servlet - may not request filter."); + return _metaData.getFilters()[ getFilterIndex() ].getFilter(); + } + + + public void pushFilter( ServletRequest request, ServletResponse response ) { + if (!isFilterActive()) throw new IllegalStateException( "Current context is a servlet - may not push filter."); + if (!(request instanceof HttpServletRequest)) throw new IllegalArgumentException( "HttpUnit does not support non-HTTP request wrappers" ); + if (!(response instanceof HttpServletResponse)) throw new IllegalArgumentException( "HttpUnit does not support non-HTTP response wrappers" ); + + _filterStack.push( new FilterContext( (HttpServletRequest) request, (HttpServletResponse) response ) ); + } + + + public boolean mayPopFilter() { + return getFilterIndex() > 0; + } + + + public void popFilter() { + _filterStack.pop(); + } + + + private int getFilterIndex() { + return _filterStack.size(); + } + } + + + static class FilterContext { + HttpServletRequest _request; + HttpServletResponse _response; + + + public FilterContext( HttpServletRequest request, HttpServletResponse response ) { + _request = request; + _response = response; + } + + + public HttpServletResponse getResponse() { + return _response; + } + + + public HttpServletRequest getRequest() { + return _request; + } } @@ -184,16 +323,10 @@ final private static Cookie[] NO_COOKIES = new Cookie[0]; - private ServletUnitClient _client; - + private ServletUnitClient _client; private WebApplication _application; - private HttpServletRequest _request; - private ServletUnitHttpResponse _response = new ServletUnitHttpResponse(); - private URL _requestURL; - private Stack _servletStack = new Stack(); private String _target; - private Servlet _servlet; private WebResponse _webResponse; @@ -212,4 +345,9 @@ } return (Cookie[]) cookies.toArray( new Cookie[ cookies.size() ] ); } + + + private ExecutionContext getContext() { + return (ExecutionContext) _contextStack.lastElement(); + } } \ No newline at end of file Index: ServletMetaData.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletMetaData.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- ServletMetaData.java 13 Feb 2003 20:25:55 -0000 1.1 +++ ServletMetaData.java 26 Feb 2004 17:36:47 -0000 1.2 @@ -21,6 +21,7 @@ *******************************************************************************************************************/ import javax.servlet.Servlet; import javax.servlet.ServletException; +import java.util.List; /** @@ -45,4 +46,10 @@ */ String getPathInfo(); + + /** + * Returns an ordered list of the filters associated with this servlet. + */ + FilterMetaData[] getFilters(); + } Index: ServletUnitClient.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitClient.java,v retrieving revision 1.11 retrieving revision 1.12 diff -u -r1.11 -r1.12 --- ServletUnitClient.java 27 Feb 2003 23:36:03 -0000 1.11 +++ ServletUnitClient.java 26 Feb 2004 17:36:47 -0000 1.12 @@ -91,7 +91,7 @@ try { InvocationContext invocation = newInvocation( request ); - invocation.getServlet().service( invocation.getRequest(), invocation.getResponse() ); + invocation.service(); return invocation.getServletResponse(); } catch (ServletException e) { throw new HttpInternalErrorException( request.getURL(), e ); Index: ServletUnitHttpRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitHttpRequest.java,v retrieving revision 1.29 retrieving revision 1.30 diff -u -r1.29 -r1.30 --- ServletUnitHttpRequest.java 24 Mar 2003 03:22:10 -0000 1.29 +++ ServletUnitHttpRequest.java 26 Feb 2004 17:36:47 -0000 1.30 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2003, Russell Gold +* Copyright (c) 2000-2004, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -27,7 +27,6 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; -import java.net.URL; import java.util.*; import javax.servlet.http.HttpServletRequest; @@ -692,11 +691,6 @@ } - void writeFormAuthentication( String userName, String password ) { - getServletSession().setUserInformation( userName, toArray( password ) ); - } - - private ServletUnitHttpSession getServletSession() { return (ServletUnitHttpSession) getSession(); } @@ -720,7 +714,7 @@ } } - private String[] toArray( String roleList ) { + static String[] toArray( String roleList ) { StringTokenizer st = new StringTokenizer( roleList, "," ); String[] result = new String[ st.countTokens() ]; for (int i = 0; i < result.length; i++) { @@ -730,16 +724,6 @@ } - void setOriginalURL( URL originalURL ) { - getServletSession().setOriginalURL( originalURL ); - } - - - URL getOriginalURL() { - return getServletSession().getOriginalURL(); - } - - void recordAuthenticationInfo( String userName, String[] roles ) { _userName = userName; _roles = roles; Index: WebApplication.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/WebApplication.java,v retrieving revision 1.22 retrieving revision 1.23 diff -u -r1.22 -r1.23 --- WebApplication.java 15 Feb 2004 06:42:01 -0000 1.22 +++ WebApplication.java 26 Feb 2004 17:36:47 -0000 1.23 @@ -33,7 +33,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; @@ -52,10 +51,16 @@ private final ServletConfiguration SECURITY_CHECK_CONFIGURATION = new ServletConfiguration( SecurityCheckServlet.class.getName() ); - private final ServletMapping SECURITY_CHECK_MAPPING = new ServletMapping( SECURITY_CHECK_CONFIGURATION ); + private final WebResourceMapping SECURITY_CHECK_MAPPING = new WebResourceMapping( SECURITY_CHECK_CONFIGURATION ); - /** A mapping of resource names to servlet class names. **/ - private ServletMap _servletMapping = new ServletMap(); + /** A mapping of resource names to servlet configurations. **/ + private WebResourceMap _servletMapping = new WebResourceMap(); + + /** A mapping of resource names to filter configurations. **/ + private FilterUrlMap _filterUrlMapping = new FilterUrlMap(); + + /** A mapping of servlet names to filter configurations. **/ + private Hashtable _filterMapping = new Hashtable(); private ArrayList _securityConstraints = new ArrayList(); @@ -118,6 +123,7 @@ _contextDir = file; _contextPath = contextPath == null ? "" : contextPath; registerServlets( document ); + registerFilters( document ); extractSecurityConstraints( document ); extractContextParameters( document ); extractLoginConfiguration( document ); @@ -130,7 +136,7 @@ private void extractListeners( Document document ) throws SAXException { NodeList nl = document.getElementsByTagName( "listener" ); for (int i = 0; i < nl.getLength(); i++) { - String listenerName = getChildNodeValue((Element) nl.item(i), "listener-class").trim(); + String listenerName = XMLUtils.getChildNodeValue((Element) nl.item(i), "listener-class").trim(); try { Object listener = Class.forName( listenerName ).newInstance(); @@ -245,7 +251,7 @@ * Calls the destroy method for every active servlet. */ void destroyServlets() { - _servletMapping.destroyServlets(); + _servletMapping.destroyWebResources(); } @@ -398,20 +404,62 @@ //--------------------------------------------------- private members -------------------------------------------------- + private void registerFilters( Document document ) throws SAXException { + Hashtable nameToClass = new Hashtable(); + NodeList nl = document.getElementsByTagName( "filter" ); + for (int i = 0; i < nl.getLength(); i++) registerFilterClass( nameToClass, (Element) nl.item( i ) ); + nl = document.getElementsByTagName( "filter-mapping" ); + for (int i = 0; i < nl.getLength(); i++) registerFilter( nameToClass, (Element) nl.item( i ) ); + } + + + private void registerFilterClass( Dictionary mapping, Element filterElement ) throws SAXException { + String filterName = XMLUtils.getChildNodeValue( filterElement, "filter-name" ); + mapping.put( filterName, new FilterConfiguration( filterName, filterElement ) ); + } + + + private void registerFilter( Dictionary mapping, Element filterElement ) throws SAXException { + if (XMLUtils.hasChildNode( filterElement, "servlet-name" )) { + registerFilterForServlet( XMLUtils.getChildNodeValue( filterElement, "servlet-name" ), + (FilterConfiguration) mapping.get( XMLUtils.getChildNodeValue( filterElement, "filter-name" ) ) ); + } + if (XMLUtils.hasChildNode( filterElement, "url-pattern" )) { + registerFilterForUrl( XMLUtils.getChildNodeValue( filterElement, "url-pattern" ), + (FilterConfiguration) mapping.get( XMLUtils.getChildNodeValue( filterElement, "filter-name" ) ) ); + } + } + + + private void registerFilterForUrl( String resourceName, FilterConfiguration filterConfiguration ) { + _filterUrlMapping.put( resourceName, filterConfiguration ); + } + + + private void registerFilterForServlet( String servletName, FilterConfiguration filterConfiguration ) { + List list = (List) _filterMapping.get( servletName ); + if (list == null) { + list = new ArrayList(); + _filterMapping.put( servletName, list ); + } + list.add( filterConfiguration ); + } + + private void extractLoginConfiguration( Document document ) throws MalformedURLException, SAXException { NodeList nl = document.getElementsByTagName( "login-config" ); if (nl.getLength() == 1) { final Element loginConfigElement = (Element) nl.item( 0 ); - String authenticationMethod = getChildNodeValue( loginConfigElement, "auth-method", "BASIC" ); - _authenticationRealm = getChildNodeValue( loginConfigElement, "realm-name", "" ); + String authenticationMethod = XMLUtils.getChildNodeValue( loginConfigElement, "auth-method", "BASIC" ); + _authenticationRealm = XMLUtils.getChildNodeValue( loginConfigElement, "realm-name", "" ); if (authenticationMethod.equalsIgnoreCase( "BASIC" )) { _useBasicAuthentication = true; if (_authenticationRealm.length() == 0) throw new SAXException( "No realm specified for BASIC Authorization" ); } else if (authenticationMethod.equalsIgnoreCase( "FORM" )) { _useFormAuthentication = true; if (_authenticationRealm.length() == 0) throw new SAXException( "No realm specified for FORM Authorization" ); - _loginURL = new URL( "http", "localhost", getChildNodeValue( loginConfigElement, "form-login-page" ) ); - _errorURL = new URL( "http", "localhost", getChildNodeValue( loginConfigElement, "form-error-page" ) ); + _loginURL = new URL( "http", "localhost", XMLUtils.getChildNodeValue( loginConfigElement, "form-login-page" ) ); + _errorURL = new URL( "http", "localhost", XMLUtils.getChildNodeValue( loginConfigElement, "form-error-page" ) ); } } } @@ -427,14 +475,14 @@ private void registerServletClass( Dictionary mapping, Element servletElement ) throws SAXException { - mapping.put( getChildNodeValue( servletElement, "servlet-name" ), + mapping.put( XMLUtils.getChildNodeValue( servletElement, "servlet-name" ), new ServletConfiguration( servletElement ) ); } private void registerServlet( Dictionary mapping, Element servletElement ) throws SAXException { - registerServlet( getChildNodeValue( servletElement, "url-pattern" ), - (ServletConfiguration) mapping.get( getChildNodeValue( servletElement, "servlet-name" ) ) ); + registerServlet( XMLUtils.getChildNodeValue( servletElement, "url-pattern" ), + (ServletConfiguration) mapping.get( XMLUtils.getChildNodeValue( servletElement, "servlet-name" ) ) ); } @@ -442,38 +490,13 @@ NodeList nl = document.getElementsByTagName( "context-param" ); for (int i = 0; i < nl.getLength(); i++) { Element param = (Element) nl.item( i ); - String name = getChildNodeValue( param, "param-name" ); - String value = getChildNodeValue( param, "param-value" ); + String name = XMLUtils.getChildNodeValue( param, "param-name" ); + String value = XMLUtils.getChildNodeValue( param, "param-value" ); _contextParameters.put( name, value ); } } - private static String getChildNodeValue( Element root, String childNodeName ) throws SAXException { - return getChildNodeValue( root, childNodeName, null ); - } - - - private static String getChildNodeValue( Element root, String childNodeName, String defaultValue ) throws SAXException { - NodeList nl = root.getElementsByTagName( childNodeName ); - if (nl.getLength() == 1) { - return getTextValue( nl.item( 0 ) ).trim(); - } else if (defaultValue == null) { - throw new SAXException( "Node <" + root.getNodeName() + "> has no child named <" + childNodeName + ">" ); - } else { - return defaultValue; - } - } - - - private static String getTextValue( Node node ) throws SAXException { - Node textNode = node.getFirstChild(); - if (textNode == null) return ""; - if (textNode.getNodeType() != Node.TEXT_NODE) throw new SAXException( "No text value found for <" + node.getNodeName() + "> node" ); - return textNode.getNodeValue(); - } - - private static boolean patternMatches( String urlPattern, String urlPath ) { return urlPattern.equals( urlPath ); } @@ -485,57 +508,58 @@ static class SecurityCheckServlet extends HttpServlet { protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException { - handleLogin( (ServletUnitHttpRequest) req, resp ); + handleLogin( req, resp ); } protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException { - handleLogin( (ServletUnitHttpRequest) req, resp ); + handleLogin( req, resp ); } - private void handleLogin( ServletUnitHttpRequest req, HttpServletResponse resp ) throws IOException { + private void handleLogin( HttpServletRequest req, HttpServletResponse resp ) throws IOException { final String username = req.getParameter( "j_username" ); - final String password = req.getParameter( "j_password" ); - req.writeFormAuthentication( username, password ); - resp.sendRedirect( req.getOriginalURL().toExternalForm() ); + final String roleList = req.getParameter( "j_password" ); + getServletSession( req ).setUserInformation( username, ServletUnitHttpRequest.toArray( roleList ) ); + resp.sendRedirect( getServletSession( req ).getOriginalURL().toExternalForm() ); + } + + + private ServletUnitHttpSession getServletSession( HttpServletRequest req ) { + return (ServletUnitHttpSession) req.getSession(); } } + + //============================================= ServletConfiguration class ============================================= final static int DONT_AUTOLOAD = Integer.MIN_VALUE; final static int ANY_LOAD_ORDER = Integer.MAX_VALUE; - class ServletConfiguration { + class ServletConfiguration extends WebResourceConfiguration { private Servlet _servlet; - private String _className; - private Hashtable _initParams = new Hashtable(); + private String _servletName; private int _loadOrder = DONT_AUTOLOAD; ServletConfiguration( String className ) { - _className = className; + super( className ); } ServletConfiguration( String className, Hashtable initParams ) { - _className = className; - if (initParams != null) _initParams = initParams; + super( className, initParams ); } ServletConfiguration( Element servletElement ) throws SAXException { - this( getChildNodeValue( servletElement, "servlet-class" ) ); - final NodeList initParams = servletElement.getElementsByTagName( "init-param" ); - for (int i = initParams.getLength() - 1; i >= 0; i--) { - _initParams.put( getChildNodeValue( (Element) initParams.item( i ), "param-name" ), - getChildNodeValue( (Element) initParams.item( i ), "param-value" ) ); - } + super( servletElement, "servlet-class" ); + _servletName = XMLUtils.getChildNodeValue( servletElement, "servlet-name" ); final NodeList loadOrder = servletElement.getElementsByTagName( "load-on-startup" ); for (int i = 0; i < loadOrder.getLength(); i++) { - String order = getTextValue( loadOrder.item(i) ); + String order = XMLUtils.getTextValue( loadOrder.item(i) ); try { _loadOrder = Integer.parseInt( order ); } catch (NumberFormatException e) { @@ -556,18 +580,13 @@ } - synchronized void destroyServlet() { + synchronized void destroyResource() { if (_servlet != null) _servlet.destroy(); } - String getClassName() { - return _className; - } - - - Hashtable getInitParams() { - return _initParams; + String getServletName() { + return _servletName; } @@ -582,6 +601,53 @@ } +//============================================= FilterConfiguration class ============================================= + + + class FilterConfiguration extends WebResourceConfiguration implements FilterMetaData { + + private Filter _filter; + private String _name; + + + FilterConfiguration( String name, Element filterElement ) throws SAXException { + super( filterElement, "filter-class" ); + _name = name; + } + + + public synchronized Filter getFilter() throws ServletException { + try { + if (_filter == null) { + Class filterClass = Class.forName( getClassName() ); + _filter = (Filter) filterClass.newInstance(); + _filter.init( new FilterConfigImpl( _name, getServletContext(), getInitParams() ) ); + } + + return _filter; + } catch (ClassNotFoundException e) { + throw new ServletException( "Did not find filter class: " + getClassName() ); + } catch (IllegalAccessException e) { + throw new ServletException( "Filter class " + getClassName() + " lacks a public no-arg constructor" ); + } catch (InstantiationException e) { + throw new ServletException( "Filter class " + getClassName() + " instantiation threw" + e.getCause() ); + } catch (ClassCastException e) { + throw new ServletException( "Filter class " + getClassName() + " does not implement" + Filter.class.getName() ); + } + } + + + boolean isLoadOnStartup() { + return false; + } + + + synchronized void destroyResource() { + if (_filter != null) _filter.destroy(); + } + } + + //=================================== SecurityConstract interface and implementations ================================== @@ -614,7 +680,7 @@ SecurityConstraintImpl( Element root ) throws SAXException { final NodeList roleNames = root.getElementsByTagName( "role-name" ); - for (int i = 0; i < roleNames.getLength(); i++) _roleList.add( getTextValue( roleNames.item( i ) ) ); + for (int i = 0; i < roleNames.getLength(); i++) _roleList.add( XMLUtils.getTextValue( roleNames.item( i ) ) ); final NodeList resources = root.getElementsByTagName( "web-resource-collection" ); for (int i = 0; i < resources.getLength(); i++) _resources.add( new WebResourceCollection( (Element) resources.item( i ) ) ); @@ -652,7 +718,7 @@ WebResourceCollection( Element root ) throws SAXException { final NodeList urlPatterns = root.getElementsByTagName( "url-pattern" ); - for (int i = 0; i < urlPatterns.getLength(); i++) _urlPatterns.add( getTextValue( urlPatterns.item( i ) ) ); + for (int i = 0; i < urlPatterns.getLength(); i++) _urlPatterns.add( XMLUtils.getTextValue( urlPatterns.item( i ) ) ); } @@ -670,17 +736,24 @@ } + static final FilterMetaData[] NO_FILTERS = new FilterMetaData[0]; + + static class ServletRequestImpl implements ServletMetaData { - private URL _url; - private String _servletName; - private ServletMapping _mapping; + private URL _url; + private String _fullServletPath; + private WebResourceMapping _mapping; + private Hashtable _filtersPerName; + private FilterUrlMap _filtersPerUrl; - ServletRequestImpl( URL url, String servletName, ServletMapping mapping ) { - _url = url; - _servletName = servletName; - _mapping = mapping; + ServletRequestImpl( URL url, String servletPath, WebResourceMapping mapping, Hashtable filtersPerName, FilterUrlMap filtersPerUrl ) { + _url = url; + _fullServletPath = servletPath; + _mapping = mapping; + _filtersPerName = filtersPerName; + _filtersPerUrl = filtersPerUrl; } @@ -702,102 +775,138 @@ public String getServletPath() { - return _mapping == null ? null : _mapping.getServletPath( _servletName ); + return _mapping == null ? null : _mapping.getServletPath( _fullServletPath ); } public String getPathInfo() { - return _mapping == null ? null : _mapping.getPathInfo( _servletName ); + return _mapping == null ? null : _mapping.getPathInfo( _fullServletPath ); + } + + + public FilterMetaData[] getFilters() { + if (getConfiguration() == null) return NO_FILTERS; + + List filters = new ArrayList(); + addFiltersForPath( filters, _fullServletPath ); + addFiltersForServletWithName( filters, getConfiguration().getServletName() ); + + return (FilterMetaData[]) filters.toArray( new FilterMetaData[ filters.size() ]); + } + + + private void addFiltersForPath( List filters, String fullServletPath ) { + FilterMetaData[] matches = _filtersPerUrl.getMatchingFilters( fullServletPath ); + for (int i = 0; i < matches.length; i++) { + filters.add( matches[i] ); + } + } + + + private void addFiltersForServletWithName( List filters, String servletName ) { + if (servletName == null) return; + List matches = (List) _filtersPerName.get( servletName ); + if (matches != null) filters.addAll( matches ); } private ServletConfiguration getConfiguration() { - return _mapping == null ? null : _mapping.getConfiguration(); + return _mapping == null ? null : (ServletConfiguration) _mapping.getConfiguration(); } } - static class ServletMapping { + static class WebResourceMapping { - private ServletConfiguration _configuration; + private WebResourceConfiguration _configuration; - ServletConfiguration getConfiguration() { + WebResourceConfiguration getConfiguration() { return _configuration; } - ServletMapping( ServletConfiguration configuration ) { + WebResourceMapping( WebResourceConfiguration configuration ) { _configuration = configuration; } - String getServletPath( String servletName ) { - return servletName; + /** + * Returns the portion of the request path which was actually used to select the servlet. This default + * implementation returns the full specified path. + * @param requestPath the full path of the request, relative to the application root. + */ + String getServletPath( String requestPath ) { + return requestPath; } - String getPathInfo( String servletName ) { + /** + * Returns the portion of the request path which was not used to select the servlet, and can be + * used as data by the servlet. This default implementation returns null. + * @param requestPath the full path of the request, relative to the application root. + */ + String getPathInfo( String requestPath ) { return null; } - public void destroyServlet() { - getConfiguration().destroyServlet(); + public void destroyResource() { + getConfiguration().destroyResource(); } } - static class PartialMatchServletMapping extends ServletMapping { + static class PartialMatchWebResourceMapping extends WebResourceMapping { private String _prefix; - public PartialMatchServletMapping( ServletConfiguration configuration, String prefix ) { + public PartialMatchWebResourceMapping( WebResourceConfiguration configuration, String prefix ) { super( configuration ); if (!prefix.endsWith( "/*" )) throw new IllegalArgumentException( prefix + " does not end with '/*'" ); _prefix = prefix.substring( 0, prefix.length()-2 ); } - String getServletPath( String servletName ) { + String getServletPath( String requestPath ) { return _prefix; } - String getPathInfo( String servletName ) { - return servletName.length() > _prefix.length() - ? servletName.substring( _prefix.length() ) + String getPathInfo( String requestPath ) { + return requestPath.length() > _prefix.length() + ? requestPath.substring( _prefix.length() ) : null; } } /** - * A utility class for mapping servlets to url patterns. This implements the + * A utility class for mapping web resources to url patterns. This implements the * matching algorithm documented in section 10 of the JSDK-2.2 reference. */ - class ServletMap { + class WebResourceMap { private final Map _exactMatches = new HashMap(); private final Map _extensions = new HashMap(); private final Map _urlTree = new HashMap(); - private ServletMapping _defaultMapping; + private WebResourceMapping _defaultMapping; - void put( String mapping, ServletConfiguration servletConfiguration ) { + void put( String mapping, WebResourceConfiguration configuration ) { if (mapping.equals( "/" )) { - _defaultMapping = new ServletMapping( servletConfiguration ); + _defaultMapping = new WebResourceMapping( configuration ); } else if (mapping.startsWith( "*." )) { - _extensions.put( mapping.substring( 2 ), new ServletMapping( servletConfiguration ) ); + _extensions.put( mapping.substring( 2 ), new WebResourceMapping( configuration ) ); } else if (!mapping.startsWith( "/" ) || !mapping.endsWith( "/*" )) { - _exactMatches.put( mapping, new ServletMapping( servletConfiguration ) ); + _exactMatches.put( mapping, new WebResourceMapping( configuration ) ); } else { ParsedPath path = new ParsedPath( mapping ); Map context = _urlTree; while (path.hasNext()) { String part = path.next(); if (part.equals( "*" )) { - context.put( "*", new PartialMatchServletMapping( servletConfiguration, mapping ) ); + context.put( "*", new PartialMatchWebResourceMapping( configuration, mapping ) ); return; } if (!context.containsKey( part )) { @@ -813,17 +922,17 @@ String file = url.getFile(); if (!file.startsWith( _contextPath )) throw new HttpNotFoundException( "File path does not begin with '" + _contextPath + "'", url ); - String servletName = getServletName( file.substring( _contextPath.length() ) ); + String servletPath = getServletPath( file.substring( _contextPath.length() ) ); - if (servletName.endsWith( "j_security_check" )) { - return new ServletRequestImpl( url, servletName, SECURITY_CHECK_MAPPING ); + if (servletPath.endsWith( "j_security_check" )) { + return new ServletRequestImpl( url, servletPath, SECURITY_CHECK_MAPPING, _filterMapping, _filterUrlMapping ); } else { - return new ServletRequestImpl( url, servletName, getMapping( servletName ) ); + return new ServletRequestImpl( url, servletPath, getMapping( servletPath ), _filterMapping, _filterUrlMapping ); } } - private String getServletName( String urlFile ) { + private String getServletPath( String urlFile ) { if (urlFile.indexOf( '?' ) < 0) { return urlFile; } else { @@ -832,22 +941,22 @@ } - public void destroyServlets() { - if (_defaultMapping != null) _defaultMapping.destroyServlet(); - destroyServlets( _exactMatches ); - destroyServlets( _extensions ); - destroyServlets( _urlTree ); + public void destroyWebResources() { + if (_defaultMapping != null) _defaultMapping.destroyResource(); + destroyWebResources( _exactMatches ); + destroyWebResources( _extensions ); + destroyWebResources( _urlTree ); } - private void destroyServlets( Map map ) { + private void destroyWebResources( Map map ) { for (Iterator iterator = map.values().iterator(); iterator.hasNext();) { Object o = iterator.next(); - if (o instanceof ServletMapping) { - ServletMapping servletMapping = (ServletMapping) o; - servletMapping.destroyServlet(); + if (o instanceof WebResourceMapping) { + WebResourceMapping webResourceMapping = (WebResourceMapping) o; + webResourceMapping.destroyResource(); } else { - destroyServlets( (Map) o ); + destroyWebResources( (Map) o ); } } } @@ -883,8 +992,8 @@ private void collectAutoLoadableServlets( Collection collection, Map map ) { for (Iterator iterator = map.values().iterator(); iterator.hasNext();) { Object o = iterator.next(); - if (o instanceof ServletMapping) { - ServletMapping servletMapping = (ServletMapping) o; + if (o instanceof WebResourceMapping) { + WebResourceMapping servletMapping = (WebResourceMapping) o; if (servletMapping.getConfiguration().isLoadOnStartup()) collection.add( servletMapping.getConfiguration() ); } else { collectAutoLoadableServlets( collection, (Map) o ); @@ -893,15 +1002,15 @@ } - private ServletMapping getMapping( String url ) { - if (_exactMatches.containsKey( url )) return (ServletMapping) _exactMatches.get( url ); + private WebResourceMapping getMapping( String url ) { + if (_exactMatches.containsKey( url )) return (WebResourceMapping) _exactMatches.get( url ); Map context = getContextForLongestPathPrefix( url ); - if (context.containsKey( "*" )) return (ServletMapping) context.get( "*" ); + if (context.containsKey( "*" )) return (WebResourceMapping) context.get( "*" ); - if (_extensions.containsKey( getExtension( url ))) return (ServletMapping) _extensions.get( getExtension( url ) ); + if (_extensions.containsKey( getExtension( url ))) return (WebResourceMapping) _extensions.get( getExtension( url ) ); - if (_urlTree.containsKey( "/" )) return (ServletMapping) _urlTree.get( "/" ); + if (_urlTree.containsKey( "/" )) return (WebResourceMapping) _urlTree.get( "/" ); if (_defaultMapping != null) return _defaultMapping; @@ -911,7 +1020,7 @@ String className = url.substring( prefix.length() ); try { Class.forName( className ); - return new ServletMapping( new ServletConfiguration( className ) ); + return new WebResourceMapping( new ServletConfiguration( className ) ); } catch (ClassNotFoundException e) { return null; } |
Update of /cvsroot/httpunit/httpunit/test/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv12499/test/com/meterware/servletunit Modified Files: HttpServletRequestTest.java RequestDispatcherTest.java ServletUnitSuite.java WebXMLString.java Added Files: FiltersTest.java Log Message: Added support for Servlet 2.3 filters ***** Error reading new file[Errno 2] No such file or directory: 'FiltersTest.java' Index: HttpServletRequestTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/HttpServletRequestTest.java,v retrieving revision 1.18 retrieving revision 1.19 diff -u -r1.18 -r1.19 --- HttpServletRequestTest.java 24 Mar 2003 03:22:11 -0000 1.18 +++ HttpServletRequestTest.java 26 Feb 2004 17:36:47 -0000 1.19 @@ -19,10 +19,7 @@ * DEALINGS IN THE SOFTWARE. * *******************************************************************************************************************/ -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Map; -import java.util.Locale; +import java.util.*; import java.net.MalformedURLException; import java.io.InputStream; import java.io.ByteArrayInputStream; @@ -439,6 +436,11 @@ public String getPathInfo() { return null; } + + + public FilterMetaData[] getFilters() { + return null; + } }; } Index: RequestDispatcherTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/RequestDispatcherTest.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- RequestDispatcherTest.java 13 Feb 2003 20:25:56 -0000 1.2 +++ RequestDispatcherTest.java 26 Feb 2004 17:36:47 -0000 1.3 @@ -74,6 +74,7 @@ public void testRequestDispatcherParameters() throws Exception { InvocationContext ic = _runner.newClient().newInvocation( "http://localhost/sample/" + outerServletName + "?param=original¶m1=first" ); + final HttpServletRequest request = ic.getRequest(); final HttpServletResponse response = ic.getResponse(); RequestDispatcherServlet servlet = (RequestDispatcherServlet) ic.getServlet(); Index: ServletUnitSuite.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/ServletUnitSuite.java,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- ServletUnitSuite.java 23 Feb 2004 03:10:42 -0000 1.9 +++ ServletUnitSuite.java 26 Feb 2004 17:36:47 -0000 1.10 @@ -47,6 +47,7 @@ suite.addTest( ConfigTest.suite() ); suite.addTest( WebXMLTest.suite() ); suite.addTest( ListenersTest.suite() ); + suite.addTest( FiltersTest.suite() ); suite.addTest( RequestContextTest.suite() ); suite.addTest( RequestDispatcherTest.suite() ); addOptionalTestCase( suite, "com.meterware.servletunit.JUnitServletTest" ); Index: WebXMLString.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/WebXMLString.java,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- WebXMLString.java 13 Feb 2004 03:17:46 -0000 1.4 +++ WebXMLString.java 26 Feb 2004 17:36:47 -0000 1.5 @@ -38,11 +38,17 @@ private ArrayList _servlets = new ArrayList(); private ArrayList _mappings = new ArrayList(); private ArrayList _servletNames = new ArrayList(); + private Hashtable _initParams = new Hashtable(); + private ArrayList _listeners = new ArrayList(); + private ArrayList _filters = new ArrayList(); + private Hashtable _filterMappings = new Hashtable(); + private ArrayList _filterNames = new ArrayList(); + private Hashtable _filterParams = new Hashtable(); + private String _loginConfig = ""; private Hashtable _resources = new Hashtable(); - private Hashtable _initParams = new Hashtable(); private Hashtable _contextParams = new Hashtable(); private Hashtable _loadOnStartup = new Hashtable(); @@ -60,6 +66,17 @@ result.append( " <context-param>\n <param-name>" ).append( entry.getKey() ); result.append( "</param-name>\n <param-value>" ).append( entry.getValue() ).append( "</param-value>\n </context-param>\n" ); } + for (int i = 0; i < _filters.size(); i++) { + Object name = _filterNames.get( i ); + result.append( " <filter>\n <filter-name>" ).append( name ).append( "</filter-name>\n" ); + result.append( " <filter-class>" ).append( ((Class) _filters.get( i )).getName() ).append( "</filter-class>\n" ); + appendParams( result, "init-param", (Hashtable) _filterParams.get( name ) ); + result.append( " </filter>\n" ); + } + for (int i = 0; i < _filters.size(); i++) { + result.append( " <filter-mapping>\n <filter-name>" ).append( _filterNames.get( i ) ).append( "</filter-name>\n" ); + result.append( " " ).append( _filterMappings.get( _filterNames.get( i ) ) ).append( "\n </filter-mapping>\n" ); + } for (int i = 0; i < _listeners.size(); i++) { Class aClass = (Class) _listeners.get( i ); result.append( " <listener><listener-class>" ).append( aClass.getName() ); @@ -120,8 +137,6 @@ _mappings.add( urlPattern ); _servletNames.add( name ); } - - void addServlet( String name, String urlPattern, Class servletClass, Properties initParams ) { _initParams.put( name, initParams ); addServlet( name, urlPattern, servletClass ); @@ -138,6 +153,29 @@ } + void addFilterForServlet( String name, Class filterClass, String servletName, Properties initParams ) { + _filterParams.put( name, initParams ); + addFilterForServlet( name, filterClass, servletName ); + } + + + void addFilterForServlet( String name, Class filterClass, String servletName ) { + addFilter( filterClass, name, "<servlet-name>" + servletName + "</servlet-name>" ); + } + + + void addFilterForUrl( String name, Class filterClass, String urlPattern ) { + addFilter( filterClass, name, "<url-pattern>" + urlPattern + "</url-pattern>" ); + } + + + private void addFilter( Class filterClass, String name, String mapping ) { + _filters.add( filterClass ); + _filterNames.add( name ); + _filterMappings.put( name, mapping ); + } + + void requireBasicAuthorization( String realmName ) { _loginConfig = " <login-config>\n" + " <auth-method>BASIC</auth-method>\n" + |
|
From: Russell G. <rus...@us...> - 2004-02-26 17:52:41
|
Update of /cvsroot/httpunit/httpunit/doc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv12499/doc Modified Files: release_notes.txt Log Message: Added support for Servlet 2.3 filters Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.323 retrieving revision 1.324 diff -u -r1.323 -r1.324 --- release_notes.txt 15 Feb 2004 06:42:00 -0000 1.323 +++ release_notes.txt 26 Feb 2004 17:36:46 -0000 1.324 @@ -13,6 +13,10 @@ Revision History: +26-Feb-2004 +Additions: + 1. Added support for filters + 14-Feb-2004 Additions: 1. Added support for ServletContextAttributeListener and HttpSessionAttributeListener |
|
From: Russell G. <rus...@us...> - 2004-02-23 03:23:53
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31019/test/com/meterware/servletunit Modified Files: ServletUnitSuite.java Log Message: remove anticipatory test Index: ServletUnitSuite.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/ServletUnitSuite.java,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- ServletUnitSuite.java 23 Feb 2004 02:04:53 -0000 1.8 +++ ServletUnitSuite.java 23 Feb 2004 03:10:42 -0000 1.9 @@ -47,7 +47,6 @@ suite.addTest( ConfigTest.suite() ); suite.addTest( WebXMLTest.suite() ); suite.addTest( ListenersTest.suite() ); - suite.addTest( FiltersTest.suite() ); suite.addTest( RequestContextTest.suite() ); suite.addTest( RequestDispatcherTest.suite() ); addOptionalTestCase( suite, "com.meterware.servletunit.JUnitServletTest" ); |
|
From: Russell G. <rus...@us...> - 2004-02-23 02:17:59
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20779/test/com/meterware/servletunit Modified Files: ServletUnitSuite.java WebXMLTest.java Added Files: ListenersTest.java Log Message: split out listeners test ***** Error reading new file[Errno 2] No such file or directory: 'ListenersTest.java' Index: ServletUnitSuite.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/ServletUnitSuite.java,v retrieving revision 1.7 retrieving revision 1.8 diff -u -r1.7 -r1.8 --- ServletUnitSuite.java 12 Feb 2003 13:47:24 -0000 1.7 +++ ServletUnitSuite.java 23 Feb 2004 02:04:53 -0000 1.8 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2003, Russell Gold +* Copyright (c) 2000-2004, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -46,6 +46,8 @@ suite.addTest( NavigationTest.suite() ); suite.addTest( ConfigTest.suite() ); suite.addTest( WebXMLTest.suite() ); + suite.addTest( ListenersTest.suite() ); + suite.addTest( FiltersTest.suite() ); suite.addTest( RequestContextTest.suite() ); suite.addTest( RequestDispatcherTest.suite() ); addOptionalTestCase( suite, "com.meterware.servletunit.JUnitServletTest" ); Index: WebXMLTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/WebXMLTest.java,v retrieving revision 1.19 retrieving revision 1.20 diff -u -r1.19 -r1.20 --- WebXMLTest.java 15 Feb 2004 06:42:01 -0000 1.19 +++ WebXMLTest.java 23 Feb 2004 02:04:53 -0000 1.20 @@ -39,10 +39,10 @@ import org.xml.sax.SAXException; import junit.framework.TestSuite; -import junit.framework.Assert; +import junit.framework.TestCase; -public class WebXMLTest extends EventAwareTestCase { +public class WebXMLTest extends TestCase { public static void main(String args[]) { junit.textui.TestRunner.run( suite() ); @@ -117,7 +117,7 @@ params.setProperty( "age", "12" ); wxs.addServlet( "simple", "/SimpleServlet", SimpleGetServlet.class, params ); - ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); + ServletRunner sr = new ServletRunner( wxs.asInputStream() ); ServletUnitClient client = sr.newClient(); InvocationContext ic = client.newInvocation( "http://localhost/SimpleServlet" ); ServletConfig servletConfig = ic.getServlet().getServletConfig(); @@ -134,7 +134,7 @@ wxs.addContextParam( "cone", "waffle" ); wxs.addContextParam( "topping", "" ); - ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); + ServletRunner sr = new ServletRunner( wxs.asInputStream() ); ServletUnitClient client = sr.newClient(); assertEquals( "Context parameter 'icecream'", "vanilla", sr.getContextParameter( "icecream" ) ); InvocationContext ic = client.newInvocation( "http://localhost/SimpleServlet" ); @@ -149,194 +149,6 @@ } - public void testContextListeners() throws Exception { - WebXMLString wxs = new WebXMLString(); - wxs.addServlet( "/SimpleServlet", SimpleGetServlet.class ); - EventVerifier verifyContext = new ServletContextEventVerifier(); - - wxs.addContextListener( ListenerClass1.class ); - wxs.addContextListener( ListenerClass2.class ); - - clearEvents(); - expectEvent( "startup", ListenerClass1.class, verifyContext ); - expectEvent( "startup", ListenerClass2.class, verifyContext ); - ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); - verifyEvents(); - - clearEvents(); - expectEvent( "shutdown", ListenerClass2.class, verifyContext ); - expectEvent( "shutdown", ListenerClass1.class, verifyContext ); - sr.shutDown(); - verifyEvents(); - } - - - static class ServletContextEventVerifier implements EventVerifier { - - public void verifyEvent( String eventLabel, Object eventObject ) { - if (!(eventObject instanceof ServletContextEvent)) fail( "Event " + eventLabel + " did not include a servlet context event" ); - } - } - - - public void testSessionLifecycleListeners() throws Exception { - WebXMLString wxs = new WebXMLString(); - wxs.addServlet( "/SimpleServlet", SimpleGetServlet.class ); - EventVerifier verifyContext = new HttpSessionEventVerifier(); - - wxs.addContextListener( ListenerClass3.class ); - wxs.addContextListener( ListenerClass4.class ); - - clearEvents(); - ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); - - ServletUnitClient client = sr.newClient(); - InvocationContext ic = client.newInvocation( "http://localhost/SimpleServlet" ); - verifyEvents(); - - expectEvent( "created", ListenerClass3.class, verifyContext ); - expectEvent( "created", ListenerClass4.class ); - HttpSession session = ic.getRequest().getSession(); - verifyEvents(); - - expectEvent( "destroyed", ListenerClass3.class, verifyContext ); - expectEvent( "destroyed", ListenerClass4.class ); - session.invalidate(); - verifyEvents(); - - sr.shutDown(); - } - - - static class HttpSessionEventVerifier implements EventVerifier { - - public void verifyEvent( String eventLabel, Object eventObject ) { - if (!(eventObject instanceof HttpSessionEvent)) fail( "Event " + eventLabel + " did not include an http session event" ); - } - } - - - public void testSessionAttributeListeners() throws Exception { - WebXMLString wxs = new WebXMLString(); - wxs.addServlet( "/SimpleServlet", SimpleGetServlet.class ); - HttpSessionAttributeEventVerifier verifyAttribute = new HttpSessionAttributeEventVerifier(); - - wxs.addContextListener( ListenerClass5.class ); - wxs.addContextListener( ListenerClass6.class ); - - clearEvents(); - ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); - - ServletUnitClient client = sr.newClient(); - InvocationContext ic = client.newInvocation( "http://localhost/SimpleServlet" ); - HttpSession session = ic.getRequest().getSession(); - verifyEvents(); - - verifyAttribute.expect( "one", new Integer(1) ); - expectEvent( "added", ListenerClass5.class, verifyAttribute ); - expectEvent( "added", ListenerClass6.class, verifyAttribute ); - session.setAttribute( "one", new Integer(1) ); - verifyEvents(); - - expectEvent( "replaced", ListenerClass5.class, verifyAttribute ); - expectEvent( "replaced", ListenerClass6.class, verifyAttribute ); - session.setAttribute( "one", "I" ); - verifyEvents(); - - verifyAttribute.expect( "one", "I" ); - expectEvent( "removed", ListenerClass5.class, verifyAttribute ); - expectEvent( "removed", ListenerClass6.class ); - session.removeAttribute( "one" ); - verifyEvents(); - - sr.shutDown(); - } - - - static class HttpSessionAttributeEventVerifier implements EventVerifier { - - private String _name; - private Object _value; - - - public void verifyEvent( String eventLabel, Object eventObject ) { - if (!(eventObject instanceof HttpSessionBindingEvent)) fail( "Event " + eventLabel + " did not include an http session binding event" ); - HttpSessionBindingEvent bindingChange = (HttpSessionBindingEvent) eventObject; - Assert.assertEquals( "Changed attribute name", _name, bindingChange.getName() ); - Assert.assertEquals( "Changed attribute value", _value, bindingChange.getValue() ); - } - - - public void expect( String name, Object value ) { - _name = name; - _value = value; - } - } - - - - public void testContextAttributeListeners() throws Exception { - WebXMLString wxs = new WebXMLString(); - wxs.addServlet( "/SimpleServlet", SimpleGetServlet.class ); - ContextAttributeEventVerifier verifyAttribute = new ContextAttributeEventVerifier(); - - wxs.addContextListener( ListenerClass7.class ); - wxs.addContextListener( ListenerClass8.class ); - - clearEvents(); - ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); - - ServletUnitClient client = sr.newClient(); - verifyAttribute.expect( "initialized", "SimpleGetServlet" ); - expectEvent( "added", ListenerClass7.class, verifyAttribute ); - expectEvent( "added", ListenerClass8.class, verifyAttribute ); - InvocationContext ic = client.newInvocation( "http://localhost/SimpleServlet" ); - ServletContext context = ic.getServlet().getServletConfig().getServletContext(); - verifyEvents(); - - verifyAttribute.expect( "deux", new Integer(2) ); - expectEvent( "added", ListenerClass7.class, verifyAttribute ); - expectEvent( "added", ListenerClass8.class, verifyAttribute ); - context.setAttribute( "deux", new Integer(2) ); - verifyEvents(); - - expectEvent( "replaced", ListenerClass7.class, verifyAttribute ); - expectEvent( "replaced", ListenerClass8.class, verifyAttribute ); - context.setAttribute( "deux", "II" ); - verifyEvents(); - - verifyAttribute.expect( "deux", "II" ); - expectEvent( "removed", ListenerClass7.class, verifyAttribute ); - expectEvent( "removed", ListenerClass8.class ); - context.removeAttribute( "deux" ); - verifyEvents(); - - sr.shutDown(); - } - - - static class ContextAttributeEventVerifier implements EventVerifier { - - private String _name; - private Object _value; - - - public void verifyEvent( String eventLabel, Object eventObject ) { - if (!(eventObject instanceof ServletContextAttributeEvent)) fail( "Event " + eventLabel + " did not include an http session binding event" ); - ServletContextAttributeEvent bindingChange = (ServletContextAttributeEvent) eventObject; - Assert.assertEquals( "Changed attribute name", _name, bindingChange.getName() ); - Assert.assertEquals( "Changed attribute value", _value, bindingChange.getValue() ); - } - - - public void expect( String name, Object value ) { - _name = name; - _value = value; - } - } - - - private Document newDocument( String contents ) throws UnsupportedEncodingException, SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); return fac.newDocumentBuilder().parse( toInputStream( contents ) ); } @@ -354,7 +166,7 @@ wxs.addSecureURL( "SecureArea1", "/SimpleServlet" ); wxs.addAuthorizedRole( "SecureArea1", "supervisor" ); - ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); + ServletRunner sr = new ServletRunner( wxs.asInputStream() ); ServletUnitClient wc = sr.newClient(); try { wc.getResponse( "http://localhost/SimpleServlet" ); @@ -392,7 +204,7 @@ wxs.addSecureURL( "SecureArea1", "/Example/SimpleServlet" ); wxs.addAuthorizedRole( "SecureArea1", "supervisor" ); - ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); + ServletRunner sr = new ServletRunner( wxs.asInputStream() ); ServletUnitClient wc = sr.newClient(); WebResponse response = wc.getResponse( "http://localhost/Example/SimpleServlet" ); WebForm form = response.getFormWithID( "login" ); @@ -417,12 +229,12 @@ WebXMLString wxs = new WebXMLString(); wxs.addServlet( "/SimpleServlet", SimpleGetServlet.class ); - ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ), "/mount" ); + ServletRunner sr = new ServletRunner( wxs.asInputStream(), "/mount" ); ServletUnitClient wc = sr.newClient(); InvocationContext ic = wc.newInvocation( "http://localhost/mount/SimpleServlet" ); assertEquals("/mount", ic.getRequest().getContextPath()); - sr = new ServletRunner( toInputStream( wxs.asText() ) ); + sr = new ServletRunner( wxs.asInputStream() ); wc = sr.newClient(); ic = wc.newInvocation( "http://localhost/SimpleServlet" ); assertEquals("", ic.getRequest().getContextPath()); @@ -433,7 +245,7 @@ WebXMLString wxs = new WebXMLString(); wxs.addServlet( "/SimpleServlet", SimpleGetServlet.class ); - ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ), "/mount" ); + ServletRunner sr = new ServletRunner( wxs.asInputStream(), "/mount" ); ServletUnitClient wc = sr.newClient(); InvocationContext ic = wc.newInvocation( "http://localhost/mount/SimpleServlet" ); assertTrue(ic.getServlet() instanceof SimpleGetServlet); @@ -454,7 +266,7 @@ wxs.addServlet( "/catalog", Servlet3.class ); wxs.addServlet( "*.bop", Servlet4.class ); wxs.addServlet( "/", Servlet5.class ); - ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); + ServletRunner sr = new ServletRunner( wxs.asInputStream() ); ServletUnitClient wc = sr.newClient(); checkMapping( wc, "http://localhost/foo/bar/index.html", Servlet1.class, "/foo/bar", "/index.html" ); @@ -586,42 +398,6 @@ static class Servlet5 extends SimpleGetServlet {} - static class EventDispatcher { - - public void contextInitialized( ServletContextEvent event ) { sendEvent( "startup", this, event ); } - - public void contextDestroyed( ServletContextEvent event ) { sendEvent( "shutdown", this, event ); } - - public void sessionCreated( HttpSessionEvent event ) { sendEvent( "created", this, event ); } - - public void sessionDestroyed( HttpSessionEvent event ) { sendEvent( "destroyed", this, event ); } - - public void attributeAdded( HttpSessionBindingEvent event ) { sendEvent( "added", this, event ); } - - public void attributeRemoved( HttpSessionBindingEvent event ) { sendEvent( "removed", this, event ); } - - public void attributeReplaced( HttpSessionBindingEvent event ) { sendEvent( "replaced", this, event ); } - - public void attributeAdded( ServletContextAttributeEvent event ) { sendEvent( "added", this, event ); } - - public void attributeRemoved( ServletContextAttributeEvent event ) { sendEvent( "removed", this, event ); } - - public void attributeReplaced( ServletContextAttributeEvent event ) { sendEvent( "replaced", this, event ); } - } - - - static class ListenerClass1 extends EventDispatcher implements ServletContextListener {} - static class ListenerClass2 extends EventDispatcher implements ServletContextListener {} - - static class ListenerClass3 extends EventDispatcher implements HttpSessionListener {} - static class ListenerClass4 extends EventDispatcher implements HttpSessionListener {} - - static class ListenerClass5 extends EventDispatcher implements HttpSessionAttributeListener {} - static class ListenerClass6 extends EventDispatcher implements HttpSessionAttributeListener {} - - static class ListenerClass7 extends EventDispatcher implements ServletContextAttributeListener {} - static class ListenerClass8 extends EventDispatcher implements ServletContextAttributeListener {} - } |
Update of /cvsroot/httpunit/httpunit/src/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24680/src/com/meterware/servletunit Modified Files: ServletUnitContext.java ServletUnitHttpSession.java ServletUnitServletContext.java SessionListenerDispatcher.java WebApplication.java Log Message: Added support for attribute binding listeners Index: ServletUnitContext.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitContext.java,v retrieving revision 1.6 retrieving revision 1.7 diff -u -r1.6 -r1.7 --- ServletUnitContext.java 13 Feb 2004 05:45:19 -0000 1.6 +++ ServletUnitContext.java 15 Feb 2004 06:42:01 -0000 1.7 @@ -34,6 +34,9 @@ this( null, new SessionListenerDispatcher() { public void sendSessionCreated( HttpSession session ) {} public void sendSessionDestroyed( HttpSession session ) {} + public void sendAttributeAdded( HttpSession session, String name, Object value ) {} + public void sendAttributeReplaced( HttpSession session, String name, Object oldValue ) {} + public void sendAttributeRemoved( HttpSession session, String name, Object oldValue ) {} } ); } Index: ServletUnitHttpSession.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitHttpSession.java,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- ServletUnitHttpSession.java 13 Feb 2004 05:45:19 -0000 1.9 +++ ServletUnitHttpSession.java 15 Feb 2004 06:42:01 -0000 1.10 @@ -174,7 +174,15 @@ **/ public void setAttribute( String name, Object value ) { if (_invalid) throw new IllegalStateException(); - _values.put( name, value ); + + if (!_values.containsKey( name )) { + _values.put( name, value ); + _listenerDispatcher.sendAttributeAdded( this, name, value ); + } else { + Object oldValue = _values.get( name ); + _values.put( name, value ); + _listenerDispatcher.sendAttributeReplaced( this, name, oldValue ); + } } @@ -184,7 +192,11 @@ **/ public void removeAttribute( String name ) { if (_invalid) throw new IllegalStateException(); - _values.remove( name ); + if (_values.containsKey( name )) { + Object oldValue = _values.get( name ); + _values.remove( name ); + _listenerDispatcher.sendAttributeRemoved( this, name, oldValue ); + } } Index: ServletUnitServletContext.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitServletContext.java,v retrieving revision 1.12 retrieving revision 1.13 diff -u -r1.12 -r1.13 --- ServletUnitServletContext.java 11 Feb 2003 04:32:01 -0000 1.12 +++ ServletUnitServletContext.java 15 Feb 2004 06:42:01 -0000 1.13 @@ -287,12 +287,21 @@ } public void setAttribute( String name, Object attribute ) { - _attributes.put( name, attribute ); + if (!_attributes.containsKey( name )) { + _attributes.put( name, attribute ); + _application.sendAttributeAdded( name, attribute ); + } else { + Object oldValue = _attributes.get( name ); + _attributes.put( name, attribute ); + _application.sendAttributeReplaced( name, oldValue ); + } } public void removeAttribute( String name ) { + Object oldValue = _attributes.get( name ); _attributes.remove( name ); + _application.sendAttributeRemoved( name, oldValue ); } Index: SessionListenerDispatcher.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/SessionListenerDispatcher.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- SessionListenerDispatcher.java 13 Feb 2004 05:45:19 -0000 1.1 +++ SessionListenerDispatcher.java 15 Feb 2004 06:42:01 -0000 1.2 @@ -34,4 +34,13 @@ void sendSessionDestroyed( HttpSession session ); + + void sendAttributeAdded( HttpSession session, String name, Object value ); + + + void sendAttributeReplaced( HttpSession session, String name, Object oldValue ); + + + void sendAttributeRemoved( HttpSession session, String name, Object oldValue ); + } Index: WebApplication.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/WebApplication.java,v retrieving revision 1.21 retrieving revision 1.22 diff -u -r1.21 -r1.22 --- WebApplication.java 13 Feb 2004 05:45:19 -0000 1.21 +++ WebApplication.java 15 Feb 2004 06:42:01 -0000 1.22 @@ -61,8 +61,12 @@ private ArrayList _contextListeners = new ArrayList(); + private ArrayList _contextAttributeListeners = new ArrayList(); + private ArrayList _sessionListeners = new ArrayList(); + private ArrayList _sessionAttributeListeners = new ArrayList(); + private boolean _useBasicAuthentication; private boolean _useFormAuthentication; @@ -131,7 +135,9 @@ Object listener = Class.forName( listenerName ).newInstance(); if (listener instanceof ServletContextListener) _contextListeners.add( listener ); + if (listener instanceof ServletContextAttributeListener) _contextAttributeListeners.add( listener ); if (listener instanceof HttpSessionListener) _sessionListeners.add( listener ); + if (listener instanceof HttpSessionAttributeListener) _sessionAttributeListeners.add( listener ); } catch (Throwable x) { throw new RuntimeException("Unable to load context listener " + listenerName, x); } @@ -164,6 +170,36 @@ } + void sendAttributeAdded( String name, Object value ) { + ServletContextAttributeEvent event = new ServletContextAttributeEvent( getServletContext(), name, value ); + + for (Iterator i = _contextAttributeListeners.iterator(); i.hasNext();) { + ServletContextAttributeListener listener = (ServletContextAttributeListener) i.next(); + listener.attributeAdded( event ); + } + } + + + void sendAttributeReplaced( String name, Object value ) { + ServletContextAttributeEvent event = new ServletContextAttributeEvent( getServletContext(), name, value ); + + for (Iterator i = _contextAttributeListeners.iterator(); i.hasNext();) { + ServletContextAttributeListener listener = (ServletContextAttributeListener) i.next(); + listener.attributeReplaced( event ); + } + } + + + void sendAttributeRemoved( String name, Object value ) { + ServletContextAttributeEvent event = new ServletContextAttributeEvent( getServletContext(), name, value ); + + for (Iterator i = _contextAttributeListeners.iterator(); i.hasNext();) { + ServletContextAttributeListener listener = (ServletContextAttributeListener) i.next(); + listener.attributeRemoved( event ); + } + } + + private void extractSecurityConstraints( Document document ) throws SAXException { NodeList nl = document.getElementsByTagName( "security-constraint" ); for (int i = 0; i < nl.getLength(); i++) { @@ -329,6 +365,36 @@ } + public void sendAttributeAdded( HttpSession session, String name, Object value ) { + HttpSessionBindingEvent event = new HttpSessionBindingEvent( session, name, value ); + + for (Iterator i = _sessionAttributeListeners.iterator(); i.hasNext();) { + HttpSessionAttributeListener listener = (HttpSessionAttributeListener) i.next(); + listener.attributeAdded( event ); + } + } + + + public void sendAttributeReplaced( HttpSession session, String name, Object oldValue ) { + HttpSessionBindingEvent event = new HttpSessionBindingEvent( session, name, oldValue ); + + for (Iterator i = _sessionAttributeListeners.iterator(); i.hasNext();) { + HttpSessionAttributeListener listener = (HttpSessionAttributeListener) i.next(); + listener.attributeReplaced( event ); + } + } + + + public void sendAttributeRemoved( HttpSession session, String name, Object oldValue ) { + HttpSessionBindingEvent event = new HttpSessionBindingEvent( session, name, oldValue ); + + for (Iterator i = _sessionAttributeListeners.iterator(); i.hasNext();) { + HttpSessionAttributeListener listener = (HttpSessionAttributeListener) i.next(); + listener.attributeRemoved( event ); + } + } + + //--------------------------------------------------- private members -------------------------------------------------- @@ -441,6 +507,7 @@ final static int DONT_AUTOLOAD = Integer.MIN_VALUE; final static int ANY_LOAD_ORDER = Integer.MAX_VALUE; + class ServletConfiguration { private Servlet _servlet; |
|
From: Russell G. <rus...@us...> - 2004-02-15 06:49:17
|
Update of /cvsroot/httpunit/httpunit/doc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24680/doc Modified Files: release_notes.txt Log Message: Added support for attribute binding listeners Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.322 retrieving revision 1.323 diff -u -r1.322 -r1.323 --- release_notes.txt 13 Feb 2004 05:45:19 -0000 1.322 +++ release_notes.txt 15 Feb 2004 06:42:00 -0000 1.323 @@ -13,6 +13,10 @@ Revision History: +14-Feb-2004 +Additions: + 1. Added support for ServletContextAttributeListener and HttpSessionAttributeListener + 12-Feb-2004 Acknowledgements: Thanks to Jarom Smith for finding some typos in the tutorial. |
|
From: Russell G. <rus...@us...> - 2004-02-15 06:49:17
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24680/test/com/meterware/servletunit Modified Files: WebXMLTest.java Log Message: Added support for attribute binding listeners Index: WebXMLTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/WebXMLTest.java,v retrieving revision 1.18 retrieving revision 1.19 diff -u -r1.18 -r1.19 --- WebXMLTest.java 13 Feb 2004 05:45:19 -0000 1.18 +++ WebXMLTest.java 15 Feb 2004 06:42:01 -0000 1.19 @@ -39,6 +39,7 @@ import org.xml.sax.SAXException; import junit.framework.TestSuite; +import junit.framework.Assert; public class WebXMLTest extends EventAwareTestCase { @@ -215,6 +216,126 @@ } + public void testSessionAttributeListeners() throws Exception { + WebXMLString wxs = new WebXMLString(); + wxs.addServlet( "/SimpleServlet", SimpleGetServlet.class ); + HttpSessionAttributeEventVerifier verifyAttribute = new HttpSessionAttributeEventVerifier(); + + wxs.addContextListener( ListenerClass5.class ); + wxs.addContextListener( ListenerClass6.class ); + + clearEvents(); + ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); + + ServletUnitClient client = sr.newClient(); + InvocationContext ic = client.newInvocation( "http://localhost/SimpleServlet" ); + HttpSession session = ic.getRequest().getSession(); + verifyEvents(); + + verifyAttribute.expect( "one", new Integer(1) ); + expectEvent( "added", ListenerClass5.class, verifyAttribute ); + expectEvent( "added", ListenerClass6.class, verifyAttribute ); + session.setAttribute( "one", new Integer(1) ); + verifyEvents(); + + expectEvent( "replaced", ListenerClass5.class, verifyAttribute ); + expectEvent( "replaced", ListenerClass6.class, verifyAttribute ); + session.setAttribute( "one", "I" ); + verifyEvents(); + + verifyAttribute.expect( "one", "I" ); + expectEvent( "removed", ListenerClass5.class, verifyAttribute ); + expectEvent( "removed", ListenerClass6.class ); + session.removeAttribute( "one" ); + verifyEvents(); + + sr.shutDown(); + } + + + static class HttpSessionAttributeEventVerifier implements EventVerifier { + + private String _name; + private Object _value; + + + public void verifyEvent( String eventLabel, Object eventObject ) { + if (!(eventObject instanceof HttpSessionBindingEvent)) fail( "Event " + eventLabel + " did not include an http session binding event" ); + HttpSessionBindingEvent bindingChange = (HttpSessionBindingEvent) eventObject; + Assert.assertEquals( "Changed attribute name", _name, bindingChange.getName() ); + Assert.assertEquals( "Changed attribute value", _value, bindingChange.getValue() ); + } + + + public void expect( String name, Object value ) { + _name = name; + _value = value; + } + } + + + + public void testContextAttributeListeners() throws Exception { + WebXMLString wxs = new WebXMLString(); + wxs.addServlet( "/SimpleServlet", SimpleGetServlet.class ); + ContextAttributeEventVerifier verifyAttribute = new ContextAttributeEventVerifier(); + + wxs.addContextListener( ListenerClass7.class ); + wxs.addContextListener( ListenerClass8.class ); + + clearEvents(); + ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); + + ServletUnitClient client = sr.newClient(); + verifyAttribute.expect( "initialized", "SimpleGetServlet" ); + expectEvent( "added", ListenerClass7.class, verifyAttribute ); + expectEvent( "added", ListenerClass8.class, verifyAttribute ); + InvocationContext ic = client.newInvocation( "http://localhost/SimpleServlet" ); + ServletContext context = ic.getServlet().getServletConfig().getServletContext(); + verifyEvents(); + + verifyAttribute.expect( "deux", new Integer(2) ); + expectEvent( "added", ListenerClass7.class, verifyAttribute ); + expectEvent( "added", ListenerClass8.class, verifyAttribute ); + context.setAttribute( "deux", new Integer(2) ); + verifyEvents(); + + expectEvent( "replaced", ListenerClass7.class, verifyAttribute ); + expectEvent( "replaced", ListenerClass8.class, verifyAttribute ); + context.setAttribute( "deux", "II" ); + verifyEvents(); + + verifyAttribute.expect( "deux", "II" ); + expectEvent( "removed", ListenerClass7.class, verifyAttribute ); + expectEvent( "removed", ListenerClass8.class ); + context.removeAttribute( "deux" ); + verifyEvents(); + + sr.shutDown(); + } + + + static class ContextAttributeEventVerifier implements EventVerifier { + + private String _name; + private Object _value; + + + public void verifyEvent( String eventLabel, Object eventObject ) { + if (!(eventObject instanceof ServletContextAttributeEvent)) fail( "Event " + eventLabel + " did not include an http session binding event" ); + ServletContextAttributeEvent bindingChange = (ServletContextAttributeEvent) eventObject; + Assert.assertEquals( "Changed attribute name", _name, bindingChange.getName() ); + Assert.assertEquals( "Changed attribute value", _value, bindingChange.getValue() ); + } + + + public void expect( String name, Object value ) { + _name = name; + _value = value; + } + } + + private Document newDocument( String contents ) throws UnsupportedEncodingException, SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); @@ -474,6 +595,18 @@ public void sessionCreated( HttpSessionEvent event ) { sendEvent( "created", this, event ); } public void sessionDestroyed( HttpSessionEvent event ) { sendEvent( "destroyed", this, event ); } + + public void attributeAdded( HttpSessionBindingEvent event ) { sendEvent( "added", this, event ); } + + public void attributeRemoved( HttpSessionBindingEvent event ) { sendEvent( "removed", this, event ); } + + public void attributeReplaced( HttpSessionBindingEvent event ) { sendEvent( "replaced", this, event ); } + + public void attributeAdded( ServletContextAttributeEvent event ) { sendEvent( "added", this, event ); } + + public void attributeRemoved( ServletContextAttributeEvent event ) { sendEvent( "removed", this, event ); } + + public void attributeReplaced( ServletContextAttributeEvent event ) { sendEvent( "replaced", this, event ); } } @@ -483,6 +616,12 @@ static class ListenerClass3 extends EventDispatcher implements HttpSessionListener {} static class ListenerClass4 extends EventDispatcher implements HttpSessionListener {} + static class ListenerClass5 extends EventDispatcher implements HttpSessionAttributeListener {} + static class ListenerClass6 extends EventDispatcher implements HttpSessionAttributeListener {} + + static class ListenerClass7 extends EventDispatcher implements ServletContextAttributeListener {} + static class ListenerClass8 extends EventDispatcher implements ServletContextAttributeListener {} + } |
Update of /cvsroot/httpunit/httpunit/src/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11966/src/com/meterware/servletunit Modified Files: ServletRunner.java ServletUnitContext.java ServletUnitHttpSession.java WebApplication.java Added Files: SessionListenerDispatcher.java Log Message: Add support for HttpSessionListener ***** Error reading new file[Errno 2] No such file or directory: 'SessionListenerDispatcher.java' Index: ServletRunner.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletRunner.java,v retrieving revision 1.23 retrieving revision 1.24 diff -u -r1.23 -r1.24 --- ServletRunner.java 13 Feb 2004 03:17:46 -0000 1.23 +++ ServletRunner.java 13 Feb 2004 05:45:19 -0000 1.24 @@ -50,7 +50,7 @@ } /** - * Constructor which expects the full path to the web.xml for the + * Constructor which expects the full path to the web.xml for the * application. * * @param webXMLFileSpec the full path to the web.xml file @@ -62,7 +62,7 @@ /** - * Constructor which expects the full path to the web.xml for the + * Constructor which expects the full path to the web.xml for the * application and a context path under which to mount it. * * @param webXMLFileSpec the full path to the web.xml file @@ -100,7 +100,7 @@ private void completeInitialization( String contextPath ) { - _context = new ServletUnitContext( contextPath ); + _context = new ServletUnitContext( contextPath, _application ); _application.registerServlet( "*.jsp", _jspServletDescriptor.getClassName(), _jspServletDescriptor.getInitializationParameters( null, null ) ); } Index: ServletUnitContext.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitContext.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- ServletUnitContext.java 17 Mar 2003 01:35:44 -0000 1.5 +++ ServletUnitContext.java 13 Feb 2004 05:45:19 -0000 1.6 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2003, Russell Gold +* Copyright (c) 2000-2004, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -21,24 +21,34 @@ *******************************************************************************************************************/ +import javax.servlet.http.HttpSession; import java.util.*; import java.util.Hashtable; class ServletUnitContext { + private SessionListenerDispatcher _listenerDispatcher; + + ServletUnitContext() { - this( null ); + this( null, new SessionListenerDispatcher() { + public void sendSessionCreated( HttpSession session ) {} + public void sendSessionDestroyed( HttpSession session ) {} + } ); } - ServletUnitContext( String contextPath ) { + + ServletUnitContext( String contextPath, SessionListenerDispatcher dispatcher ) { _contextPath = (contextPath != null ? contextPath : ""); + _listenerDispatcher = dispatcher; } Set getSessionIDs() { return _sessions.keySet(); } - + + /** * Returns the session with the specified ID, if any. **/ @@ -51,8 +61,9 @@ * Creates a new session with a unique ID. **/ ServletUnitHttpSession newSession() { - ServletUnitHttpSession result = new ServletUnitHttpSession(); + ServletUnitHttpSession result = new ServletUnitHttpSession( _listenerDispatcher ); _sessions.put( result.getId(), result ); + _listenerDispatcher.sendSessionCreated( result ); return result; } Index: ServletUnitHttpSession.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitHttpSession.java,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- ServletUnitHttpSession.java 25 Feb 2003 17:17:29 -0000 1.8 +++ ServletUnitHttpSession.java 13 Feb 2004 05:45:19 -0000 1.9 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2003 Russell Gold +* Copyright (c) 2000-2004 Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -35,6 +35,14 @@ final static public String SESSION_COOKIE_NAME = "JSESSION"; + private SessionListenerDispatcher _listenerDispatcher; + + + public ServletUnitHttpSession( SessionListenerDispatcher listenerDispatcher ) { + _listenerDispatcher = listenerDispatcher; + } + + /** * Returns the maximum time interval, in seconds, that the servlet engine will keep this session open * between client requests. You can set the maximum time interval with the setMaxInactiveInterval method. @@ -104,6 +112,7 @@ * Invalidates this session and unbinds any objects bound to it. **/ public void invalidate() { + _listenerDispatcher.sendSessionDestroyed( this ); _invalid = true; _values.clear(); } Index: WebApplication.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/WebApplication.java,v retrieving revision 1.20 retrieving revision 1.21 diff -u -r1.20 -r1.21 --- WebApplication.java 13 Feb 2004 03:17:46 -0000 1.20 +++ WebApplication.java 13 Feb 2004 05:45:19 -0000 1.21 @@ -29,9 +29,7 @@ import java.util.*; import javax.servlet.*; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.*; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -48,7 +46,7 @@ * @author <a href="ba...@we...">Donald Ball</a> * @author <a href="jay...@us...">Jay Dunning</a> **/ -class WebApplication { +class WebApplication implements SessionListenerDispatcher { private final static SecurityConstraint NULL_SECURITY_CONSTRAINT = new NullSecurityConstraint(); @@ -63,6 +61,8 @@ private ArrayList _contextListeners = new ArrayList(); + private ArrayList _sessionListeners = new ArrayList(); + private boolean _useBasicAuthentication; private boolean _useFormAuthentication; @@ -117,25 +117,24 @@ extractSecurityConstraints( document ); extractContextParameters( document ); extractLoginConfiguration( document ); - extractContextListeners( document ); + extractListeners( document ); notifyContextInitialized(); _servletMapping.autoLoadServlets(); } - private void extractContextListeners( Document document ) throws SAXException { - ServletContextListener listener; + private void extractListeners( Document document ) throws SAXException { NodeList nl = document.getElementsByTagName( "listener" ); for (int i = 0; i < nl.getLength(); i++) { String listenerName = getChildNodeValue((Element) nl.item(i), "listener-class").trim(); try { - listener = (ServletContextListener) Class.forName(listenerName).newInstance(); - } catch (Exception x) { - throw new RuntimeException("Unable to load context listener " + listenerName, x); - } catch (Error x) { + Object listener = Class.forName( listenerName ).newInstance(); + + if (listener instanceof ServletContextListener) _contextListeners.add( listener ); + if (listener instanceof HttpSessionListener) _sessionListeners.add( listener ); + } catch (Throwable x) { throw new RuntimeException("Unable to load context listener " + listenerName, x); } - _contextListeners.add(listener); } } @@ -307,8 +306,30 @@ return _contextParameters; } +//---------------------------------------- SessionListenerDispatcher methods ------------------------------------------- + + + public void sendSessionCreated( HttpSession session ) { + HttpSessionEvent event = new HttpSessionEvent( session ); + + for (Iterator i = _sessionListeners.iterator(); i.hasNext();) { + HttpSessionListener listener = (HttpSessionListener) i.next(); + listener.sessionCreated( event ); + } + } + + + public void sendSessionDestroyed( HttpSession session ) { + HttpSessionEvent event = new HttpSessionEvent( session ); + + for (Iterator i = _sessionListeners.iterator(); i.hasNext();) { + HttpSessionListener listener = (HttpSessionListener) i.next(); + listener.sessionDestroyed( event ); + } + } + -//------------------------------------------------ private members --------------------------------------------- +//--------------------------------------------------- private members -------------------------------------------------- private void extractLoginConfiguration( Document document ) throws MalformedURLException, SAXException { |
|
From: Russell G. <rus...@us...> - 2004-02-13 05:50:45
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11966/test/com/meterware/servletunit Modified Files: WebXMLTest.java Log Message: Add support for HttpSessionListener Index: WebXMLTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/WebXMLTest.java,v retrieving revision 1.17 retrieving revision 1.18 diff -u -r1.17 -r1.18 --- WebXMLTest.java 13 Feb 2004 03:17:46 -0000 1.17 +++ WebXMLTest.java 13 Feb 2004 05:45:19 -0000 1.18 @@ -31,9 +31,7 @@ import java.util.Arrays; import javax.servlet.*; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.*; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -180,6 +178,44 @@ } + public void testSessionLifecycleListeners() throws Exception { + WebXMLString wxs = new WebXMLString(); + wxs.addServlet( "/SimpleServlet", SimpleGetServlet.class ); + EventVerifier verifyContext = new HttpSessionEventVerifier(); + + wxs.addContextListener( ListenerClass3.class ); + wxs.addContextListener( ListenerClass4.class ); + + clearEvents(); + ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); + + ServletUnitClient client = sr.newClient(); + InvocationContext ic = client.newInvocation( "http://localhost/SimpleServlet" ); + verifyEvents(); + + expectEvent( "created", ListenerClass3.class, verifyContext ); + expectEvent( "created", ListenerClass4.class ); + HttpSession session = ic.getRequest().getSession(); + verifyEvents(); + + expectEvent( "destroyed", ListenerClass3.class, verifyContext ); + expectEvent( "destroyed", ListenerClass4.class ); + session.invalidate(); + verifyEvents(); + + sr.shutDown(); + } + + + static class HttpSessionEventVerifier implements EventVerifier { + + public void verifyEvent( String eventLabel, Object eventObject ) { + if (!(eventObject instanceof HttpSessionEvent)) fail( "Event " + eventLabel + " did not include an http session event" ); + } + } + + + private Document newDocument( String contents ) throws UnsupportedEncodingException, SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); return fac.newDocumentBuilder().parse( toInputStream( contents ) ); } @@ -434,12 +470,19 @@ public void contextInitialized( ServletContextEvent event ) { sendEvent( "startup", this, event ); } public void contextDestroyed( ServletContextEvent event ) { sendEvent( "shutdown", this, event ); } + + public void sessionCreated( HttpSessionEvent event ) { sendEvent( "created", this, event ); } + + public void sessionDestroyed( HttpSessionEvent event ) { sendEvent( "destroyed", this, event ); } } static class ListenerClass1 extends EventDispatcher implements ServletContextListener {} static class ListenerClass2 extends EventDispatcher implements ServletContextListener {} + static class ListenerClass3 extends EventDispatcher implements HttpSessionListener {} + static class ListenerClass4 extends EventDispatcher implements HttpSessionListener {} + } |
|
From: Russell G. <rus...@us...> - 2004-02-13 05:50:44
|
Update of /cvsroot/httpunit/httpunit/doc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11966/doc Modified Files: release_notes.txt Log Message: Add support for HttpSessionListener Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.321 retrieving revision 1.322 diff -u -r1.321 -r1.322 --- release_notes.txt 13 Feb 2004 03:17:46 -0000 1.321 +++ release_notes.txt 13 Feb 2004 05:45:19 -0000 1.322 @@ -29,6 +29,7 @@ Additions: 1. Patch #890995 - Implemented ServletUnitHttpResponse.containsHeader 2. Patch #890936 - Added ServletContextListener support + 3. Added HttpSessionListener support 4-Dec-2003 Acknowledgements: |
|
From: Russell G. <rus...@us...> - 2004-02-13 03:23:07
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20086/test/com/meterware/servletunit Modified Files: WebXMLString.java WebXMLTest.java Added Files: EventAwareTestCase.java Log Message: Patch #890936 - Jay Dunning added ServletContextListener support ***** Error reading new file[Errno 2] No such file or directory: 'EventAwareTestCase.java' Index: WebXMLString.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/WebXMLString.java,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- WebXMLString.java 19 Feb 2003 19:18:00 -0000 1.3 +++ WebXMLString.java 13 Feb 2004 03:17:46 -0000 1.4 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * - * Copyright (c) 2001-2003, Russell Gold + * Copyright (c) 2001-2004, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -38,6 +38,7 @@ private ArrayList _servlets = new ArrayList(); private ArrayList _mappings = new ArrayList(); private ArrayList _servletNames = new ArrayList(); + private ArrayList _listeners = new ArrayList(); private String _loginConfig = ""; private Hashtable _resources = new Hashtable(); @@ -45,6 +46,7 @@ private Hashtable _contextParams = new Hashtable(); private Hashtable _loadOnStartup = new Hashtable(); + ByteArrayInputStream asInputStream() throws UnsupportedEncodingException { return new ByteArrayInputStream( asText().getBytes( "UTF-8" ) ); } @@ -58,6 +60,11 @@ result.append( " <context-param>\n <param-name>" ).append( entry.getKey() ); result.append( "</param-name>\n <param-value>" ).append( entry.getValue() ).append( "</param-value>\n </context-param>\n" ); } + for (int i = 0; i < _listeners.size(); i++) { + Class aClass = (Class) _listeners.get( i ); + result.append( " <listener><listener-class>" ).append( aClass.getName() ); + result.append( "</listener-class></listener>\n" ); + } for (int i = _servlets.size() - 1; i >= 0; i--) { Object name = _servletNames.get( i ); result.append( " <servlet>\n <servlet-name>" ).append( name ).append( "</servlet-name>\n" ); @@ -169,6 +176,11 @@ } + void addContextListener( Class aClass ) { + _listeners.add( aClass ); + } + + private WebResourceSpec getWebResource( String resourceName ) { WebResourceSpec result = (WebResourceSpec) _resources.get( resourceName ); if (result == null) { Index: WebXMLTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/WebXMLTest.java,v retrieving revision 1.16 retrieving revision 1.17 diff -u -r1.16 -r1.17 --- WebXMLTest.java 17 Jun 2003 11:17:45 -0000 1.16 +++ WebXMLTest.java 13 Feb 2004 03:17:46 -0000 1.17 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2001-2003, Russell Gold +* Copyright (c) 2001-2004, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -30,8 +30,7 @@ import java.util.List; import java.util.Arrays; -import javax.servlet.ServletException; -import javax.servlet.ServletConfig; +import javax.servlet.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -41,11 +40,10 @@ import org.w3c.dom.Document; import org.xml.sax.SAXException; -import junit.framework.TestCase; import junit.framework.TestSuite; -public class WebXMLTest extends TestCase { +public class WebXMLTest extends EventAwareTestCase { public static void main(String args[]) { junit.textui.TestRunner.run( suite() ); @@ -152,6 +150,36 @@ } + public void testContextListeners() throws Exception { + WebXMLString wxs = new WebXMLString(); + wxs.addServlet( "/SimpleServlet", SimpleGetServlet.class ); + EventVerifier verifyContext = new ServletContextEventVerifier(); + + wxs.addContextListener( ListenerClass1.class ); + wxs.addContextListener( ListenerClass2.class ); + + clearEvents(); + expectEvent( "startup", ListenerClass1.class, verifyContext ); + expectEvent( "startup", ListenerClass2.class, verifyContext ); + ServletRunner sr = new ServletRunner( toInputStream( wxs.asText() ) ); + verifyEvents(); + + clearEvents(); + expectEvent( "shutdown", ListenerClass2.class, verifyContext ); + expectEvent( "shutdown", ListenerClass1.class, verifyContext ); + sr.shutDown(); + verifyEvents(); + } + + + static class ServletContextEventVerifier implements EventVerifier { + + public void verifyEvent( String eventLabel, Object eventObject ) { + if (!(eventObject instanceof ServletContextEvent)) fail( "Event " + eventLabel + " did not include a servlet context event" ); + } + } + + private Document newDocument( String contents ) throws UnsupportedEncodingException, SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); return fac.newDocumentBuilder().parse( toInputStream( contents ) ); } @@ -400,6 +428,18 @@ static class Servlet4 extends SimpleGetServlet {} static class Servlet5 extends SimpleGetServlet {} + + static class EventDispatcher { + + public void contextInitialized( ServletContextEvent event ) { sendEvent( "startup", this, event ); } + + public void contextDestroyed( ServletContextEvent event ) { sendEvent( "shutdown", this, event ); } + } + + + static class ListenerClass1 extends EventDispatcher implements ServletContextListener {} + static class ListenerClass2 extends EventDispatcher implements ServletContextListener {} + } |
|
From: Russell G. <rus...@us...> - 2004-02-13 03:23:07
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20086/src/com/meterware/servletunit Modified Files: ServletRunner.java WebApplication.java Log Message: Patch #890936 - Jay Dunning added ServletContextListener support Index: ServletRunner.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletRunner.java,v retrieving revision 1.22 retrieving revision 1.23 diff -u -r1.22 -r1.23 --- ServletRunner.java 17 Jun 2003 11:17:45 -0000 1.22 +++ ServletRunner.java 13 Feb 2004 03:17:46 -0000 1.23 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2003, Russell Gold +* Copyright (c) 2000-2004, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -142,10 +142,11 @@ /** * Shuts down the servlet container, returning any resources held by it. - * Calls the destroy method of each active servlet. + * Calls the destroy method of each active servlet, then notifies + * ContextListeners of server shutdown. */ public void shutDown() { - _application.destroyServlets(); + _application.shutDown(); } Index: WebApplication.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/WebApplication.java,v retrieving revision 1.19 retrieving revision 1.20 diff -u -r1.19 -r1.20 --- WebApplication.java 27 Feb 2003 13:33:45 -0000 1.19 +++ WebApplication.java 13 Feb 2004 03:17:46 -0000 1.20 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * - * Copyright (c) 2001-2003, Russell Gold + * Copyright (c) 2001-2004, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -28,9 +28,7 @@ import java.net.URL; import java.util.*; -import javax.servlet.Servlet; -import javax.servlet.ServletException; -import javax.servlet.ServletContext; +import javax.servlet.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -48,6 +46,7 @@ * * @author <a href="mailto:rus...@ht...">Russell Gold</a> * @author <a href="ba...@we...">Donald Ball</a> + * @author <a href="jay...@us...">Jay Dunning</a> **/ class WebApplication { @@ -62,6 +61,8 @@ private ArrayList _securityConstraints = new ArrayList(); + private ArrayList _contextListeners = new ArrayList(); + private boolean _useBasicAuthentication; private boolean _useFormAuthentication; @@ -116,10 +117,54 @@ extractSecurityConstraints( document ); extractContextParameters( document ); extractLoginConfiguration( document ); + extractContextListeners( document ); + notifyContextInitialized(); _servletMapping.autoLoadServlets(); } + private void extractContextListeners( Document document ) throws SAXException { + ServletContextListener listener; + NodeList nl = document.getElementsByTagName( "listener" ); + for (int i = 0; i < nl.getLength(); i++) { + String listenerName = getChildNodeValue((Element) nl.item(i), "listener-class").trim(); + try { + listener = (ServletContextListener) Class.forName(listenerName).newInstance(); + } catch (Exception x) { + throw new RuntimeException("Unable to load context listener " + listenerName, x); + } catch (Error x) { + throw new RuntimeException("Unable to load context listener " + listenerName, x); + } + _contextListeners.add(listener); + } + } + + private void notifyContextInitialized() { + ServletContextEvent event = new ServletContextEvent( getServletContext() ); + + for (Iterator i = _contextListeners.iterator(); i.hasNext();) { + ServletContextListener listener = (ServletContextListener) i.next(); + listener.contextInitialized( event ); + } + } + + + void shutDown() { + destroyServlets(); + notifyContextDestroyed(); + } + + + private void notifyContextDestroyed() { + ServletContextEvent event = new ServletContextEvent( getServletContext() ); + + for (ListIterator i = _contextListeners.listIterator( _contextListeners.size() ); i.hasPrevious();) { + ServletContextListener listener = (ServletContextListener) i.previous(); + listener.contextDestroyed( event ); + } + } + + private void extractSecurityConstraints( Document document ) throws SAXException { NodeList nl = document.getElementsByTagName( "security-constraint" ); for (int i = 0; i < nl.getLength(); i++) { |
|
From: Russell G. <rus...@us...> - 2004-02-13 03:23:07
|
Update of /cvsroot/httpunit/httpunit/doc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20086/doc Modified Files: release_notes.txt Log Message: Patch #890936 - Jay Dunning added ServletContextListener support Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.320 retrieving revision 1.321 diff -u -r1.320 -r1.321 --- release_notes.txt 12 Feb 2004 17:46:29 -0000 1.320 +++ release_notes.txt 13 Feb 2004 03:17:46 -0000 1.321 @@ -17,6 +17,7 @@ Acknowledgements: Thanks to Jarom Smith for finding some typos in the tutorial. Thanks to Jay Dunning for providing an implementation of HttpServletResponse.containsHeader + and implementing support for ServletContextListeners. Problems fixed: 1. Window.open() using an empty name was replacing the main window rather than creating a new one. @@ -27,6 +28,7 @@ Additions: 1. Patch #890995 - Implemented ServletUnitHttpResponse.containsHeader + 2. Patch #890936 - Added ServletContextListener support 4-Dec-2003 Acknowledgements: |
|
From: Russell G. <rus...@us...> - 2004-02-12 22:52:25
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/cookies In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31098/src/com/meterware/httpunit/cookies Modified Files: CookieJar.java Log Message: accept exact match cookie domain if lenient matching Index: CookieJar.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/cookies/CookieJar.java,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- CookieJar.java 12 Feb 2004 13:03:24 -0000 1.8 +++ CookieJar.java 12 Feb 2004 22:46:42 -0000 1.9 @@ -337,6 +337,8 @@ if (cookie.getDomain() == null) { cookie.setDomain( _sourceURL.getHost() ); + } else if (!CookieProperties.isDomainMatchingStrict() && cookie.getDomain().equalsIgnoreCase( _sourceURL.getHost() )) { + cookie.setDomain( _sourceURL.getHost() ); } else { int status = getDomainAttributeStatus( cookie.getDomain(), _sourceURL.getHost() ); if (status != CookieListener.ACCEPTED) { |
|
From: Russell G. <rus...@us...> - 2004-02-12 22:52:06
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/cookies In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31098/test/com/meterware/httpunit/cookies Modified Files: CookieTest.java Log Message: accept exact match cookie domain if lenient matching Index: CookieTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/cookies/CookieTest.java,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- CookieTest.java 12 Feb 2004 13:03:24 -0000 1.8 +++ CookieTest.java 12 Feb 2004 22:46:43 -0000 1.9 @@ -113,6 +113,7 @@ checkAcceptance( 6, false, "www.meterware.com/servlets/special", ".com", null ); checkAcceptance( 7, false, "www.meterware.com/servlets/special", ".httpunit.org", null ); checkAcceptance( 8, false, "www.some.meterware.com/servlets/special", ".meterware.com", null ); + checkAcceptance( 9, false, "www.meterware.com/servlets/special", "www.meterware.com", null ); } @@ -196,10 +197,11 @@ CookieProperties.setDomainMatchingStrict( false ); checkAcceptance( 1, true, "www.some.meterware.com/servlets/special", ".meterware.com", null ); checkAcceptance( 2, false, "www.meterware.com/servlets/special", ".meterware.com", "/servlets/ordinary" ); + checkAcceptance( 3, true, "www.meterware.com/servlets/special", "www.meterware.com", null ); CookieProperties.setPathMatchingStrict( false ); - checkAcceptance( 3, true, "www.meterware.com/servlets/special", ".meterware.com", "/servlets/ordinary" ); - checkMatching( 4, true, new URL( "http://www.meterware.com/servlets/sample" ), "www.meterware.com", "/servlets/sample/data" ); + checkAcceptance( 11, true, "www.meterware.com/servlets/special", ".meterware.com", "/servlets/ordinary" ); + checkMatching( 12, true, new URL( "http://www.meterware.com/servlets/sample" ), "www.meterware.com", "/servlets/sample/data" ); } |
|
From: Russell G. <rus...@us...> - 2004-02-12 17:51:32
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24775/test/com/meterware/servletunit Modified Files: HttpServletResponseTest.java Log Message: #890995 - Implemented ServletUnitHttpResponse.containsHeader Index: HttpServletResponseTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/HttpServletResponseTest.java,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- HttpServletResponseTest.java 24 Mar 2003 03:22:12 -0000 1.10 +++ HttpServletResponseTest.java 12 Feb 2004 17:46:29 -0000 1.11 @@ -183,9 +183,11 @@ ServletUnitHttpResponse servletResponse = new ServletUnitHttpResponse(); servletResponse.setContentType( "text/html" ); + assertFalse( "header foo wrongly detected", servletResponse.containsHeader( "foo" ) ); servletResponse.setHeader( "foo", "bar" ); String headerValue = servletResponse.getHeaderField( "foo" ); assertEquals( "header is wrong", "bar", headerValue ); + assertTrue( "header foo not detected", servletResponse.containsHeader( "foo" ) ); servletResponse.setHeader( "foo", "baz" ); headerValue = servletResponse.getHeaderField( "foo" ); |
|
From: Russell G. <rus...@us...> - 2004-02-12 17:51:32
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/servletunit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24775/src/com/meterware/servletunit Modified Files: ServletUnitHttpResponse.java Log Message: #890995 - Implemented ServletUnitHttpResponse.containsHeader Index: ServletUnitHttpResponse.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitHttpResponse.java,v retrieving revision 1.19 retrieving revision 1.20 diff -u -r1.19 -r1.20 --- ServletUnitHttpResponse.java 24 Mar 2003 03:22:11 -0000 1.19 +++ ServletUnitHttpResponse.java 12 Feb 2004 17:46:29 -0000 1.20 @@ -69,8 +69,8 @@ * Checks whether the response message header has a field with * the specified name. */ - public boolean containsHeader(String name) { - throw new RuntimeException( "containsHeader not implemented" ); + public boolean containsHeader( String name ) { + return _headers.containsKey( name.toUpperCase() ); } |