Search in sources :

Example 1 with ResponseWriter

use of org.mockserver.responsewriter.ResponseWriter in project mockserver by mock-server.

the class HttpState method handle.

public boolean handle(HttpRequest request, ResponseWriter responseWriter, boolean warDeployment) {
    request.withLogCorrelationId(UUIDService.getUUID());
    setPort(request);
    if (MockServerLogger.isEnabled(Level.TRACE)) {
        mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.TRACE).setHttpRequest(request).setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT).setArguments(request));
    }
    if (request.matches("PUT")) {
        CompletableFuture<Boolean> canHandle = new CompletableFuture<>();
        if (request.matches("PUT", PATH_PREFIX + "/expectation", "/expectation")) {
            if (controlPlaneRequestAuthenticated(request, responseWriter)) {
                List<Expectation> upsertedExpectations = new ArrayList<>();
                for (Expectation expectation : getExpectationSerializer().deserializeArray(request.getBodyAsJsonOrXmlString(), false)) {
                    if (!warDeployment || validateSupportedFeatures(expectation, request, responseWriter)) {
                        upsertedExpectations.addAll(add(expectation));
                    }
                }
                responseWriter.writeResponse(request, response().withStatusCode(CREATED.code()).withBody(getExpectationSerializer().serialize(upsertedExpectations), MediaType.JSON_UTF_8), true);
            }
            canHandle.complete(true);
        } else if (request.matches("PUT", PATH_PREFIX + "/openapi", "/openapi")) {
            if (controlPlaneRequestAuthenticated(request, responseWriter)) {
                try {
                    List<Expectation> upsertedExpectations = new ArrayList<>();
                    for (OpenAPIExpectation openAPIExpectation : getOpenAPIExpectationSerializer().deserializeArray(request.getBodyAsJsonOrXmlString(), false)) {
                        upsertedExpectations.addAll(add(openAPIExpectation));
                    }
                    responseWriter.writeResponse(request, response().withStatusCode(CREATED.code()).withBody(getExpectationSerializer().serialize(upsertedExpectations), MediaType.JSON_UTF_8), true);
                } catch (IllegalArgumentException iae) {
                    mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setMessageFormat("exception handling request for open api expectation:{}error:{}").setArguments(request, iae.getMessage()).setThrowable(iae));
                    responseWriter.writeResponse(request, BAD_REQUEST, (!iae.getMessage().startsWith(OPEN_API_LOAD_ERROR) ? OPEN_API_LOAD_ERROR + (isNotBlank(iae.getMessage()) ? ", " : "") : "") + iae.getMessage(), MediaType.create("text", "plain").toString());
                }
            }
            canHandle.complete(true);
        } else if (request.matches("PUT", PATH_PREFIX + "/clear", "/clear")) {
            if (controlPlaneRequestAuthenticated(request, responseWriter)) {
                clear(request);
                responseWriter.writeResponse(request, OK);
            }
            canHandle.complete(true);
        } else if (request.matches("PUT", PATH_PREFIX + "/reset", "/reset")) {
            if (controlPlaneRequestAuthenticated(request, responseWriter)) {
                reset();
                responseWriter.writeResponse(request, OK);
            }
            canHandle.complete(true);
        } else if (request.matches("PUT", PATH_PREFIX + "/retrieve", "/retrieve")) {
            if (controlPlaneRequestAuthenticated(request, responseWriter)) {
                responseWriter.writeResponse(request, retrieve(request), true);
            }
            canHandle.complete(true);
        } else if (request.matches("PUT", PATH_PREFIX + "/verify", "/verify")) {
            if (controlPlaneRequestAuthenticated(request, responseWriter)) {
                verify(getVerificationSerializer().deserialize(request.getBodyAsJsonOrXmlString()), result -> {
                    if (isEmpty(result)) {
                        responseWriter.writeResponse(request, ACCEPTED);
                    } else {
                        responseWriter.writeResponse(request, NOT_ACCEPTABLE, result, MediaType.create("text", "plain").toString());
                    }
                    canHandle.complete(true);
                });
            } else {
                canHandle.complete(true);
            }
        } else if (request.matches("PUT", PATH_PREFIX + "/verifySequence", "/verifySequence")) {
            if (controlPlaneRequestAuthenticated(request, responseWriter)) {
                verify(getVerificationSequenceSerializer().deserialize(request.getBodyAsJsonOrXmlString()), result -> {
                    if (isEmpty(result)) {
                        responseWriter.writeResponse(request, ACCEPTED);
                    } else {
                        responseWriter.writeResponse(request, NOT_ACCEPTABLE, result, MediaType.create("text", "plain").toString());
                    }
                    canHandle.complete(true);
                });
            } else {
                canHandle.complete(true);
            }
        } else {
            canHandle.complete(false);
        }
        try {
            return canHandle.get(configuration.maxFutureTimeoutInMillis(), MILLISECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException ex) {
            mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setMessageFormat("exception handling request:{}error:{}").setArguments(request, ex.getMessage()).setThrowable(ex));
            return false;
        }
    } else {
        return false;
    }
}
Also used : LocalCallbackRegistry(org.mockserver.closurecallback.websocketregistry.LocalCallbackRegistry) WebSocketClientRegistry(org.mockserver.closurecallback.websocketregistry.WebSocketClientRegistry) Arrays(java.util.Arrays) AuthenticationException(org.mockserver.authentication.AuthenticationException) UUIDService(org.mockserver.uuid.UUIDService) TRACE(org.slf4j.event.Level.TRACE) TimeoutException(java.util.concurrent.TimeoutException) CompletableFuture(java.util.concurrent.CompletableFuture) StringUtils(org.apache.commons.lang3.StringUtils) NEW_LINE(org.mockserver.character.Character.NEW_LINE) ArrayList(java.util.ArrayList) HttpRequest.request(org.mockserver.model.HttpRequest.request) Future(java.util.concurrent.Future) Scheduler(org.mockserver.scheduler.Scheduler) OpenAPIConverter(org.mockserver.openapi.OpenAPIConverter) Level(org.slf4j.event.Level) MemoryMonitoring(org.mockserver.memory.MemoryMonitoring) CLEARED(org.mockserver.log.model.LogEntry.LogMessageType.CLEARED) Cause(org.mockserver.mock.listeners.MockServerMatcherNotifier.Cause) HOST(io.netty.handler.codec.http.HttpHeaderNames.HOST) MockServerEventLog(org.mockserver.log.MockServerEventLog) OPEN_API_LOAD_ERROR(org.mockserver.openapi.OpenAPIParser.OPEN_API_LOAD_ERROR) UTF_8(java.nio.charset.StandardCharsets.UTF_8) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) AuthenticationHandler(org.mockserver.authentication.AuthenticationHandler) ExpectationFileSystemPersistence(org.mockserver.persistence.ExpectationFileSystemPersistence) Verification(org.mockserver.verify.Verification) Collectors(java.util.stream.Collectors) ExpectationFileWatcher(org.mockserver.persistence.ExpectationFileWatcher) org.mockserver.serialization(org.mockserver.serialization) RETRIEVED(org.mockserver.log.model.LogEntry.LogMessageType.RETRIEVED) ExecutionException(java.util.concurrent.ExecutionException) Consumer(java.util.function.Consumer) RECEIVED_REQUEST_MESSAGE_FORMAT(org.mockserver.log.model.LogEntryMessages.RECEIVED_REQUEST_MESSAGE_FORMAT) Configuration(org.mockserver.configuration.Configuration) List(java.util.List) org.mockserver.model(org.mockserver.model) ResponseWriter(org.mockserver.responsewriter.ResponseWriter) ExpectationToJavaSerializer(org.mockserver.serialization.java.ExpectationToJavaSerializer) LogEntry(org.mockserver.log.model.LogEntry) VisibleForTesting(com.google.common.annotations.VisibleForTesting) MockServerLogger(org.mockserver.logging.MockServerLogger) ExpectationInitializerLoader(org.mockserver.server.initialize.ExpectationInitializerLoader) Collections(java.util.Collections) SECONDS(java.util.concurrent.TimeUnit.SECONDS) HttpResponse.response(org.mockserver.model.HttpResponse.response) VerificationSequence(org.mockserver.verify.VerificationSequence) ArrayList(java.util.ArrayList) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) List(java.util.List) ExecutionException(java.util.concurrent.ExecutionException) LogEntry(org.mockserver.log.model.LogEntry) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with ResponseWriter

