Search in sources :

Example 11 with LogEntry

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

the class ExpectationFileWatcher method addExpectationsFromInitializer.

private synchronized void addExpectationsFromInitializer() {
    ExpectationInitializerLoader.expandedInitializationJsonPaths(configuration.initializationJsonPath()).forEach(initializationJsonPath -> {
        Expectation[] expectations = new Expectation[0];
        if (isNotBlank(initializationJsonPath)) {
            try {
                String jsonExpectations = FileReader.readFileFromClassPathOrPath(initializationJsonPath);
                if (isNotBlank(jsonExpectations)) {
                    expectations = expectationSerializer.deserializeArray(jsonExpectations, true);
                }
            } catch (Throwable throwable) {
                if (MockServerLogger.isEnabled(WARN)) {
                    mockServerLogger.logEvent(new LogEntry().setType(SERVER_CONFIGURATION).setLogLevel(WARN).setMessageFormat("exception while loading JSON initialization file with file watcher, ignoring file:{}").setArguments(initializationJsonPath).setThrowable(throwable));
                }
            }
        }
        if (MockServerLogger.isEnabled(TRACE)) {
            mockServerLogger.logEvent(new LogEntry().setLogLevel(TRACE).setMessageFormat("updating expectations:{}from file:{}").setArguments(Arrays.asList(expectations), initializationJsonPath));
        }
        requestMatchers.update(expectations, new MockServerMatcherNotifier.Cause(initializationJsonPath, MockServerMatcherNotifier.Cause.Type.FILE_WATCHER));
    });
}
Also used : MockServerMatcherNotifier(org.mockserver.mock.listeners.MockServerMatcherNotifier) Expectation(org.mockserver.mock.Expectation) LogEntry(org.mockserver.log.model.LogEntry)

Example 12 with LogEntry

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

the class ExpectationInitializerLoader method retrieveExpectationsFromJson.

@SuppressWarnings("FuseStreamOperations")
private Expectation[] retrieveExpectationsFromJson() {
    List<String> initializationJsonPaths = ExpectationInitializerLoader.expandedInitializationJsonPaths(configuration.initializationJsonPath());
    List<Expectation> collect = initializationJsonPaths.stream().flatMap(initializationJsonPath -> {
        Expectation[] expectations = new Expectation[0];
        if (isNotBlank(initializationJsonPath)) {
            if (MockServerLogger.isEnabled(INFO)) {
                mockServerLogger.logEvent(new LogEntry().setType(SERVER_CONFIGURATION).setLogLevel(INFO).setMessageFormat("loading JSON initialization file:{}").setArguments(initializationJsonPath));
            }
            try {
                String jsonExpectations = FileReader.readFileFromClassPathOrPath(initializationJsonPath);
                if (isNotBlank(jsonExpectations)) {
                    expectations = expectationSerializer.deserializeArray(jsonExpectations, true);
                }
            } catch (Throwable throwable) {
                if (MockServerLogger.isEnabled(WARN)) {
                    mockServerLogger.logEvent(new LogEntry().setType(SERVER_CONFIGURATION).setLogLevel(WARN).setMessageFormat("exception while loading JSON initialization file, ignoring file:{}").setArguments(initializationJsonPath).setThrowable(throwable));
                }
            }
        }
        if (expectations.length > 0) {
            if (MockServerLogger.isEnabled(TRACE)) {
                mockServerLogger.logEvent(new LogEntry().setLogLevel(TRACE).setMessageFormat("loaded expectations:{}from file:{}").setArguments(Arrays.asList(expectations), initializationJsonPath));
            }
            requestMatchers.update(expectations, new MockServerMatcherNotifier.Cause(initializationJsonPath, Cause.Type.FILE_INITIALISER));
        }
        return Arrays.stream(expectations);
    }).collect(Collectors.toList());
    return collect.toArray(new Expectation[0]);
}
Also used : LRUCache(org.mockserver.cache.LRUCache) ExpectationSerializer(org.mockserver.serialization.ExpectationSerializer) Arrays(java.util.Arrays) FileReader(org.mockserver.file.FileReader) SERVER_CONFIGURATION(org.mockserver.log.model.LogEntry.LogMessageType.SERVER_CONFIGURATION) ArrayUtils(org.apache.commons.lang3.ArrayUtils) MockServerMatcherNotifier(org.mockserver.mock.listeners.MockServerMatcherNotifier) Expectation(org.mockserver.mock.Expectation) Constructor(java.lang.reflect.Constructor) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) Configuration(org.mockserver.configuration.Configuration) List(java.util.List) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) LogEntry(org.mockserver.log.model.LogEntry) RequestMatchers(org.mockserver.mock.RequestMatchers) Level(org.slf4j.event.Level) VisibleForTesting(com.google.common.annotations.VisibleForTesting) MockServerLogger(org.mockserver.logging.MockServerLogger) Cause(org.mockserver.mock.listeners.MockServerMatcherNotifier.Cause) Cause(org.mockserver.mock.listeners.MockServerMatcherNotifier.Cause) Expectation(org.mockserver.mock.Expectation) LogEntry(org.mockserver.log.model.LogEntry)

