Search in sources :

Example 96 with LogEntry

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

the class ExpandedParameterDecoder method retrieveFormParameters.

public Parameters retrieveFormParameters(String parameterString, boolean hasPath) {
    Parameters parameters = new Parameters();
    Map<String, List<String>> parameterMap = new HashMap<>();
    if (isNotBlank(parameterString)) {
        try {
            hasPath = parameterString.startsWith("/") || parameterString.contains("?") || hasPath;
            parameterMap.putAll(new QueryStringDecoder(parameterString, HttpConstants.DEFAULT_CHARSET, hasPath, Integer.MAX_VALUE, !configuration.useSemicolonAsQueryParameterSeparator()).parameters());
        } catch (IllegalArgumentException iae) {
            mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setMessageFormat("exception{}while parsing query string{}").setArguments(parameterString, iae.getMessage()).setThrowable(iae));
        }
    }
    return parameters.withEntries(parameterMap);
}
Also used : QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) Parameters(org.mockserver.model.Parameters) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List) NottableString(org.mockserver.model.NottableString) LogEntry(org.mockserver.log.model.LogEntry)

Example 97 with LogEntry

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

the class ConfigurationProperties method readInetSocketAddressProperty.

private static InetSocketAddress readInetSocketAddressProperty(String key, String environmentVariableKey) {
    InetSocketAddress inetSocketAddress = null;
    String proxy = readPropertyHierarchically(PROPERTIES, key, environmentVariableKey, "");
    if (isNotBlank(proxy)) {
        String[] proxyParts = proxy.split(":");
        if (proxyParts.length > 1) {
            try {
                inetSocketAddress = new InetSocketAddress(proxyParts[0], Integer.parseInt(proxyParts[1]));
            } catch (NumberFormatException nfe) {
                MOCK_SERVER_LOGGER.logEvent(new LogEntry().setLogLevel(Level.ERROR).setMessageFormat("NumberFormatException converting value \"" + proxyParts[1] + "\" into an integer").setThrowable(nfe));
            }
        }
    }
    return inetSocketAddress;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) LogEntry(org.mockserver.log.model.LogEntry)

Example 98 with LogEntry

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

the class ConfigurationProperties method readPropertyFile.

@SuppressWarnings("ConstantConditions")
private static Properties readPropertyFile() {
    Properties properties = new Properties();
    try (InputStream inputStream = ConfigurationProperties.class.getClassLoader().getResourceAsStream(propertyFile())) {
        if (inputStream != null) {
            try {
                properties.load(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
                if (MOCK_SERVER_LOGGER != null) {
                    MOCK_SERVER_LOGGER.logEvent(new LogEntry().setAlwaysLog(true).setLogLevel(Level.ERROR).setMessageFormat("exception loading property file [" + propertyFile() + "]").setThrowable(e));
                }
            }
        } else {
            if (MOCK_SERVER_LOGGER != null && MockServerLogger.isEnabled(DEBUG)) {
                MOCK_SERVER_LOGGER.logEvent(new LogEntry().setType(SERVER_CONFIGURATION).setLogLevel(DEBUG).setMessageFormat("property file not found on classpath using path [" + propertyFile() + "]"));
            }
            try {
                properties.load(new FileInputStream(propertyFile()));
            } catch (FileNotFoundException e) {
                if (MOCK_SERVER_LOGGER != null && MockServerLogger.isEnabled(DEBUG)) {
                    MOCK_SERVER_LOGGER.logEvent(new LogEntry().setType(SERVER_CONFIGURATION).setLogLevel(DEBUG).setMessageFormat("property file not found using path [" + propertyFile() + "]"));
                }
            } catch (IOException e) {
                e.printStackTrace();
                if (MOCK_SERVER_LOGGER != null) {
                    MOCK_SERVER_LOGGER.logEvent(new LogEntry().setAlwaysLog(true).setLogLevel(Level.ERROR).setMessageFormat("exception loading property file [" + propertyFile() + "]").setThrowable(e));
                }
            }
        }
    } catch (IOException ioe) {
    // ignore
    }
    if (!properties.isEmpty()) {
        Enumeration<?> propertyNames = properties.propertyNames();
        StringBuilder propertiesLogDump = new StringBuilder();
        propertiesLogDump.append("Reading properties from property file [").append(propertyFile()).append("]:").append(NEW_LINE);
        while (propertyNames.hasMoreElements()) {
            String propertyName = String.valueOf(propertyNames.nextElement());
            propertiesLogDump.append("  ").append(propertyName).append(" = ").append(properties.getProperty(propertyName)).append(NEW_LINE);
        }
        Level logLevel = Level.valueOf(getSLF4JOrJavaLoggerToSLF4JLevelMapping().get(readPropertyHierarchically(properties, MOCKSERVER_LOG_LEVEL, "MOCKSERVER_LOG_LEVEL", DEFAULT_LOG_LEVEL).toUpperCase()));
        if (MOCK_SERVER_LOGGER != null && MockServerLogger.isEnabled(Level.INFO, logLevel)) {
            MOCK_SERVER_LOGGER.logEvent(new LogEntry().setAlwaysLog(true).setType(SERVER_CONFIGURATION).setLogLevel(Level.INFO).setMessageFormat(propertiesLogDump.toString()));
        }
    }
    return properties;
}
Also used : Level(org.slf4j.event.Level) LogEntry(org.mockserver.log.model.LogEntry)

Example 99 with LogEntry

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

the class EchoServer method getLastRequest.

public HttpRequest getLastRequest() {
    try {
        HttpRequest httpRequest = lastRequest.httpRequest.get().get();
        lastRequest.httpRequest.set(new CompletableFuture<>());
        return httpRequest;
    } catch (InterruptedException | ExecutionException e) {
        mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setMessageFormat("exception while waiting to receive request - " + e.getMessage()).setThrowable(e));
        return null;
    }
}
Also used : HttpRequest(org.mockserver.model.HttpRequest) ExecutionException(java.util.concurrent.ExecutionException) LogEntry(org.mockserver.log.model.LogEntry)