use of org.mockserver.responsewriter.ResponseWriter in project mockserver by mock-server.

the class ProxyServlet method service.

@Override
public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
    ResponseWriter responseWriter = new ServletResponseWriter(configuration(), new MockServerLogger(), httpServletResponse);
    HttpRequest request = null;
    try {
        request = httpServletRequestToMockServerRequestDecoder.mapHttpServletRequestToMockServerRequest(httpServletRequest);
        final String hostHeader = request.getFirstHeader(HOST.toString());
        if (isNotBlank(hostHeader)) {
            scheduler.submit(() -> configuration.addSubjectAlternativeName(hostHeader));
        }
        if (!httpStateHandler.handle(request, responseWriter, true)) {
            if (request.getPath().getValue().equals("/_mockserver_callback_websocket")) {
                responseWriter.writeResponse(request, NOT_IMPLEMENTED, "ExpectationResponseCallback, ExpectationForwardCallback or ExpectationForwardAndResponseCallback is not supported by MockServer deployed as a WAR", "text/plain");
            } else if (request.matches("PUT", PATH_PREFIX + "/status", "/status") || isNotBlank(configuration.livenessHttpGetPath()) && request.matches("GET", configuration.livenessHttpGetPath())) {
                responseWriter.writeResponse(request, OK, portBindingSerializer.serialize(portBinding(httpServletRequest.getLocalPort())), "application/json");
            } else if (request.matches("PUT", PATH_PREFIX + "/bind", "/bind")) {
                responseWriter.writeResponse(request, NOT_IMPLEMENTED);
            } else if (request.matches("PUT", PATH_PREFIX + "/stop", "/stop")) {
                responseWriter.writeResponse(request, NOT_IMPLEMENTED);
            } else {
                String portExtension = "";
                if (!(httpServletRequest.getLocalPort() == 443 && httpServletRequest.isSecure() || httpServletRequest.getLocalPort() == 80)) {
                    portExtension = ":" + httpServletRequest.getLocalPort();
                }
                actionHandler.processAction(request, responseWriter, null, ImmutableSet.of(httpServletRequest.getLocalAddr() + portExtension, "localhost" + portExtension, "127.0.0.1" + portExtension), true, true);
            }
        }
    } catch (IllegalArgumentException iae) {
        mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setHttpRequest(request).setMessageFormat("exception processing request:{}error:{}").setArguments(request, iae.getMessage()));
        // send request without API CORS headers
        responseWriter.writeResponse(request, BAD_REQUEST, iae.getMessage(), MediaType.create("text", "plain").toString());
    } catch (Exception e) {
        mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setHttpRequest(request).setMessageFormat("exception processing " + request).setThrowable(e));
        responseWriter.writeResponse(request, response().withStatusCode(BAD_REQUEST.code()).withBody(e.getMessage()), true);
    }
}
Also used : HttpRequest(org.mockserver.model.HttpRequest) ServletResponseWriter(org.mockserver.servlet.responsewriter.ServletResponseWriter) ResponseWriter(org.mockserver.responsewriter.ResponseWriter) MockServerLogger(org.mockserver.logging.MockServerLogger) ServletResponseWriter(org.mockserver.servlet.responsewriter.ServletResponseWriter) LogEntry(org.mockserver.log.model.LogEntry)

