Search in sources :

Example 6 with LogEntry

use of org.mockserver.log.model.LogEntry in project mockserver by mock-server.

the class VelocityTemplateEngineTest method shouldHandleHttpRequestsWithVelocityResponseTemplateSecondExample.

@Test
public void shouldHandleHttpRequestsWithVelocityResponseTemplateSecondExample() throws JsonProcessingException {
    // given
    String template = "#if ( $request.method == 'POST' && $request.path == '/somePath' )" + NEW_LINE + "    {" + NEW_LINE + "        'statusCode': 200," + NEW_LINE + "        'body': \"{'name': 'value'}\"" + NEW_LINE + "    }" + NEW_LINE + "#else" + NEW_LINE + "    {" + NEW_LINE + "        'statusCode': 406," + NEW_LINE + "        'body': \"$!request.body\"" + NEW_LINE + "    }" + NEW_LINE + "#end";
    HttpRequest request = request().withPath("/someOtherPath").withBody("some_body");
    // when
    HttpResponse actualHttpResponse = new VelocityTemplateEngine(logFormatter).executeTemplate(template, request, HttpResponseDTO.class);
    // then
    assertThat(actualHttpResponse, is(response().withStatusCode(406).withBody("some_body")));
    verify(logFormatter).logEvent(new LogEntry().setType(TEMPLATE_GENERATED).setLogLevel(INFO).setHttpRequest(request).setMessageFormat("generated output:{}from template:{}for request:{}").setArguments(OBJECT_MAPPER.readTree("" + "    {" + NEW_LINE + "        'statusCode': 406," + NEW_LINE + "        'body': \"some_body\"" + NEW_LINE + "    }" + NEW_LINE), template, request));
}
Also used : HttpRequest(org.mockserver.model.HttpRequest) HttpResponse(org.mockserver.model.HttpResponse) Matchers.containsString(org.hamcrest.Matchers.containsString) LogEntry(org.mockserver.log.model.LogEntry)

Example 7 with LogEntry

use of org.mockserver.log.model.LogEntry in project mockserver by mock-server.

the class HttpActionHandler method writeForwardActionResponse.

void writeForwardActionResponse(final HttpResponse response, final ResponseWriter responseWriter, final HttpRequest request, final Action action) {
    try {
        responseWriter.writeResponse(request, response, false);
        mockServerLogger.logEvent(new LogEntry().setType(FORWARDED_REQUEST).setLogLevel(Level.INFO).setCorrelationId(request.getLogCorrelationId()).setHttpRequest(request).setHttpResponse(response).setExpectation(request, response).setMessageFormat("returning response:{}for forwarded request" + NEW_LINE + NEW_LINE + " in json:{}" + NEW_LINE + NEW_LINE + " in curl:{}for action:{}from expectation:{}").setArguments(response, response, httpRequestToCurlSerializer.toCurl(request), action, action.getExpectationId()));
    } catch (Throwable throwable) {
        mockServerLogger.logEvent(new LogEntry().setType(EXCEPTION).setLogLevel(Level.ERROR).setCorrelationId(request.getLogCorrelationId()).setHttpRequest(request).setMessageFormat(throwable.getMessage()).setThrowable(throwable));
    }
}
Also used : LogEntry(org.mockserver.log.model.LogEntry)

Example 8 with LogEntry

use of org.mockserver.log.model.LogEntry in project mockserver by mock-server.

the class JDKCertificateToMockServerX509Certificate method setClientCertificates.

public HttpRequest setClientCertificates(HttpRequest httpRequest, Certificate[] clientCertificates) {
    if (clientCertificates != null) {
        List<X509Certificate> x509Certificates = Arrays.stream(clientCertificates).flatMap(certificate -> {
            try {
                LazyJavaxX509Certificate x509Certificate = new LazyJavaxX509Certificate(certificate.getEncoded());
                return Stream.of(new X509Certificate().withSerialNumber(x509Certificate.getSerialNumber().toString()).withIssuerDistinguishedName(x509Certificate.getIssuerDN().getName()).withSubjectDistinguishedName(x509Certificate.getSubjectDN().getName()).withSignatureAlgorithmName(x509Certificate.getSigAlgName()).withCertificate(certificate));
            } catch (Throwable throwable) {
                if (MockServerLogger.isEnabled(INFO)) {
                    mockServerLogger.logEvent(new LogEntry().setLogLevel(INFO).setHttpRequest(httpRequest).setMessageFormat("exception decoding client certificate").setThrowable(throwable));
                }
            }
            return Stream.empty();
        }).collect(Collectors.toList());
        httpRequest.withClientCertificateChain(x509Certificates);
    }
    return httpRequest;
}
Also used : Arrays(java.util.Arrays) List(java.util.List) Certificate(java.security.cert.Certificate) Stream(java.util.stream.Stream) HttpRequest(org.mockserver.model.HttpRequest) LogEntry(org.mockserver.log.model.LogEntry) LazyJavaxX509Certificate(io.netty.handler.ssl.util.LazyJavaxX509Certificate) MockServerLogger(org.mockserver.logging.MockServerLogger) X509Certificate(org.mockserver.model.X509Certificate) INFO(org.slf4j.event.Level.INFO) Collectors(java.util.stream.Collectors) LazyJavaxX509Certificate(io.netty.handler.ssl.util.LazyJavaxX509Certificate) LazyJavaxX509Certificate(io.netty.handler.ssl.util.LazyJavaxX509Certificate) X509Certificate(org.mockserver.model.X509Certificate) LogEntry(org.mockserver.log.model.LogEntry)