Example 100 with LogEntry

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

the class EchoServerHandler method channelRead0.

protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) {
    mockServerEventLog.add(new LogEntry().setType(RECEIVED_REQUEST).setLogLevel(INFO).setHttpRequest(request).setMessageFormat("EchoServer received request{}").setArguments(request));
    if (!lastRequest.httpRequest.get().isDone()) {
        lastRequest.httpRequest.get().complete(request);
    }
    if (!nextResponse.httpResponse.isEmpty()) {
        // WARNING: this logic is only for unit tests that run in series and is NOT thread safe!!!
        DefaultHttpObject httpResponse = new MockServerHttpResponseToFullHttpResponse(mockServerLogger).mapMockServerResponseToNettyResponse(nextResponse.httpResponse.remove()).get(0);
        ctx.writeAndFlush(httpResponse);
    } else {
        HttpResponse httpResponse = response().withStatusCode(request.getPath().equalsIgnoreCase("/not_found") ? NOT_FOUND.code() : OK.code()).withHeaders(request.getHeaderList());
        if (request.getBody() instanceof BodyWithContentType) {
            httpResponse.withBody((BodyWithContentType<?>) request.getBody());
        } else {
            httpResponse.withBody(request.getBodyAsString());
        }
        // set hop-by-hop headers
        final int length = httpResponse.getBody() != null ? httpResponse.getBody().getRawBytes().length : 0;
        if (error == EchoServer.Error.LARGER_CONTENT_LENGTH) {
            httpResponse.replaceHeader(CONTENT_LENGTH.toString(), String.valueOf(length * 2));
        } else if (error == EchoServer.Error.SMALLER_CONTENT_LENGTH) {
            httpResponse.replaceHeader(CONTENT_LENGTH.toString(), String.valueOf(length / 2));
        } else {
            httpResponse.replaceHeader(CONTENT_LENGTH.toString(), String.valueOf(length));
        }
        if (MockServerLogger.isEnabled(INFO)) {
            mockServerEventLog.add(new LogEntry().setLogLevel(INFO).setHttpRequest(request).setHttpResponse(httpResponse).setMessageFormat("EchoServer returning response{}for request{}").setArguments(httpResponse, request));
        }
        // write and flush
        ctx.writeAndFlush(httpResponse);
        if (error == EchoServer.Error.LARGER_CONTENT_LENGTH || error == EchoServer.Error.SMALLER_CONTENT_LENGTH) {
            ctx.close();
        }
    }
}
Also used : MockServerHttpResponseToFullHttpResponse(org.mockserver.mappers.MockServerHttpResponseToFullHttpResponse) HttpResponse(org.mockserver.model.HttpResponse) MockServerHttpResponseToFullHttpResponse(org.mockserver.mappers.MockServerHttpResponseToFullHttpResponse) LogEntry(org.mockserver.log.model.LogEntry) BodyWithContentType(org.mockserver.model.BodyWithContentType) DefaultHttpObject(io.netty.handler.codec.http.DefaultHttpObject)

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