Search in sources :

Example 1 with OPEN_API_LOAD_ERROR

use of org.mockserver.openapi.OpenAPIParser.OPEN_API_LOAD_ERROR 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 OPEN_API_LOAD_ERROR

use of org.mockserver.openapi.OpenAPIParser.OPEN_API_LOAD_ERROR in project mockserver by mock-server.

the class HttpRequestsPropertiesMatcher method apply.

@VisibleForTesting
public boolean apply(RequestDefinition requestDefinition, List<LogEntry> logEntries) {
    OpenAPIDefinition openAPIDefinition = requestDefinition instanceof OpenAPIDefinition ? (OpenAPIDefinition) requestDefinition : null;
    if (this.openAPIDefinition == null || !this.openAPIDefinition.equals(openAPIDefinition)) {
        this.openAPIDefinition = openAPIDefinition;
        if (openAPIDefinition != null && isNotBlank(openAPIDefinition.getSpecUrlOrPayload())) {
            httpRequestPropertiesMatchers = new ArrayList<>();
            httpRequests = new ArrayList<>();
            OpenAPISerialiser openAPISerialiser = new OpenAPISerialiser(mockServerLogger);
            try {
                OpenAPI openAPI = buildOpenAPI(openAPIDefinition.getSpecUrlOrPayload(), mockServerLogger);
                try {
                    final Map<String, List<Pair<String, Operation>>> stringListMap = openAPISerialiser.retrieveOperations(openAPI, openAPIDefinition.getOperationId());
                    stringListMap.forEach((path, operations) -> operations.forEach(methodOperationPair -> {
                        Operation operation = methodOperationPair.getValue();
                        if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) {
                            operation.getRequestBody().getContent().forEach(handleRequestBody(openAPIDefinition, openAPI, path, methodOperationPair, Boolean.TRUE.equals(operation.getRequestBody().getRequired()), logEntries));
                        } else {
                            HttpRequest httpRequest = createHttpRequest(openAPIDefinition, openAPI, path, methodOperationPair);
                            try {
                                addRequestMatcher(openAPIDefinition, methodOperationPair, httpRequest, "");
                            } catch (Throwable throwable) {
                                logEntries.add(new LogEntry().setLogLevel(ERROR).setMessageFormat("exception while creating adding request matcher for operation:{}method:{}in open api:{}").setArguments(methodOperationPair.getRight().getOperationId(), methodOperationPair.getLeft(), openAPIDefinition));
                            }
                        }
                    }));
                } catch (Throwable throwable) {
                    logEntries.add(new LogEntry().setLogLevel(ERROR).setMessageFormat((StringUtils.isBlank(throwable.getMessage()) || !throwable.getMessage().contains(OPEN_API_LOAD_ERROR) ? OPEN_API_LOAD_ERROR + (isNotBlank(throwable.getMessage()) ? ", " : "") : "") + throwable.getMessage() + " for open api:{}").setArguments(openAPIDefinition));
                }
            } catch (Throwable throwable) {
                String message = (StringUtils.isBlank(throwable.getMessage()) || !throwable.getMessage().contains(OPEN_API_LOAD_ERROR) ? OPEN_API_LOAD_ERROR + (isNotBlank(throwable.getMessage()) ? ", " : "") : "") + throwable.getMessage();
                throw new IllegalArgumentException(message, throwable);
            }
            logEntries.forEach(mockServerLogger::logEvent);
        }
        this.hashCode = 0;
        if (MockServerLogger.isEnabled(TRACE)) {
            mockServerLogger.logEvent(new LogEntry().setLogLevel(TRACE).setHttpRequest(requestDefinition).setMessageFormat("created request matcher{}for open api definition{}").setArguments(this, requestDefinition));
        }
        return true;
    } else {
        return false;
    }
}
Also used : ObjectMapperFactory(org.mockserver.serialization.ObjectMapperFactory) java.util(java.util) ParameterStyle(org.mockserver.model.ParameterStyle) JsonNodeExampleSerializer(org.mockserver.openapi.examples.JsonNodeExampleSerializer) Parameter(io.swagger.v3.oas.models.parameters.Parameter) TRACE(org.slf4j.event.Level.TRACE) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement) OpenAPISerialiser(org.mockserver.openapi.OpenAPISerialiser) NottableSchemaString.schemaString(org.mockserver.model.NottableSchemaString.schemaString) Operation(io.swagger.v3.oas.models.Operation) StringUtils(org.apache.commons.lang3.StringUtils) ERROR(org.slf4j.event.Level.ERROR) Pair(org.apache.commons.lang3.tuple.Pair) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Level(org.slf4j.event.Level) JsonSchemaBody.jsonSchema(org.mockserver.model.JsonSchemaBody.jsonSchema) BiConsumer(java.util.function.BiConsumer) Schema(io.swagger.v3.oas.models.media.Schema) NottableOptionalString.optional(org.mockserver.model.NottableOptionalString.optional) OpenAPIParser(org.mockserver.openapi.OpenAPIParser) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) OPEN_API_LOAD_ERROR(org.mockserver.openapi.OpenAPIParser.OPEN_API_LOAD_ERROR) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) OpenAPIParser.buildOpenAPI(org.mockserver.openapi.OpenAPIParser.buildOpenAPI) MediaType(io.swagger.v3.oas.models.media.MediaType) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) NottableString.string(org.mockserver.model.NottableString.string) Configuration(org.mockserver.configuration.Configuration) org.mockserver.model(org.mockserver.model) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) LogEntry(org.mockserver.log.model.LogEntry) VisibleForTesting(com.google.common.annotations.VisibleForTesting) MockServerLogger(org.mockserver.logging.MockServerLogger) CONTENT_TYPE(io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE) Encoding(io.swagger.v3.oas.models.media.Encoding) AUTHORIZATION(io.netty.handler.codec.http.HttpHeaderNames.AUTHORIZATION) Joiner(com.google.common.base.Joiner) NottableSchemaString.schemaString(org.mockserver.model.NottableSchemaString.schemaString) Operation(io.swagger.v3.oas.models.Operation) OpenAPISerialiser(org.mockserver.openapi.OpenAPISerialiser) OpenAPI(io.swagger.v3.oas.models.OpenAPI) OpenAPIParser.buildOpenAPI(org.mockserver.openapi.OpenAPIParser.buildOpenAPI) LogEntry(org.mockserver.log.model.LogEntry) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 Collectors (java.util.stream.Collectors)2 StringUtils (org.apache.commons.lang3.StringUtils)2 Configuration (org.mockserver.configuration.Configuration)2 LogEntry (org.mockserver.log.model.LogEntry)2 MockServerLogger (org.mockserver.logging.MockServerLogger)2 org.mockserver.model (org.mockserver.model)2 OPEN_API_LOAD_ERROR (org.mockserver.openapi.OpenAPIParser.OPEN_API_LOAD_ERROR)2 Level (org.slf4j.event.Level)2 TRACE (org.slf4j.event.Level.TRACE)2 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 Joiner (com.google.common.base.Joiner)1 AUTHORIZATION (io.netty.handler.codec.http.HttpHeaderNames.AUTHORIZATION)1 CONTENT_TYPE (io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE)1 HOST (io.netty.handler.codec.http.HttpHeaderNames.HOST)1 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)1 OpenAPI (io.swagger.v3.oas.models.OpenAPI)1 Operation (io.swagger.v3.oas.models.Operation)1 Encoding (io.swagger.v3.oas.models.media.Encoding)1 MediaType (io.swagger.v3.oas.models.media.MediaType)1