Example 3 with ResponseWriter

use of org.mockserver.responsewriter.ResponseWriter in project mockserver by mock-server.

the class HttpActionHandlerTest method shouldProcessForwardObjectCallbackAction.

@Test
public void shouldProcessForwardObjectCallbackAction() {
    // given
    HttpObjectCallback callback = new HttpObjectCallback().withClientId("some_forward_client_id");
    expectation = new Expectation(request).thenForward(callback);
    when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);
    ResponseWriter mockResponseWriter = mock(ResponseWriter.class);
    // when
    actionHandler.processAction(request, mockResponseWriter, null, new HashSet<>(), false, true);
    // then
    verify(mockHttpForwardObjectCallbackActionHandler).handle(any(HttpActionHandler.class), same(callback), same(request), same(mockResponseWriter), eq(true), any(Runnable.class));
    verify(mockServerLogger).logEvent(new LogEntry().setType(RECEIVED_REQUEST).setLogLevel(Level.INFO).setHttpRequest(request).setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT).setArguments(request));
}
Also used : ResponseWriter(org.mockserver.responsewriter.ResponseWriter) Expectation(org.mockserver.mock.Expectation) LogEntry(org.mockserver.log.model.LogEntry)

Example 4 with ResponseWriter

use of org.mockserver.responsewriter.ResponseWriter in project mockserver by mock-server.