Example 9 with LogEntry

use of org.mockserver.log.model.LogEntry in project mockserver by mock-server.

the class FileReader method expandFilePathGlobs.

public static List<String> expandFilePathGlobs(String filePath) {
    if (isNotBlank(filePath) && filePath.contains(".")) {
        if (filePath.contains("*") || filePath.contains("?")) {
            List<String> expandedFilePaths = new ArrayList<>();
            PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + filePath);
            Finder finder = new Finder(filePath, pathMatcher);
            try {
                String startingDir = filePath.contains("/") ? StringUtils.substringBeforeLast(StringUtils.substringBefore(filePath, "*"), "/") : ".";
                if (new File(startingDir).exists()) {
                    Files.walkFileTree(new File(startingDir).toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, finder);
                    expandedFilePaths.addAll(finder.getMatchingPaths());
                } else {
                    new MockServerLogger(FileReader.class).logEvent(new LogEntry().setLogLevel(ERROR).setMessageFormat("can't find directory:{}for file path:{}").setArguments(startingDir, filePath));
                }
            } catch (Throwable throwable) {
                new MockServerLogger(FileReader.class).logEvent(new LogEntry().setLogLevel(ERROR).setMessageFormat("exception finding files for file path:{}").setArguments(filePath).setThrowable(throwable));
                throw new RuntimeException(throwable);
            }
            try (ScanResult result = new ClassGraph().scan()) {
                ResourceList resources = result.getResourcesWithExtension(StringUtils.substringAfterLast(filePath, "."));
                expandedFilePaths.addAll(resources.stream().map(Resource::getPath).filter(path -> pathMatcher.matches(new File(path).toPath())).collect(Collectors.toList()));
            }
            return expandedFilePaths.stream().sorted().collect(Collectors.toList());
        } else {
            return Collections.singletonList(filePath);
        }
    } else {
        return Collections.emptyList();
    }
}
Also used : ScanResult(io.github.classgraph.ScanResult) MockServerLogger(org.mockserver.logging.MockServerLogger) ClassGraph(io.github.classgraph.ClassGraph) ArrayList(java.util.ArrayList) ResourceList(io.github.classgraph.ResourceList) LogEntry(org.mockserver.log.model.LogEntry)

Example 10 with LogEntry

use of org.mockserver.log.model.LogEntry in project mockserver by mock-server.

the class FullHttpRequestToMockServerHttpRequest method mapFullHttpRequestToMockServerRequest.

public HttpRequest mapFullHttpRequestToMockServerRequest(FullHttpRequest fullHttpRequest) {
    HttpRequest httpRequest = new HttpRequest();
    try {
        if (fullHttpRequest != null) {
            if (fullHttpRequest.decoderResult().isFailure()) {
                mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setMessageFormat("exception decoding request " + fullHttpRequest.decoderResult().cause().getMessage()).setThrowable(fullHttpRequest.decoderResult().cause()));
            }
            setMethod(httpRequest, fullHttpRequest);
            setPath(httpRequest, fullHttpRequest);
            setQueryString(httpRequest, fullHttpRequest);
            setHeaders(httpRequest, fullHttpRequest);
            setCookies(httpRequest, fullHttpRequest);
            setBody(httpRequest, fullHttpRequest);
            setSocketAddress(httpRequest, isSecure, port, fullHttpRequest);
            jdkCertificateToMockServerX509Certificate.setClientCertificates(httpRequest, clientCertificates);
            httpRequest.withKeepAlive(isKeepAlive(fullHttpRequest));
            httpRequest.withSecure(isSecure);
        }
    } catch (Throwable throwable) {
        mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setMessageFormat("exception decoding request{}").setArguments(fullHttpRequest).setThrowable(throwable));
    }
    return httpRequest;
}
Also used : HttpRequest(org.mockserver.model.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) LogEntry(org.mockserver.log.model.LogEntry)

Aggregations

LogEntry (org.mockserver.log.model.LogEntry)269 Test (org.junit.Test)114 HttpRequest (org.mockserver.model.HttpRequest)79 HttpResponse (org.mockserver.model.HttpResponse)58 Level (org.slf4j.event.Level)34 MockServerLogger (org.mockserver.logging.MockServerLogger)32 Expectation (org.mockserver.mock.Expectation)32 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)25 VerificationSequence (org.mockserver.verify.VerificationSequence)20 DashboardLogEntryDTO (org.mockserver.dashboard.model.DashboardLogEntryDTO)17 OpenAPIExpectation.openAPIExpectation (org.mockserver.mock.OpenAPIExpectation.openAPIExpectation)16 MockServerEventLog (org.mockserver.log.MockServerEventLog)14 List (java.util.List)13 CompletableFuture (java.util.concurrent.CompletableFuture)13 IOException (java.io.IOException)12 InetSocketAddress (java.net.InetSocketAddress)12 ArrayList (java.util.ArrayList)10 Date (java.util.Date)9 ResponseWriter (org.mockserver.responsewriter.ResponseWriter)9 JsonNode (com.fasterxml.jackson.databind.JsonNode)8