Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.github.kristofa.test.http;
  
  
Mock Http Server which can be used to return upfront defined responses for a set of http requests.

Mock http server will in its default configuration return code 598 in case it receives a request which was not foreseen. In case of an internal exception it will return http returncode 599.

Author(s):
kristof
 
 public class MockHttpServer {
 
     private final static Logger LOGGER = LoggerFactory.getLogger(MockHttpServer.class);
 
     public class ExpectationHandler implements Container {
 
         public ExpectationHandler() {
         }
 
         @Override
         public void handle(final Request reqfinal Response response) {
 
             try {
                 final FullHttpRequest receivedFullRequest = RequestConvertor.convert(req);
                 // We need to copy it because HttpResponseProvider works with HttpRequest, not with FullHttpRequest.
                 // If we did not copy matching would fail.
                 final HttpRequest receivedRequest = new HttpRequestImpl(receivedFullRequest);
                 if (.isDebugEnabled()) {
                     .debug("Got request: " + receivedRequest);
                 }
                 final HttpResponse expectedResponse = .getResponse(receivedRequest);
 
                 if (expectedResponse != null) {
                     if (.isDebugEnabled()) {
                         .debug("Got response for request: " + expectedResponse);
                     }
                     response.setCode(expectedResponse.getHttpCode());
                     if (!StringUtils.isEmpty(expectedResponse.getContentType())) {
                         response.set("Content-Type"expectedResponse.getContentType());
                     }
                     OutputStream body = null;
                     try {
                         body = response.getOutputStream();
                         if (expectedResponse.getContent() != null) {
                             body.write(expectedResponse.getContent());
                         }
                         body.close();
                     } catch (final IOException e) {
                         .error("IOException when getting response content."e);
                     }
                 } else {
                     .error("Did receive an unexpected request:" + receivedRequest);
                     response.setCode();
                     response.set("Content-Type""text/plain;charset=utf-8");
                     PrintStream body;
                     try {
                         body = response.getPrintStream();
                         body.print("Received unexpected request " + receivedRequest);
                         body.close();
                     } catch (final IOException e) {
                         .error("IOException when writing response content."e);
                     }
                 }
             } catch (final Exception e) {
                 .error("Unexpected exception."e);
                 response.setCode();
                 try {
                     response.getPrintStream().close();
                 } catch (final IOException e2) {
                     .error("IOException when writing response content."e2);
                 }
             }
         }
 
         public void verify() throws UnsatisfiedExpectationException {
             .verify();
         }
     }
 
     private ExpectationHandler handler;
     private final HttpResponseProvider responseProvider;
 
     private final int port;
    public static final String GET = "GET";
    public static final String POST = "POST";
    public static final String PUT = "PUT";
    public static final String DELETE = "DELETE";
    private Connection connection;
    private int connectedPort = -1;
    private int noMatchFoundResponseCode = 598;
    private int exceptionResponseCode = 599;

    
Creates a new instance.

Parameters:
port Port on which mock server should operate. If you provide 0 as port number a free port will be choosen for you. You can get the port through getPort()
responseProvider HttpResponseProvider. Should not be null.
    public MockHttpServer(final int portfinal HttpResponseProvider responseProvider) {
        Validate.notNull(responseProvider);
        this. = port;
        this. = responseProvider;
    }

    
Starts the server.

Returns:
Port used by server.
Throws:
java.io.IOException In case starting fails.
    public int start() throws IOException {
         = new ExpectationHandler();
         = new SocketConnection();
        final SocketAddress address = new InetSocketAddress();
        final InetSocketAddress connectedAddress = (InetSocketAddress.connect(address);
         = connectedAddress.getPort();
        return ;
    }
    
    
Return the port used by the server.

Returns:
The port in case the server is successfully started or -1 in case the server has not been started yet.
    public int getPort() {
    	return ;
    }

    
Closes the server.

Throws:
java.io.IOException In case closing fails.
    public void stop() throws IOException {
        .close();
    }

    
Verify if we got all requests as expected.

Throws:
UnsatisfiedExpectationException In case we got unexpected requests or we did not get all requests we expected.
    public void verify() throws UnsatisfiedExpectationException {
        .verify();
    }

    
Allows you to set a custom response code to be returned when no matching response is found.

If not set the default code is 598.

Parameters:
code HTTP response code to return when no matching response is found.
    public void setNoMatchFoundResponseCode(final int code) {
         = code;
    }

    
Allows to set a custom response code to be returned when an unexpected exception happens.

If not set the default code is 599.

Parameters:
code HTTP response code to return when an unexpected exception happens.
    public void setExceptionResponseCode(final int code) {
         = code;
    }
New to GrepCode? Check out our FAQ X