Example 13 with LogEntry

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

the class KeyAndCertificateFactoryFactory method createKeyAndCertificateFactory.

@SuppressWarnings("unchecked")
public static KeyAndCertificateFactory createKeyAndCertificateFactory(Configuration configuration, MockServerLogger mockServerLogger) {
    if (customKeyAndCertificateFactorySupplier != null) {
        return customKeyAndCertificateFactorySupplier.apply(mockServerLogger);
    } else {
        if (configuration.useBouncyCastleForKeyAndCertificateGeneration() || canNotLoadSunSecurityPackages()) {
            if (canNotLoadBouncyCastleClasses()) {
                if (configuration.useBouncyCastleForKeyAndCertificateGeneration()) {
                    mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setMessageFormat("failed to instantiate the BouncyCastle KeyAndCertificateFactory because BouncyCastle library is not available in classpath please ensure the following dependencies are available").setArguments("<dependency>\n" + "    <groupId>org.bouncycastle</groupId>\n" + "    <artifactId>bcprov-jdk15on</artifactId>\n" + "    <version>1.70</version>\n" + "</dependency>\n" + "<dependency>\n" + "    <groupId>org.bouncycastle</groupId>\n" + "    <artifactId>bcpkix-jdk15on</artifactId>\n" + "    <version>1.70</version>\n" + "</dependency>"));
                } else {
                    mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.WARN).setMessageFormat("can not load classes in 'sun.security.x509' or 'sun.security.util' so falling back to BouncyCastle KeyAndCertificateFactory but failed to instantiate BouncyCastle; for " + (JDKVersion.getVersion() >= 16 ? "this Java version " + JDKVersion.getVersion() + " (which is >= 16)" : "Java versions >= 16") + " access to packages 'sun.security.x509' and 'sun.security.util' is denied by default at runtime EITHER (1) allow this by adding JVM arguments '--add-exports=java.base/sun.security.x509=ALL-UNNAMED' and '--add-exports=java.base/sun.security.util=ALL-UNNAMED' OR (2) ensure the following dependencies for BouncyCastle are available").setArguments("<dependency>\n" + "    <groupId>org.bouncycastle</groupId>\n" + "    <artifactId>bcprov-jdk15on</artifactId>\n" + "    <version>1.70</version>\n" + "</dependency>\n" + "<dependency>\n" + "    <groupId>org.bouncycastle</groupId>\n" + "    <artifactId>bcpkix-jdk15on</artifactId>\n" + "    <version>1.70</version>\n" + "</dependency>"));
                }
            }
            try {
                Class<KeyAndCertificateFactory> keyAndCertificateFactorClass = (Class<KeyAndCertificateFactory>) CLASS_LOADER.loadClass("org.mockserver.socket.tls.bouncycastle.BCKeyAndCertificateFactory");
                Constructor<KeyAndCertificateFactory> keyAndCertificateFactorConstructor = keyAndCertificateFactorClass.getDeclaredConstructor(Configuration.class, MockServerLogger.class);
                if (MockServerLogger.isEnabled(Level.TRACE)) {
                    mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.TRACE).setMessageFormat("using Bouncy Castle for X.509 Certificate and Private Key generation"));
                }
                return keyAndCertificateFactorConstructor.newInstance(configuration, mockServerLogger);
            } catch (Throwable throwable) {
                mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setMessageFormat("failed to instantiate the BouncyCastle KeyAndCertificateFactory").setThrowable(throwable));
                throw new RuntimeException("failed to instantiate the BouncyCastle KeyAndCertificateFactory");
            }
        } else {
            return new JDKKeyAndCertificateFactory(configuration, mockServerLogger);
        }
    }
}
Also used : JDKKeyAndCertificateFactory(org.mockserver.socket.tls.jdk.JDKKeyAndCertificateFactory) JDKKeyAndCertificateFactory(org.mockserver.socket.tls.jdk.JDKKeyAndCertificateFactory) LogEntry(org.mockserver.log.model.LogEntry)