the class HttpForwardObjectCallbackActionHandlerTest method shouldReturnNotFound.

@Test
public void shouldReturnNotFound() throws ExecutionException, InterruptedException {
    // given
    HttpActionHandler mockActionHandler = mock(HttpActionHandler.class);
    HttpState mockHttpStateHandler = mock(HttpState.class);
    WebSocketClientRegistry mockWebSocketClientRegistry = mock(WebSocketClientRegistry.class);
    HttpObjectCallback httpObjectCallback = new HttpObjectCallback().withClientId("some_clientId");
    HttpRequest request = request().withBody("some_body");
    ResponseWriter mockResponseWriter = mock(ResponseWriter.class);
    when(mockHttpStateHandler.getWebSocketClientRegistry()).thenReturn(mockWebSocketClientRegistry);
    when(mockHttpStateHandler.getMockServerLogger()).thenReturn(new MockServerLogger());
    when(mockWebSocketClientRegistry.sendClientMessage(eq("some_clientId"), any(HttpRequest.class), isNull())).thenReturn(false);
    // when
    new HttpForwardObjectCallbackActionHandler(mockHttpStateHandler, null).handle(mockActionHandler, httpObjectCallback, request, mockResponseWriter, true, null);
    // then
    verify(mockWebSocketClientRegistry).registerForwardCallbackHandler(any(String.class), any(WebSocketRequestCallback.class));
    verify(mockWebSocketClientRegistry).sendClientMessage(eq("some_clientId"), any(HttpRequest.class), isNull());
    ArgumentCaptor<HttpForwardActionResult> httpForwardActionResultArgumentCaptor = ArgumentCaptor.forClass(HttpForwardActionResult.class);
    verify(mockActionHandler).writeForwardActionResponse(httpForwardActionResultArgumentCaptor.capture(), same(mockResponseWriter), same(request), same(httpObjectCallback), eq(true));
    assertThat(httpForwardActionResultArgumentCaptor.getValue().getHttpResponse().get(), is(notFoundResponse()));
}
Also used : HttpRequest(org.mockserver.model.HttpRequest) HttpObjectCallback(org.mockserver.model.HttpObjectCallback) ResponseWriter(org.mockserver.responsewriter.ResponseWriter) MockServerLogger(org.mockserver.logging.MockServerLogger) WebSocketRequestCallback(org.mockserver.closurecallback.websocketregistry.WebSocketRequestCallback) WebSocketClientRegistry(org.mockserver.closurecallback.websocketregistry.WebSocketClientRegistry) HttpState(org.mockserver.mock.HttpState) Test(org.junit.Test)

