[Webtest] ApplyFilters

Marc Guillemot webtest@lists.canoo.com
Mon, 29 May 2006 23:46:04 -0700 (PDT)


Hi Lawrence,

filter can't be applied before response is parsed. To achieve this, you can
change the WebConnection of the WebClient to fix the response before it
comes to the WebClient. Below is a code example (here to change all
occurences of "'User ID" to "foo User foo Id"). Next release of htmlunit
will probably provide an easy to extend base class to perform changes on a
received response before it gets parsed.

Marc.

<groovy>
import com.gargoylesoftware.htmlunit.*

def webClient = (WebClient) step.context.webClient

class FixerWebConnection extends WebConnection
{
	WebConnection wrappedConnection
	
	FixerWebConnection(WebConnection _wrappedConnection)
	{
		super(_wrappedConnection.webClient)
		wrappedConnection = _wrappedConnection
	}

	WebResponse getResponse(WebRequestSettings settings)
	{
		WebResponse response = wrappedConnection.getResponse(settings)
		
		def text = response.getContentAsString()
		if (text.contains('User ID'))
		{
			text = text.replaceAll('User ID', 'foo User foo Id')
			def newResponseData = new
WebResponseData(TextUtil.stringToByteArray(text), response.statusCode,
response.statusMessage, response.responseHeaders)
			response = new WebResponseImpl(newResponseData, response.url,
response.requestMethod, response.loadTimeInMilliSeconds)
		}
		return response
	}

	org.apache.commons.httpclient.HttpState getStateForUrl(URL url) { return
wrappedConnection.getStateForUrl(url) }
}

webClient.webConnection = new FixerWebConnection((WebConnection)
webClient.webConnection)

</groovy>
--
View this message in context: http://www.nabble.com/ApplyFilters-t1697243.html#a4621875
Sent from the WebTest forum at Nabble.com.