if (null != running.get(port)) {
throw new ServiceException("Server already running on port " + port);
}
final Undertow server = Undertow.builder()
.addHttpListener(port, host)
.setHandler(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final ResourceDefinition endpoint = getEndpoint(mock, exchange);
if (null == endpoint) {
LOGGER.info("Sending HTTP {} for request: {}", StatusCodes.NOT_FOUND, exchange.getRequestPath());
exchange.setResponseCode(StatusCodes.NOT_FOUND);
} else {
if (exchange.getQueryParameters().containsKey("blueprint")
&& settingsService.isDocumentationEnabled()) {
// documentation
LOGGER.info("Sending documentation for mock request: {}", exchange.getRequestPath());
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
exchange.getResponseSender().send(parsingService.parseMarkdownFile(mock.getBlueprintFile()));
} else {
// match request
final RequestDefinition request;
try {
request = matchRequest(exchange, endpoint);
} catch (ResourceNotFoundException e) {
LOGGER.info("Sending HTTP {} for request: {}", StatusCodes.NOT_FOUND, exchange.getRequestPath());
exchange.setResponseCode(StatusCodes.NOT_FOUND);
return;
} catch (MethodNotAllowedException e) {
LOGGER.info("Sending HTTP {} for request: {}", StatusCodes.METHOD_NOT_ALLOWED, exchange.getRequestPath());
exchange.setResponseCode(StatusCodes.METHOD_NOT_ALLOWED);
return;
}
// match response
final ResponseDefinition response = matchResponse(exchange, endpoint, request);
final int responseCode = response.getCode();
LOGGER.info("Sending HTTP {} for mock request: {}", responseCode,
exchange.getRequestPath());
exchange.setResponseCode(responseCode);
populateResponseHeaders(response, exchange.getResponseHeaders());
// body
final String body = response.getBody();
exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "" + (null != body ? body.length() : 0));
exchange.getResponseSender().send(body);
}
}
}
}).build();
server.start();
LOGGER.info("Started mock server on host {} and port {} for mock {}", host, port, mock);
// remember
running.put(port, server);