Example 14 with LogEntry

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

the class JDKKeyAndCertificateFactory method buildAndSaveCertificateAuthorityPrivateKeyAndX509Certificate.

@Override
public void buildAndSaveCertificateAuthorityPrivateKeyAndX509Certificate() {
    if (dynamicallyUpdateCertificateAuthority() && certificateAuthorityCertificateNotYetCreated()) {
        try {
            X509AndPrivateKey certificateAuthorityX509AndPrivateKey = x509Generator.generateRootX509AndPrivateKey(new CertificateSigningRequest().setKeyPairAlgorithm(KEY_GENERATION_ALGORITHM).setSigningAlgorithm(SIGNING_ALGORITHM).setCommonName(ROOT_COMMON_NAME).setKeyPairSize(ROOT_KEY_SIZE));
            saveAsPEMFile(certificateAuthorityX509AndPrivateKey.getCert(), certificateAuthorityX509CertificatePath(), "Certificate Authority X509 Certificate");
            saveAsPEMFile(certificateAuthorityX509AndPrivateKey.getPrivateKey(), certificateAuthorityPrivateKeyPath(), "Certificate Authority Private Key");
        } catch (Exception e) {
            mockServerLogger.logEvent(new LogEntry().setLogLevel(Level.ERROR).setMessageFormat("exception while generating certificate authority private key and X509 certificate").setThrowable(e));
        }
    }
}
Also used : CertificateSigningRequest(org.mockserver.socket.tls.jdk.CertificateSigningRequest) IOException(java.io.IOException) LogEntry(org.mockserver.log.model.LogEntry)

Example 15 with LogEntry

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

the class MockServerLoggerTest method shouldFormatLogMessagesWithException.

@Test
public void shouldFormatLogMessagesWithException() {
    Level originalLevel = logLevel();
    try {
        // given
        logLevel("INFO");
        Logger mockLogger = mock(Logger.class);
        MockServerLogger logFormatter = new MockServerLogger(mockLogger);
        HttpRequest request = request("some_path");
        RuntimeException exception = new RuntimeException("TEST EXCEPTION");
        // when
        logFormatter.logEvent(new LogEntry().setLogLevel(Level.ERROR).setHttpRequest(request).setMessageFormat("some random message with{}and{}").setArguments("some" + NEW_LINE + "multi-line" + NEW_LINE + "object", "another" + NEW_LINE + "multi-line" + NEW_LINE + "object").setThrowable(exception));
        // then
        String message = "some random message with" + NEW_LINE + NEW_LINE + "  some" + NEW_LINE + "  multi-line" + NEW_LINE + "  object" + NEW_LINE + NEW_LINE + " and" + NEW_LINE + NEW_LINE + "  another" + NEW_LINE + "  multi-line" + NEW_LINE + "  object" + NEW_LINE;
        verify(mockLogger).error(message, exception);
    } finally {
        logLevel(originalLevel.toString());
    }
}
Also used : HttpRequest(org.mockserver.model.HttpRequest) Level(org.slf4j.event.Level) ConfigurationProperties.logLevel(org.mockserver.configuration.ConfigurationProperties.logLevel) StringContains.containsString(org.hamcrest.core.StringContains.containsString) Logger(org.slf4j.Logger) LogEntry(org.mockserver.log.model.LogEntry) Test(org.junit.Test)

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