A very simple HTTP server that binds to a port and responds to all requests
with a predefined response.
| Method from org.apache.cactus.integration.ant.container.MockHttpServer Detail: |
public void expectMethod(String theMethod) {
this.expectedMethod = theMethod;
}
Advise the server to expect a specific HTTP method in requests. |
public void expectRequestCount(int theRequestCount) {
this.expectedRequestCount = theRequestCount;
}
Advise the server to expect a specific number of requests. |
public void expectUri(String theUri) {
this.expectedUri = theUri;
}
Advise the server to expect a specific request URI in requests. |
public static int findUnusedLocalPort(String theHost,
int theLowest,
int theHighest) throws IOException {
final Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < 10; i++)
{
int port = (int)
(random.nextFloat() * (theHighest - theLowest)) + theLowest;
Socket s = null;
try
{
s = new Socket(theHost, port);
}
catch (ConnectException e)
{
return port;
}
finally
{
if (s != null)
{
s.close();
}
}
}
return -1;
}
Returns a free port number on the specified host within the given range. |
public int getPort() {
return this.port;
}
Returns the port number the server is listening on. |
public boolean isStopped() {
return this.stopFlag;
}
Returns whether the server is stopped (or about to stop, to be precise). |
public void run() {
if (this.response == null)
{
throw new IllegalStateException("Response content not set");
}
try
{
ServerSocket serverSocket = new ServerSocket(port);
while (!this.stopFlag)
{
Socket socket = serverSocket.accept();
try
{
if (!this.stopFlag)
{
processRequest(socket);
}
}
catch (IOException ioe)
{
this.log.error("Couldn't process request", ioe);
}
finally
{
socket.close();
}
}
serverSocket.close();
}
catch (IOException ioe)
{
this.log.error("Problem with server socket", ioe);
}
}
The main server thread. The server will wait for connections until it
receives a special request containing the string 'SHUTDOWN'. |
public void setResponse(String theResponse) {
this.response = theResponse;
}
Sets the content of the request to send back on any request. |
public void stop() {
this.stopFlag = true;
try
{
Socket sock = new Socket("localhost", this.port);
sock.getOutputStream().write("SHUTDOWN\n".getBytes());
}
catch (IOException ioe)
{
this.log.error("Error while trying to stop", ioe);
}
}
|
public void verify() {
if (this.expectedRequestCount >= 0)
{
Assert.assertTrue("Expected " + this.expectedRequestCount
+ " requests, but got " + this.actualRequestCount,
this.expectedRequestCount == this.actualRequestCount);
}
if (this.expectedMethod != null)
{
Assert.assertEquals(this.expectedMethod, this.actualMethod);
}
if (this.expectedUri != null)
{
Assert.assertEquals(this.expectedUri, this.actualUri);
}
}
Verifies whether the requests sent to the server matched those expected. |