Search in sources :

Example 1 with NEW_LINE

use of org.mockserver.character.Character.NEW_LINE in project mockserver by mock-server.

the class HttpState method retrieve.

public HttpResponse retrieve(HttpRequest request) {
    final String logCorrelationId = UUIDService.getUUID();
    CompletableFuture<HttpResponse> httpResponseFuture = new CompletableFuture<>();
    HttpResponse response = response().withStatusCode(OK.code());
    if (request != null) {
        try {
            final RequestDefinition requestDefinition = isNotBlank(request.getBodyAsString()) ? getRequestDefinitionSerializer().deserialize(request.getBodyAsJsonOrXmlString()) : request();
            requestDefinition.withLogCorrelationId(logCorrelationId);
            Format format = Format.valueOf(defaultIfEmpty(request.getFirstQueryStringParameter("format").toUpperCase(), "JSON"));
            RetrieveType type = RetrieveType.valueOf(defaultIfEmpty(request.getFirstQueryStringParameter("type").toUpperCase(), "REQUESTS"));
            switch(type) {
                case LOGS:
                    {
                        mockServerLog.retrieveMessageLogEntries(requestDefinition, (List<LogEntry> logEntries) -> {
                            StringBuilder stringBuffer = new StringBuilder();
                            for (int i = 0; i < logEntries.size(); i++) {
                                LogEntry messageLogEntry = logEntries.get(i);
                                stringBuffer.append(messageLogEntry.getTimestamp()).append(" - ").append(messageLogEntry.getMessage());
                                if (i < logEntries.size() - 1) {
                                    stringBuffer.append(LOG_SEPARATOR);
                                }
                            }
                            stringBuffer.append(NEW_LINE);
                            response.withBody(stringBuffer.toString(), MediaType.PLAIN_TEXT_UTF_8);
                            if (MockServerLogger.isEnabled(Level.INFO)) {
                                mockServerLogger.logEvent(new LogEntry().setType(RETRIEVED).setLogLevel(Level.INFO).setCorrelationId(logCorrelationId).setHttpRequest(requestDefinition).setMessageFormat("retrieved logs that match:{}").setArguments(requestDefinition));
                            }
                            httpResponseFuture.complete(response);
                        });
                        break;
                    }
                case REQUESTS:
                    {
                        LogEntry logEntry = new LogEntry().setType(RETRIEVED).setLogLevel(Level.INFO).setCorrelationId(logCorrelationId).setHttpRequest(requestDefinition).setMessageFormat("retrieved requests in " + format.name().toLowerCase() + " that match:{}").setArguments(requestDefinition);
                        switch(format) {
                            case JAVA:
                                mockServerLog.retrieveRequests(requestDefinition, requests -> {
                                    response.withBody(getRequestDefinitionSerializer().serialize(requests), MediaType.create("application", "java").withCharset(UTF_8));
                                    mockServerLogger.logEvent(logEntry);
                                    httpResponseFuture.complete(response);
                                });
                                break;
                            case JSON:
                                mockServerLog.retrieveRequests(requestDefinition, requests -> {
                                    response.withBody(getRequestDefinitionSerializer().serialize(true, requests), MediaType.JSON_UTF_8);
                                    mockServerLogger.logEvent(logEntry);
                                    httpResponseFuture.complete(response);
                                });
                                break;
                            case LOG_ENTRIES:
                                mockServerLog.retrieveRequestLogEntries(requestDefinition, logEntries -> {
                                    response.withBody(getLogEntrySerializer().serialize(logEntries), MediaType.JSON_UTF_8);
                                    mockServerLogger.logEvent(logEntry);
                                    httpResponseFuture.complete(response);
                                });
                                break;
                        }
                        break;
                    }
                case REQUEST_RESPONSES:
                    {
                        LogEntry logEntry = new LogEntry().setType(RETRIEVED).setLogLevel(Level.INFO).setCorrelationId(logCorrelationId).setHttpRequest(requestDefinition).setMessageFormat("retrieved requests and responses in " + format.name().toLowerCase() + " that match:{}").setArguments(requestDefinition);
                        switch(format) {
                            case JAVA:
                                response.withBody("JAVA not supported for REQUEST_RESPONSES", MediaType.create("text", "plain").withCharset(UTF_8));
                                mockServerLogger.logEvent(logEntry);
                                httpResponseFuture.complete(response);
                                break;
                            case JSON:
                                mockServerLog.retrieveRequestResponses(requestDefinition, httpRequestAndHttpResponses -> {
                                    response.withBody(getHttpRequestResponseSerializer().serialize(httpRequestAndHttpResponses), MediaType.JSON_UTF_8);
                                    mockServerLogger.logEvent(logEntry);
                                    httpResponseFuture.complete(response);
                                });
                                break;
                            case LOG_ENTRIES:
                                mockServerLog.retrieveRequestResponseMessageLogEntries(requestDefinition, logEntries -> {
                                    response.withBody(getLogEntrySerializer().serialize(logEntries), MediaType.JSON_UTF_8);
                                    mockServerLogger.logEvent(logEntry);
                                    httpResponseFuture.complete(response);
                                });
                                break;
                        }
                        break;
                    }
                case RECORDED_EXPECTATIONS:
                    {
                        LogEntry logEntry = new LogEntry().setType(RETRIEVED).setLogLevel(Level.INFO).setCorrelationId(logCorrelationId).setHttpRequest(requestDefinition).setMessageFormat("retrieved recorded expectations in " + format.name().toLowerCase() + " that match:{}").setArguments(requestDefinition);
                        switch(format) {
                            case JAVA:
                                mockServerLog.retrieveRecordedExpectations(requestDefinition, requests -> {
                                    response.withBody(getExpectationToJavaSerializer().serialize(requests), MediaType.create("application", "java").withCharset(UTF_8));
                                    mockServerLogger.logEvent(logEntry);
                                    httpResponseFuture.complete(response);
                                });
                                break;
                            case JSON:
                                mockServerLog.retrieveRecordedExpectations(requestDefinition, requests -> {
                                    response.withBody(getExpectationSerializerThatSerializesBodyDefault().serialize(requests), MediaType.JSON_UTF_8);
                                    mockServerLogger.logEvent(logEntry);
                                    httpResponseFuture.complete(response);
                                });
                                break;
                            case LOG_ENTRIES:
                                mockServerLog.retrieveRecordedExpectationLogEntries(requestDefinition, logEntries -> {
                                    response.withBody(getLogEntrySerializer().serialize(logEntries), MediaType.JSON_UTF_8);
                                    mockServerLogger.logEvent(logEntry);
                                    httpResponseFuture.complete(response);
                                });
                                break;
                        }
                        break;
                    }
                case ACTIVE_EXPECTATIONS:
                    {
                        List<Expectation> expectations = requestMatchers.retrieveActiveExpectations(requestDefinition);
                        switch(format) {
                            case JAVA:
                                response.withBody(getExpectationToJavaSerializer().serialize(expectations), MediaType.create("application", "java").withCharset(UTF_8));
                                break;
                            case JSON:
                                response.withBody(getExpectationSerializer().serialize(expectations), MediaType.JSON_UTF_8);
                                break;
                            case LOG_ENTRIES:
                                response.withBody("LOG_ENTRIES not supported for ACTIVE_EXPECTATIONS", MediaType.create("text", "plain").withCharset(UTF_8));
                                break;
                        }
                        if (MockServerLogger.isEnabled(Level.INFO)) {
                            mockServerLogger.logEvent(new LogEntry().setType(RETRIEVED).setLogLevel(Level.INFO).setCorrelationId(logCorrelationId).setHttpRequest(requestDefinition).setMessageFormat("retrieved " + expectations.size() + " active expectations in " + format.name().toLowerCase() + " that match:{}").setArguments(requestDefinition));
                        }
                        httpResponseFuture.complete(response);
                        break;
                    }
            }
            try {
                return httpResponseFuture.get(configuration.maxFutureTimeoutInMillis(), MILLISECONDS);
            } catch (ExecutionException | InterruptedException | TimeoutException ex) {
                mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setCorrelationId(logCorrelationId).setMessageFormat("exception handling request:{}error:{}").setArguments(request, ex.getMessage()).setThrowable(ex));
                throw new RuntimeException("Exception retrieving state for " + request, ex);
            }
        } catch (IllegalArgumentException iae) {
            mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setCorrelationId(logCorrelationId).setMessageFormat("exception handling request:{}error:{}").setArguments(request, iae.getMessage()).setThrowable(iae));
            if (iae.getMessage().contains(RetrieveType.class.getSimpleName())) {
                throw new IllegalArgumentException("\"" + request.getFirstQueryStringParameter("type") + "\" is not a valid value for \"type\" parameter, only the following values are supported " + Arrays.stream(RetrieveType.values()).map(input -> input.name().toLowerCase()).collect(Collectors.toList()));
            }
            if (iae.getMessage().contains(Format.class.getSimpleName())) {
                throw new IllegalArgumentException("\"" + request.getFirstQueryStringParameter("format") + "\" is not a valid value for \"format\" parameter, only the following values are supported " + Arrays.stream(Format.values()).map(input -> input.name().toLowerCase()).collect(Collectors.toList()));
            }
            throw iae;
        }
    } else {
        return response().withStatusCode(200);
    }
}
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) 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)

Aggregations

VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 HOST (io.netty.handler.codec.http.HttpHeaderNames.HOST)1 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)1 UTF_8 (java.nio.charset.StandardCharsets.UTF_8)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 List (java.util.List)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 ExecutionException (java.util.concurrent.ExecutionException)1 Future (java.util.concurrent.Future)1 MILLISECONDS (java.util.concurrent.TimeUnit.MILLISECONDS)1 SECONDS (java.util.concurrent.TimeUnit.SECONDS)1 TimeoutException (java.util.concurrent.TimeoutException)1 Consumer (java.util.function.Consumer)1 Collectors (java.util.stream.Collectors)1 StringUtils (org.apache.commons.lang3.StringUtils)1 AuthenticationException (org.mockserver.authentication.AuthenticationException)1 AuthenticationHandler (org.mockserver.authentication.AuthenticationHandler)1 NEW_LINE (org.mockserver.character.Character.NEW_LINE)1