httpunit-commit Mailing List for httpunit (Page 66)
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...> - 2002-01-25 19:09:11
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv10169/doc Modified Files: release_notes.txt Log Message: Added writeMessageBody to WebClient Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.81 retrieving revision 1.82 diff -u -r1.81 -r1.82 --- release_notes.txt 2002/01/24 17:59:45 1.81 +++ release_notes.txt 2002/01/25 19:09:08 1.82 @@ -14,6 +14,7 @@ 24-Jan-2002 Additions: 1. You can now call HttpUnitOptions.setAutoRedirect( false ) to enable explicit testing of redirect requests. + 2. WebClient now exposes the protected method writeMessageBody to ease implementation of new subclasses 23-Jan-2002 Problems fixed: |
From: Russell G. <rus...@us...> - 2002-01-25 19:09:11
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv10169/src/com/meterware/httpunit Modified Files: MessageBodyWebRequest.java WebClient.java WebRequest.java Log Message: Added writeMessageBody to WebClient Index: MessageBodyWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/MessageBodyWebRequest.java,v retrieving revision 1.7 retrieving revision 1.8 diff -u -r1.7 -r1.8 --- MessageBodyWebRequest.java 2002/01/22 20:00:37 1.7 +++ MessageBodyWebRequest.java 2002/01/25 19:09:08 1.8 @@ -4,12 +4,12 @@ * * Copyright (c) 2001-2002, 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 +* 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 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * -* The above copyright notice and this permission notice shall be included in all copies or substantial portions +* The above copyright notice and this permission notice shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO @@ -64,7 +64,7 @@ /** * Subclasses must override this method to provide a message body for the * request. - **/ + **/ abstract protected MessageBody getMessageBody(); @@ -72,6 +72,11 @@ //---------------------------------- WebRequest methods -------------------------------- + protected void writeMessageBody( OutputStream stream ) throws IOException { + getMessageBody().writeTo( stream ); + } + + /** * Performs any additional processing necessary to complete the request. **/ @@ -81,7 +86,7 @@ connection.setDoOutput( true ); OutputStream stream = connection.getOutputStream(); - getMessageBody().writeTo( stream ); + writeMessageBody( stream ); stream.flush(); stream.close(); } @@ -98,15 +103,15 @@ * A method request message body read directly from an input stream. **/ public static class InputStreamMessageBody extends MessageBody { - - + + public InputStreamMessageBody( MessageBodyWebRequest request, InputStream source, String contentType ) { super( request ); _source = source; _contentType = contentType; } - - + + /** * Returns the content type of this message body. **/ @@ -125,11 +130,11 @@ outputStream.write( buffer, 0, count ); count = _source.read( buffer, 0, buffer.length ); } while (count != -1); - + _source.close(); } - - + + private InputStream _source; private String _contentType; } Index: WebClient.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebClient.java,v retrieving revision 1.15 retrieving revision 1.16 diff -u -r1.15 -r1.16 --- WebClient.java 2002/01/24 17:59:45 1.15 +++ WebClient.java 2002/01/25 19:09:08 1.16 @@ -20,6 +20,7 @@ * *******************************************************************************************************************/ import java.io.IOException; +import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; @@ -171,6 +172,14 @@ **/ abstract protected WebResponse newResponse( WebRequest request ) throws MalformedURLException, IOException; + + + /** + * Writes the message body for the request. + **/ + final protected void writeMessageBody( WebRequest request, OutputStream stream ) throws IOException { + request.writeMessageBody( stream ); + } /** Index: WebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebRequest.java,v retrieving revision 1.37 retrieving revision 1.38 diff -u -r1.37 -r1.38 --- WebRequest.java 2002/01/17 19:38:09 1.37 +++ WebRequest.java 2002/01/25 19:09:08 1.38 @@ -23,6 +23,7 @@ import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; +import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -331,6 +332,13 @@ * Performs any additional processing necessary to complete the request. **/ protected void completeRequest( URLConnection connection ) throws IOException { + } + + + /** + * Writes the contents of the message body to the specified stream. + */ + protected void writeMessageBody( OutputStream stream ) throws IOException { } |
From: Russell G. <rus...@us...> - 2002-01-24 17:59:49
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv2108/src/com/meterware/httpunit Modified Files: HttpUnitOptions.java WebClient.java Log Message: Permit disable of auto-redirect Index: HttpUnitOptions.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/HttpUnitOptions.java,v retrieving revision 1.15 retrieving revision 1.16 diff -u -r1.15 -r1.16 --- HttpUnitOptions.java 2002/01/10 15:42:00 1.15 +++ HttpUnitOptions.java 2002/01/24 17:59:45 1.16 @@ -42,6 +42,7 @@ _loggingHttpHeaders = false; _matchesIgnoreCase = true; _autoRefresh = false; + _autoRedirect = true; _redirectDelay = 0; _characterSet = HttpUnitUtils.DEFAULT_CHARACTER_SET; _contentType = DEFAULT_CONTENT_TYPE; @@ -220,6 +221,24 @@ /** + * Returns true if HttpUnit should automatically follow page redirect requests (status 3xx). + * By default, this is true. + **/ + public static boolean getAutoRedirect() { + return _autoRedirect; + } + + + /** + * Determines whether HttpUnit should automatically follow page redirect requests (status 3xx). + * By default, this is true in order to simulate normal browser operation. + **/ + public static void setAutoRedirect( boolean autoRedirect ) { + _autoRedirect = autoRedirect; + } + + + /** * Returns the delay, in milliseconds, before a redirect request is issues. **/ public static int getRedirectDelay() { @@ -298,6 +317,8 @@ private static boolean _matchesIgnoreCase = true; private static boolean _autoRefresh; + + private static boolean _autoRedirect; private static boolean _postIncludesCharset = false; Index: WebClient.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebClient.java,v retrieving revision 1.14 retrieving revision 1.15 diff -u -r1.14 -r1.15 --- WebClient.java 2002/01/17 19:36:27 1.14 +++ WebClient.java 2002/01/24 17:59:45 1.15 @@ -210,7 +210,7 @@ validateHeaders( response ); if (HttpUnitOptions.getAutoRefresh() && response.getRefreshRequest() != null) { getResponse( response.getRefreshRequest() ); - } else if (response.getHeaderField( "Location" ) == null) { + } else if (!HttpUnitOptions.getAutoRedirect() || response.getHeaderField( "Location" ) == null) { updateFrames( response ); } else { delay( HttpUnitOptions.getRedirectDelay() ); |
From: Russell G. <rus...@us...> - 2002-01-24 17:59:48
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv2108/doc Modified Files: release_notes.txt Log Message: Permit disable of auto-redirect Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.80 retrieving revision 1.81 diff -u -r1.80 -r1.81 --- release_notes.txt 2002/01/23 18:35:56 1.80 +++ release_notes.txt 2002/01/24 17:59:45 1.81 @@ -11,7 +11,11 @@ Revision History: -23-Jab-2002 +24-Jan-2002 +Additions: + 1. You can now call HttpUnitOptions.setAutoRedirect( false ) to enable explicit testing of redirect requests. + +23-Jan-2002 Problems fixed: 1. Control characters and spaces created by breaking HTML in the middle are now trimmed from link parameters. |
From: Russell G. <rus...@us...> - 2002-01-23 18:36:02
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv25414/src/com/meterware/httpunit Modified Files: WebLink.java Log Message: Trim link parameters Index: WebLink.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebLink.java,v retrieving revision 1.15 retrieving revision 1.16 diff -u -r1.15 -r1.16 --- WebLink.java 2002/01/17 19:38:09 1.15 +++ WebLink.java 2002/01/23 18:35:56 1.16 @@ -251,8 +251,8 @@ String value = ((index < 0) ? null : ((index == param.length() - 1) ? "" - : HttpUnitUtils.decode( param.substring( index + 1 ) ))); - String name = (index < 0) ? param : HttpUnitUtils.decode( param.substring( 0, index ) ); + : HttpUnitUtils.decode( param.substring( index + 1 ) ).trim() )); + String name = (index < 0) ? param.trim() : HttpUnitUtils.decode( param.substring( 0, index ) ).trim(); map.put( name, withNewValue( (String[]) map.get( name ), value ) ); list.add( new LinkParameter( name, value ) ); } |
From: Russell G. <rus...@us...> - 2002-01-23 18:36:01
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv25414/test/com/meterware/httpunit Modified Files: WebLinkTest.java Log Message: Trim link parameters Index: WebLinkTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/WebLinkTest.java,v retrieving revision 1.18 retrieving revision 1.19 diff -u -r1.18 -r1.19 --- WebLinkTest.java 2002/01/17 19:38:09 1.18 +++ WebLinkTest.java 2002/01/23 18:35:56 1.19 @@ -341,7 +341,7 @@ WebConversation wc = new WebConversation(); defineWebPage( "encodedLinks", "<html><head><title>Encode Test</title></head>" + "<body>" + - "<a href='/request?arg0=0&arg1&arg0=2&valueless='>request</a>" + + "<a href='/request?arg0=0\n&arg1&arg0=2&valueless='>request</a>" + "</body></html>" ); WebResponse mapPage = wc.getResponse( getHostPath() + "/encodedLinks.html" ); WebLink link = mapPage.getLinks()[0]; |
From: Russell G. <rus...@us...> - 2002-01-23 18:36:00
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv25414/doc Modified Files: release_notes.txt Log Message: Trim link parameters Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.79 retrieving revision 1.80 diff -u -r1.79 -r1.80 --- release_notes.txt 2002/01/22 15:25:16 1.79 +++ release_notes.txt 2002/01/23 18:35:56 1.80 @@ -11,6 +11,10 @@ Revision History: +23-Jab-2002 +Problems fixed: + 1. Control characters and spaces created by breaking HTML in the middle are now trimmed from link parameters. + 21-Jan-2002 Additions: 1. MessageBodyWebRequest's constructors and inner class are now public, allowing outside code to create new request classes. |
From: Russell G. <rus...@us...> - 2002-01-22 21:38:26
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv26078/src/com/meterware/httpunit Modified Files: MessageBodyWebRequest.java Log Message: Make constructor public Index: MessageBodyWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/MessageBodyWebRequest.java,v retrieving revision 1.6 retrieving revision 1.7 diff -u -r1.6 -r1.7 --- MessageBodyWebRequest.java 2002/01/22 15:24:44 1.6 +++ MessageBodyWebRequest.java 2002/01/22 20:00:37 1.7 @@ -100,7 +100,7 @@ public static class InputStreamMessageBody extends MessageBody { - InputStreamMessageBody( MessageBodyWebRequest request, InputStream source, String contentType ) { + public InputStreamMessageBody( MessageBodyWebRequest request, InputStream source, String contentType ) { super( request ); _source = source; _contentType = contentType; |
From: Russell G. <rus...@us...> - 2002-01-22 15:25:20
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/servletunit In directory usw-pr-cvs1:/tmp/cvs-serv15629/test/com/meterware/servletunit Modified Files: NavigationTest.java Log Message: Added initial support for RequestDispatcher Index: NavigationTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/NavigationTest.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- NavigationTest.java 2001/06/18 20:21:30 1.2 +++ NavigationTest.java 2002/01/22 15:25:16 1.3 @@ -63,13 +63,47 @@ } + public void testForward() throws Exception { + ServletRunner sr = new ServletRunner(); + sr.registerServlet( "target", TargetServlet.class.getName() ); + sr.registerServlet( "origin", FowarderServlet.class.getName() ); + WebClient wc = sr.newClient(); + WebResponse response = wc.getResponse( "http://localhost/origin" ); + assertNotNull( "No response received", response ); + assertEquals( "requested resource", TargetServlet.RESPONSE_TEXT, response.getText() ); + assertEquals( "Returned cookie count", 0, response.getNewCookieNames().length ); + } + + + + static class OriginServlet extends HttpServlet { protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException,IOException { resp.setContentType( "text/plain" ); resp.sendRedirect( "http://localhost/target" ); + } + + } + + + static class FowarderServlet extends HttpServlet { + + protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException,IOException { + getServletContext().getRequestDispatcher( "/target" ).forward( req, resp ); + } + + } + + + static class IncluderServlet extends HttpServlet { + static final String PREFIX = "expecting: "; + + protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException,IOException { + resp.getOutputStream().print( PREFIX ); + getServletContext().getRequestDispatcher( "/target" ).include( req, resp ); } } |
Update of /cvsroot/httpunit/httpunit/src/com/meterware/servletunit In directory usw-pr-cvs1:/tmp/cvs-serv15629/src/com/meterware/servletunit Modified Files: ServletUnitHttpResponse.java ServletUnitServletConfig.java ServletUnitServletContext.java WebApplication.java Added Files: RequestDispatcherImpl.java Log Message: Added initial support for RequestDispatcher ***** Error reading new file[Errno 2] No such file or directory: 'RequestDispatcherImpl.java' Index: ServletUnitHttpResponse.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitHttpResponse.java,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- ServletUnitHttpResponse.java 2001/11/14 14:40:31 1.8 +++ ServletUnitHttpResponse.java 2002/01/22 15:25:16 1.9 @@ -405,6 +405,17 @@ //---------------------------------------------- package methods -------------------------------------------------- + /** + * Clears all headers and content. + */ + void restartResponse() { + _headers = new Hashtable(); + _headersComplete = false; + _outputStream = null; + _servletStream = null; + _status = SC_OK; + _writer = null; + } /** * Returns the content type defined for this response. Index: ServletUnitServletConfig.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitServletConfig.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- ServletUnitServletConfig.java 2001/11/26 14:20:12 1.2 +++ ServletUnitServletConfig.java 2002/01/22 15:25:16 1.3 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2001, Russell Gold +* Copyright (c) 2000-2002, 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 @@ -33,14 +33,10 @@ class ServletUnitServletConfig implements ServletConfig { - ServletUnitServletConfig( Servlet servlet ) { - this( servlet, NO_PARAMS ); - } - - - ServletUnitServletConfig( Servlet servlet, Hashtable initParams ) { + ServletUnitServletConfig( Servlet servlet, WebApplication application, Hashtable initParams ) { _name = servlet.getClass().getName(); _initParameters = initParams; + _context = new ServletUnitServletContext( application ); } @@ -82,11 +78,9 @@ //----------------------------------------------- private members ------------------------------------------------------ - private final static Hashtable NO_PARAMS = new Hashtable(); - private String _name; - private Hashtable _initParameters; + private final Hashtable _initParameters; - private ServletContext _context = new ServletUnitServletContext(); + private final ServletContext _context; } Index: ServletUnitServletContext.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitServletContext.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- ServletUnitServletContext.java 2001/11/26 14:20:12 1.5 +++ ServletUnitServletContext.java 2002/01/22 15:25:16 1.6 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2001, Russell Gold +* Copyright (c) 2000-2002, 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,6 +23,7 @@ import java.io.IOException; import java.net.URL; +import java.net.MalformedURLException; import java.util.Enumeration; import java.util.Hashtable; @@ -38,6 +39,11 @@ **/ class ServletUnitServletContext implements ServletContext { + public ServletUnitServletContext( WebApplication application ) { + _application = application; + } + + /** * Returns a ServletContext object that corresponds to a specified URL on the server. * <p> @@ -48,7 +54,7 @@ * In a security conscious environment, the servlet container may return null for a given URL. **/ public javax.servlet.ServletContext getContext(java.lang.String A) { - throw new RuntimeException( "getContext not implemented" ); + return null; } @@ -132,7 +138,13 @@ * RequestDispatcher. **/ public javax.servlet.RequestDispatcher getRequestDispatcher( String path ) { - return null; // XXX not implemented + try { + return new RequestDispatcherImpl( _application.getServlet( new URL( "http", "localhost", path ) ) ); + } catch (ServletException e) { + return null; + } catch (MalformedURLException e) { + return null; + } } @@ -317,5 +329,7 @@ //------------------------------------------- private members ---------------------------------------------------- private final static Vector EMPTY_VECTOR = new Vector(); - private Hashtable _attributes = new Hashtable(); + + private Hashtable _attributes = new Hashtable(); + private WebApplication _application; } Index: WebApplication.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/WebApplication.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- WebApplication.java 2002/01/01 19:29:08 1.2 +++ WebApplication.java 2002/01/22 15:25:16 1.3 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * - * Copyright (c) 2001, Russell Gold + * Copyright (c) 2001-2002, 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 @@ -98,7 +98,7 @@ if (!Servlet.class.isAssignableFrom( servletClass )) throw new HttpInternalErrorException( url ); Servlet servlet = (Servlet) servletClass.newInstance(); // XXX cache instances - by class? - servlet.init( new ServletUnitServletConfig( servlet, configuration.getInitParams() ) ); + servlet.init( new ServletUnitServletConfig( servlet, this, configuration.getInitParams() ) ); return servlet; } catch (ClassNotFoundException e) { throw new HttpNotFoundException( url, e ); |
From: Russell G. <rus...@us...> - 2002-01-22 15:25:19
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv15629/doc Modified Files: release_notes.txt todo.txt Log Message: Added initial support for RequestDispatcher Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.78 retrieving revision 1.79 diff -u -r1.78 -r1.79 --- release_notes.txt 2002/01/17 19:38:09 1.78 +++ release_notes.txt 2002/01/22 15:25:16 1.79 @@ -11,6 +11,12 @@ Revision History: +21-Jan-2002 +Additions: + 1. MessageBodyWebRequest's constructors and inner class are now public, allowing outside code to create new request classes. + 2. ServletUnit now supports creating a RequestDispatcher from ServletContext to forward to other servlets. + Support for this is rudimentary at present: query parameters on the request dispatcher create are ignored. + 17-Jan-2002 Problems fixed: 1. Link parameters are now sent in the proper order, as long as parameter validation is not turned off. Index: todo.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/todo.txt,v retrieving revision 1.25 retrieving revision 1.26 diff -u -r1.25 -r1.26 --- todo.txt 2002/01/17 19:38:09 1.25 +++ todo.txt 2002/01/22 15:25:16 1.26 @@ -1,5 +1,4 @@ High Priority -o Prevent setParameter calls from working on requests built from links if validation is enabled o Handle frames with the same name as one of their ancestors - fix both removal and lookup Medium priority: |
From: Russell G. <rus...@us...> - 2002-01-22 15:24:47
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv15466/src/com/meterware/httpunit Modified Files: MessageBodyWebRequest.java Log Message: Changed protection to allow extensions Index: MessageBodyWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/MessageBodyWebRequest.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- MessageBodyWebRequest.java 2002/01/14 18:13:45 1.5 +++ MessageBodyWebRequest.java 2002/01/22 15:24:44 1.6 @@ -38,6 +38,30 @@ /** + * Constructs a web request using a specific absolute url string. + **/ + protected MessageBodyWebRequest( String urlString ) { + super( urlString ); + } + + + /** + * Constructs a web request with a specific target. + **/ + protected MessageBodyWebRequest( URL urlBase, String urlString, String target ) { + super( urlBase, urlString, target ); + } + + + /** + * Constructs a web request for a form. + **/ + protected MessageBodyWebRequest( WebForm sourceForm, SubmitButton button, int x, int y ) { + super( sourceForm, button, x, y ); + } + + + /** * Subclasses must override this method to provide a message body for the * request. **/ @@ -68,41 +92,12 @@ } -//----------------------------------- package members ----------------------------------- - - - /** - * Constructs a web request using a specific absolute url string. - **/ - MessageBodyWebRequest( String urlString ) { - super( urlString ); - } - - - /** - * Constructs a web request with a specific target. - **/ - MessageBodyWebRequest( URL urlBase, String urlString, String target ) { - super( urlBase, urlString, target ); - } - - - /** - * Constructs a web request for a form. - **/ - MessageBodyWebRequest( WebForm sourceForm, SubmitButton button, int x, int y ) { - super( sourceForm, button, x, y ); - } - - - - //============================= class InputStreamMessageBody ====================================== /** * A method request message body read directly from an input stream. **/ - static class InputStreamMessageBody extends MessageBody { + public static class InputStreamMessageBody extends MessageBody { InputStreamMessageBody( MessageBodyWebRequest request, InputStream source, String contentType ) { |
From: Russell G. <rus...@us...> - 2002-01-17 19:38:14
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv32318/test/com/meterware/httpunit Modified Files: FileUploadTest.java WebFrameTest.java WebLinkTest.java Log Message: Make WebLink implement ParameterHolder to support validation and parameter ordering Index: FileUploadTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/FileUploadTest.java,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- FileUploadTest.java 2002/01/14 18:13:45 1.10 +++ FileUploadTest.java 2002/01/17 19:38:09 1.11 @@ -106,7 +106,7 @@ try { formSubmit.selectFile( "message", file ); fail( "Should not allow setting of a text parameter to a file value" ); - } catch (IllegalNonFileParameterException e) { + } catch (IllegalRequestParameterException e) { } } @@ -126,7 +126,7 @@ try { formSubmit.selectFile( "message", file ); fail( "Should not allow setting of a file parameter in a form which specifies url-encoding" ); - } catch (MultipartFormRequiredException e) { + } catch (IllegalRequestParameterException e) { } } Index: WebFrameTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/WebFrameTest.java,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- WebFrameTest.java 2001/10/26 14:00:10 1.8 +++ WebFrameTest.java 2002/01/17 19:38:09 1.9 @@ -140,6 +140,36 @@ } + public void testDuplicateFrameNames() throws Exception { + defineWebPage( "Linker", "This is a trivial page with <a href=Target.html>one link</a>" ); + defineWebPage( "Target", "This is another page with <a href=Form.html target=\"_top\">one link</a>" ); + defineWebPage( "Form", "This is a page with a simple form: " + + "<form action=submit><input name=name><input type=submit></form>" + + "<a href=Linker.html target=red>a link</a>"); + defineResource( "Frames.html", + "<HTML><HEAD><TITLE>Initial</TITLE></HEAD>" + + "<FRAMESET cols=\"20%,80%\">" + + " <FRAME src='SubFrames.html'>" + + " <FRAME src=Form.html>" + + "</FRAMESET></HTML>" ); + + defineResource( "SubFrames.html", + "<HTML><HEAD><TITLE>Initial</TITLE></HEAD>" + + "<FRAMESET cols=\"20%,80%\">" + + " <FRAME src=\"Linker.html\">" + + " <FRAME src=Form.html>" + + "</FRAMESET></HTML>" ); + + WebResponse response = _wc.getResponse( getHostPath() + "/Frames.html" ); + WebResponse linker = getFrameWithURL( _wc, "Linker" ); + assertNotNull( "Linker not found", linker ); + + response = _wc.getResponse( linker.getLinks()[0].getRequest() ); + WebResponse target = getFrameWithURL( _wc, "Target" ); + assertTrue( "Second response not the same as source frame contents", response == target ); + } + + public void testUnnamedFrames() throws Exception { defineWebPage( "Linker", "This is a trivial page with <a href=Target.html>one link</a>" ); defineWebPage( "Target", "This is another page with <a href=Form.html target=\"_top\">one link</a>" ); Index: WebLinkTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/WebLinkTest.java,v retrieving revision 1.17 retrieving revision 1.18 diff -u -r1.17 -r1.18 --- WebLinkTest.java 2001/11/27 16:40:47 1.17 +++ WebLinkTest.java 2002/01/17 19:38:09 1.18 @@ -141,6 +141,17 @@ } + public void testLinkImageAsText() throws Exception { + WebConversation wc = new WebConversation(); + defineWebPage( "HasImage", "<a href='somwhere.html' >\r\n<img src='blah.gif' alt='Blah Blah' >\r\n</a>" ); + + WebResponse initialPage = wc.getResponse( getHostPath() + "/HasImage.html" ); + WebLink link = initialPage.getLinks()[0]; + assertEquals( "Link text", "", link.asText() ); + initialPage.getLinkWithImageText("Blah Blah"); + } + + public void testLinkFollowing() throws Exception { WebConversation wc = new WebConversation(); defineWebPage( "Initial", "Go to <a href=\"Next.html\">the next page.</a> <a name=\"bottom\">Bottom</a>" ); @@ -323,6 +334,38 @@ WebRequest wr = link.getRequest(); assertMatchingSet( "Request parameter names", new String[] { "arg1", "valueless" }, toStringArray( wr.getParameterNames() ) ); assertEquals( "Value of arg1", null, wr.getParameter( "arg1" ) ); + } + + + public void testLinkParameterOrder() throws Exception { + WebConversation wc = new WebConversation(); + defineWebPage( "encodedLinks", "<html><head><title>Encode Test</title></head>" + + "<body>" + + "<a href='/request?arg0=0&arg1&arg0=2&valueless='>request</a>" + + "</body></html>" ); + WebResponse mapPage = wc.getResponse( getHostPath() + "/encodedLinks.html" ); + WebLink link = mapPage.getLinks()[0]; + WebRequest wr = link.getRequest(); + assertMatchingSet( "Request parameter names", new String[] { "arg0", "arg1", "valueless" }, toStringArray( wr.getParameterNames() ) ); + assertMatchingSet( "Value of arg0", new String[] { "0", "2" }, wr.getParameterValues( "arg0" ) ); + assertEquals( "Actual query", "arg0=0&arg1&arg0=2&valueless=", wr.getQueryString() ); + } + + + public void testLinkParameterValidation() throws Exception { + WebConversation wc = new WebConversation(); + defineWebPage( "encodedLinks", "<html><head><title>Encode Test</title></head>" + + "<body>" + + "<a href='/request?arg0=0&arg1&arg0=2&valueless='>request</a>" + + "</body></html>" ); + WebResponse mapPage = wc.getResponse( getHostPath() + "/encodedLinks.html" ); + WebLink link = mapPage.getLinks()[0]; + WebRequest wr = link.getRequest(); + wr.setParameter( "arg0", new String[] { "0", "2" } ); + try { + wr.setParameter( "arg0", "3" ); + fail( "Did not prevent change to link parameters" ); + } catch (IllegalRequestParameterException e) {} } |
From: Russell G. <rus...@us...> - 2002-01-17 19:38:13
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv32318/src/com/meterware/httpunit Modified Files: FormControl.java GetMethodWebRequest.java ParameterHolder.java PostMethodWebRequest.java UncheckedParameterHolder.java WebForm.java WebLink.java WebRequest.java WebRequestSource.java Log Message: Make WebLink implement ParameterHolder to support validation and parameter ordering Index: FormControl.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/FormControl.java,v retrieving revision 1.6 retrieving revision 1.7 diff -u -r1.6 -r1.7 --- FormControl.java 2002/01/14 18:13:45 1.6 +++ FormControl.java 2002/01/17 19:38:09 1.7 @@ -39,7 +39,7 @@ final static String[] NO_VALUE = new String[0]; - private final String _name; + private String _name; private final String _valueAttribute; private final boolean _readOnly; private final boolean _disabled; @@ -144,23 +144,23 @@ /** - * Sets this control to the next compatible value from the list, removing it from the list. + * Remove any required values for this control from the list, throwing an exception if they are missing. **/ - void claimValue( List values ) { + void claimRequiredValues( List values ) { } /** * Sets this control to the next compatible value from the list, removing it from the list. **/ - void claimUniqueValue( List values ) { + void claimValue( List values ) { } /** - * Remove any required values for this control from the list, throwing an exception if they are missing. + * Sets this control to the next compatible value from the list, removing it from the list. **/ - void claimRequiredValues( List values ) { + void claimUniqueValue( List values ) { } Index: GetMethodWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/GetMethodWebRequest.java,v retrieving revision 1.12 retrieving revision 1.13 diff -u -r1.12 -r1.13 --- GetMethodWebRequest.java 2002/01/14 18:13:45 1.12 +++ GetMethodWebRequest.java 2002/01/17 19:38:09 1.13 @@ -70,6 +70,14 @@ } + /** + * Constructs a web request for a link. + **/ + GetMethodWebRequest( WebLink sourceLink ) { + super( sourceLink ); + } + + //------------------------------------- protected members --------------------------------------------- Index: ParameterHolder.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/ParameterHolder.java,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- ParameterHolder.java 2002/01/14 18:13:45 1.3 +++ ParameterHolder.java 2002/01/17 19:38:09 1.4 @@ -31,58 +31,83 @@ * * @author <a href="mailto:rus...@ac...">Russell Gold</a> **/ -interface ParameterHolder { +abstract class ParameterHolder { /** - * Specifies the position at which an image button (if any) was clicked. + * Specifies the position at which an image button (if any) was clicked. This default implementation does nothing. **/ - public void selectImageButtonPosition( SubmitButton imageButton, int x, int y ); + void selectImageButtonPosition( SubmitButton imageButton, int x, int y ) {} /** * Iterates through the parameters in this holder, recording them in the supplied parameter processor. **/ - public void recordParameters( ParameterProcessor processor ) throws IOException; + abstract + void recordParameters( ParameterProcessor processor ) throws IOException; /** * Returns an array of all parameter names in this collection. **/ - public String[] getParameterNames(); + abstract + String[] getParameterNames(); /** * Returns the multiple default values of the named parameter. **/ + abstract String[] getParameterValues( String name ); /** * Removes a parameter name from this collection. **/ + abstract void removeParameter( String name ); /** * Sets the value of a parameter in a web request. **/ + abstract void setParameter( String name, String value ); /** * Sets the multiple values of a parameter in a web request. **/ + abstract void setParameter( String name, String[] values ); /** * Sets the multiple values of a file upload parameter in a web request. **/ + abstract void setParameter( String name, UploadFileSpec[] files ); /** - * Returns true if the specified parameter is a file field. + * Returns true if the specified name is that of a file parameter. The default implementation returns false. + */ + boolean isFileParameter( String name ) { + return false; + } + + + /** + * Returns the character set encoding for the request. **/ - boolean isFileParameter( String name ); + String getCharacterSet() { + return HttpUnitUtils.DEFAULT_CHARACTER_SET; + } + + + abstract + boolean isSubmitAsMime(); + + + abstract + void setSubmitAsMime( boolean mimeEncoded ); } Index: PostMethodWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/PostMethodWebRequest.java,v retrieving revision 1.21 retrieving revision 1.22 diff -u -r1.21 -r1.22 --- PostMethodWebRequest.java 2002/01/14 18:13:45 1.21 +++ PostMethodWebRequest.java 2002/01/17 19:38:09 1.22 @@ -66,13 +66,12 @@ /** * Selects whether MIME-encoding will be used for this request. MIME-encoding changes the way the request is sent - * and is required for requests which include file parameters. This method may only be called for a request which - * was not created from a form. + * and is required for requests which include file parameters. This method may only be called for a request + * which was not created from a form. **/ public void setMimeEncoded( boolean mimeEncoded ) { - if (isFormBased()) throw new IllegalStateException( "Encoding is defined by the form from which this request is derived." ); - _mimeEncoded = mimeEncoded; + super.setMimeEncoded( mimeEncoded ); } @@ -89,15 +88,7 @@ */ protected boolean maySelectFile( String parameterName ) { - return !isFormBased() || super.isFileParameter( parameterName ); - } - - - /** - * Returns true if this request is to be MIME-encoded. - **/ - protected boolean isMimeEncoded() { - return isFormBased() ? super.isMimeEncoded() : _mimeEncoded; + return isMimeEncoded() && isFileParameter( parameterName ); } Index: UncheckedParameterHolder.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/UncheckedParameterHolder.java,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- UncheckedParameterHolder.java 2002/01/14 18:13:45 1.3 +++ UncheckedParameterHolder.java 2002/01/17 19:38:09 1.4 @@ -32,13 +32,15 @@ * * @author <a href="mailto:rus...@ac...">Russell Gold</a> **/ -class UncheckedParameterHolder implements ParameterHolder { +class UncheckedParameterHolder extends ParameterHolder { - private Hashtable _parameters = new Hashtable(); private static final String[] NO_VALUES = new String[ 0 ]; private final String _characterSet; + private Hashtable _parameters = new Hashtable(); + private boolean _submitAsMime; + UncheckedParameterHolder() { _characterSet = "iso-8859-1"; } @@ -46,6 +48,7 @@ UncheckedParameterHolder( WebRequestSource source ) { _characterSet = source.getCharacterSet(); + _submitAsMime = source.isSubmitAsMime(); String[] names = source.getParameterNames(); for (int i = 0; i < names.length; i++) { if (!source.isFileParameter( names[i] )) { @@ -58,7 +61,7 @@ /** * Specifies the position at which an image button (if any) was clicked. **/ - public void selectImageButtonPosition( SubmitButton imageButton, int x, int y ) { + void selectImageButtonPosition( SubmitButton imageButton, int x, int y ) { setParameter( imageButton.getName() + ".x", Integer.toString( x ) ); setParameter( imageButton.getName() + ".y", Integer.toString( y ) ); } @@ -67,7 +70,7 @@ /** * Iterates through the parameters in this holder, recording them in the supplied parameter processor. **/ - public void recordParameters( ParameterProcessor processor ) throws IOException { + void recordParameters( ParameterProcessor processor ) throws IOException { Enumeration e = _parameters.keys(); while (e.hasMoreElements()) { @@ -86,18 +89,18 @@ } - public String[] getParameterNames() { + String[] getParameterNames() { return (String[]) _parameters.keySet().toArray( new String[ _parameters.size() ] ); } - public String getParameterValue( String name ) { + String getParameterValue( String name ) { String[] values = getParameterValues( name ); return values.length == 0 ? null : values[0]; } - public String[] getParameterValues( String name ) { + String[] getParameterValues( String name ) { Object result = _parameters.get( name ); if (result instanceof String) return new String[] { (String) result }; if (result instanceof String[]) return (String[]) result; @@ -106,27 +109,37 @@ } - public void removeParameter( String name ) { + void removeParameter( String name ) { _parameters.remove( name ); } - public void setParameter( String name, String value ) { + void setParameter( String name, String value ) { _parameters.put( name, value ); } - public void setParameter( String name, String[] values ) { + void setParameter( String name, String[] values ) { _parameters.put( name, values ); } - public void setParameter( String name, UploadFileSpec[] files ) { + void setParameter( String name, UploadFileSpec[] files ) { _parameters.put( name, files ); } + + boolean isFileParameter( String name ) { + return true; + } + + + boolean isSubmitAsMime() { + return _submitAsMime; + } + - public boolean isFileParameter( String name ) { - return false; + void setSubmitAsMime( boolean mimeEncoded ) { + _submitAsMime = mimeEncoded; } } Index: WebForm.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebForm.java,v retrieving revision 1.42 retrieving revision 1.43 diff -u -r1.42 -r1.43 --- WebForm.java 2002/01/14 18:13:45 1.42 +++ WebForm.java 2002/01/17 19:38:09 1.43 @@ -41,7 +41,7 @@ * defined for the form, the structure of the form (as a DOM), or the text of the form. They * may also create a {@link WebRequest} to simulate the submission of the form. **/ -public class WebForm extends WebRequestSource implements ParameterHolder { +public class WebForm extends WebRequestSource { private static final FormParameter UNKNOWN_PARAMETER = new FormParameter(); @@ -57,7 +57,7 @@ * Returns the action defined for this form. **/ public String getAction() { - return NodeUtils.getNodeAttribute( getNode(), "action" ); + return getDestination(); } @@ -215,12 +215,7 @@ * Returns the displayed options defined for the specified parameter name. **/ public String[] getOptions( String name ) { - ArrayList optionList = new ArrayList(); - FormControl[] controls = getParameter( name ).getControls(); - for (int i = 0; i < controls.length; i++) { - optionList.addAll( Arrays.asList( controls[i].getDisplayedOptions() ) ); - } - return (String[]) optionList.toArray( new String[ optionList.size() ] ); + return getParameter( name ).getOptions(); } @@ -236,38 +231,28 @@ * Returns true if the named parameter accepts multiple values. **/ public boolean isMultiValuedParameter( String name ) { - FormControl[] controls = getParameter( name ).getControls(); - for (int i = 0; i < controls.length; i++) { - if (controls[i].isMultiValued()) return true; - if (!controls[i].isExclusive() && controls.length > 1) return true; - } - return false; - } + return getParameter( name ).isMultiValuedParameter(); + } /** * Returns the number of text parameters in this form with the specified name. **/ public int getNumTextParameters( String name ) { - int result = 0; - FormControl[] controls = getParameter( name ).getControls(); - for (int i = 0; i < controls.length; i++) { - if (controls[i].isTextControl()) result++; - } - return result; + return getParameter( name ).getNumTextParameters(); } - /** * Returns true if the named parameter accepts free-form text. **/ public boolean isTextParameter( String name ) { - FormControl[] controls = getParameter( name ).getControls(); - for (int i = 0; i < controls.length; i++) { - if (controls[i].isTextControl()) return true; - } - return false; + return getParameter( name ).isTextParameter(); + } + + + void setSubmitAsMime( boolean mimeEncoded ) { + throw new IllegalStateException( "May not change the encoding for a validated request created from a form" ); } @@ -292,11 +277,7 @@ * Returns true if the named parameter accepts files for upload. **/ public boolean isFileParameter( String name ) { - FormControl[] controls = getParameter( name ).getControls(); - for (int i = 0; i < controls.length; i++) { - if (controls[i].isFileParameter()) return true; - } - return false; + return getParameter( name ).isFileParameter(); } @@ -313,19 +294,8 @@ * Returns the multiple default values of the named parameter. **/ public String[] getParameterValues( String name ) { - ArrayList valueList = new ArrayList(); - FormControl[] controls = getParameter( name ).getControls(); - for (int i = 0; i < controls.length; i++) { - valueList.addAll( Arrays.asList( controls[i].getValues() ) ); - } - return (String[]) valueList.toArray( new String[ valueList.size() ] ); - } - - - String getRelativeURL() { - String action = getAction(); - if (action.trim().length() == 0) action = getBaseURL().getFile(); - return action; + final FormParameter parameter = getParameter( name ); + return parameter.getValues(); } @@ -399,7 +369,7 @@ * from that page. **/ WebForm( URL baseURL, String parentTarget, Node node, String characterSet ) { - super( node, baseURL, parentTarget ); + super( node, baseURL, NodeUtils.getNodeAttribute( node, "action" ), parentTarget ); _characterSet = characterSet; } @@ -524,12 +494,22 @@ } - FormControl[] getControls() { + private FormControl[] getControls() { if (_controls == null) _controls = (FormControl[]) _controlList.toArray( new FormControl[ _controlList.size() ] ); return _controls; } + String[] getValues() { + ArrayList valueList = new ArrayList(); + FormControl[] controls = getControls(); + for (int i = 0; i < controls.length; i++) { + valueList.addAll( Arrays.asList( controls[i].getValues() ) ); + } + return (String[]) valueList.toArray( new String[ valueList.size() ] ); + } + + void setValues( String[] values ) { ArrayList list = new ArrayList( values.length ); list.addAll( Arrays.asList( values ) ); @@ -548,12 +528,60 @@ } + String[] getOptions() { + ArrayList optionList = new ArrayList(); + FormControl[] controls = getControls(); + for (int i = 0; i < controls.length; i++) { + optionList.addAll( Arrays.asList( controls[i].getDisplayedOptions() ) ); + } + return (String[]) optionList.toArray( new String[ optionList.size() ] ); + } + + String[] getOptionValues() { ArrayList valueList = new ArrayList(); for (int i = 0; i < getControls().length; i++) { valueList.addAll( Arrays.asList( getControls()[i].getOptionValues() ) ); } return (String[]) valueList.toArray( new String[ valueList.size() ] ); + } + + + boolean isMultiValuedParameter() { + FormControl[] controls = getControls(); + for (int i = 0; i < controls.length; i++) { + if (controls[i].isMultiValued()) return true; + if (!controls[i].isExclusive() && controls.length > 1) return true; + } + return false; + } + + + int getNumTextParameters() { + int result = 0; + FormControl[] controls = getControls(); + for (int i = 0; i < controls.length; i++) { + if (controls[i].isTextControl()) result++; + } + return result; + } + + + boolean isTextParameter() { + FormControl[] controls = getControls(); + for (int i = 0; i < controls.length; i++) { + if (controls[i].isTextControl()) return true; + } + return false; + } + + + boolean isFileParameter() { + FormControl[] controls = getControls(); + for (int i = 0; i < controls.length; i++) { + if (controls[i].isFileParameter()) return true; + } + return false; } Index: WebLink.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebLink.java,v retrieving revision 1.14 retrieving revision 1.15 diff -u -r1.14 -r1.15 --- WebLink.java 2002/01/09 23:22:10 1.14 +++ WebLink.java 2002/01/17 19:38:09 1.15 @@ -26,6 +26,9 @@ import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; +import java.util.List; +import java.util.Arrays; +import java.io.IOException; import org.w3c.dom.Node; @@ -74,10 +77,7 @@ * Creates and returns a web request which will simulate clicking on this link. **/ public WebRequest getRequest() { - WebRequest request = new GetMethodWebRequest( getBaseURL(), getRelativeURL(), getTarget() ); - addPresetParameters( request ); - request.setHeaderField( "Referer", getBaseURL().toExternalForm() ); - return request; + return new GetMethodWebRequest( this ); } @@ -85,7 +85,7 @@ * Returns an array containing the names of any parameters defined as part of this link's URL. **/ public String[] getParameterNames() { - ArrayList parameterNames = new ArrayList( getPresetParameters().keySet() ); + ArrayList parameterNames = new ArrayList( getPresetParameterMap().keySet() ); return (String[]) parameterNames.toArray( new String[ parameterNames.size() ] ); } @@ -94,33 +94,109 @@ * Returns the multiple default values of the named parameter. **/ public String[] getParameterValues( String name ) { - final String[] values = (String[]) getPresetParameters().get( name ); + final String[] values = (String[]) getPresetParameterMap().get( name ); return values == null ? NO_VALUES : values; } +//--------------------------------- ParameterHolder methods -------------------------------------- + + /** - * Returns the HREF URL w/o its parameters. + * Specifies the position at which an image button (if any) was clicked. **/ - String getRelativeURL() { - final String url = getURLString(); - final int questionMarkIndex = url.indexOf("?"); - if (questionMarkIndex >= 1 && questionMarkIndex < url.length() - 1) { - return url.substring(0, questionMarkIndex); + void selectImageButtonPosition( SubmitButton imageButton, int x, int y ) { + throw new IllegalLinkParametersRequest(); + } + + + /** + * Iterates through the parameters in this holder, recording them in the supplied parameter processor. + **/ + void recordParameters( ParameterProcessor processor ) throws IOException { + Iterator i = getPresetParameterList().iterator(); + while (i.hasNext()) { + LinkParameter o = (LinkParameter) i.next(); + processor.addParameter( o.getName(), o.getValue(), getCharacterSet() ); + } + } + + + /** + * Removes a parameter name from this collection. + **/ + void removeParameter( String name ) { + throw new IllegalLinkParametersRequest(); + } + + + /** + * Sets the value of a parameter in a web request. + **/ + void setParameter( String name, String value ) { + setParameter( name, new String[] { value } ); + } + + + /** + * Sets the multiple values of a parameter in a web request. + **/ + void setParameter( String name, String[] values ) { + if (values == null) { + throw new IllegalArgumentException( "May not supply a null argument array to setParameter()" ); + } else if (!getPresetParameterMap().containsKey( name )) { + throw new IllegalLinkParametersRequest(); + } else if (!equals( getParameterValues( name ), values )) { + throw new IllegalLinkParametersRequest(); } - return url; } -//--------------------------------------------------- package members -------------------------------------------------- + private boolean equals( String[] left, String[] right ) { + if (left.length != right.length) return false; + List rightValues = Arrays.asList( right ); + for (int i = 0; i < left.length; i++) { + if (!rightValues.contains( left[i] )) return false; + } + return true; + } /** + * Sets the multiple values of a file upload parameter in a web request. + **/ + void setParameter( String name, UploadFileSpec[] files ) { + throw new IllegalLinkParametersRequest(); + } + + + /** + * Returns true if the specified parameter is a file field. + **/ + boolean isFileParameter( String name ) { + return false; + } + + + boolean isSubmitAsMime() { + return false; + } + + + void setSubmitAsMime( boolean mimeEncoded ) { + throw new IllegalStateException( "May not change the encoding for a validated request created from a link" ); + } + + + //--------------------------------------------------- package members -------------------------------------------------- + + + /** * Contructs a web link given the URL of its source page and the DOM extracted * from that page. **/ WebLink( URL baseURL, String parentTarget, Node node ) { - super( node, baseURL, parentTarget ); + super( node, baseURL, NodeUtils.getNodeAttribute( node, "href" ), parentTarget ); } @@ -130,19 +206,10 @@ private static final String[] NO_VALUES = new String[0]; private static final String PARAM_DELIM = "&"; - private Map _presetParameters; + private Map _presetParameterMap; + private ArrayList _presetParameterList; - private void addPresetParameters(WebRequest request) { - Map params = getPresetParameters(); - Iterator i = params.keySet().iterator(); - while (i.hasNext()) { - String key = (String) i.next(); - request.setParameter( key, (String[]) params.get( key ) ); - } - } - - /** * Gets all parameters from a URL **/ @@ -156,30 +223,38 @@ } - /** - * Builds list of parameters - **/ - private Map getPresetParameters() { - if (_presetParameters == null) { - _presetParameters = new HashMap(); - StringTokenizer st = new StringTokenizer( getParametersString(), PARAM_DELIM ); - while (st.hasMoreTokens()) stripOneParameter( _presetParameters, st.nextToken() ); - } - return _presetParameters; + private Map getPresetParameterMap() { + if (_presetParameterMap == null) loadPresetParameters(); + return _presetParameterMap; + } + + + private ArrayList getPresetParameterList() { + if (_presetParameterList == null) loadPresetParameters(); + return _presetParameterList; + } + + + private void loadPresetParameters() { + _presetParameterMap = new HashMap(); + _presetParameterList = new ArrayList(); + StringTokenizer st = new StringTokenizer( getParametersString(), PARAM_DELIM ); + while (st.hasMoreTokens()) stripOneParameter( _presetParameterList, _presetParameterMap, st.nextToken() ); } /** * add a pair key-value to the hashtable, creates an array of values if param already exists. **/ - private void stripOneParameter( Map params, String param ) { + private void stripOneParameter( ArrayList list, Map map, String param ) { final int index = param.indexOf( "=" ); String value = ((index < 0) ? null : ((index == param.length() - 1) ? "" : HttpUnitUtils.decode( param.substring( index + 1 ) ))); - String key = (index < 0) ? param : HttpUnitUtils.decode( param.substring( 0, index ) ); - params.put( key, withNewValue( (String[]) params.get( key ), value ) ); + String name = (index < 0) ? param : HttpUnitUtils.decode( param.substring( 0, index ) ); + map.put( name, withNewValue( (String[]) map.get( name ), value ) ); + list.add( new LinkParameter( name, value ) ); } @@ -197,6 +272,40 @@ } return result; } + +} + + +class LinkParameter { + private String _name; + private String _value; + + + public LinkParameter( String name, String value ) { + _name = name; + _value = value; + } + + + public String getName() { + return _name; + } + + + public String getValue() { + return _value; + } +} + + +class IllegalLinkParametersRequest extends IllegalRequestParameterException { + + public IllegalLinkParametersRequest() { + } + + public String getMessage() { + return "May not modify parameters for a request derived from a link with parameter checking enabled."; + } } Index: WebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebRequest.java,v retrieving revision 1.36 retrieving revision 1.37 diff -u -r1.36 -r1.37 --- WebRequest.java 2002/01/14 18:13:45 1.36 +++ WebRequest.java 2002/01/17 19:38:09 1.37 @@ -249,17 +249,20 @@ * Constructs a web request from a form. **/ protected WebRequest( WebForm sourceForm, SubmitButton button, int x, int y ) { - this( sourceForm.getBaseURL(), sourceForm.getRelativeURL(), sourceForm.getTarget(), newParameterHolder( sourceForm ) ); - _sourceForm = sourceForm; + this( sourceForm ); if (button != null && button.isImageButton() && button.getName().length() > 0) { _parameterHolder.selectImageButtonPosition( button, x, y ); } + } + - setHeaderField( "Referer", sourceForm.getBaseURL().toExternalForm() ); + protected WebRequest( WebRequestSource requestSource ) { + this( requestSource.getBaseURL(), requestSource.getRelativeURL(), requestSource.getTarget(), newParameterHolder( requestSource ) ); + setHeaderField( "Referer", requestSource.getBaseURL().toExternalForm() ); } - private static ParameterHolder newParameterHolder( WebForm requestSource ) { + private static ParameterHolder newParameterHolder( WebRequestSource requestSource ) { if (HttpUnitOptions.getParameterValuesValidated()) { return requestSource; } else { @@ -280,15 +283,6 @@ /** - * Returns true if this request is based on a web form. - **/ - final - protected boolean isFormBased() { - return _sourceForm != null; - } - - - /** * Returns true if selectFile may be called with this parameter. */ protected boolean maySelectFile( String parameterName ) @@ -298,10 +292,21 @@ /** + * Selects whether MIME-encoding will be used for this request. MIME-encoding changes the way the request is sent + * and is required for requests which include file parameters. This method may only be called for a POST request + * which was not created from a form. + **/ + protected void setMimeEncoded( boolean mimeEncoded ) + { + _parameterHolder.setSubmitAsMime( mimeEncoded ); + } + + + /** * Returns true if this request is to be MIME-encoded. **/ protected boolean isMimeEncoded() { - return _sourceForm != null && _sourceForm.isSubmitAsMime(); + return _parameterHolder.isSubmitAsMime(); } @@ -318,11 +323,7 @@ **/ final protected String getCharacterSet() { - if (_sourceForm == null) { - return HttpUnitUtils.DEFAULT_CHARACTER_SET; - } else { - return _sourceForm.getCharacterSet(); - } + return _parameterHolder.getCharacterSet(); } @@ -393,7 +394,6 @@ private URL _urlBase; private String _urlString; - private WebForm _sourceForm; private String _target = TOP_FRAME; private Hashtable _headers; Index: WebRequestSource.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebRequestSource.java,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- WebRequestSource.java 2002/01/10 15:42:00 1.4 +++ WebRequestSource.java 2002/01/17 19:38:09 1.5 @@ -26,7 +26,7 @@ abstract -public class WebRequestSource { +public class WebRequestSource extends ParameterHolder { /** * Returns the ID associated with this request source. @@ -87,25 +87,32 @@ /** - * Returns the character set encoding for the request. - **/ - String getCharacterSet() { - return HttpUnitUtils.DEFAULT_CHARACTER_SET; + * Returns the URL relative to the current page which will handle the request. + */ + String getRelativeURL() { + final String url = getDestinationPage(); + final int questionMarkIndex = url.indexOf("?"); + if (questionMarkIndex >= 1 && questionMarkIndex < url.length() - 1) { + return url.substring(0, questionMarkIndex); + } + return url; } - /** - * Returns the URL relative to the current page which will handle the request. - */ - abstract - String getRelativeURL(); + private String getDestinationPage() { + String result = trimFragment( getDestination() ); + if (result.trim().length() == 0) result = getBaseURL().getFile(); + return result; + } - /** - * Returns true if the specified name is that of a file parameter. The default implementation returns false. - */ - boolean isFileParameter( String name ) { - return false; + private String trimFragment( String href ) { + final int hashIndex = href.indexOf( '#' ); + if (hashIndex < 0) { + return href; + } else { + return href.substring( 0, hashIndex ); + } } @@ -115,10 +122,11 @@ * Contructs a web form given the URL of its source page and the DOM extracted * from that page. **/ - WebRequestSource( Node node, URL baseURL, String parentTarget ) { + WebRequestSource( Node node, URL baseURL, String destination, String parentTarget ) { if (node == null) throw new IllegalArgumentException( "node must not be null" ); _node = node; _baseURL = baseURL; + _destination = destination; _parentTarget = parentTarget; } @@ -128,6 +136,11 @@ } + protected String getDestination() { + return _destination; + } + + /** * Returns the actual DOM for this request source, not a copy. **/ @@ -143,6 +156,9 @@ /** The URL of the page containing this entity. **/ private URL _baseURL; + + /** The raw destination specified for the request, including anchors and parameters. **/ + private String _destination; /** The DOM node representing this entity. **/ private Node _node; |
From: Russell G. <rus...@us...> - 2002-01-17 19:38:12
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv32318/doc Modified Files: release_notes.txt todo.txt Log Message: Make WebLink implement ParameterHolder to support validation and parameter ordering Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.77 retrieving revision 1.78 diff -u -r1.77 -r1.78 --- release_notes.txt 2002/01/14 18:13:45 1.77 +++ release_notes.txt 2002/01/17 19:38:09 1.78 @@ -4,7 +4,6 @@ 1. The "_parent" and "_empty" frame targets are not handled correctly 2. The "accept-charset" attribute for forms is ignored; the page content character set is used to encode any response. This behavior matches that currently used by IE and Navigator. - 3. No parameter validation is done for requests built from links Limitations: 1. HttpUnit does not support JavaScript @@ -12,11 +11,24 @@ Revision History: +17-Jan-2002 +Problems fixed: + 1. Link parameters are now sent in the proper order, as long as parameter validation is not turned off. + 2. Parameter validation is now done for requests built from links + +15-Jan-2002 +Acknowledgements: + Thanks to Stefan G. Renz for identifying the infinite loop bug in frame handling + +Problems fixed: + 1. An infinite loop would result if a frame had the same name as one of its sub-frames + 14-Jan-2002 Problems fixed: 1. Parameters are now submitted in the order specified in the form, as long as parameter validation is not turned off. 2. It is no longer permitted to change hidden parameters with parameter validation enabled. + 3. An infinite loop would result if a frame had the same name as one of its sub-frames Additions: 1. HttpUnit now handles multiple file form controls with the same name. Index: todo.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/todo.txt,v retrieving revision 1.24 retrieving revision 1.25 diff -u -r1.24 -r1.25 --- todo.txt 2002/01/14 18:13:45 1.24 +++ todo.txt 2002/01/17 19:38:09 1.25 @@ -1,5 +1,6 @@ High Priority o Prevent setParameter calls from working on requests built from links if validation is enabled +o Handle frames with the same name as one of their ancestors - fix both removal and lookup Medium priority: o Support optional tags which hide their contents (as in IFRAME, OBJECT, etc.) |
From: Russell G. <rus...@us...> - 2002-01-17 19:36:30
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv31953/src/com/meterware/httpunit Modified Files: WebClient.java Log Message: Avoid infinite loop when subframe has same name as parent Index: WebClient.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebClient.java,v retrieving revision 1.13 retrieving revision 1.14 diff -u -r1.13 -r1.14 --- WebClient.java 2001/11/27 19:51:27 1.13 +++ WebClient.java 2002/01/17 19:36:27 1.14 @@ -303,7 +303,7 @@ String[] names = (String[]) _subFrames.get( targetName ); if (names == null) return; for (int i = 0; i < names.length; i++) { - removeSubFrames( names[i] ); + if (!targetName.equals( names[i] )) removeSubFrames( names[i] ); _frameContents.remove( names[i] ); _subFrames.remove( names[i] ); } |
From: Russell G. <rus...@us...> - 2002-01-14 18:13:50
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv25860/src/com/meterware/httpunit Modified Files: FormControl.java GetMethodWebRequest.java MessageBodyWebRequest.java MimeEncodedMessageBody.java ParameterHolder.java ParameterProcessor.java PostMethodWebRequest.java SubmitButton.java UncheckedParameterHolder.java WebForm.java WebRequest.java Added Files: UploadFileSpec.java Log Message: Parameter values now stored in WebForm ***** Error reading new file[Errno 2] No such file or directory: 'UploadFileSpec.java' Index: FormControl.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/FormControl.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- FormControl.java 2002/01/10 22:18:58 1.5 +++ FormControl.java 2002/01/14 18:13:45 1.6 @@ -27,6 +27,9 @@ import java.util.Hashtable; import java.util.Vector; import java.util.ArrayList; +import java.util.List; +import java.util.Arrays; +import java.io.IOException; /** @@ -137,11 +140,38 @@ } - void updateRequiredValues( Hashtable required ) { + abstract void addValues( ParameterProcessor processor, String characterSet ) throws IOException; + + + /** + * Sets this control to the next compatible value from the list, removing it from the list. + **/ + void claimValue( List values ) { } /** + * Sets this control to the next compatible value from the list, removing it from the list. + **/ + void claimUniqueValue( List values ) { + } + + + /** + * Remove any required values for this control from the list, throwing an exception if they are missing. + **/ + void claimRequiredValues( List values ) { + } + + + /** + * Specifies a file to be uploaded via this control. + **/ + void claimUploadSpecification( List files ) { + } + + + /** * Returns the default value of this control in the form. If no value is specified, defaults to the empty string. **/ protected String getValueAttribute() { @@ -149,6 +179,15 @@ } + /** + * Removes the specified required value from the list of values, throwing an exception if it is missing. + **/ + final protected void claimValueIsRequired( List values, final String value ) { + if (!values.contains( value )) throw new MissingParameterValueException( getName(), value, (String[]) values.toArray( new String[ values.size() ]) ); + values.remove( value ); + } + + static FormControl newFormParameter( WebForm form, Node node ) { if (node.getNodeType() != Node.ELEMENT_NODE) { return null; @@ -167,8 +206,10 @@ return null; } else { final String type = NodeUtils.getNodeAttribute( node, "type", "text" ); - if (type.equalsIgnoreCase( "text" ) || type.equalsIgnoreCase( "hidden" ) || type.equalsIgnoreCase( "password" )) { + if (type.equalsIgnoreCase( "text" ) || type.equalsIgnoreCase( "password" )) { return new TextFieldFormControl( node ); + } else if (type.equalsIgnoreCase( "hidden" )) { + return new HiddenFieldFormControl( node ); } else if (type.equalsIgnoreCase( "radio" )) { return new RadioButtonFormControl( node ); } else if (type.equalsIgnoreCase( "checkbox" )) { @@ -207,6 +248,11 @@ } + public void setChecked( boolean checked ) { + _isChecked = checked; + } + + /** * Returns the current value(s) associated with this control. These values will be transmitted to the server * if the control is 'successful'. @@ -224,6 +270,24 @@ } + void addValues( ParameterProcessor processor, String characterSet ) throws IOException { + if (isChecked()) processor.addParameter( getName(), getQueryValue(), characterSet ); + } + + + /** + * Remove any required values for this control from the list, throwing an exception if they are missing. + **/ + void claimRequiredValues( List values ) { + if (isValueRequired()) claimValueIsRequired( values, getQueryValue() ); + } + + + protected boolean isValueRequired() { + return isReadOnly() && isChecked(); + } + + abstract String getQueryValue(); @@ -253,26 +317,106 @@ String getQueryValue() { return getValueAttribute(); } +} + + +class RadioGroupFormControl extends FormControl { + private List _buttonList = new ArrayList(); + private RadioButtonFormControl[] _buttons; + private String[] _allowedValues; - void updateRequiredValues( Hashtable required ) { - if (isReadOnly() && isChecked()) { - required.put( getName(), getQueryValue() ); + + public RadioGroupFormControl() { + } + + void addRadioButton( RadioButtonFormControl control ) { + _buttonList.add( control ); + _buttons = null; + _allowedValues = null; + } + + + public String[] getValues() { + for (int i = 0; i < getButtons().length; i++) { + if (getButtons()[i].isChecked()) return getButtons()[i].getValues(); + } + return NO_VALUE; + } + + + /** + * Returns the option values defined for this radio button group. + **/ + public String[] getOptionValues() { + ArrayList valueList = new ArrayList(); + FormControl[] buttons = getButtons(); + for (int i = 0; i < buttons.length; i++) { + valueList.addAll( Arrays.asList( buttons[i].getOptionValues() ) ); + } + return (String[]) valueList.toArray( new String[ valueList.size() ] ); + } + + + void addValues( ParameterProcessor processor, String characterSet ) throws IOException { + for (int i = 0; i < getButtons().length; i++) getButtons()[i].addValues( processor, characterSet ); + } + + + /** + * Remove any required values for this control from the list, throwing an exception if they are missing. + **/ + void claimRequiredValues( List values ) { + for (int i = 0; i < getButtons().length; i++) { + getButtons()[i].claimRequiredValues( values ); + } + } + + + void claimUniqueValue( List values ) { + int matchingButtonIndex = -1; + for (int i = 0; i < getButtons().length && matchingButtonIndex < 0; i++) { + if (!getButtons()[i].isReadOnly() && values.contains( getButtons()[i].getQueryValue() )) matchingButtonIndex = i; + } + if (matchingButtonIndex <0) throw new IllegalParameterValueException( getButtons()[0].getName(), (String) values.get(0), getAllowedValues() ); + + for (int i = 0; i < getButtons().length; i++) { + if (!getButtons()[i].isReadOnly()) getButtons()[i].setChecked( i == matchingButtonIndex ); } + values.remove( getButtons()[ matchingButtonIndex ].getQueryValue() ); } + + + private String[] getAllowedValues() { + if (_allowedValues == null) { + _allowedValues = new String[ getButtons().length ]; + for (int i = 0; i < _allowedValues.length; i++) { + _allowedValues[i] = getButtons()[i].getQueryValue(); + } + } + return _allowedValues; + } + + + private RadioButtonFormControl[] getButtons() { + if (_buttons == null) _buttons = (RadioButtonFormControl[]) _buttonList.toArray( new RadioButtonFormControl[ _buttonList.size() ] ); + return _buttons; + } } class CheckboxFormControl extends BooleanFormControl { + + public CheckboxFormControl( Node node ) { super( node ); } - void updateRequiredValues( Hashtable required ) { - if (isReadOnly() && isChecked()) { - addValue( required, getName(), getQueryValue() ); - } + void claimUniqueValue( List values ) { + if (isValueRequired()) return; + setChecked( values.contains( getQueryValue() ) ); + if (isChecked()) values.remove( getQueryValue() ); } @@ -333,10 +477,31 @@ return true; } + + void addValues( ParameterProcessor processor, String characterSet ) throws IOException { + if (getName().length() > 0) processor.addParameter( getName(), getValues()[0], characterSet ); + } + - void updateRequiredValues( Hashtable required ) { - if (isReadOnly()) required.put( getName(), _defaultValue ); + void claimValue( List values ) { + if (isReadOnly()) return; + if (values.isEmpty()) { + _value[0] = ""; + } else { + _value[0] = (String) values.get(0); + values.remove(0); + } } + + + void claimRequiredValues( List values ) { + if (isReadOnly()) claimValueIsRequired( values ); + } + + + protected void claimValueIsRequired( List values ) { + claimValueIsRequired( values, _defaultValue[0] ); + } } @@ -348,6 +513,23 @@ } +class HiddenFieldFormControl extends TextFieldFormControl { + public HiddenFieldFormControl( Node node ) { + super( node ); + } + + + void claimRequiredValues( List values ) { + claimValueIsRequired( values ); + } + + + void claimValue( List values ) { + } + +} + + class TextAreaFormControl extends TextFormControl { public TextAreaFormControl( Node node ) { @@ -368,6 +550,9 @@ class FileSubmitFormControl extends FormControl { + private UploadFileSpec _fileToUpload; + + public FileSubmitFormControl( Node node ) { super( node ); } @@ -384,6 +569,26 @@ public String[] getValues() { return null; // XXX what should this really do? } + + + /** + * Specifies a number of file upload specifications for this control. + **/ + void claimUploadSpecification( List files ) { + if (files.isEmpty()) { + _fileToUpload = null; + } else { + _fileToUpload = (UploadFileSpec) files.get(0); + files.remove(0); + } + } + + + void addValues( ParameterProcessor processor, String characterSet ) throws IOException { + if (!isDisabled() && _fileToUpload != null) { + processor.addFile( getName(), _fileToUpload ); + } + } } @@ -434,6 +639,40 @@ } + void addValues( ParameterProcessor processor, String characterSet ) throws IOException { + for (int i = 0; i < getValues().length; i++) { + processor.addParameter( getName(), getValues()[i], characterSet ); + } + } + + + void claimUniqueValue( List values ) { + boolean[] matches = new boolean[ _optionValues.length ]; + int numMatches = 0; + for (int i = 0; i < matches.length; i++) { + matches[i] = values.contains( _optionValues[i] ); + if (matches[i]) { + numMatches++; + if (!_multiSelect) break; + } + } + + if (!_multiSelect) { + if (numMatches == 0) throw new IllegalParameterValueException( getName(), (String) values.get(0), getOptionValues() ); + + } + + ArrayList newValues = new ArrayList( matches.length ); + for (int i = 0; i < matches.length; i++) { + if (matches[i]) { + values.remove( _optionValues[i] ); + newValues.add( _optionValues[i] ); + } + } + _values = (String[]) newValues.toArray( new String[ values.size() ] ); + } + + private String[] getInitialValues( Node selectionNode, String[] optionValues ) { ArrayList selected = new ArrayList(); NodeList nl = ((Element) selectionNode).getElementsByTagName( "option" ); @@ -491,6 +730,73 @@ return (value == null) ? "" : value; } +} +//============================= exception class IllegalParameterValueException ====================================== + + +/** + * This exception is thrown on an attempt to set a parameter to a value not permitted to it by the form. + **/ +class IllegalParameterValueException extends IllegalRequestParameterException { + + + IllegalParameterValueException( String parameterName, String badValue, String[] allowed ) { + _parameterName = parameterName; + _badValue = badValue; + _allowedValues = allowed; + } + + + public String getMessage() { + StringBuffer sb = new StringBuffer(HttpUnitUtils.DEFAULT_TEXT_BUFFER_SIZE); + sb.append( "May not set parameter '" ).append( _parameterName ).append( "' to '" ); + sb.append( _badValue ).append( "'. Value must be one of: { " ); + for (int i = 0; i < _allowedValues.length; i++) { + if (i != 0) sb.append( ", " ); + sb.append( _allowedValues[i] ); + } + sb.append( " }" ); + return sb.toString(); + } + + + private String _parameterName; + private String _badValue; + private String[] _allowedValues; +} + +//============================= exception class MissingParameterValueException ====================================== + + +/** + * This exception is thrown on an attempt to remove a required value from a form parameter. + **/ +class MissingParameterValueException extends IllegalRequestParameterException { + + + MissingParameterValueException( String parameterName, String missingValue, String[] proposed ) { + _parameterName = parameterName; + _missingValue = missingValue; + _proposedValues = proposed; + } + + + public String getMessage() { + StringBuffer sb = new StringBuffer(HttpUnitUtils.DEFAULT_TEXT_BUFFER_SIZE); + sb.append( "Parameter '" ).append( _parameterName ).append( "' must have the value '" ); + sb.append( _missingValue ).append( "'. Attempted to set it to: { " ); + for (int i = 0; i < _proposedValues.length; i++) { + if (i != 0) sb.append( ", " ); + sb.append( _proposedValues[i] ); + } + sb.append( " }" ); + return sb.toString(); + } + + + private String _parameterName; + private String _missingValue; + private String[] _proposedValues; } Index: GetMethodWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/GetMethodWebRequest.java,v retrieving revision 1.11 retrieving revision 1.12 diff -u -r1.11 -r1.12 --- GetMethodWebRequest.java 2002/01/10 15:42:00 1.11 +++ GetMethodWebRequest.java 2002/01/14 18:13:45 1.12 @@ -4,12 +4,12 @@ * * Copyright (c) 2000-2002, 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 +* 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 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * -* The above copyright notice and this permission notice shall be included in all copies or substantial portions +* The above copyright notice and this permission notice shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO @@ -26,7 +26,7 @@ **/ public class GetMethodWebRequest extends WebRequest { - + /** * Constructs a web request using a specific absolute url string. **/ @@ -65,8 +65,8 @@ /** * Constructs a web request for a form. **/ - GetMethodWebRequest( WebForm sourceForm, SubmitButton button ) { - super( sourceForm, button ); + GetMethodWebRequest( WebForm sourceForm, SubmitButton button, int x, int y ) { + super( sourceForm, button, x, y ); } Index: MessageBodyWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/MessageBodyWebRequest.java,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- MessageBodyWebRequest.java 2002/01/09 23:22:10 1.4 +++ MessageBodyWebRequest.java 2002/01/14 18:13:45 1.5 @@ -90,8 +90,8 @@ /** * Constructs a web request for a form. **/ - MessageBodyWebRequest( WebForm sourceForm, SubmitButton button ) { - super( sourceForm, button ); + MessageBodyWebRequest( WebForm sourceForm, SubmitButton button, int x, int y ) { + super( sourceForm, button, x, y ); } Index: MimeEncodedMessageBody.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/MimeEncodedMessageBody.java,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- MimeEncodedMessageBody.java 2001/11/27 19:51:27 1.10 +++ MimeEncodedMessageBody.java 2002/01/14 18:13:45 1.11 @@ -58,39 +58,9 @@ * Transmits the body of this request as a sequence of bytes. **/ void writeTo( OutputStream outputStream ) throws IOException { - for (Enumeration e = getRequest().getParameterNames(); e.hasMoreElements();) { - String name = (String) e.nextElement(); - String[] values = getRequest().getParameterValues( name ); - for (int i = 0; i < values.length; i++) { - writeLn( outputStream, "--" + BOUNDARY ); - writeLn( outputStream, "Content-Disposition: form-data; name=\"" + name + '"' ); // XXX need to handle non-ascii names here - writeLn( outputStream, "Content-Type: text/plain; charset=" + getRequest().getCharacterSet() ); - writeLn( outputStream, "" ); - writeLn( outputStream, values[ i ], getRequest().getCharacterSet() ); - } - } - - Dictionary files = getPostRequest().getSelectedFiles(); - byte[] buffer = new byte[ 8 * 1024 ]; - for (Enumeration e = files.keys(); e.hasMoreElements();) { - String name = (String) e.nextElement(); - WebRequest.UploadFileSpec spec = (WebRequest.UploadFileSpec) files.get( name ); - writeLn( outputStream, "--" + BOUNDARY ); - writeLn( outputStream, "Content-Disposition: form-data; name=\"" + encode( name ) + "\"; filename=\"" + encode( spec.getFileName() ) + '"' ); // XXX need to handle non-ascii names here - writeLn( outputStream, "Content-Type: " + spec.getContentType() ); - writeLn( outputStream, "" ); - - InputStream in = spec.getInputStream(); - int count = 0; - do { - outputStream.write( buffer, 0, count ); - count = in.read( buffer, 0, buffer.length ); - } while (count != -1); - - in.close(); - writeLn( outputStream, "" ); - } - writeLn( outputStream, "--" + BOUNDARY + "--" ); + MimeEncoding encoding = new MimeEncoding( outputStream ); + getRequest().getParameterHolder().recordParameters( encoding ); + encoding.sendClose(); } @@ -120,6 +90,50 @@ private void writeLn( OutputStream os, String value ) throws IOException { writeLn( os, value, getRequest().getCharacterSet() ); + } + + + class MimeEncoding implements ParameterProcessor { + + public MimeEncoding( OutputStream outputStream ) { + _outputStream = outputStream; + } + + + public void sendClose() throws IOException { + writeLn( _outputStream, "--" + BOUNDARY + "--" ); + } + + + public void addParameter( String name, String value, String characterSet ) throws IOException { + writeLn( _outputStream, "--" + BOUNDARY ); + writeLn( _outputStream, "Content-Disposition: form-data; name=\"" + name + '"' ); // XXX need to handle non-ascii names here + writeLn( _outputStream, "Content-Type: text/plain; charset=" + getRequest().getCharacterSet() ); + writeLn( _outputStream, "" ); + writeLn( _outputStream, value, getRequest().getCharacterSet() ); + } + + + public void addFile( String name, UploadFileSpec spec ) throws IOException { + byte[] buffer = new byte[ 8 * 1024 ]; + + writeLn( _outputStream, "--" + BOUNDARY ); + writeLn( _outputStream, "Content-Disposition: form-data; name=\"" + encode( name ) + "\"; filename=\"" + encode( spec.getFileName() ) + '"' ); // XXX need to handle non-ascii names here + writeLn( _outputStream, "Content-Type: " + spec.getContentType() ); + writeLn( _outputStream, "" ); + + InputStream in = spec.getInputStream(); + int count = 0; + do { + _outputStream.write( buffer, 0, count ); + count = in.read( buffer, 0, buffer.length ); + } while (count != -1); + + in.close(); + writeLn( _outputStream, "" ); + } + + private OutputStream _outputStream; } } Index: ParameterHolder.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/ParameterHolder.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- ParameterHolder.java 2002/01/10 15:42:00 1.2 +++ ParameterHolder.java 2002/01/14 18:13:45 1.3 @@ -21,6 +21,7 @@ *******************************************************************************************************************/ import java.io.File; import java.io.InputStream; +import java.io.IOException; import java.util.Enumeration; @@ -33,15 +34,21 @@ interface ParameterHolder { /** + * Specifies the position at which an image button (if any) was clicked. + **/ + public void selectImageButtonPosition( SubmitButton imageButton, int x, int y ); + + + /** * Iterates through the parameters in this holder, recording them in the supplied parameter processor. **/ - public void recordParameters( ParameterProcessor processor ); + public void recordParameters( ParameterProcessor processor ) throws IOException; /** - * Returns an enumeration of all parameter names in this collection. + * Returns an array of all parameter names in this collection. **/ - Enumeration getParameterNames(); + public String[] getParameterNames(); /** @@ -68,28 +75,14 @@ void setParameter( String name, String[] values ); - /** - * Returns true if the specified parameter is a file field. - **/ - boolean isFileParameter( String name ); - - - /** - * Sets the file for a parameter upload in a web request. - **/ - void selectFile( String parameterName, File file ); - - /** - * Sets the file for a parameter upload in a web request. + * Sets the multiple values of a file upload parameter in a web request. **/ - void selectFile( String parameterName, File file, String contentType ); + void setParameter( String name, UploadFileSpec[] files ); /** - * Sets the file for a parameter upload in a web request. + * Returns true if the specified parameter is a file field. **/ - void selectFile( String parameterName, String fileName, InputStream inputStream, String contentType ); - - + boolean isFileParameter( String name ); } Index: ParameterProcessor.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/ParameterProcessor.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- ParameterProcessor.java 2002/01/10 15:42:00 1.1 +++ ParameterProcessor.java 2002/01/14 18:13:45 1.2 @@ -1,5 +1,4 @@ package com.meterware.httpunit; - /******************************************************************************************************************** * $Id$ * @@ -20,8 +19,7 @@ * DEALINGS IN THE SOFTWARE. * *******************************************************************************************************************/ - -import java.util.*; +import java.io.IOException; /** @@ -29,5 +27,8 @@ * @author <a href="mailto:rus...@ac...">Russell Gold</a> **/ interface ParameterProcessor { - void addParameter( String name, String value, String characterSet ); + + void addParameter( String name, String value, String characterSet ) throws IOException; + + void addFile( String parameterName, UploadFileSpec fileSpec ) throws IOException; } Index: PostMethodWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/PostMethodWebRequest.java,v retrieving revision 1.20 retrieving revision 1.21 diff -u -r1.20 -r1.21 --- PostMethodWebRequest.java 2002/01/09 23:22:10 1.20 +++ PostMethodWebRequest.java 2002/01/14 18:13:45 1.21 @@ -85,36 +85,6 @@ /** - * Sets the file for a parameter upload in a web request. - **/ - public void selectFile( String parameterName, File file ) { - super.selectFile( parameterName, file ); - - _files.put( parameterName, new UploadFileSpec( file ) ); - } - - - /** - * Sets the file for a parameter upload in a web request. - **/ - public void selectFile( String parameterName, File file, String contentType ) { - super.selectFile( parameterName, file, contentType ); - - _files.put( parameterName, new UploadFileSpec( file, contentType ) ); - } - - - /** - * Sets the file for a parameter upload in a web request. - **/ - public void selectFile( String parameterName, String fileName, InputStream inputStream, String contentType ) { - super.selectFile( parameterName, fileName, inputStream, contentType ); - - _files.put( parameterName, new UploadFileSpec( fileName, inputStream, contentType ) ); - } - - - /** * Returns true if selectFile may be called with this parameter. */ protected boolean maySelectFile( String parameterName ) @@ -148,24 +118,15 @@ /** * Constructs a web request for a form. - **/ - PostMethodWebRequest( WebForm sourceForm, SubmitButton button ) { - super( sourceForm, button ); - } - - - /** - * Returns a mapping of file parameters to upload specs. **/ - Dictionary getSelectedFiles() { - return (Dictionary) _files.clone(); + PostMethodWebRequest( WebForm sourceForm, SubmitButton button, int x, int y ) { + super( sourceForm, button, x, y ); } - //---------------------------------- private members ------------------------------------- + - private Hashtable _files = new Hashtable(); private InputStream _source; private MessageBody _body; Index: SubmitButton.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/SubmitButton.java,v retrieving revision 1.7 retrieving revision 1.8 diff -u -r1.7 -r1.8 --- SubmitButton.java 2002/01/10 22:18:58 1.7 +++ SubmitButton.java 2002/01/14 18:13:45 1.8 @@ -19,6 +19,8 @@ * DEALINGS IN THE SOFTWARE. * *******************************************************************************************************************/ +import java.io.IOException; + import org.w3c.dom.Node; /** @@ -64,6 +66,17 @@ } + void addValues( ParameterProcessor processor, String characterSet ) throws IOException { + if (_pressed && !isDisabled() && getName().length() > 0 && getValueAttribute().length() > 0) { + processor.addParameter( getName(), getValueAttribute(), characterSet ); + if (_isImageButton) { + processor.addParameter( getName() + ".x", Integer.toString( _x ), characterSet ); + processor.addParameter( getName() + ".y", Integer.toString( _y ), characterSet ); + } + } + } + + //------------------------------------ Object methods ---------------------------------------- @@ -97,12 +110,20 @@ } + public void setLocation( int x, int y ) { + _x = x; + _y = y; + } + + //------------------------------------------ private members ---------------------------------- private final String _id; private final boolean _isImageButton; private boolean _pressed; + private int _x; + private int _y; private String[] _value = new String[1]; Index: UncheckedParameterHolder.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/UncheckedParameterHolder.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- UncheckedParameterHolder.java 2002/01/10 22:18:58 1.2 +++ UncheckedParameterHolder.java 2002/01/14 18:13:45 1.3 @@ -21,6 +21,7 @@ *******************************************************************************************************************/ import java.io.File; import java.io.InputStream; +import java.io.IOException; import java.util.Hashtable; import java.util.Enumeration; @@ -55,9 +56,18 @@ /** + * Specifies the position at which an image button (if any) was clicked. + **/ + public void selectImageButtonPosition( SubmitButton imageButton, int x, int y ) { + setParameter( imageButton.getName() + ".x", Integer.toString( x ) ); + setParameter( imageButton.getName() + ".y", Integer.toString( y ) ); + } + + + /** * Iterates through the parameters in this holder, recording them in the supplied parameter processor. **/ - public void recordParameters( ParameterProcessor processor ) { + public void recordParameters( ParameterProcessor processor ) throws IOException { Enumeration e = _parameters.keys(); while (e.hasMoreElements()) { @@ -68,13 +78,16 @@ } else if (value instanceof String[]) { String[] values = (String[]) value; for (int i = 0; i < values.length; i++) processor.addParameter( name, values[i], _characterSet ); + } else if (value instanceof UploadFileSpec[]) { + UploadFileSpec[] files = (UploadFileSpec[]) value; + for (int i = 0; i < files.length; i++) processor.addFile( name, files[i] ); } } } - public Enumeration getParameterNames() { - return _parameters.keys(); + public String[] getParameterNames() { + return (String[]) _parameters.keySet().toArray( new String[ _parameters.size() ] ); } @@ -88,7 +101,7 @@ Object result = _parameters.get( name ); if (result instanceof String) return new String[] { (String) result }; if (result instanceof String[]) return (String[]) result; - if (result instanceof WebRequest.UploadFileSpec) return new String[] { result.toString() }; + if (result instanceof UploadFileSpec) return new String[] { result.toString() }; return NO_VALUES; } @@ -108,19 +121,12 @@ } - public boolean isFileParameter( String name ) { - return false; + public void setParameter( String name, UploadFileSpec[] files ) { + _parameters.put( name, files ); } - public void selectFile( String parameterName, File file ) { - } - - - public void selectFile( String parameterName, File file, String contentType ) { - } - - - public void selectFile( String parameterName, String fileName, InputStream inputStream, String contentType ) { + public boolean isFileParameter( String name ) { + return false; } } Index: WebForm.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebForm.java,v retrieving revision 1.41 retrieving revision 1.42 diff -u -r1.41 -r1.42 --- WebForm.java 2002/01/10 22:18:58 1.41 +++ WebForm.java 2002/01/14 18:13:45 1.42 @@ -27,6 +27,8 @@ import java.util.HashMap; import java.util.Arrays; import java.util.Map; +import java.util.Iterator; +import java.io.IOException; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -39,7 +41,7 @@ * defined for the form, the structure of the form (as a DOM), or the text of the form. They * may also create a {@link WebRequest} to simulate the submission of the form. **/ -public class WebForm extends WebRequestSource { +public class WebForm extends WebRequestSource implements ParameterHolder { private static final FormParameter UNKNOWN_PARAMETER = new FormParameter(); @@ -60,21 +62,6 @@ /** - * Returns the character set encoding for this form. - **/ - public String getCharacterSet() { - return _characterSet; - } - - - /** - * Sets the value of a parameter in this form. - **/ - public void setParameter( String name, String value ) { - } - - - /** * Returns true if a parameter with given name exists in this form. **/ public boolean hasParameterNamed( String soughtName ) { @@ -95,37 +82,6 @@ /** - * Returns an array containing the names of the parameters defined for this form. - **/ - public String[] getParameterNames() { - ArrayList parameterNames = new ArrayList( getFormParameters().keySet() ); - return (String[]) parameterNames.toArray( new String[ parameterNames.size() ] ); - } - - - /** - * Returns a map of parameter name to form parameter objects. Each form parameter object represents the set of form - * controls with a particular name. Unnamed parameters are ignored. - */ - private Map getFormParameters() { - if (_formParameters == null) { - _formParameters = new HashMap(); - FormControl[] controls = getFormControls(); - for (int i = 0; i < controls.length; i++) { - if (controls[i].getName().length() == 0) continue; - FormParameter parameter = (FormParameter) _formParameters.get( controls[i].getName() ); - if (parameter == null) { - parameter = new FormParameter(); - _formParameters.put( controls[i].getName(), parameter ); - } - parameter.addControl( controls[i] ); - } - } - return _formParameters; - } - - - /** * Returns an array containing the submit buttons defined for this form. **/ public SubmitButton[] getSubmitButtons() { @@ -138,28 +94,6 @@ } - private Vector _buttonVector; - - private Vector getSubmitButtonVector() { - if (_buttonVector == null) { - _buttonVector = new Vector(); - FormControl[] controls = getFormControls(); - for (int i = 0; i < controls.length; i++) { - FormControl control = controls[ i ]; - if (control instanceof SubmitButton) _buttonVector.add( control ); - } - - if (_buttonVector.isEmpty()) _buttonVector.addElement( SubmitButton.UNNAMED_BUTTON ); - } - return _buttonVector; - } - - - private boolean hasMatchingAttribute( Node node, String attributeName, String attributeValue ) { - return NodeUtils.getNodeAttribute( node, attributeName ).equalsIgnoreCase( attributeValue ); - } - - /** * Returns the submit button defined in this form with the specified name. * If more than one such button exists, will return the first found. @@ -209,14 +143,6 @@ /** - * Creates and returns a web request which will simulate the submission of this form with an unnamed submit button. - **/ - public WebRequest getRequest() { - return getRequest( (SubmitButton) null ); - } - - - /** * Creates and returns a web request which will simulate the submission of this form with a button with the specified name and value. **/ public WebRequest getRequest( String submitButtonName, String submitButtonValue ) { @@ -236,25 +162,12 @@ } - private SubmitButton getDefaultButton() { - if (getSubmitButtons().length == 1) { - return getSubmitButtons()[0]; - } else if (getSubmitButtonVector().contains( SubmitButton.UNNAMED_BUTTON )) { - return getSubmitButton( "" ); - } else { - return null; - } - } - - /** * Creates and returns a web request which will simulate the submission of this form by pressing the specified button. * If the button is null, simulates the pressing of the default button. **/ - public WebRequest getRequest( SubmitButton button, int x, int y ) { - WebRequest request = getRequest( button ); - request.setSubmitPosition( x, y ); - return request; + public WebRequest getRequest( SubmitButton button ) { + return getRequest( button, 0, 0 ); } @@ -262,7 +175,7 @@ * Creates and returns a web request which will simulate the submission of this form by pressing the specified button. * If the button is null, simulates the pressing of the default button. **/ - public WebRequest getRequest( SubmitButton button ) { + public WebRequest getRequest( SubmitButton button, int x, int y ) { if (button == null) button = getDefaultButton(); if (HttpUnitOptions.getParameterValuesValidated()) { @@ -282,20 +195,13 @@ button.setPressed( true ); if (getMethod().equalsIgnoreCase( "post" )) { - return new PostMethodWebRequest( this, button ); + return new PostMethodWebRequest( this, button, x, y ); } else { - return new GetMethodWebRequest( this, button ); + return new GetMethodWebRequest( this, button, x, y ); } } - String getRelativeURL() { - String action = getAction(); - if (action.trim().length() == 0) action = getBaseURL().getFile(); - return action; - } - - /** * Returns the default value of the named parameter. If the parameter does not exist returns null. **/ @@ -306,25 +212,6 @@ /** - * Returns the multiple default values of the named parameter. - **/ - public String[] getParameterValues( String name ) { - ArrayList valueList = new ArrayList(); - FormControl[] controls = getParameter( name ).getControls(); - for (int i = 0; i < controls.length; i++) { - valueList.addAll( Arrays.asList( controls[i].getValues() ) ); - } - return (String[]) valueList.toArray( new String[ valueList.size() ] ); - } - - - private FormParameter getParameter( String name ) { - final FormParameter parameter = ((FormParameter) getFormParameters().get( name )); - return parameter != null ? parameter : UNKNOWN_PARAMETER; - } - - - /** * Returns the displayed options defined for the specified parameter name. **/ public String[] getOptions( String name ) { @@ -341,12 +228,7 @@ * Returns the option values defined for the specified parameter name. **/ public String[] getOptionValues( String name ) { - ArrayList valueList = new ArrayList(); - FormControl[] controls = getParameter( name ).getControls(); - for (int i = 0; i < controls.length; i++) { - valueList.addAll( Arrays.asList( controls[i].getOptionValues() ) ); - } - return (String[]) valueList.toArray( new String[ valueList.size() ] ); + return getParameter( name ).getOptionValues(); } @@ -390,6 +272,23 @@ /** + * Returns true if this form is to be submitted using mime encoding (the default is URL encoding). + **/ + public boolean isSubmitAsMime() { + return "multipart/form-data".equalsIgnoreCase( NodeUtils.getNodeAttribute( getNode(), "enctype" ) ); + } + +//---------------------------------- WebRequestSource methods -------------------------------- + + /** + * Returns the character set encoding for this form. + **/ + public String getCharacterSet() { + return _characterSet; + } + + + /** * Returns true if the named parameter accepts files for upload. **/ public boolean isFileParameter( String name ) { @@ -402,13 +301,97 @@ /** - * Returns true if this form is to be submitted using mime encoding (the default is URL encoding). + * Returns an array containing the names of the parameters defined for this form. **/ - public boolean isSubmitAsMime() { - return "multipart/form-data".equalsIgnoreCase( NodeUtils.getNodeAttribute( getNode(), "enctype" ) ); + public String[] getParameterNames() { + ArrayList parameterNames = new ArrayList( getFormParameters().keySet() ); + return (String[]) parameterNames.toArray( new String[ parameterNames.size() ] ); + } + + + /** + * Returns the multiple default values of the named parameter. + **/ + public String[] getParameterValues( String name ) { + ArrayList valueList = new ArrayList(); + FormControl[] controls = getParameter( name ).getControls(); + for (int i = 0; i < controls.length; i++) { + valueList.addAll( Arrays.asList( controls[i].getValues() ) ); + } + return (String[]) valueList.toArray( new String[ valueList.size() ] ); + } + + + String getRelativeURL() { + String action = getAction(); + if (action.trim().length() == 0) action = getBaseURL().getFile(); + return action; } + /** + * Creates and returns a web request which will simulate the submission of this form with an unnamed submit button. + **/ + public WebRequest getRequest() { + return getRequest( (SubmitButton) null ); + } + + +//---------------------------------- ParameterHolder methods -------------------------------- + + + /** + * Specifies the position at which an image button (if any) was clicked. + **/ + public void selectImageButtonPosition( SubmitButton imageButton, int x, int y ) { + imageButton.setLocation( x, y ); + } + + + /** + * Iterates through the parameters in this holder, recording them in the supplied parameter processor. + **/ + public void recordParameters( ParameterProcessor processor ) throws IOException { + FormControl[] controls = getFormControls(); + for (int i = 0; i < controls.length; i++) { + controls[i].addValues( processor, getCharacterSet() ); + } + } + + + /** + * Removes a parameter name from this collection. + **/ + public void removeParameter( String name ) { + setParameter( name, NO_VALUES ); + } + + + /** + * Sets the multiple values of a file upload parameter in a web request. + **/ + public void setParameter( String name, UploadFileSpec[] files ) { + FormParameter parameter = getParameter( name ); + if (parameter == null) throw new NoSuchParameterException( name ); + parameter.setFiles( files ); + } + + + /** + * Sets the value of a parameter in this form. + **/ + public void setParameter( String name, String value ) { + setParameter( name, new String[] { value } ); + } + + + public void setParameter( String name, final String[] values ) { + FormParameter parameter = getParameter( name ); + if (parameter == null) throw new NoSuchParameterException( name ); + parameter.setValues( values ); + } + + //---------------------------------- package members -------------------------------- /** @@ -421,19 +404,10 @@ } - /** - * Returns the values which *must* for the specified parameter name. - **/ - String[] getRequiredValues( String name ) { - Object result = getParameterRequiredValues().get( name ); - if (result instanceof String[]) return (String[]) result; - if (result instanceof String) return new String[] { (String) result }; - return new String[0]; - } - - //---------------------------------- private members -------------------------------- + private final static String[] NO_VALUES = new String[0]; + /** The attributes of the form parameters. **/ private FormControl[] _parameters; @@ -445,25 +419,35 @@ /** A map of parameter names to form parameter objects. **/ private Map _formParameters; + + private Vector _buttonVector; - /** A map of parameter names to their required values. **/ - private Hashtable _required; + private SubmitButton getDefaultButton() { + if (getSubmitButtons().length == 1) { + return getSubmitButtons()[0]; + } else if (getSubmitButtonVector().contains( SubmitButton.UNNAMED_BUTTON )) { + return getSubmitButton( "" ); + } else { + return null; + } + } - private Hashtable getParameterRequiredValues() { - if (_required == null) { - FormControl[] parameters = getFormControls(); - Hashtable required = new Hashtable(); - for (int i = 0; i < parameters.length; i++) { - parameters[i].updateRequiredValues( required ); + private Vector getSubmitButtonVector() { + if (_buttonVector == null) { + _buttonVector = new Vector(); + FormControl[] controls = getFormControls(); + for (int i = 0; i < controls.length; i++) { + FormControl control = controls[ i ]; + if (control instanceof SubmitButton) _buttonVector.add( control ); } - _required = required; + + if (_buttonVector.isEmpty()) _buttonVector.addElement( SubmitButton.UNNAMED_BUTTON ); } - return _required; + return _buttonVector; } - /** * Returns an array of form parameter attributes for this form. **/ @@ -479,6 +463,34 @@ } + private FormParameter getParameter( String name ) { + final FormParameter parameter = ((FormParameter) getFormParameters().get( name )); + return parameter != null ? parameter : UNKNOWN_PARAMETER; + } + + + /** + * Returns a map of parameter name to form parameter objects. Each form parameter object represents the set of form + * controls with a particular name. Unnamed parameters are ignored. + */ + private Map getFormParameters() { + if (_formParameters == null) { + _formParameters = new HashMap(); + FormControl[] controls = getFormControls(); + for (int i = 0; i < controls.length; i++) { + if (controls[i].getName().length() == 0) continue; + FormParameter parameter = (FormParameter) _formParameters.get( controls[i].getName() ); + if (parameter == null) { + parameter = new FormParameter(); + _formParameters.put( controls[i].getName(), parameter ); + } + parameter.addControl( controls[i] ); + } + } + return _formParameters; + } + + private void addFormParametersToList( NodeList children, Vector list ) { for (int i = 0; i < children.getLength(); i++) { addFormParametersToList( children.item(i), list ); @@ -501,8 +513,14 @@ class FormParameter { void addControl( FormControl control ) { - _controlList.add( control ); _controls = null; + if (_name == null) _name = control.getName(); + if (!_name.equalsIgnoreCase( control.getName() )) throw new RuntimeException( "all controls should have the same name" ); + if (control.isExclusive()) { + getRadioGroup().addRadioButton( (RadioButtonFormControl) control ); + } else { + _controlList.add( control ); + } } @@ -512,11 +530,132 @@ } + void setValues( String[] values ) { + ArrayList list = new ArrayList( values.length ); + list.addAll( Arrays.asList( values ) ); + for (int i = 0; i < getControls().length; i++) getControls()[i].claimRequiredValues( list ); + for (int i = 0; i < getControls().length; i++) getControls()[i].claimUniqueValue( list ); + for (int i = 0; i < getControls().length; i++) getControls()[i].claimValue( list ); + if (!list.isEmpty()) throw new UnusedParameterValueException( _name, (String) list.get(0) ); + } + + + void setFiles( UploadFileSpec[] fileArray ) { + ArrayList list = new ArrayList( fileArray.length ); + list.addAll( Arrays.asList( fileArray ) ); + for (int i = 0; i < getControls().length; i++) getControls()[i].claimUploadSpecification( list ); + if (!list.isEmpty()) throw new UnusedUploadFileException( _name, fileArray.length - list.size(), fileArray.length ); + } + + + String[] getOptionValues() { + ArrayList valueList = new ArrayList(); + for (int i = 0; i < getControls().length; i++) { + valueList.addAll( Arrays.asList( getControls()[i].getOptionValues() ) ); + } + return (String[]) valueList.toArray( new String[ valueList.size() ] ); + } + + private FormControl[] _controls; private ArrayList _controlList = new ArrayList(); + private RadioGroupFormControl _group; + private String _name; + + private RadioGroupFormControl getRadioGroup() { + if (_group == null) { + _group = new RadioGroupFormControl(); + _controlList.add( _group ); + } + return _group; + } } +//================================ exception class NoSuchParameterException ========================================= + + +/** + * This exception is thrown on an attempt to set a parameter to a value not permitted to it by the form. + **/ +class NoSuchParameterException extends IllegalRequestParameterException { + + + NoSuchParameterException( String parameterName ) { + _parameterName = parameterName; + } + + + public String getMessage() { + return "No parameter named '" + _parameterName + "' is defined in the form"; + } + + + private String _parameterName; + +} + + +//============================= exception class UnusedParameterValueException ====================================== + + +/** + * This exception is thrown on an attempt to set a parameter to a value not permitted to it by the form. + **/ +class UnusedParameterValueException extends IllegalRequestParameterException { + + + UnusedParameterValueException( String parameterName, String badValue ) { + _parameterName = parameterName; + _badValue = badValue; + } + + + public String getMessage() { + StringBuffer sb = new StringBuffer(HttpUnitUtils.DEFAULT_TEXT_BUFFER_SIZE); + sb.append( "Attempted to assign to parameter '" ).append( _parameterName ); + sb.append( "' the extraneous value '" ).append( _badValue ).append( "'." ); + return sb.toString(); + } + + + private String _parameterName; + private String _badValue; +} + + +//============================= exception class UnusedUploadFileException ====================================== + + +/** + * This exception is thrown on an attempt to upload more files than permitted by the form. + **/ +class UnusedUploadFileException extends IllegalRequestParameterException { + + + UnusedUploadFileException( String parameterName, int numFilesExpected, int numFilesSupplied ) { + _parameterName = parameterName; + _numExpected = numFilesExpected; + _numSupplied = numFilesSupplied; + } + + + public String getMessage() { + StringBuffer sb = new StringBuffer( HttpUnitUtils.DEFAULT_TEXT_BUFFER_SIZE ); + sb.append( "Attempted to upload " ).append( _numSupplied ).append( " files using parameter '" ).append( _parameterName ); + if (_numExpected == 0) { + sb.append( "' which is not a file parameter." ); + } else { + sb.append( "' which only has room for " ).append( _numExpected ).append( '.' ); + } + return sb.toString(); + } + + + private String _parameterName; + private int _numExpected; + private int _numSupplied; +} //============================= exception class IllegalUnnamedSubmitButtonException ====================================== Index: WebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebRequest.java,v retrieving revision 1.35 retrieving revision 1.36 diff -u -r1.35 -r1.36 --- WebRequest.java 2002/01/10 22:18:58 1.35 +++ WebRequest.java 2002/01/14 18:13:45 1.36 @@ -38,6 +38,8 @@ import java.util.Dictionary; import java.util.Enumeration; import java.util.Hashtable; +import java.util.Vector; +import java.util.Arrays; /** * A request sent to a web server. @@ -45,7 +47,6 @@ abstract public class WebRequest { - /** * Sets the value of a header to be sent with this request. A header set here will override any matching header set * in the WebClient when the request is actually sent. @@ -101,8 +102,7 @@ * Sets the value of a parameter in a web request. **/ public void setParameter( String name, String value ) { - if (HttpUnitOptions.getParameterValuesValidated()) validateParameterValue( name, value ); - _parameterCollection.setParameter( name, value ); + _parameterHolder.setParameter( name, value ); } @@ -110,8 +110,17 @@ * Sets the multiple values of a parameter in a web request. **/ public void setParameter( String name, String[] values ) { - if (HttpUnitOptions.getParameterValuesValidated()) validateParameterValues( name, values ); - _parameterCollection.setParameter( name, values ); + _parameterHolder.setParameter( name, values ); + } + + + /** + * Sets the multiple values of a file upload parameter in a web request. + **/ + public void setParameter( String parameterName, UploadFileSpec[] files ) { + if (!maySelectFile( parameterName )) throw new IllegalNonFileParameterException( parameterName ); + if (!isMimeEncoded()) throw new MultipartFormRequiredException(); + _parameterHolder.setParameter( parameterName, files ); } @@ -119,7 +128,7 @@ * Returns true if the specified parameter is a file field. **/ public boolean isFileParameter( String name ) { - return _sourceForm != null && _sourceForm.isFileParameter( name ); + return _parameterHolder.isFileParameter( name ); } @@ -127,8 +136,7 @@ * Sets the file for a parameter upload in a web request. **/ public void selectFile( String parameterName, File file ) { - assertFileParameter( parameterName ); - if (!isMimeEncoded()) throw new MultipartFormRequiredException(); + setParameter( parameterName, new UploadFileSpec[] { new UploadFileSpec( file ) } ); } @@ -136,8 +144,7 @@ * Sets the file for a parameter upload in a web request. **/ public void selectFile( String parameterName, File file, String contentType ) { - assertFileParameter( parameterName ); - if (!isMimeEncoded()) throw new MultipartFormRequiredException(); + setParameter( parameterName, new UploadFileSpec[] { new UploadFileSpec( file, contentType ) } ); } @@ -145,25 +152,25 @@ * Sets the file for a parameter upload in a web request. **/ public void selectFile( String parameterName, String fileName, InputStream inputStream, String contentType ) { - assertFileParameter( parameterName ); + setParameter( parameterName, new UploadFileSpec[] { new UploadFileSpec( fileName, inputStream, contentType ) } ); } /** - * Throws an exception if the specified parameter may not be set as a file. - */ - private void assertFileParameter( String parameterName ) - { - if (!maySelectFile( parameterName )) throw new IllegalNonFileParameterException( parameterName ); - if (!isMimeEncoded()) throw new MultipartFormRequiredException(); + * Returns an enumeration of all parameters in this web request. + * @deprecated use getRequestParameterNames instead + **/ + public Enumeration getParameterNames() { + return new Vector( Arrays.asList( _parameterHolder.getParameterNames() ) ).elements(); } /** - * Returns an enumeration of all parameters in this web request. + * Returns an array of all parameter names in this web request. + * @since 1.3.1 **/ - public Enumeration getParameterNames() { - return _parameterCollection.getParameterNames(); + public String[] getRequestParameterNames() { + return _parameterHolder.getParameterNames(); } @@ -182,7 +189,7 @@ * Returns the multiple default values of the named parameter. **/ public String[] getParameterValues( String name ) { - return _parameterCollection.getParameterValues( name ); + return _parameterHolder.getParameterValues( name ); } @@ -190,7 +197,7 @@ * Removes a parameter from this web request. **/ public void removeParameter( String name ) { - _parameterCollection.removeParameter( name ); + _parameterHolder.removeParameter( name ); } @@ -223,40 +230,52 @@ /** + * Constructs a web request using a base request and a relative URL string. + **/ + protected WebRequest( WebRequest baseRequest, String urlString, String target ) throws MalformedURLException { + this( baseRequest.getURL(), urlString, target ); + } + + + /** * Constructs a web request using a base URL, a relative URL string, and a target. **/ protected WebRequest( URL urlBase, String urlString, String target ) { - _urlBase = urlBase; - _urlString = urlString; - _target = target; + this( urlBase, urlString, target, new UncheckedParameterHolder() ); } /** * Constructs a web request from a form. **/ - protected WebRequest( WebForm sourceForm, SubmitButton button ) { - this( sourceForm.getBaseURL(), sourceForm.getRelativeURL(), sourceForm.getTarget() ); + protected WebRequest( WebForm sourceForm, SubmitButton button, int x, int y ) { + this( sourceForm.getBaseURL(), sourceForm.getRelativeURL(), sourceForm.getTarget(), newParameterHolder( sourceForm ) ); _sourceForm = sourceForm; - _parameterCollection = new UncheckedParameterHolder( sourceForm ); + if (button != null && button.isImageButton() && button.getName().length() > 0) { + _parameterHolder.selectImageButtonPosition( button, x, y ); + } setHeaderField( "Referer", sourceForm.getBaseURL().toExternalForm() ); + } - if (button != null && button.getName().length() > 0) { - if (button.isImageButton()) { - _imageButtonName = button.getName(); - setSubmitPosition( 0, 0 ); - } - } + private static ParameterHolder newParameterHolder( WebForm requestSource ) { + if (HttpUnitOptions.getParameterValuesValidated()) { + return requestSource; + } else { + return new UncheckedParameterHolder( requestSource ); + } } /** - * Constructs a web request using a base request and a relative URL string. + * Constructs a web request using a base URL, a relative URL string, and a target. **/ - protected WebRequest( WebRequest baseRequest, String urlString, String target ) throws MalformedURLException { - this( baseRequest.getURL(), urlString, target ); + private WebRequest( URL urlBase, String urlString, String target, ParameterHolder parameterHolder ) { + _urlBase = urlBase; + _urlString = urlString; + _target = target; + _parameterHolder = parameterHolder; } @@ -327,26 +346,28 @@ final protected String getParameterString() { - URLEncodedString encoder = new URLEncodedString(); - _parameterCollection.recordParameters( encoder ); - return enco... [truncated message content] |
From: Russell G. <rus...@us...> - 2002-01-14 18:13:49
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv25860/test/com/meterware/httpunit Modified Files: FileUploadTest.java FormParametersTest.java FormSubmitTest.java HttpUnitTest.java WebFormTest.java Log Message: Parameter values now stored in WebForm Index: FileUploadTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/FileUploadTest.java,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- FileUploadTest.java 2001/11/09 18:35:14 1.9 +++ FileUploadTest.java 2002/01/14 18:13:45 1.10 @@ -67,7 +67,7 @@ WebResponse simplePage = wc.getResponse( request ); WebRequest formSubmit = simplePage.getForms()[0].getRequest(); WebResponse encoding = wc.getResponse( formSubmit ); - assertEqualQueries( "http://dummy?update=age&age=12", "http://dummy?" + encoding.getText().trim() ); + assertEquals( "http://dummy?age=12&update=age", "http://dummy?" + encoding.getText().trim() ); } @@ -86,7 +86,7 @@ try { formSubmit.setParameter( "message", "text/plain" ); fail( "Should not allow setting of a file parameter to a text value" ); - } catch (IllegalFileParameterException e) { + } catch (IllegalRequestParameterException e) { } } @@ -150,12 +150,79 @@ WebRequest formSubmit = simplePage.getForms()[0].getRequest(); formSubmit.selectFile( "message", file ); WebResponse encoding = wc.getResponse( formSubmit ); - assertEquals( "update=age&text/plain:message.name=temp.txt&message.lines=2", encoding.getText().trim() ); + assertEquals( "text/plain:message.name=temp.txt&message.lines=2&update=age", encoding.getText().trim() ); file.delete(); } + public void testMultiFileSubmit() throws Exception { + File file = new File( "temp.txt" ); + FileWriter fw = new FileWriter( file ); + PrintWriter pw = new PrintWriter( fw ); + pw.println( "Not much text" ); + pw.println( "But two lines" ); + pw.close(); + + File file2 = new File( "temp2.txt" ); + fw = new FileWriter( file2 ); + pw = new PrintWriter( fw ); + pw.println( "Even less text on one line" ); + pw.close(); + + defineResource( "ListParams", new MimeEcho() ); + defineWebPage( "Default", "<form method=POST action = \"ListParams\" enctype=\"multipart/form-data\"> " + + "<Input type=file name=message>" + + "<Input type=file name=message>" + + "<Input type=submit name=update value=age>" + + "</form>" ); + WebConversation wc = new WebConversation(); + WebRequest request = new GetMethodWebRequest( getHostPath() + "/Default.html" ); + WebResponse simplePage = wc.getResponse( request ); + WebRequest formSubmit = simplePage.getForms()[0].getRequest(); + formSubmit.setParameter( "message", new UploadFileSpec[] { new UploadFileSpec( file ), new UploadFileSpec( file2, "text/more" ) } ); + WebResponse encoding = wc.getResponse( formSubmit ); + assertEquals( "text/plain:message.name=temp.txt&message.lines=2&text/more:message.name=temp2.txt&message.lines=1&update=age", encoding.getText().trim() ); + + file.delete(); + file2.delete(); + } + + + public void testIllegalMultiFileSubmit() throws Exception { + File file = new File( "temp.txt" ); + FileWriter fw = new FileWriter( file ); + PrintWriter pw = new PrintWriter( fw ); + pw.println( "Not much text" ); + pw.println( "But two lines" ); + pw.close(); + + File file2 = new File( "temp2.txt" ); + fw = new FileWriter( file2 ); + pw = new PrintWriter( fw ); + pw.println( "Even less text on one line" ); + pw.close(); + + defineResource( "ListParams", new MimeEcho() ); + defineWebPage( "Default", "<form method=POST action = \"ListParams\" enctype=\"multipart/form-data\"> " + + "<Input type=file name=message>" + + "<Input type=submit name=update value=age>" + + "</form>" ); + WebConversation wc = new WebConversation(); + WebRequest request = new GetMethodWebRequest( getHostPath() + "/Default.html" ); + WebResponse simplePage = wc.getResponse( request ); + WebRequest formSubmit = simplePage.getForms()[0].getRequest(); + try { + formSubmit.setParameter( "message", new UploadFileSpec[] { new UploadFileSpec( file ), new UploadFileSpec( file2, "text/more" ) } ); + fail( "Permitted two files on a single file parameter" ); + } catch (IllegalRequestParameterException e) { + } + + file.delete(); + file2.delete(); + } + + public void testInputStreamAsFile() throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream( "Not much text\nBut two lines\n".getBytes() ); @@ -170,7 +237,7 @@ WebRequest formSubmit = simplePage.getForms()[0].getRequest(); formSubmit.selectFile( "message", "temp.txt", bais, "text/plain" ); WebResponse encoding = wc.getResponse( formSubmit ); - assertEquals( "update=age&text/plain:message.name=temp.txt&message.lines=2", encoding.getText().trim() ); + assertEquals( "text/plain:message.name=temp.txt&message.lines=2&update=age", encoding.getText().trim() ); } @@ -183,7 +250,7 @@ formSubmit.setMimeEncoded( true ); formSubmit.selectFile( "message", "temp.txt", bais, "text/plain" ); WebResponse encoding = wc.getResponse( formSubmit ); - assertEqualQueries( "text/plain:message.name=temp.txt&message.lines=2", encoding.getText().trim() ); + assertEquals( "text/plain:message.name=temp.txt&message.lines=2", encoding.getText().trim() ); } Index: FormParametersTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/FormParametersTest.java,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- FormParametersTest.java 2002/01/08 23:21:53 1.9 +++ FormParametersTest.java 2002/01/14 18:13:45 1.10 @@ -55,6 +55,7 @@ public void testChoiceParameterValidationBypass() throws Exception { + HttpUnitOptions.setParameterValuesValidated( false ); defineWebPage( "Default", "<form method=GET action = \"/ask\">" + "<Select name=colors><Option>blue<Option>red</Select>" + "<Select name=fish><Option value=red>snapper<Option value=pink>salmon</select>" + @@ -62,7 +63,6 @@ "<Input type=submit name=submit value=submit></form>" ); WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); WebRequest request = page.getForms()[0].getRequest(); - HttpUnitOptions.setParameterValuesValidated( false ); request.setParameter( "noSuchControl", "green" ); request.setParameter( "colors", "green" ); request.setParameter( "fish", "purple" ); @@ -98,6 +98,7 @@ public void testTextParameterValidationBypass() throws Exception { + HttpUnitOptions.setParameterValuesValidated( false ); defineWebPage( "Default", "<form method=GET action = \"/ask\">" + "<Input type=text name=color>" + "<Input type=password name=password>" + @@ -105,7 +106,6 @@ "<Input type=submit></form>" ); WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); WebRequest request = page.getForms()[0].getRequest(); - HttpUnitOptions.setParameterValuesValidated( false ); request.setParameter( "color", "green" ); request.setParameter( "password", "purple" ); request.setParameter( "secret", "value" ); @@ -119,7 +119,7 @@ defineWebPage( "Default", "<form method=GET action = \"/ask\">" + "<Input type=text name=color>" + "<Input type=password name=password>" + - "<Input type=hidden name=secret>" + + "<Input type=hidden name=secret value=value>" + "<Input type=submit></form>" ); WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); WebRequest request = page.getForms()[0].getRequest(); @@ -136,7 +136,7 @@ defineWebPage( "Default", "<form method=GET action = \"/ask\">" + "<Input type=text name=color>" + "<Input type=password name=password>" + - "<Input type=hidden name=color>" + + "<Input type=hidden name=color value='green'>" + "<Input type=submit></form>" ); WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); WebForm form = page.getForms()[0]; @@ -154,6 +154,7 @@ public void testRadioButtonValidationBypass() throws Exception { + HttpUnitOptions.setParameterValuesValidated( false ); defineWebPage( "Default", "<form method=GET action = \"/ask\">" + "<Input type=radio name=color value=red>" + "<Input type=radio name=color value=blue>" + @@ -161,7 +162,6 @@ "<Input type=submit></form>" ); WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); WebRequest request = page.getForms()[0].getRequest(); - HttpUnitOptions.setParameterValuesValidated( false ); request.setParameter( "color", "black" ); request.setParameter( "color", new String[] { "blue", "red" } ); } @@ -184,19 +184,28 @@ } - public void testCheckboxValidation() throws Exception { + public void testCheckboxValidationBypass() throws Exception { defineWebPage( "Default", "<form method=GET action = \"/ask\">" + "<Input type=checkbox name=use_color>" + "<Input type=checkbox name=color value=red>" + "<Input type=checkbox name=color value=blue>" + "<Input type=submit></form>" ); + HttpUnitOptions.setParameterValuesValidated( false ); WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); WebRequest request = page.getForms()[0].getRequest(); - HttpUnitOptions.setParameterValuesValidated( false ); request.setParameter( "use_color", "red" ); request.setParameter( "color", "green" ); + } - HttpUnitOptions.setParameterValuesValidated( true ); + + public void testCheckboxValidation() throws Exception { + defineWebPage( "Default", "<form method=GET action = \"/ask\">" + + "<Input type=checkbox name=use_color>" + + "<Input type=checkbox name=color value=red>" + + "<Input type=checkbox name=color value=blue>" + + "<Input type=submit></form>" ); + WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); + WebRequest request = page.getForms()[0].getRequest(); request.setParameter( "use_color", "on" ); request.removeParameter( "use_color" ); validateSetParameterRejected( request, "use_color", "red", "setting checkbox to a string value" ); @@ -230,8 +239,8 @@ validateSetParameterRejected( request, "color", "blue", "unchecking 'red'" ); validateSetParameterRejected( request, "color", new String[] { "blue" }, "unchecking 'red'" ); validateSetParameterRejected( request, "species", "hippo", "selecting 'hippo'" ); - validateSetParameterRejected( request, "age", "15", "changing a disabled text parameter value" ); - validateSetParameterRejected( request, "big", "go-go", "changing a disabled textarea parameter value" ); + validateSetParameterRejected( request, "age", "15", "changing a read-only text parameter value" ); + validateSetParameterRejected( request, "big", "go-go", "changing a read-only textarea parameter value" ); request.setParameter( "color", "red" ); request.setParameter( "color", new String[] { "red", "blue" } ); Index: FormSubmitTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/FormSubmitTest.java,v retrieving revision 1.12 retrieving revision 1.13 diff -u -r1.12 -r1.13 --- FormSubmitTest.java 2002/01/09 12:57:48 1.12 +++ FormSubmitTest.java 2002/01/14 18:13:45 1.13 @@ -77,7 +77,7 @@ WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); WebForm form = page.getForms()[0]; WebRequest request = form.getRequest(); - assertEqualQueries( getHostPath() + "/ask?age=12", request.getURL().toExternalForm() ); + assertEquals( "Empty choice query", getHostPath() + "/ask?age=12", request.getURL().toExternalForm() ); } @@ -202,7 +202,7 @@ WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); WebForm form = page.getForms()[0]; WebRequest request = form.getRequest(); - assertEqualQueries( getHostPath() + "/ask?update=name&update.y=0&update.x=0&age=12", request.getURL().toExternalForm() ); + assertEquals( "Query", getHostPath() + "/ask?age=12&update=name&update.x=0&update.y=0", request.getURL().toExternalForm() ); } @@ -226,7 +226,7 @@ WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); WebForm form = page.getForms()[0]; WebRequest request = form.getRequest( form.getSubmitButton( "update" ), 10, 15 ); - assertEqualQueries( getHostPath() + "/ask?update=name&update.y=15&update.x=10&age=12", request.getURL().toExternalForm() ); + assertEquals( getHostPath() + "/ask?age=12&update=name&update.x=10&update.y=15", request.getURL().toExternalForm() ); } @@ -289,13 +289,13 @@ WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); WebForm form = page.getForms()[0]; WebRequest request = form.getRequest( form.getSubmitButton( "update", "name" ) ); - assertEqualQueries( getHostPath() + "/ask?update=name&age=12", request.getURL().toExternalForm() ); + assertEquals( getHostPath() + "/ask?age=12&update=name", request.getURL().toExternalForm() ); request = form.getRequest( "update", "name" ); - assertEqualQueries( getHostPath() + "/ask?update=name&age=12", request.getURL().toExternalForm() ); + assertEquals( getHostPath() + "/ask?age=12&update=name", request.getURL().toExternalForm() ); request = form.getRequest( "update" ); - assertEqualQueries( getHostPath() + "/ask?update=age&age=12", request.getURL().toExternalForm() ); + assertEquals( getHostPath() + "/ask?age=12&update=age", request.getURL().toExternalForm() ); } @@ -363,7 +363,7 @@ WebForm form = wr.getForms()[0]; WebRequest req = form.getRequest( "apply" ); req.setParameter( "aTextField", "test" ); - assertEqualQueries( getHostPath() + "/abc/form.html?apply=Apply&aTextField=test", + assertEquals( getHostPath() + "/abc/form.html?aTextField=test&apply=Apply", req.getURL().toExternalForm() ); } Index: HttpUnitTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/HttpUnitTest.java,v retrieving revision 1.17 retrieving revision 1.18 diff -u -r1.17 -r1.18 --- HttpUnitTest.java 2001/10/26 14:00:10 1.17 +++ HttpUnitTest.java 2002/01/14 18:13:45 1.18 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2001, Russell Gold +* Copyright (c) 2000-2002, 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 @@ -99,17 +99,13 @@ } - protected void assertEqualQueries( String query1, String query2 ) { - assertEquals( new QuerySpec( query1 ), new QuerySpec( query2 ) ); - } - - protected void assertEquals( String comment, Object[] expected, Object[] found ) { if (!equals( expected, found )) { fail( comment + " expected: " + asText( expected ) + " but found " + asText( found ) ); } } + private boolean equals( Object[] first, Object[] second ) { if (first.length != second.length) return false; @@ -201,45 +197,6 @@ private String _hostPath; private PseudoServer _server; - - static class QuerySpec { - QuerySpec( String urlString ) { - if (urlString.indexOf( '?' ) < 0) { - _path = urlString; - } else { - _path = urlString.substring( 0, urlString.indexOf( '?' ) ); - } - _fullString = urlString; - - StringTokenizer st = new StringTokenizer( urlString.substring( urlString.indexOf( '?' )+ 1 ), "&" ); - while (st.hasMoreTokens()) _parameters.addElement( st.nextToken() ); - } - - public String toString() { - return _fullString; - } - - public boolean equals( Object o ) { - return getClass().equals( o.getClass() ) && equals( (QuerySpec) o ); - } - - private String _path; - private String _fullString; - private Vector _parameters = new Vector(); - - private boolean equals( QuerySpec o ) { - if (!_path.equals( o._path )) { - return false; - } else if (_parameters.size() != o._parameters.size() ) { - return false; - } else { - for (Enumeration e = o._parameters.elements(); e.hasMoreElements();) { - if (!_parameters.contains( e.nextElement() )) return false; - } - return true; - } - } - } } Index: WebFormTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/WebFormTest.java,v retrieving revision 1.17 retrieving revision 1.18 diff -u -r1.17 -r1.18 --- WebFormTest.java 2002/01/08 23:21:53 1.17 +++ WebFormTest.java 2002/01/14 18:13:45 1.18 @@ -130,8 +130,8 @@ assertTrue( "Did not find parameter with prefix 'nam'", form.hasParameterStartingWithPrefix( "nam" ) ); assertEquals( "Original text area value", "Something", form.getParameterValue( "name" ) ); -// form.setParameter( "name", "Something Else" ); -// assertEquals( "Changed text area value", "Something Else", form.getParameterValue( "name" ) ); + form.setParameter( "name", "Something Else" ); + assertEquals( "Changed text area value", "Something Else", form.getParameterValue( "name" ) ); } @@ -159,6 +159,16 @@ WebRequest request = form.getRequest(); assertEquals( "surprise", request.getParameter( "secret" ) ); assertEquals( "nothing", request.getParameter( "typeless" ) ); + form.setParameter( "secret", "surprise" ); + assertEquals( "surprise", request.getParameter( "secret" ) ); + + try { + form.setParameter( "secret", "illegal" ); + fail( "Should have rejected change to hidden parameter 'secret'" ); + } catch (IllegalRequestParameterException e) { + } + + assertEquals( "surprise", request.getParameter( "secret" ) ); } @@ -200,6 +210,16 @@ assertEquals( "Default name", "", form.getParameterValue( "name" ) ); assertEquals( "Default sex", "female", form.getParameterValue( "sex" ) ); WebRequest request = form.getRequest(); + + form.setParameter( "sex", "neuter" ); + assertEquals( "New value for sex", "neuter", form.getParameterValue( "sex" ) ); + + try { + form.setParameter( "sex", "illegal" ); + fail( "Should have rejected change to radio parameter 'sex'" ); + } catch (IllegalRequestParameterException e) { + } + assertEquals( "Preserved value for sex", "neuter", form.getParameterValue( "sex" ) ); } @@ -220,6 +240,15 @@ WebRequest request = form.getRequest(); assertEquals( "Submitted color", "red", request.getParameter( "color" ) ); assertEquals( "Submitted text", "Sample text", request.getParameter( "text" ) ); + + form.setParameter( "color", "green" ); + assertEquals( "New select value", "green", form.getParameterValue( "color" ) ); + + try { + form.setParameter( "color", new String[] { "red", "green" } ); + fail( "Should have rejected set with multiple values" ); + } catch (IllegalRequestParameterException e) { + } } @@ -242,6 +271,18 @@ WebRequest request = form.getRequest(); assertMatchingSet( "Request defaults", new String[] { "red", "pink" }, request.getParameterValues( "colors" ) ); assertEquals( "URL", getHostPath() + "/ask?colors=red&colors=pink", request.getURL().toExternalForm() ); + + + form.setParameter( "colors", "green" ); + assertEquals( "New select value", new String[] { "green" }, form.getParameterValues( "colors" ) ); + form.setParameter( "colors", new String[] { "blue", "pink" } ); + assertEquals( "New select value", new String[] { "blue", "pink" }, form.getParameterValues( "colors" ) ); + + try { + form.setParameter( "colors", new String[] { "red", "colors" } ); + fail( "Should have rejected set with bad values" ); + } catch (IllegalRequestParameterException e) { + } } @@ -267,7 +308,7 @@ } - public void testCheckboxDefaults() throws Exception { + public void testCheckboxControls() throws Exception { defineWebPage( "Default", "<form method=GET action = \"/ask\">" + "<Input type=checkbox name=ready value=yes checked>" + "<Input type=checkbox name=color value=red checked>" + @@ -283,6 +324,15 @@ assertEquals( "ready state", "yes", form.getParameterValue( "ready" ) ); assertMatchingSet( "default genders allowed", new String[] { "male" }, form.getParameterValues( "gender" ) ); assertMatchingSet( "default colors", new String[] { "red", "blue" }, form.getParameterValues( "color" ) ); + + form.setParameter( "color", "red" ); + assertMatchingSet( "default colors", new String[] { "red" }, form.getParameterValues( "color" ) ); + try { + form.setParameter( "color", new String[] { "red", "purple" } ); + fail( "Should have rejected set with bad values" ); + } catch (IllegalRequestParameterException e) { + } + } |
From: Russell G. <rus...@us...> - 2002-01-14 18:13:49
|
Update of /cvsroot/httpunit/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv25860 Modified Files: .cvsignore build.xml index.html Log Message: Parameter values now stored in WebForm Index: .cvsignore =================================================================== RCS file: /cvsroot/httpunit/httpunit/.cvsignore,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- .cvsignore 2001/12/17 14:53:40 1.1 +++ .cvsignore 2002/01/14 18:13:45 1.2 @@ -1,2 +1,3 @@ build -*.ipr \ No newline at end of file +*.ipr +savejars \ No newline at end of file Index: build.xml =================================================================== RCS file: /cvsroot/httpunit/httpunit/build.xml,v retrieving revision 1.37 retrieving revision 1.38 diff -u -r1.37 -r1.38 --- build.xml 2002/01/09 12:57:47 1.37 +++ build.xml 2002/01/14 18:13:45 1.38 @@ -7,6 +7,10 @@ <property name="Name" value="HttpUnit" /> <property name="version" value="1.3" /> + <property name="debug" value="on" /> + <property name="deprecation" value="off" /> + <property name="optimize" value="off" /> + <property name="src.dir" value="src" /> <property name="tstsrc.dir" value="test" /> <property name="examples.dir" value="examples" /> @@ -64,7 +68,7 @@ <target name="compile" depends="prepare,check_for_optional_packages"> <mkdir dir="${build.classes}" /> <javac srcdir="${src.dir}" destdir="${build.classes}" - debug="on" deprecation="on" optimize="off"> + debug="${debug}" deprecation="${deprecation}" optimize="${optimize}"> <classpath refid="base.classpath" /> <exclude name="**/servletunit/*" unless="jsdk.present" /> </javac> @@ -77,7 +81,7 @@ <target name="testcompile" depends="compile,check_for_optional_packages"> <mkdir dir="${test.classes}" /> <javac srcdir="${tstsrc.dir}" destdir="${test.classes}" - debug="on" deprecation="on" optimize="off"> + debug="on" deprecation="off" optimize="off"> <classpath> <path refid="base.classpath" /> <pathelement location="${build.classes}" /> Index: index.html =================================================================== RCS file: /cvsroot/httpunit/httpunit/index.html,v retrieving revision 1.19 retrieving revision 1.20 diff -u -r1.19 -r1.20 --- index.html 2002/01/09 03:13:13 1.19 +++ index.html 2002/01/14 18:13:45 1.20 @@ -41,8 +41,7 @@ <h2>Where do I get releases?</h2> <blockquote>Releases of HttpUnit are available from <a href="http://sourceforge.net/project/showfiles.php?group_id=6550"> the project download page.</a> -<var:publish><br><var:publish>Other builds are available by <a href="ftp://httpunit.sourceforge.net/pub/httpunit"> -<var:publish>anonymous ftp</a>. +<br>Other builds are available from <a href="http://httpunit.sourceforge.net/prerelease">the pre-release directory</a>. </blockquote> <h2>How do I get help, contribute, give feedback, fix bugs and so on?</h2> |
From: Russell G. <rus...@us...> - 2002-01-14 18:13:49
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv25860/doc Modified Files: release_notes.txt todo.txt Log Message: Parameter values now stored in WebForm Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.76 retrieving revision 1.77 diff -u -r1.76 -r1.77 --- release_notes.txt 2002/01/10 22:18:14 1.76 +++ release_notes.txt 2002/01/14 18:13:45 1.77 @@ -4,8 +4,7 @@ 1. The "_parent" and "_empty" frame targets are not handled correctly 2. The "accept-charset" attribute for forms is ignored; the page content character set is used to encode any response. This behavior matches that currently used by IE and Navigator. - 3. No order is guaranteed for parameters from forms, contrary to the HTML 4.01 spec - 4. No parameter validation is done for requests built from links + 3. No parameter validation is done for requests built from links Limitations: 1. HttpUnit does not support JavaScript @@ -13,7 +12,25 @@ Revision History: +14-Jan-2002 + +Problems fixed: + 1. Parameters are now submitted in the order specified in the form, as long as parameter validation is not turned off. + 2. It is no longer permitted to change hidden parameters with parameter validation enabled. + +Additions: + 1. HttpUnit now handles multiple file form controls with the same name. + 2. It is now possible to set values for a form directly into the form. All such changes will be validated. + These will be used by any requests derived from the form. + +Notes: + 1. Parameter validation is now handled by the form. Requests created from the form while parameter validation is + enabled will share the variable space of the form and therefore be validated. Requests created while validation + is disabled will have their own variable space, which is initialized to that of the form. + 10-Jan-2002 + +Problems fixed: 1. Empty cookies were not being recognized. 12-Dec-2001 Index: todo.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/todo.txt,v retrieving revision 1.23 retrieving revision 1.24 diff -u -r1.23 -r1.24 --- todo.txt 2001/12/03 15:40:33 1.23 +++ todo.txt 2002/01/14 18:13:45 1.24 @@ -7,7 +7,6 @@ o Support IFRAME tag o Support reset button detection o Support _new frame tag -o Send parameters in proper (HTML-file) order o Documentation, Documentation Possibles: |
From: Russell G. <rus...@us...> - 2002-01-10 22:19:01
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv11521/src/com/meterware/httpunit Modified Files: FormControl.java SubmitButton.java UncheckedParameterHolder.java WebForm.java WebRequest.java Log Message: Handle buttons much like other parameters Index: FormControl.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/FormControl.java,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- FormControl.java 2002/01/09 12:57:48 1.4 +++ FormControl.java 2002/01/10 22:18:58 1.5 @@ -149,13 +149,20 @@ } - static FormControl newFormParameter( Node node ) { + static FormControl newFormParameter( WebForm form, Node node ) { if (node.getNodeType() != Node.ELEMENT_NODE) { return null; } else if (node.getNodeName().equals( "textarea" )) { return new TextAreaFormControl( node ); } else if (node.getNodeName().equals( "select" )) { return new SelectionFormControl( node ); + } else if (node.getNodeName().equals( "button" )) { + final String type = NodeUtils.getNodeAttribute( node, "type", "submit" ); + if (type.equalsIgnoreCase( "submit" )) { + return new SubmitButton( form, node ); + } else { + return null; + } } else if (!node.getNodeName().equals( "input" )) { return null; } else { @@ -166,8 +173,8 @@ return new RadioButtonFormControl( node ); } else if (type.equalsIgnoreCase( "checkbox" )) { return new CheckboxFormControl( node ); -// } else if (type.equalsIgnoreCase( "submit" ) || type.equalsIgnoreCase( "image" )) { -// return new SubmitButton( node ); + } else if (type.equalsIgnoreCase( "submit" ) || type.equalsIgnoreCase( "image" )) { + return new SubmitButton( form, node ); } else if (type.equalsIgnoreCase( "file" )) { return new FileSubmitFormControl( node ); } else { Index: SubmitButton.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/SubmitButton.java,v retrieving revision 1.6 retrieving revision 1.7 diff -u -r1.6 -r1.7 --- SubmitButton.java 2002/01/09 12:57:48 1.6 +++ SubmitButton.java 2002/01/10 22:18:58 1.7 @@ -60,7 +60,7 @@ * if the control is 'successful'. **/ public String[] getValues() { - return isDisabled() ? NO_VALUE : toArray( getValueAttribute() ); + return (isDisabled() || !_pressed) ? NO_VALUE : toArray( getValueAttribute() ); } @@ -85,18 +85,24 @@ //------------------------------------------ package members ---------------------------------- - SubmitButton( Node node ) { + SubmitButton( WebForm form, Node node ) { super( node ); _isImageButton = NodeUtils.getNodeAttribute( node, "type" ).equalsIgnoreCase( "image" ); _id = NodeUtils.getNodeAttribute( node, "id" ); } + public void setPressed( boolean pressed ) { + _pressed = pressed; + } + + //------------------------------------------ private members ---------------------------------- private final String _id; private final boolean _isImageButton; + private boolean _pressed; private String[] _value = new String[1]; Index: UncheckedParameterHolder.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/UncheckedParameterHolder.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- UncheckedParameterHolder.java 2002/01/10 15:42:00 1.1 +++ UncheckedParameterHolder.java 2002/01/10 22:18:58 1.2 @@ -47,7 +47,7 @@ _characterSet = source.getCharacterSet(); String[] names = source.getParameterNames(); for (int i = 0; i < names.length; i++) { - if (names[i].length() > 0 && !source.isFileParameter( names[i] )) { + if (!source.isFileParameter( names[i] )) { _parameters.put( names[i], source.getParameterValues( names[i] ) ); } } Index: WebForm.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebForm.java,v retrieving revision 1.40 retrieving revision 1.41 diff -u -r1.40 -r1.41 --- WebForm.java 2002/01/09 23:22:10 1.40 +++ WebForm.java 2002/01/10 22:18:58 1.41 @@ -105,13 +105,14 @@ /** * Returns a map of parameter name to form parameter objects. Each form parameter object represents the set of form - * controls with a particular name. + * controls with a particular name. Unnamed parameters are ignored. */ private Map getFormParameters() { if (_formParameters == null) { _formParameters = new HashMap(); FormControl[] controls = getFormControls(); for (int i = 0; i < controls.length; i++) { + if (controls[i].getName().length() == 0) continue; FormParameter parameter = (FormParameter) _formParameters.get( controls[i].getName() ); if (parameter == null) { parameter = new FormParameter(); @@ -142,20 +143,12 @@ private Vector getSubmitButtonVector() { if (_buttonVector == null) { _buttonVector = new Vector(); - - NodeList nl = ((Element) getNode()).getElementsByTagName( "input" ); - for (int i = 0; i < nl.getLength(); i++) { - if (hasMatchingAttribute( nl.item(i), "type", "submit" ) || hasMatchingAttribute( nl.item(i), "type", "image" )) { - _buttonVector.addElement( new SubmitButton( nl.item(i) ) ); - } + FormControl[] controls = getFormControls(); + for (int i = 0; i < controls.length; i++) { + FormControl control = controls[ i ]; + if (control instanceof SubmitButton) _buttonVector.add( control ); } - nl = ((Element) getNode()).getElementsByTagName( "button" ); - for (int i = 0; i < nl.getLength(); i++) { - if (hasMatchingAttribute( nl.item(i), "type", "submit" ) || hasMatchingAttribute( nl.item(i), "type", "" )) { - _buttonVector.addElement( new SubmitButton( nl.item(i) ) ); - } - } if (_buttonVector.isEmpty()) _buttonVector.addElement( SubmitButton.UNNAMED_BUTTON ); } return _buttonVector; @@ -282,6 +275,12 @@ } } + SubmitButton[] buttons = getSubmitButtons(); + for (int i = 0; i < buttons.length; i++) { + buttons[i].setPressed( false ); + } + button.setPressed( true ); + if (getMethod().equalsIgnoreCase( "post" )) { return new PostMethodWebRequest( this, button ); } else { @@ -488,7 +487,7 @@ private void addFormParametersToList( Node child, Vector list ) { - final FormControl formParameter = FormControl.newFormParameter( child ); + final FormControl formParameter = FormControl.newFormParameter( this, child ); if (formParameter != null) { list.addElement( formParameter ); } else if (child.hasChildNodes()) { Index: WebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebRequest.java,v retrieving revision 1.34 retrieving revision 1.35 diff -u -r1.34 -r1.35 --- WebRequest.java 2002/01/10 15:42:00 1.34 +++ WebRequest.java 2002/01/10 22:18:58 1.35 @@ -243,7 +243,6 @@ setHeaderField( "Referer", sourceForm.getBaseURL().toExternalForm() ); if (button != null && button.getName().length() > 0) { - _parameterCollection.setParameter( button.getName(), button.getValue() ); if (button.isImageButton()) { _imageButtonName = button.getName(); setSubmitPosition( 0, 0 ); |
From: Russell G. <rus...@us...> - 2002-01-10 22:18:16
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv11271/test/com/meterware/httpunit Modified Files: PseudoServerTest.java Log Message: Handle initial empty cookie Index: PseudoServerTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/PseudoServerTest.java,v retrieving revision 1.18 retrieving revision 1.19 diff -u -r1.18 -r1.19 --- PseudoServerTest.java 2001/11/26 14:20:13 1.18 +++ PseudoServerTest.java 2002/01/10 22:18:14 1.19 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2001, Russell Gold +* Copyright (c) 2000-2002, 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 @@ -195,6 +195,7 @@ PseudoServer ps = new PseudoServer(); int port = ps.getConnectedPort(); ps.setResource( resourceName, resourceValue ); + ps.addResourceHeader( resourceName, "Set-Cookie: HSBCLoginFailReason=; path=/" ); ps.addResourceHeader( resourceName, "Set-Cookie: age=12, name= george" ); ps.addResourceHeader( resourceName, "Set-Cookie: type=short" ); ps.addResourceHeader( resourceName, "Set-Cookie: funky=ab$==" ); @@ -207,7 +208,8 @@ WebResponse response = wc.getResponse( request ); assertEquals( "requested resource", resourceValue, response.getText().trim() ); assertEquals( "content type", "text/html", response.getContentType() ); - assertEquals( "number of cookies", 7, wc.getCookieNames().length ); + assertEquals( "number of cookies", 8, wc.getCookieNames().length ); + assertEquals( "cookie 'HSBCLoginFailReason' value", "", wc.getCookieValue( "HSBCLoginFailReason" ) ); assertEquals( "cookie 'age' value", "12", wc.getCookieValue( "age" ) ); assertEquals( "cookie 'name' value", "george", wc.getCookieValue( "name" ) ); assertEquals( "cookie 'type' value", "short", wc.getCookieValue( "type" ) ); |
From: Russell G. <rus...@us...> - 2002-01-10 22:18:16
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv11271/doc Modified Files: release_notes.txt Log Message: Handle initial empty cookie Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.75 retrieving revision 1.76 diff -u -r1.75 -r1.76 --- release_notes.txt 2001/12/12 17:27:21 1.75 +++ release_notes.txt 2002/01/10 22:18:14 1.76 @@ -13,6 +13,9 @@ Revision History: +10-Jan-2002 + 1. Empty cookies were not being recognized. + 12-Dec-2001 Problems fixed: |
From: Russell G. <rus...@us...> - 2002-01-10 22:18:16
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv11271/src/com/meterware/httpunit Modified Files: WebResponse.java Log Message: Handle initial empty cookie Index: WebResponse.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebResponse.java,v retrieving revision 1.57 retrieving revision 1.58 diff -u -r1.57 -r1.58 --- WebResponse.java 2002/01/10 15:42:00 1.57 +++ WebResponse.java 2002/01/10 22:18:13 1.58 @@ -651,10 +651,12 @@ tokensToAdd = ""; } else { tokensToAdd = token + tokensToAdd; - String preceedingToken = (String) tokens.elementAt( i - 1 ); - char lastChar = preceedingToken.charAt( preceedingToken.length() - 1 ); - if (lastChar != '=') { - tokensToAdd = "," + tokensToAdd; + if (i > 0) { + String preceedingToken = (String) tokens.elementAt( i - 1 ); + char lastChar = preceedingToken.charAt( preceedingToken.length() - 1 ); + if (lastChar != '=') { + tokensToAdd = "," + tokensToAdd; + } } } } @@ -667,10 +669,10 @@ * part of a Base64-encoded value. */ private int getEqualsIndex( String token ) { - if (!token.endsWith( "=" )) { + if (!token.endsWith( "==" )) { return token.indexOf( '=' ); } else { - return getEqualsIndex( token.substring( 0, token.length()-1 ) ); + return getEqualsIndex( token.substring( 0, token.length()-2 ) ); } } @@ -711,8 +713,7 @@ } - private boolean isCookieAttribute( String string, - int version ) { + private boolean isCookieAttribute( String string, int version ) { String stringLowercase = string.toLowerCase(); if (version == IETF_RFC2109) { return stringLowercase.equals("path") || @@ -995,7 +996,7 @@ * Returns the value for the specified header field. If no such field is defined, will return null. **/ public String getHeaderField( String fieldName ) { - if (fieldName.equals( "Content-type" )) { + if (fieldName.equalsIgnoreCase( "Content-type" )) { return "text/html; charset=us-ascii"; } else { return null; |
From: Russell G. <rus...@us...> - 2002-01-10 15:42:04
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv24250/src/com/meterware/httpunit Modified Files: GetMethodWebRequest.java HttpUnitOptions.java HttpUnitUtils.java ParameterHolder.java WebRequest.java WebRequestSource.java WebResponse.java Added Files: ParameterProcessor.java UncheckedParameterHolder.java Removed Files: UncheckedParameterCollection.java Log Message: Separated parameter string generation from holder ***** Error reading new file[Errno 2] No such file or directory: 'ParameterProcessor.java' ***** Error reading new file[Errno 2] No such file or directory: 'UncheckedParameterHolder.java' Index: GetMethodWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/GetMethodWebRequest.java,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- GetMethodWebRequest.java 2002/01/09 23:22:10 1.10 +++ GetMethodWebRequest.java 2002/01/10 15:42:00 1.11 @@ -74,10 +74,11 @@ protected String getURLString() { - if (hasNoParameters()) { + final String parameterString = getParameterString(); + if (parameterString.length() == 0) { return super.getURLString(); } else { - return super.getURLString() + "?" + getParameterString(); + return super.getURLString() + "?" + parameterString; } } Index: HttpUnitOptions.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/HttpUnitOptions.java,v retrieving revision 1.14 retrieving revision 1.15 diff -u -r1.14 -r1.15 --- HttpUnitOptions.java 2001/12/03 15:40:33 1.14 +++ HttpUnitOptions.java 2002/01/10 15:42:00 1.15 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2001, Russell Gold +* Copyright (c) 2000-2002, 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 @@ -43,7 +43,7 @@ _matchesIgnoreCase = true; _autoRefresh = false; _redirectDelay = 0; - _characterSet = DEFAULT_CHARACTER_SET; + _characterSet = HttpUnitUtils.DEFAULT_CHARACTER_SET; _contentType = DEFAULT_CONTENT_TYPE; _postIncludesCharset = false; } @@ -53,7 +53,7 @@ * Resets the default character set to the HTTP default encoding. **/ public static void resetDefaultCharacterSet() { - _characterSet = DEFAULT_CHARACTER_SET; + _characterSet = HttpUnitUtils.DEFAULT_CHARACTER_SET; } @@ -284,7 +284,6 @@ private static final String DEFAULT_CONTENT_TYPE = "text/plain"; private static final String DEFAULT_CONTENT_HEADER = DEFAULT_CONTENT_TYPE; - private static final String DEFAULT_CHARACTER_SET = "iso-8859-1"; private static boolean _parserWarningsEnabled; @@ -304,7 +303,7 @@ private static int _redirectDelay; - private static String _characterSet = DEFAULT_CHARACTER_SET; + private static String _characterSet = HttpUnitUtils.DEFAULT_CHARACTER_SET; private static String _contentType = DEFAULT_CONTENT_TYPE; Index: HttpUnitUtils.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/HttpUnitUtils.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- HttpUnitUtils.java 2001/11/27 19:51:27 1.5 +++ HttpUnitUtils.java 2002/01/10 15:42:00 1.6 @@ -28,6 +28,8 @@ public static final int DEFAULT_TEXT_BUFFER_SIZE = 2048; public static final int DEFAULT_BUFFER_SIZE = 128; + static final String DEFAULT_CHARACTER_SET = "iso-8859-1"; + /** * Returns the content type and encoding as a pair of strings. Index: ParameterHolder.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/ParameterHolder.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- ParameterHolder.java 2002/01/08 23:21:53 1.1 +++ ParameterHolder.java 2002/01/10 15:42:00 1.2 @@ -32,6 +32,11 @@ **/ interface ParameterHolder { + /** + * Iterates through the parameters in this holder, recording them in the supplied parameter processor. + **/ + public void recordParameters( ParameterProcessor processor ); + /** * Returns an enumeration of all parameter names in this collection. Index: WebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebRequest.java,v retrieving revision 1.33 retrieving revision 1.34 diff -u -r1.33 -r1.34 --- WebRequest.java 2002/01/09 23:22:10 1.33 +++ WebRequest.java 2002/01/10 15:42:00 1.34 @@ -43,7 +43,7 @@ * A request sent to a web server. **/ abstract -public class WebRequest implements ParameterHolder { +public class WebRequest { /** @@ -238,12 +238,12 @@ protected WebRequest( WebForm sourceForm, SubmitButton button ) { this( sourceForm.getBaseURL(), sourceForm.getRelativeURL(), sourceForm.getTarget() ); _sourceForm = sourceForm; - _parameterCollection = new UncheckedParameterCollection( sourceForm ); + _parameterCollection = new UncheckedParameterHolder( sourceForm ); setHeaderField( "Referer", sourceForm.getBaseURL().toExternalForm() ); if (button != null && button.getName().length() > 0) { - _parameterCollection._parameters.put( button.getName(), button.getValue() ); + _parameterCollection.setParameter( button.getName(), button.getValue() ); if (button.isImageButton()) { _imageButtonName = button.getName(); setSubmitPosition( 0, 0 ); @@ -301,7 +301,7 @@ final protected String getCharacterSet() { if (_sourceForm == null) { - return "iso-8859-1"; + return HttpUnitUtils.DEFAULT_CHARACTER_SET; } else { return _sourceForm.getCharacterSet(); } @@ -327,14 +327,10 @@ final - protected boolean hasNoParameters() { - return _parameterCollection._parameters.size() == 0; - } - - - final protected String getParameterString() { - return _parameterCollection.getParameterString(); + URLEncodedString encoder = new URLEncodedString(); + _parameterCollection.recordParameters( encoder ); + return encoder.getString(); } @@ -347,8 +343,8 @@ void setSubmitPosition( int x, int y ) { if (_imageButtonName == null) return; - _parameterCollection._parameters.put( _imageButtonName + ".x", Integer.toString( x ) ); - _parameterCollection._parameters.put( _imageButtonName + ".y", Integer.toString( y ) ); + _parameterCollection.setParameter( _imageButtonName + ".x", Integer.toString( x ) ); + _parameterCollection.setParameter( _imageButtonName + ".y", Integer.toString( y ) ); } @@ -448,7 +444,7 @@ /** The name of the JSSE class which supports the https protocol. **/ private final static String SSL_PROTOCOL_HANDLER = "com.sun.net.ssl.internal.www.protocol"; - private UncheckedParameterCollection _parameterCollection = new UncheckedParameterCollection(); + private UncheckedParameterHolder _parameterCollection = new UncheckedParameterHolder(); private URL _urlBase; private String _urlString; @@ -575,6 +571,61 @@ } + +class URLEncodedString implements ParameterProcessor { + + private StringBuffer _buffer = new StringBuffer( HttpUnitUtils.DEFAULT_BUFFER_SIZE ); + + private boolean _haveParameters = false; + + + public String getString() { + return _buffer.toString(); + } + + + public void addParameter( String name, String value, String characterSet ) { + if (_haveParameters) _buffer.append( '&' ); + _buffer.append( encode( name, characterSet ) ); + if (value != null) _buffer.append( '=' ).append( encode( value, characterSet ) ); + _haveParameters = true; + } + + + /** + * Returns a URL-encoded version of the string, including all eight bits, unlike URLEncoder, which strips the high bit. + **/ + private String encode( String source, String characterSet ) { + if (characterSet.equalsIgnoreCase( HttpUnitUtils.DEFAULT_CHARACTER_SET )) { + return URLEncoder.encode( source ); + } else { + try { + byte[] rawBytes = source.getBytes( characterSet ); + StringBuffer result = new StringBuffer( 3*rawBytes.length ); + for (int i = 0; i < rawBytes.length; i++) { + int candidate = rawBytes[i] & 0xff; + if (candidate == ' ') { + result.append( '+' ); + } else if ((candidate >= 'A' && candidate <= 'Z') || + (candidate >= 'a' && candidate <= 'z') || + (candidate == '.') || + (candidate >= '0' && candidate <= '9')) { + result.append( (char) rawBytes[i] ); + } else if (candidate < 16) { + result.append( "%0" ).append( Integer.toHexString( candidate ).toUpperCase() ); + } else { + result.append( '%' ).append( Integer.toHexString( candidate ).toUpperCase() ); + } + } + return result.toString(); + } catch (java.io.UnsupportedEncodingException e) { + return "???"; // XXX should pass the exception through as IOException ultimately + } + } + } + + +} //================================ exception class NoSuchParameterException ========================================= Index: WebRequestSource.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebRequestSource.java,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- WebRequestSource.java 2002/01/09 23:22:10 1.3 +++ WebRequestSource.java 2002/01/10 15:42:00 1.4 @@ -90,7 +90,7 @@ * Returns the character set encoding for the request. **/ String getCharacterSet() { - return "iso-8859-1"; + return HttpUnitUtils.DEFAULT_CHARACTER_SET; } Index: WebResponse.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebResponse.java,v retrieving revision 1.56 retrieving revision 1.57 diff -u -r1.56 -r1.57 --- WebResponse.java 2001/11/28 18:25:33 1.56 +++ WebResponse.java 2002/01/10 15:42:00 1.57 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2001, Russell Gold +* Copyright (c) 2000-2002, 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 @@ -838,7 +838,7 @@ private static String _defaultEncoding; - private final static String[] DEFAULT_ENCODING_CANDIDATES = { "iso-8859-1", "us-ascii", "utf-8", "utf8" }; + private final static String[] DEFAULT_ENCODING_CANDIDATES = { HttpUnitUtils.DEFAULT_CHARACTER_SET, "us-ascii", "utf-8", "utf8" }; static String getDefaultEncoding() { if (_defaultEncoding == null) { |