Example 5 with ResponseWriter

use of org.mockserver.responsewriter.ResponseWriter in project mockserver by mock-server.

the class HttpResponseObjectCallbackActionHandlerTest method shouldReturnNotFound.

@Test
public void shouldReturnNotFound() {
    // given
    HttpActionHandler mockActionHandler = mock(HttpActionHandler.class);
    HttpState mockHttpStateHandler = mock(HttpState.class);
    WebSocketClientRegistry mockWebSocketClientRegistry = mock(WebSocketClientRegistry.class);
    HttpObjectCallback httpObjectCallback = new HttpObjectCallback().withClientId("some_clientId");
    HttpRequest request = request().withBody("some_body");
    ResponseWriter mockResponseWriter = mock(ResponseWriter.class);
    when(mockHttpStateHandler.getWebSocketClientRegistry()).thenReturn(mockWebSocketClientRegistry);
    when(mockHttpStateHandler.getMockServerLogger()).thenReturn(new MockServerLogger());
    when(mockWebSocketClientRegistry.sendClientMessage(eq("some_clientId"), any(HttpRequest.class), isNull())).thenReturn(false);
    // when
    new HttpResponseObjectCallbackActionHandler(mockHttpStateHandler).handle(mockActionHandler, httpObjectCallback, request, mockResponseWriter, true, null);
    // then
    verify(mockWebSocketClientRegistry).registerResponseCallbackHandler(any(String.class), any(WebSocketResponseCallback.class));
    verify(mockWebSocketClientRegistry).sendClientMessage(eq("some_clientId"), any(HttpRequest.class), isNull());
    verify(mockActionHandler).writeResponseActionResponse(notFoundResponse().removeHeader(WEB_SOCKET_CORRELATION_ID_HEADER_NAME), mockResponseWriter, request, httpObjectCallback, true);
}
Also used : HttpRequest(org.mockserver.model.HttpRequest) HttpObjectCallback(org.mockserver.model.HttpObjectCallback) ResponseWriter(org.mockserver.responsewriter.ResponseWriter) MockServerLogger(org.mockserver.logging.MockServerLogger) WebSocketClientRegistry(org.mockserver.closurecallback.websocketregistry.WebSocketClientRegistry) HttpState(org.mockserver.mock.HttpState) WebSocketResponseCallback(org.mockserver.closurecallback.websocketregistry.WebSocketResponseCallback) Test(org.junit.Test)

Aggregations

ResponseWriter (org.mockserver.responsewriter.ResponseWriter)12 LogEntry (org.mockserver.log.model.LogEntry)8 MockServerLogger (org.mockserver.logging.MockServerLogger)7 HttpRequest (org.mockserver.model.HttpRequest)6 WebSocketClientRegistry (org.mockserver.closurecallback.websocketregistry.WebSocketClientRegistry)5 Test (org.junit.Test)4 Expectation (org.mockserver.mock.Expectation)4 HttpState (org.mockserver.mock.HttpState)4 HttpObjectCallback (org.mockserver.model.HttpObjectCallback)4 List (java.util.List)2 WebSocketRequestCallback (org.mockserver.closurecallback.websocketregistry.WebSocketRequestCallback)2 WebSocketResponseCallback (org.mockserver.closurecallback.websocketregistry.WebSocketResponseCallback)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 HOST (io.netty.handler.codec.http.HttpHeaderNames.HOST)1 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)1 BindException (java.net.BindException)1 InetSocketAddress (java.net.InetSocketAddress)1 UTF_8 (java.nio.charset.StandardCharsets.UTF_8)1 ArrayList (java.util.ArrayList)1