EmbeddedJettyProbe – a simple tool for checking your HTTP requests

sagyr@wix.com | November 19th 2012 | Java

Hi all,

EmbeddedJettyProbe is a small tool for examining the contents of  HttpRequests that arrive at an embedded Jetty instance.

This is useful for tests that need to validate the behavior of an http client.

For example (scala):

server = new EmbeddedJettyProbe(9080)

server.start

// .... send a request to url: http://localhost:9080/

requestArrivingAtServer =  server.probeForRequest(5, TimeUnit.SECONDS)

server.stop

In the above example requestArrivingAtServer has 2 properties: body and headers which contain the data from the HttpRequest arriving at the server.

You can for example check the request body using:

assertThat(requestArrivingAtServer.body,  is(".. some string .. "))

Here is the implementation:

case class ServerRequest (headers: Map[String,String], body: String)

class EmbeddedJettyProbe(port: Int) {
 val incoming = new ArrayBlockingQueue[ServerRequest](1);
 val server = new Server(9080)
 val handler = new AbstractHandler {

def handle(target: String, request: HttpServletRequest, response: HttpServletResponse, dispatch: Int) {
 request.asInstanceOf[Request].setHandled(true)
 incoming.add(ServerRequest(headers(request), body(request)))
 }

def body(request: HttpServletRequest): String = {
 Source.fromInputStream(request.getInputStream).getLines().mkString("\n")
 }

def headers(request: HttpServletRequest): Map[String, String] = {
 request.getHeaderNames
 .map(_.asInstanceOf[String]).map( headerName => ( headerName -> request.getHeader(headerName))).toMap
 }
 }
 server.setHandler(handler);

def start = server.start()
 def stop = {
 server.stop
 server.join
 }

def probeForRequest(n: Long, unit: TimeUnit) = incoming.poll(n,unit)
}
It uses an ArrayBlockingQueue as a means to pass the incoming request between the  Jetty request handler thread and the test thread.

					

Tags: ,
By sagyr@wix.com
Wix

Leave a Reply

We are always looking for excellent people. Browse Jobs Here   

At Wix Engineering we develop some of the most innovative cloud-based web applications that influence our 80+ million users worldwide.

Have any questions? Email academy@wix.com.

Find out what’s coming up at Wix Engineering:

Subscribe to our newsletter for updates, events and more.