author
int64 658
755k
| date
stringlengths 19
19
| timezone
int64 -46,800
43.2k
| hash
stringlengths 40
40
| message
stringlengths 5
490
| mods
list | language
stringclasses 20
values | license
stringclasses 3
values | repo
stringlengths 5
68
| original_message
stringlengths 12
491
|
---|---|---|---|---|---|---|---|---|---|
686,936 | 25.09.2019 18:49:31 | -3,600 | a2014e3daa573a6eca59017f5e46f6c3215b592a | Added HTTP/2 support in the jre8 version | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -43,11 +43,10 @@ allprojects {\njackson : '2.9.9',\njacksonDatabind: '2.9.9.3',\nxmlUnit : '2.6.2'\n-\n],\njava8: [\nhandlebars : '4.1.2',\n- jetty : '9.4.19.v20190610',\n+ jetty : '9.4.20.v20190813',\nguava : '27.0.1-jre',\njackson : '2.9.9',\njacksonDatabind: '2.9.9.3',\n@@ -55,7 +54,8 @@ allprojects {\n]\n]\n- def versions = project.name == 'wiremock' ?\n+ def isJava7 = project.name == 'wiremock'\n+ def versions = isJava7 ?\nversionSets.java7 :\nversionSets[project.name]\n@@ -107,12 +107,18 @@ allprojects {\ntestCompile \"com.googlecode.jarjar:jarjar:1.3\"\ntestCompile \"commons-io:commons-io:2.4\"\ntestCompile 'org.scala-lang:scala-library:2.11.12'\n- testCompile 'org.littleshoot:littleproxy:1.1.2:littleproxy-shade'\n+\ntestCompile 'org.apache.httpcomponents:httpmime:4.5'\n- // This is coming in via the shaded littleproxy already. Adding it a 2nd time breaks it.\n-// testRuntime 'org.slf4j:slf4j-log4j12:1.7.12'\n+ testRuntime 'org.slf4j:slf4j-log4j12:1.7.12'\ntestRuntime files('src/test/resources/classpath file source/classpathfiles.zip', 'src/test/resources/classpath-filesource.jar')\n+\n+ def littleProxyDep = isJava7 ? 'org.littleshoot:littleproxy:1.1.2' : 'net.jockx:littleproxy:1.1.3'\n+ testCompile (littleProxyDep) {\n+ exclude group: 'com.google.guava', module: 'guava'\n+ exclude group: 'org.apache.commons', module: 'commons-lang3'\n+ exclude group: 'org.slf4j', module: 'slf4j-api'\n+ }\n}\ncompileTestJava {\n"
},
{
"change_type": "MODIFY",
"old_path": "java8/build.gradle",
"new_path": "java8/build.gradle",
"diff": "@@ -3,3 +3,18 @@ shadowJar.baseName = 'wiremock-jre8-standalone'\nsourceCompatibility = 1.8\ntargetCompatibility = 1.8\n+\n+final jettyVersion = '9.4.20.v20190813'\n+\n+dependencies {\n+ compile \"org.eclipse.jetty.http2:http2-server:$jettyVersion\"\n+ compile \"org.eclipse.jetty:jetty-alpn-server:$jettyVersion\"\n+ compile \"org.eclipse.jetty:jetty-alpn-conscrypt-server:$jettyVersion\"\n+ compile \"org.eclipse.jetty:jetty-alpn-conscrypt-client:$jettyVersion\"\n+ testCompile \"org.eclipse.jetty:jetty-client:$jettyVersion\"\n+ testCompile \"org.eclipse.jetty.http2:http2-http-client-transport:$jettyVersion\"\n+}\n+\n+def getAlpnJarPath() {\n+ project.configurations.compile.find { it.name.startsWith(\"alpn-boot-\") }\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java",
"new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java",
"diff": "package com.github.tomakehurst.wiremock.jetty94;\n+import com.github.tomakehurst.wiremock.common.HttpsSettings;\n+import com.github.tomakehurst.wiremock.common.JettySettings;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.http.AdminRequestHandler;\nimport com.github.tomakehurst.wiremock.http.StubRequestHandler;\n-import com.github.tomakehurst.wiremock.servlet.MultipartRequestConfigurer;\n-import com.github.tomakehurst.wiremock.jetty9.JettyHttpServer;\nimport com.github.tomakehurst.wiremock.jetty9.DefaultMultipartRequestConfigurer;\n+import com.github.tomakehurst.wiremock.jetty9.JettyHttpServer;\n+import com.github.tomakehurst.wiremock.servlet.MultipartRequestConfigurer;\n+import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory;\n+import org.eclipse.jetty.http2.HTTP2Cipher;\n+import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;\n+import org.eclipse.jetty.io.NetworkTrafficListener;\n+import org.eclipse.jetty.server.*;\nimport org.eclipse.jetty.util.ssl.SslContextFactory;\npublic class Jetty94HttpServer extends JettyHttpServer {\n@@ -15,12 +22,57 @@ public class Jetty94HttpServer extends JettyHttpServer {\n}\n@Override\n- protected SslContextFactory buildSslContextFactory() {\n- return new SslContextFactory();\n+ protected MultipartRequestConfigurer buildMultipartRequestConfigurer() {\n+ return new DefaultMultipartRequestConfigurer();\n}\n@Override\n- protected MultipartRequestConfigurer buildMultipartRequestConfigurer() {\n- return new DefaultMultipartRequestConfigurer();\n+ protected ServerConnector createHttpsConnector(Server server, String bindAddress, HttpsSettings httpsSettings, JettySettings jettySettings, NetworkTrafficListener listener) {\n+ SslContextFactory.Server http2SslContextFactory = buildHttp2SslContextFactory(httpsSettings);\n+\n+ HttpConfiguration httpConfig = createHttpConfig(jettySettings);\n+ httpConfig.setSecureScheme(\"https\");\n+ httpConfig.setSecurePort(httpsSettings.port());\n+ httpConfig.setSendXPoweredBy(false);\n+ httpConfig.setSendServerVersion(false);\n+ httpConfig.addCustomizer(new SecureRequestCustomizer());\n+\n+ HttpConnectionFactory http = new HttpConnectionFactory(httpConfig);\n+ HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(httpConfig);\n+\n+ ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();\n+\n+ SslConnectionFactory ssl = new SslConnectionFactory(http2SslContextFactory, alpn.getProtocol());\n+\n+ ConnectionFactory[] connectionFactories = new ConnectionFactory[] {\n+ ssl,\n+ alpn,\n+ h2,\n+ http\n+ };\n+\n+ return createServerConnector(\n+ bindAddress,\n+ jettySettings,\n+ httpsSettings.port(),\n+ listener,\n+ connectionFactories\n+ );\n+ }\n+\n+ private SslContextFactory.Server buildHttp2SslContextFactory(HttpsSettings httpsSettings) {\n+ SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();\n+\n+ sslContextFactory.setKeyStorePath(httpsSettings.keyStorePath());\n+ sslContextFactory.setKeyManagerPassword(httpsSettings.keyStorePassword());\n+ sslContextFactory.setKeyStoreType(httpsSettings.keyStoreType());\n+ if (httpsSettings.hasTrustStore()) {\n+ sslContextFactory.setTrustStorePath(httpsSettings.trustStorePath());\n+ sslContextFactory.setTrustStorePassword(httpsSettings.trustStorePassword());\n+ }\n+ sslContextFactory.setNeedClientAuth(httpsSettings.needClientAuth());\n+ sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR);\n+ sslContextFactory.setProvider(\"Conscrypt\");\n+ return sslContextFactory;\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/Http2AcceptanceTest.java",
"diff": "+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.http.HttpClientFactory;\n+import com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import org.apache.http.client.methods.CloseableHttpResponse;\n+import org.apache.http.client.methods.HttpGet;\n+import org.apache.http.impl.client.CloseableHttpClient;\n+import org.eclipse.jetty.client.HttpClient;\n+import org.eclipse.jetty.client.api.ContentResponse;\n+import org.junit.Rule;\n+import org.junit.Test;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\n+import static com.github.tomakehurst.wiremock.client.WireMock.ok;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\n+import static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertThat;\n+\n+public class Http2AcceptanceTest {\n+\n+ @Rule\n+ public WireMockRule wm = new WireMockRule(\n+ wireMockConfig()\n+ .dynamicPort()\n+ .dynamicHttpsPort()\n+ );\n+\n+ @Test\n+ public void supportsHttp2Connections() throws Exception {\n+ HttpClient client = Http2ClientFactory.create();\n+\n+ wm.stubFor(get(\"/thing\").willReturn(ok(\"HTTP/2 response\")));\n+\n+ ContentResponse response = client.GET(\"https://localhost:\" + wm.httpsPort() + \"/thing\");\n+ assertThat(response.getStatus(), is(200));\n+ }\n+\n+ @Test\n+ public void supportsHttp1_1Connections() throws Exception {\n+ CloseableHttpClient client = HttpClientFactory.createClient();\n+\n+ wm.stubFor(get(\"/thing\").willReturn(ok(\"HTTP/1.1 response\")));\n+\n+ HttpGet get = new HttpGet(\"https://localhost:\" + wm.httpsPort() + \"/thing\");\n+ try (CloseableHttpResponse response = client.execute(get)) {\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/Http2ClientFactory.java",
"diff": "+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.common.Exceptions;\n+import org.eclipse.jetty.client.HttpClient;\n+import org.eclipse.jetty.client.HttpClientTransport;\n+import org.eclipse.jetty.http2.client.HTTP2Client;\n+import org.eclipse.jetty.http2.client.http.HttpClientTransportOverHTTP2;\n+import org.eclipse.jetty.util.ssl.SslContextFactory;\n+\n+public class Http2ClientFactory {\n+\n+ public static HttpClient create() {\n+ SslContextFactory sslContextFactory = new SslContextFactory.Client(true);\n+ sslContextFactory.setProvider(\"Conscrypt\");\n+ HttpClientTransport transport = new HttpClientTransportOverHTTP2(\n+ new HTTP2Client());\n+ HttpClient httpClient = new HttpClient(transport, sslContextFactory);\n+\n+ httpClient.setFollowRedirects(false);\n+ try {\n+ httpClient.start();\n+ } catch (Exception e) {\n+ return Exceptions.throwUnchecked(e, HttpClient.class);\n+ }\n+\n+ return httpClient;\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": "java8/src/test/resources/assets/.gitkeep",
"new_path": "java8/src/test/resources/assets/.gitkeep",
"diff": ""
},
{
"change_type": "ADD",
"old_path": "java8/src/test/resources/assets/swagger-ui/index.html",
"new_path": "java8/src/test/resources/assets/swagger-ui/index.html",
"diff": ""
},
{
"change_type": "ADD",
"old_path": "java8/src/test/resources/keystore",
"new_path": "java8/src/test/resources/keystore",
"diff": "Binary files /dev/null and b/java8/src/test/resources/keystore differ\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "java8/src/test/resources/log4j.properties",
"diff": "+log4j.rootLogger=DEBUG, stdout\n+\n+log4j.appender.stdout=org.apache.log4j.ConsoleAppender\n+log4j.appender.stdout.target=System.out\n+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout\n+log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{10}:%L - %m%n\n+\n+log4j.logger.org.apache.http=DEBUG\n+log4j.logger.org.eclipse=DEBUG\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"diff": "@@ -81,6 +81,7 @@ public class JettyHttpServer implements HttpServer {\nif (options.httpsSettings().enabled()) {\nhttpsConnector = createHttpsConnector(\n+ jettyServer,\noptions.bindAddress(),\noptions.httpsSettings(),\noptions.jettySettings(),\n@@ -243,6 +244,7 @@ public class JettyHttpServer implements HttpServer {\n}\nprotected ServerConnector createHttpsConnector(\n+ Server server,\nString bindAddress,\nHttpsSettings httpsSettings,\nJettySettings jettySettings,\n@@ -265,19 +267,32 @@ public class JettyHttpServer implements HttpServer {\nfinal int port = httpsSettings.port();\n+ HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory(httpConfig);\n+ SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(\n+ sslContextFactory,\n+ \"http/1.1\"\n+ );\n+ ConnectionFactory[] connectionFactories = ArrayUtils.addAll(\n+ new ConnectionFactory[] { sslConnectionFactory, httpConnectionFactory },\n+ buildAdditionalConnectionFactories(httpsSettings, httpConnectionFactory, sslConnectionFactory)\n+ );\n+\nreturn createServerConnector(\nbindAddress,\njettySettings,\nport,\nlistener,\n- new SslConnectionFactory(\n- sslContextFactory,\n- \"http/1.1\"\n- ),\n- new HttpConnectionFactory(httpConfig)\n+ connectionFactories\n);\n}\n+ protected ConnectionFactory[] buildAdditionalConnectionFactories(\n+ HttpsSettings httpsSettings,\n+ HttpConnectionFactory httpConnectionFactory,\n+ SslConnectionFactory sslConnectionFactory) {\n+ return new ConnectionFactory[] {};\n+ }\n+\n// Override this for platform-specific impls\nprotected SslContextFactory buildSslContextFactory() {\nreturn new SslContextFactory();\n@@ -294,8 +309,10 @@ public class JettyHttpServer implements HttpServer {\nprotected ServerConnector createServerConnector(String bindAddress,\nJettySettings jettySettings,\n- int port, NetworkTrafficListener listener,\n+ int port,\n+ NetworkTrafficListener listener,\nConnectionFactory... connectionFactories) {\n+\nint acceptors = jettySettings.getAcceptors().or(2);\nNetworkTrafficServerConnector connector = new NetworkTrafficServerConnector(\njettyServer,\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added HTTP/2 support in the jre8 version |
686,936 | 25.09.2019 18:59:49 | -3,600 | b4013ffafc9d86ba0d3785dc05829fed054e2d48 | Fixed java7 test broken by littleproxy version switching | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -54,7 +54,7 @@ allprojects {\n]\n]\n- def isJava7 = project.name == 'wiremock'\n+ def isJava7 = project.name in ['wiremock', 'java7']\ndef versions = isJava7 ?\nversionSets.java7 :\nversionSets[project.name]\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed java7 test broken by littleproxy version switching |
686,983 | 26.09.2019 10:39:50 | -7,200 | 89b98398a29a68f3ac8fd14869f33bfdb10592ae | Jackson version bump (fixing multiple CVEs) | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -40,16 +40,16 @@ allprojects {\nhandlebars : '4.0.7',\njetty : '9.2.28.v20190418', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\nguava : '20.0',\n- jackson : '2.9.9',\n- jacksonDatabind: '2.9.9.3',\n+ jackson : '2.9.10',\n+ jacksonDatabind: '2.9.10',\nxmlUnit : '2.6.2'\n],\njava8: [\nhandlebars : '4.1.2',\njetty : '9.4.20.v20190813',\nguava : '27.0.1-jre',\n- jackson : '2.9.9',\n- jacksonDatabind: '2.9.9.3',\n+ jackson : '2.9.10',\n+ jacksonDatabind: '2.9.10',\nxmlUnit : '2.6.2'\n]\n]\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Jackson version bump (fixing multiple CVEs) (#1191) |
686,936 | 26.09.2019 09:39:37 | -3,600 | a125dd914d2f5db79966bc5db9ebc8a040a700b1 | Made junit a compileOnly (provided) dependency to avoid hamcrest class clashes when using newer test libraries | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -70,13 +70,15 @@ allprojects {\n\"com.fasterxml.jackson.core:jackson-databind:$versions.jacksonDatabind\"\ncompile \"org.apache.httpcomponents:httpclient:4.5.6\"\ncompile \"org.xmlunit:xmlunit-core:$versions.xmlUnit\"\n- compile \"org.xmlunit:xmlunit-legacy:$versions.xmlUnit\"\n+ compile \"org.xmlunit:xmlunit-legacy:$versions.xmlUnit\", {\n+ exclude group: 'junit', module: 'junit'\n+ }\ncompile \"org.xmlunit:xmlunit-placeholders:$versions.xmlUnit\"\ncompile \"com.jayway.jsonpath:json-path:2.4.0\"\ncompile \"org.ow2.asm:asm:7.0\"\ncompile \"org.slf4j:slf4j-api:1.7.12\"\ncompile \"net.sf.jopt-simple:jopt-simple:5.0.3\"\n- compile(\"junit:junit:4.12\") {\n+ compileOnly(\"junit:junit:4.12\") {\nexclude group: \"org.hamcrest\", module: \"hamcrest-core\"\n}\ncompile 'org.apache.commons:commons-lang3:3.7'\n@@ -90,6 +92,7 @@ allprojects {\ncompile 'commons-fileupload:commons-fileupload:1.4'\n+ testCompile \"junit:junit:4.12\"\ntestCompile \"org.hamcrest:hamcrest-all:1.3\"\ntestCompile(\"org.jmock:jmock:2.5.1\") {\nexclude group: \"junit\", module: \"junit-dep\"\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Made junit a compileOnly (provided) dependency to avoid hamcrest class clashes when using newer test libraries |
686,936 | 26.09.2019 09:58:09 | -3,600 | f7fbb846cd7b259fddc16ae136056b6582ec47bf | Tweaked test logging in CI | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -12,5 +12,5 @@ install:\n- JAVA_HOME=$(jdk_switcher home openjdk8) ./gradlew classes testClasses -x generateApiDocs\nscript:\n- - ./gradlew check --info --stacktrace --no-daemon\n+ - ./gradlew check --stacktrace --no-daemon\n"
},
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -137,7 +137,7 @@ allprojects {\nmaxParallelForks = 3\ntestLogging {\n- events \"failed\"\n+ events \"FAILED\", \"SKIPPED\"\nexceptionFormat \"full\"\n}\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Tweaked test logging in CI |
686,936 | 30.09.2019 11:55:56 | -3,600 | 0a0fabdf9b1fb58dc0b1383bb514c65bb6bec6a3 | Fixed broken versions in Swagger and doc files | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_config.yml",
"new_path": "docs-v2/_config.yml",
"diff": "@@ -216,4 +216,4 @@ compress_html:\nignore:\nenvs: development\n-wiremock_version: 2.24.2\n+wiremock_version: 2.25.0\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/resources/swagger/wiremock-admin-api.yaml",
"new_path": "src/main/resources/swagger/wiremock-admin-api.yaml",
"diff": "@@ -2,7 +2,7 @@ openapi: 3.0.0\ninfo:\ntitle: WireMock\n- version: 2.24.2\n+ version: 2.25.0\nexternalDocs:\ndescription: WireMock user documentation\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed broken versions in Swagger and doc files |
686,936 | 02.10.2019 08:33:48 | -3,600 | bb1159d56a1f228087df2b22f5e280d9ea4905c1 | Removed 0 Jetty shutdown timeout as this appears to produce bad behaviour in the Java HTTPURLConnection client in some cases | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"diff": "@@ -325,9 +325,6 @@ public class JettyHttpServer implements HttpServer {\n);\nconnector.setPort(port);\n- connector.setStopTimeout(0);\n- connector.getSelectorManager().setStopTimeout(0);\n-\nconnector.addNetworkTrafficListener(listener);\nsetJettySettings(jettySettings, connector);\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Removed 0 Jetty shutdown timeout as this appears to produce bad behaviour in the Java HTTPURLConnection client in some cases |
686,936 | 02.10.2019 08:40:05 | -3,600 | c5d457595aac4ab4dc8743f2169e48efe36fda1d | Fixed shading for some new dependencies in standalone JAR | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -210,7 +210,7 @@ subprojects {\nrelocate \"org.mortbay\", 'wiremock.org.mortbay'\nrelocate \"org.eclipse\", 'wiremock.org.eclipse'\nrelocate \"org.codehaus\", 'wiremock.org.codehaus'\n- relocate \"com.google.common\", 'wiremock.com.google.common'\n+ relocate \"com.google\", 'wiremock.com.google'\nrelocate \"com.google.thirdparty\", 'wiremock.com.google.thirdparty'\nrelocate \"com.fasterxml.jackson\", 'wiremock.com.fasterxml.jackson'\nrelocate \"org.apache\", 'wiremock.org.apache'\n@@ -227,6 +227,7 @@ subprojects {\nrelocate \"com.github.jknack\", \"wiremock.com.github.jknack\"\nrelocate \"org.antlr\", \"wiremock.org.antlr\"\nrelocate \"javax.servlet\", \"wiremock.javax.servlet\"\n+ relocate \"org.checkerframework\", \"wiremock.org.checkerframework\"\ndependencies {\nexclude(dependency('junit:junit'))\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed shading for some new dependencies in standalone JAR |
686,936 | 03.10.2019 08:29:35 | -3,600 | 4c052a31ca4b1c42e9cb52aab31f28c36e820ea6 | Fixed - response templates not rendered when using jsonBody | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java",
"diff": "@@ -107,6 +107,11 @@ public class ResponseDefinitionBuilder {\nreturn this;\n}\n+ public ResponseDefinitionBuilder withJsonBody(JsonNode jsonBody) {\n+ this.jsonBody = jsonBody;\n+ return this;\n+ }\n+\npublic ResponseDefinitionBuilder withFixedDelay(Integer milliseconds) {\nthis.fixedDelayMilliseconds = milliseconds;\nreturn this;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformer.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.extension.responsetemplating;\n+import com.fasterxml.jackson.databind.JsonNode;\nimport com.github.jknack.handlebars.Handlebars;\nimport com.github.jknack.handlebars.Helper;\nimport com.github.jknack.handlebars.helper.AssignHelper;\n@@ -24,6 +25,7 @@ import com.github.jknack.handlebars.helper.StringHelpers;\nimport com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\nimport com.github.tomakehurst.wiremock.common.Exceptions;\nimport com.github.tomakehurst.wiremock.common.FileSource;\n+import com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.common.TextFile;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer;\n@@ -141,8 +143,9 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer i\n.build();\nif (responseDefinition.specifiesTextBodyContent()) {\n+ boolean isJsonBody = responseDefinition.getJsonBody() != null;\nHandlebarsOptimizedTemplate bodyTemplate = getTemplate(TemplateCacheKey.forInlineBody(responseDefinition), responseDefinition.getTextBody());\n- applyTemplatedResponseBody(newResponseDefBuilder, model, bodyTemplate);\n+ applyTemplatedResponseBody(newResponseDefBuilder, model, bodyTemplate, isJsonBody);\n} else if (responseDefinition.specifiesBodyFile()) {\nHandlebarsOptimizedTemplate filePathTemplate = new HandlebarsOptimizedTemplate(handlebars, responseDefinition.getBodyFileName());\nString compiledFilePath = uncheckedApplyTemplate(filePathTemplate, model);\n@@ -154,7 +157,7 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer i\nTextFile file = files.getTextFileNamed(compiledFilePath);\nHandlebarsOptimizedTemplate bodyTemplate = getTemplate(\nTemplateCacheKey.forFileBody(responseDefinition, compiledFilePath), file.readContentsAsString());\n- applyTemplatedResponseBody(newResponseDefBuilder, model, bodyTemplate);\n+ applyTemplatedResponseBody(newResponseDefBuilder, model, bodyTemplate, false);\n}\n}\n@@ -191,11 +194,16 @@ public class ResponseTemplateTransformer extends ResponseDefinitionTransformer i\nreturn Collections.emptyMap();\n}\n- private void applyTemplatedResponseBody(ResponseDefinitionBuilder newResponseDefBuilder, ImmutableMap<String, Object> model, HandlebarsOptimizedTemplate bodyTemplate) {\n+ private void applyTemplatedResponseBody(ResponseDefinitionBuilder newResponseDefBuilder, ImmutableMap<String, Object> model, HandlebarsOptimizedTemplate bodyTemplate, boolean isJsonBody) {\nString newBody = uncheckedApplyTemplate(bodyTemplate, model);\n+ if (isJsonBody) {\n+ newResponseDefBuilder.withJsonBody(Json.read(newBody, JsonNode.class));\n+ } else {\nnewResponseDefBuilder.withBody(newBody);\n}\n+ }\n+\nprivate String uncheckedApplyTemplate(HandlebarsOptimizedTemplate template, Object context) {\ntry {\nreturn template.apply(context);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseTemplatingAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseTemplatingAcceptanceTest.java",
"diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import com.github.tomakehurst.wiremock.testsupport.WireMatchers;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport org.junit.Before;\n@@ -207,6 +208,32 @@ public class ResponseTemplatingAcceptanceTest {\nassertThat(\nresponse.content(),\nresponse.statusCode(), is(200));\n+\n+ assertThat(response.content(), WireMatchers.equalToJson(\"{ \\\"modified\\\": \\\"3\\\" }\"));\n+ }\n+\n+ @Test\n+ public void jsonBodyTemplatesCanSpecifyRequestAttributes() {\n+ String stubJson = \"{\\n\" +\n+ \" \\\"request\\\": {\\n\" +\n+ \" \\\"method\\\": \\\"GET\\\",\\n\" +\n+ \" \\\"urlPath\\\": \\\"/jsonBody/template\\\"\\n\" +\n+ \" },\\n\" +\n+ \" \\\"response\\\": {\\n\" +\n+ \" \\\"jsonBody\\\": {\\n\" +\n+ \" \\\"Key\\\": \\\"Hello world {{request.query.qp}}!\\\"\\n\" +\n+ \" },\\n\" +\n+ \" \\\"status\\\": 200,\\n\" +\n+ \" \\\"transformers\\\": [\\n\" +\n+ \" \\\"response-template\\\"\\n\" +\n+ \" ]\\n\" +\n+ \" }\\n\" +\n+ \"}\";\n+ client.postJson(\"/__admin/mappings\", stubJson);\n+\n+ WireMockResponse response = client.get(\"/jsonBody/template?qp=2\");\n+\n+ assertThat(response.content(), is(\"{\\\"Key\\\":\\\"Hello world 2!\\\"}\"));\n}\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #1197 - response templates not rendered when using jsonBody |
686,936 | 03.10.2019 08:44:50 | -3,600 | 989cf4263b9028ccf3a78be59a30385347086bb9 | Fixed - documentation bug showing incorrect use of pathSegments in response templating | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/response-templating.md",
"new_path": "docs-v2/_docs/response-templating.md",
"diff": "@@ -116,7 +116,7 @@ The body file for a response can be selected dynamically by templating the file\n```java\nwm.stubFor(get(urlPathMatching(\"/static/.*\"))\n.willReturn(ok()\n- .withBodyFile(\"files/{{request.pathSegments.[1]}}\")));\n+ .withBodyFile(\"files/{{request.requestLine.pathSegments.[1]}}\")));\n```\n{% endraw %}\n@@ -132,7 +132,7 @@ wm.stubFor(get(urlPathMatching(\"/static/.*\"))\n},\n\"response\" : {\n\"status\" : 200,\n- \"bodyFileName\" : \"files/{{request.pathSegments.[1]}}\"\n+ \"bodyFileName\" : \"files/{{request.requestLine.pathSegments.[1]}}\"\n}\n}\n```\n@@ -145,7 +145,7 @@ The model of the request is supplied to the header and body templates. The follo\n`request.requestLine.path` - URL path\n-`request.requestLine.pathSegments.[<n>]`- URL path segment (zero indexed) e.g. `request.pathSegments.[2]`\n+`request.requestLine.pathSegments.[<n>]`- URL path segment (zero indexed) e.g. `request.requestLine.pathSegments.[2]`\n`request.requestLine.query.<key>`- First value of a query parameter e.g. `request.query.search`\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #1181 - documentation bug showing incorrect use of pathSegments in response templating |
686,936 | 08.10.2019 09:27:28 | -3,600 | cf453ca2e33e2cce9f82559b816396ed74bbf7fb | Fixed - blocked/timed out requests with default (too low) acceptor and container thread counts | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"diff": "@@ -41,7 +41,7 @@ public interface Options {\nint DEFAULT_PORT = 8080;\nint DYNAMIC_PORT = 0;\n- int DEFAULT_CONTAINER_THREADS = 10;\n+ int DEFAULT_CONTAINER_THREADS = 14;\nString DEFAULT_BIND_ADDRESS = \"0.0.0.0\";\nint portNumber();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"diff": "@@ -54,6 +54,7 @@ import static java.util.concurrent.Executors.newScheduledThreadPool;\npublic class JettyHttpServer implements HttpServer {\nprivate static final String FILES_URL_MATCH = String.format(\"/%s/*\", WireMockApp.FILES_ROOT);\nprivate static final String[] GZIPPABLE_METHODS = new String[] { \"POST\", \"PUT\", \"PATCH\", \"DELETE\" };\n+ private static final int DEFAULT_ACCEPTORS = 3;\nstatic {\nSystem.setProperty(\"org.eclipse.jetty.server.HttpChannelState.DEFAULT_TIMEOUT\", \"300000\");\n@@ -313,7 +314,7 @@ public class JettyHttpServer implements HttpServer {\nNetworkTrafficListener listener,\nConnectionFactory... connectionFactories) {\n- int acceptors = jettySettings.getAcceptors().or(2);\n+ int acceptors = jettySettings.getAcceptors().or(DEFAULT_ACCEPTORS);\nNetworkTrafficServerConnector connector = new NetworkTrafficServerConnector(\njettyServer,\nnull,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/DeadlockTest.java",
"diff": "+package com.github.tomakehurst.wiremock;\n+\n+import org.apache.commons.io.IOUtils;\n+import org.junit.*;\n+import org.junit.runners.MethodSorters;\n+\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.net.HttpURLConnection;\n+import java.net.SocketTimeoutException;\n+import java.net.URL;\n+import java.util.concurrent.TimeUnit;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\n+import static org.hamcrest.Matchers.instanceOf;\n+import static org.junit.Assert.*;\n+\n+@FixMethodOrder(MethodSorters.NAME_ASCENDING)\n+public class DeadlockTest {\n+\n+ private static final int READ_TIMEOUT = 500;\n+\n+ private static WireMockServer wireMockServer;\n+\n+ @BeforeClass\n+ public static void setUp() {\n+ wireMockServer = new WireMockServer(options()\n+ .dynamicPort()\n+ .dynamicHttpsPort()\n+ );\n+ wireMockServer.start();\n+ }\n+\n+ @AfterClass\n+ public static void tearDown() {\n+ wireMockServer.stop();\n+ }\n+\n+ @Before\n+ public void reset() {\n+ System.out.println(\"reset\");\n+ wireMockServer.resetAll();\n+ }\n+\n+ @Test\n+ public void test1Timeout() throws IOException {\n+ System.out.println(\"test timeout start\");\n+\n+ wireMockServer.stubFor(get(urlEqualTo(\"/timeout\"))\n+ .willReturn(aResponse()\n+ .withFixedDelay(2 * READ_TIMEOUT)\n+ .withBody(\"body1\")));\n+\n+ downloadContentAndMeasure(\"/timeout\", null);\n+\n+ System.out.println(\"test timeout end\");\n+ }\n+\n+ // This will fail with a timeout if acceptor count is < 3 and/or threads < 13\n+ @Test\n+ public void test2GetContent() throws IOException {\n+ System.out.println(\"test content start\");\n+\n+ wireMockServer.stubFor(get(urlEqualTo(\"/content\"))\n+ .willReturn(aResponse()\n+ .withBody(\"body2\")));\n+ System.out.println(\"test content stub\");\n+\n+ downloadContentAndMeasure(\"/content\", \"body2\");\n+\n+ System.out.println(\"test content end\");\n+ }\n+\n+ private void downloadContentAndMeasure(String urlDir, String expectedBody) throws IOException {\n+ System.out.printf(\"downloadContentAndMeasure urlDir=%s\", urlDir);\n+\n+ final long start = System.currentTimeMillis();\n+\n+\n+ boolean exceptionOccurred = false;\n+ try {\n+ final String url = \"http://localhost:\" + wireMockServer.port() + urlDir;\n+ final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();\n+ connection.setConnectTimeout(2000);\n+ connection.setReadTimeout(READ_TIMEOUT);\n+ connection.setDoInput(true);\n+ if (expectedBody == null) {\n+ try {\n+ httpGetContent(connection);\n+ fail(\"Expected SocketTimeoutException\");\n+ } catch (Exception e) {\n+ assertThat(e, instanceOf(SocketTimeoutException.class));\n+ }\n+ } else {\n+ final String body = httpGetContent(connection);\n+ assertEquals(expectedBody, body);\n+ }\n+ } catch (Exception e) {\n+ exceptionOccurred = true;\n+ System.out.printf(\"exception '%s' after ms %s\", e.getMessage(), TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - start));\n+ throw e;\n+ } finally {\n+ if (!exceptionOccurred) {\n+ System.out.printf(\"downloaded at ms %s\", TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - start));\n+ }\n+ }\n+ }\n+\n+ private String httpGetContent(HttpURLConnection connection) throws IOException {\n+ try (InputStream is = connection.getInputStream()) {\n+ return IOUtils.toString(is);\n+ }\n+ }\n+\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"diff": "@@ -233,9 +233,9 @@ public class CommandLineOptionsTest {\n}\n@Test\n- public void defaultsContainerThreadsTo10() {\n+ public void defaultsContainerThreadsTo14() {\nCommandLineOptions options = new CommandLineOptions();\n- assertThat(options.containerThreads(), is(10));\n+ assertThat(options.containerThreads(), is(14));\n}\n@Test\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #1190 - blocked/timed out requests with default (too low) acceptor and container thread counts |
686,983 | 28.10.2019 19:57:48 | -3,600 | e5c11e45258705a0e811de54a5073d9481e00c1b | Exclude transitive jackson dependencies | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -82,7 +82,10 @@ allprojects {\nexclude group: \"org.hamcrest\", module: \"hamcrest-core\"\n}\ncompile 'org.apache.commons:commons-lang3:3.7'\n- compile 'com.flipkart.zjsonpatch:zjsonpatch:0.4.4'\n+ compile 'com.flipkart.zjsonpatch:zjsonpatch:0.4.4', {\n+ exclude group: 'com.fasterxml.jackson.core', module: 'jackson-databind'\n+ exclude group: 'com.fasterxml.jackson.core', module: 'jackson-core'\n+ }\ncompile \"com.github.jknack:handlebars:$versions.handlebars\", {\nexclude group: 'org.mozilla', module: 'rhino'\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Exclude transitive jackson dependencies (#1215) |
686,936 | 26.11.2019 09:33:25 | 0 | 24532f76996ad52b908ad52712c5236427bdd22f | Fix for - shutdown not working when async responses enabled | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"diff": "@@ -64,6 +64,8 @@ public class JettyHttpServer implements HttpServer {\nprivate final ServerConnector httpConnector;\nprivate final ServerConnector httpsConnector;\n+ private ScheduledExecutorService scheduledExecutorService;\n+\npublic JettyHttpServer(\nOptions options,\nAdminRequestHandler adminRequestHandler,\n@@ -199,6 +201,10 @@ public class JettyHttpServer implements HttpServer {\n@Override\npublic void stop() {\ntry {\n+ if (scheduledExecutorService != null) {\n+ scheduledExecutorService.shutdown();\n+ }\n+\njettyServer.stop();\njettyServer.join();\n} catch (Exception e) {\n@@ -367,7 +373,7 @@ public class JettyHttpServer implements HttpServer {\nservletHolder.setInitParameter(WireMockHandlerDispatchingServlet.SHOULD_FORWARD_TO_FILES_CONTEXT, \"true\");\nif (asynchronousResponseSettings.isEnabled()) {\n- ScheduledExecutorService scheduledExecutorService = newScheduledThreadPool(asynchronousResponseSettings.getThreads());\n+ scheduledExecutorService = newScheduledThreadPool(asynchronousResponseSettings.getThreads());\nmockServiceContext.setAttribute(WireMockHandlerDispatchingServlet.ASYNCHRONOUS_RESPONSE_EXECUTOR, scheduledExecutorService);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java",
"diff": "@@ -401,6 +401,27 @@ public class StandaloneAcceptanceTest {\nfail(\"WireMock did not shut down\");\n}\n+ @Test\n+ public void canBeShutDownRemotelyWhenAsyncResponsesEnabled() {\n+ startRunner(\"--async-response-enabled\");\n+\n+ stubFor(get(\"/delay-this\").willReturn(ok().withFixedDelay(50)));\n+ testClient.get(\"/delay-this\");\n+ testClient.get(\"/delay-this\");\n+ testClient.get(\"/delay-this\");\n+\n+ WireMock.shutdownServer();\n+\n+ // Keep trying the server until it shuts down.\n+ long startTime = System.currentTimeMillis();\n+ while (System.currentTimeMillis() - startTime < 5000) {\n+ if (!runner.isRunning()) {\n+ return;\n+ }\n+ }\n+ fail(\"WireMock did not shut down\");\n+ }\n+\n@Test\npublic void isRunningReturnsFalseBeforeRunMethodIsExecuted() {\nrunner = new WireMockServerRunner();\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fix for #1209 - shutdown not working when async responses enabled |
686,935 | 26.11.2019 01:38:10 | 28,800 | 4385dbbfc765664adf9c41995d087a6947122d50 | Fix asm dependency convergence errors | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -74,7 +74,9 @@ allprojects {\nexclude group: 'junit', module: 'junit'\n}\ncompile \"org.xmlunit:xmlunit-placeholders:$versions.xmlUnit\"\n- compile \"com.jayway.jsonpath:json-path:2.4.0\"\n+ compile \"com.jayway.jsonpath:json-path:2.4.0\", {\n+ exclude group: 'org.ow2.asm', module: 'asm'\n+ }\ncompile \"org.ow2.asm:asm:7.0\"\ncompile \"org.slf4j:slf4j-api:1.7.12\"\ncompile \"net.sf.jopt-simple:jopt-simple:5.0.3\"\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fix asm dependency convergence errors (#1227) |
687,033 | 26.11.2019 01:42:27 | 28,800 | e5b50de2a3aa44ef45809b7750e48d0e1fb8860e | Feature: Add --http-disabled flag
Added ability to disable the HTTP connector, leaving just the HTTPS connector enabled. | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/https.md",
"new_path": "docs-v2/_docs/https.md",
"diff": "@@ -43,6 +43,12 @@ The keystore type defaults to JKS, but this can be changed if you're using anoth\n.keystoreType(\"BKS\")\n```\n+To allow only HTTPS requests, disable HTTP by adding:\n+```java\n+@Rule\n+public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().httpsPort(8443).httpDisabled(true));\n+```\n+\n## Requiring client certificates\nTo make WireMock require clients to authenticate via a certificate you\n@@ -67,7 +73,6 @@ specify a trust store containing the certificate(s).\n> See [this script](https://github.com/tomakehurst/wiremock/blob/master/scripts/create-client-cert.sh) for an example of how to build\n> a truststore containing a valid certificate (you'll probably want to edit the client-cert.conf file before running this).\n-\n## Common HTTPS issues\n`javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?`: Usually means you've tried to connect to the\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/running-standalone.md",
"new_path": "docs-v2/_docs/running-standalone.md",
"diff": "@@ -28,6 +28,8 @@ The following can optionally be specified on the command line:\n`--port`: Set the HTTP port number e.g. `--port 9999`. Use `--port 0` to dynamically determine a port.\n+`--disable-http`: Disable the HTTP listener, option available only if HTTPS is enabled.\n+\n`--https-port`: If specified, enables HTTPS on the supplied port.\nNote: When you specify this parameter, WireMock will still, additionally, bind to an HTTP port (8080 by default). So when running multiple WireMock servers you will also need to specify the `--port` parameter in order to avoid conflicts.\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/WireMockServer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/WireMockServer.java",
"diff": "@@ -176,8 +176,8 @@ public class WireMockServer implements Container, Stubbing, Admin {\npublic int port() {\ncheckState(\n- isRunning(),\n- \"Not listening on HTTP port. The WireMock server is most likely stopped\"\n+ isRunning() && !options.getHttpDisabled(),\n+ \"Not listening on HTTP port. Either HTTP is not enabled or the WireMock server is stopped.\"\n);\nreturn httpServer.port();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"diff": "@@ -45,6 +45,7 @@ public interface Options {\nString DEFAULT_BIND_ADDRESS = \"0.0.0.0\";\nint portNumber();\n+ boolean getHttpDisabled();\nHttpsSettings httpsSettings();\nJettySettings jettySettings();\nint containerThreads();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java",
"diff": "@@ -50,6 +50,7 @@ import static java.util.Collections.emptyList;\npublic class WireMockConfiguration implements Options {\nprivate int portNumber = DEFAULT_PORT;\n+ private boolean httpDisabled = false;\nprivate String bindAddress = DEFAULT_BIND_ADDRESS;\nprivate int containerThreads = DEFAULT_CONTAINER_THREADS;\n@@ -121,6 +122,11 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n+ public WireMockConfiguration httpDisabled(boolean httpDisabled) {\n+ this.httpDisabled = httpDisabled;\n+ return this;\n+ }\n+\npublic WireMockConfiguration httpsPort(Integer httpsPort) {\nthis.httpsPort = httpsPort;\nreturn this;\n@@ -348,6 +354,11 @@ public class WireMockConfiguration implements Options {\nreturn portNumber;\n}\n+ @Override\n+ public boolean getHttpDisabled() {\n+ return httpDisabled;\n+ }\n+\n@Override\npublic int containerThreads() {\nreturn containerThreads;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"diff": "@@ -74,6 +74,10 @@ public class JettyHttpServer implements HttpServer {\njettyServer = createServer(options);\nNetworkTrafficListenerAdapter networkTrafficListenerAdapter = new NetworkTrafficListenerAdapter(options.networkTrafficListener());\n+\n+ if (options.getHttpDisabled()) {\n+ httpConnector = null;\n+ } else {\nhttpConnector = createHttpConnector(\noptions.bindAddress(),\noptions.portNumber(),\n@@ -81,6 +85,7 @@ public class JettyHttpServer implements HttpServer {\nnetworkTrafficListenerAdapter\n);\njettyServer.addConnector(httpConnector);\n+ }\nif (options.httpsSettings().enabled()) {\nhttpsConnector = createHttpsConnector(\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"diff": "@@ -52,6 +52,11 @@ public class WarConfiguration implements Options {\nreturn 0;\n}\n+ @Override\n+ public boolean getHttpDisabled() {\n+ return false;\n+ }\n+\n@Override\npublic HttpsSettings httpsSettings() {\nreturn new HttpsSettings.Builder().build();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java",
"diff": "@@ -63,6 +63,7 @@ public class CommandLineOptions implements Options {\nprivate static final String PRESERVE_HOST_HEADER = \"preserve-host-header\";\nprivate static final String PROXY_VIA = \"proxy-via\";\nprivate static final String PORT = \"port\";\n+ private static final String DISABLE_HTTP = \"disable-http\";\nprivate static final String BIND_ADDRESS = \"bind-address\";\nprivate static final String HTTPS_PORT = \"https-port\";\nprivate static final String HTTPS_KEYSTORE = \"https-keystore\";\n@@ -106,6 +107,7 @@ public class CommandLineOptions implements Options {\npublic CommandLineOptions(String... args) {\nOptionParser optionParser = new OptionParser();\noptionParser.accepts(PORT, \"The port number for the server to listen on (default: 8080). 0 for dynamic port selection.\").withRequiredArg();\n+ optionParser.accepts(DISABLE_HTTP, \"Disable the default HTTP listener.\");\noptionParser.accepts(HTTPS_PORT, \"If this option is present WireMock will enable HTTPS on the specified port\").withRequiredArg();\noptionParser.accepts(BIND_ADDRESS, \"The IP to listen connections\").withRequiredArg();\noptionParser.accepts(CONTAINER_THREADS, \"The number of container threads\").withRequiredArg();\n@@ -156,6 +158,12 @@ public class CommandLineOptions implements Options {\n}\nprivate void validate() {\n+ if (optionSet.has(PORT) && optionSet.has(DISABLE_HTTP)) {\n+ throw new IllegalArgumentException(\"The HTTP listener can't have a port set and be disabled at the same time\");\n+ }\n+ if (!optionSet.has(HTTPS_PORT) && optionSet.has(DISABLE_HTTP)) {\n+ throw new IllegalArgumentException(\"HTTPS must be enabled if HTTP is not.\");\n+ }\nif (optionSet.has(HTTPS_KEYSTORE) && !optionSet.has(HTTPS_PORT)) {\nthrow new IllegalArgumentException(\"HTTPS port number must be specified if specifying the keystore path\");\n}\n@@ -228,6 +236,11 @@ public class CommandLineOptions implements Options {\nreturn DEFAULT_PORT;\n}\n+ @Override\n+ public boolean getHttpDisabled() {\n+ return optionSet.has(DISABLE_HTTP);\n+ }\n+\npublic void setResultingPort(int port) {\nresultingPort = Optional.of(port);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/HttpsAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/HttpsAcceptanceTest.java",
"diff": "@@ -20,7 +20,6 @@ import com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.core.WireMockConfiguration;\nimport com.github.tomakehurst.wiremock.http.Fault;\nimport com.github.tomakehurst.wiremock.http.HttpClientFactory;\n-import com.github.tomakehurst.wiremock.testsupport.TestFiles;\nimport com.google.common.io.Resources;\nimport org.apache.commons.lang3.SystemUtils;\nimport org.apache.http.HttpResponse;\n@@ -63,7 +62,6 @@ import static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.junit.Assume.assumeFalse;\n-import static org.junit.Assume.assumeTrue;\npublic class HttpsAcceptanceTest {\n@@ -71,6 +69,9 @@ public class HttpsAcceptanceTest {\nprivate WireMockServer proxy;\nprivate HttpClient httpClient;\n+ @Rule\n+ public ExpectedException exceptionRule = ExpectedException.none();\n+\n@After\npublic void serverShutdown() {\nif (wireMockServer != null) {\n@@ -90,6 +91,24 @@ public class HttpsAcceptanceTest {\nassertThat(contentFor(url(\"/https-test\")), is(\"HTTPS content\"));\n}\n+ @Test\n+ public void shouldReturnOnlyOnHttpsWhenHttpDisabled() throws Exception {\n+ // HTTP\n+ exceptionRule.expect(IllegalStateException.class);\n+ exceptionRule.expectMessage(\"Not listening on HTTP port. Either HTTP is not enabled or the WireMock server is stopped.\");\n+ // HTTPS\n+ WireMockConfiguration config = wireMockConfig().httpDisabled(true).dynamicHttpsPort();\n+ wireMockServer = new WireMockServer(config);\n+ wireMockServer.start();\n+ WireMock.configureFor(\"https\", \"localhost\", wireMockServer.httpsPort());\n+ httpClient = HttpClientFactory.createClient();\n+\n+ stubFor(get(urlEqualTo(\"/https-test\")).willReturn(aResponse().withStatus(200).withBody(\"HTTPS content\")));\n+\n+ wireMockServer.port();\n+ assertThat(contentFor(url(\"/https-test\")), is(\"HTTPS content\"));\n+ }\n+\n@Rule\npublic final ExpectedException exception = ExpectedException.none();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServerTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServerTest.java",
"diff": "@@ -27,15 +27,18 @@ import com.github.tomakehurst.wiremock.http.ResponseRenderer;\nimport com.github.tomakehurst.wiremock.http.StubRequestHandler;\nimport com.github.tomakehurst.wiremock.security.NoAuthenticator;\nimport com.github.tomakehurst.wiremock.verification.RequestJournal;\n+import org.eclipse.jetty.server.ServerConnector;\nimport org.jmock.Mockery;\nimport org.jmock.integration.junit4.JMock;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n+import java.lang.reflect.Field;\nimport java.util.Collections;\nimport static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertThat;\n@RunWith(JMock.class)\n@@ -83,4 +86,17 @@ public class JettyHttpServerTest {\nassertThat(jettyHttpServer.stopTimeout(), is(expectedStopTimeout));\n}\n+\n+ @Test\n+ public void testHttpConnectorIsNullWhenHttpDisabled() throws NoSuchFieldException, IllegalAccessException {\n+ WireMockConfiguration config = WireMockConfiguration.wireMockConfig().httpDisabled(true);\n+\n+ JettyHttpServer jettyHttpServer = (JettyHttpServer) serverFactory.buildHttpServer(config, adminRequestHandler, stubRequestHandler);\n+\n+ Field httpConnectorField = JettyHttpServer.class.getDeclaredField(\"httpConnector\");\n+ httpConnectorField.setAccessible(true);\n+ ServerConnector httpConnector = (ServerConnector) httpConnectorField.get(jettyHttpServer);\n+\n+ assertNull(httpConnector);\n+ }\n}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"diff": "@@ -79,6 +79,13 @@ public class CommandLineOptionsTest {\nassertThat(options.portNumber(), is(8086));\n}\n+ @Test\n+ public void disablesHttpWhenOptionPresentAndHttpsEnabled() {\n+ CommandLineOptions options = new CommandLineOptions(\"--disable-http\",\n+ \"--https-port\", \"8443\");\n+ assertThat(options.getHttpDisabled(), is(true));\n+ }\n+\n@Test\npublic void enablesHttpsAndSetsPortNumberWhenOptionPresent() {\nCommandLineOptions options = new CommandLineOptions(\"--https-port\", \"8443\");\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/ignored/Examples.java",
"new_path": "src/test/java/ignored/Examples.java",
"diff": "@@ -374,6 +374,9 @@ public class Examples extends AcceptanceTestBase {\n// Statically set the HTTP port number. Defaults to 8080.\n.port(8000)\n+ // Disable HTTP listener.\n+ .httpDisabled(true)\n+\n// Statically set the HTTPS port number. Defaults to 8443.\n.httpsPort(8001)\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Feature: Add --http-disabled flag (#1200)
Added ability to disable the HTTP connector, leaving just the HTTPS connector enabled. |
686,936 | 27.11.2019 17:48:15 | 0 | 959fb613ac101391cc5f217a346537ee15ac0f53 | Updated Spring Cloud Contract WireMock URL to unversioned doc | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/spring-boot.md",
"new_path": "docs-v2/_docs/spring-boot.md",
"diff": "@@ -9,4 +9,4 @@ The team behind Spring Cloud Contract have created a library to support running\nIt also simplifies some aspects of configuration and eliminates some common issues that occur when running Spring Boot and WireMock together.\n-See [Spring Cloud Contract WireMock](http://cloud.spring.io/spring-cloud-static/spring-cloud-contract/1.1.2.RELEASE/#_spring_cloud_contract_wiremock) for details.\n+See [Spring Cloud Contract WireMock](https://cloud.spring.io/spring-cloud-contract/reference/html/project-features.html#features-wiremock) for details.\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Updated Spring Cloud Contract WireMock URL to unversioned doc |
687,060 | 11.12.2019 16:42:25 | -39,600 | d49836d525a223d3d6a272e269309128b3ca139d | Don't update the gems. | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/Gemfile.lock",
"new_path": "docs-v2/Gemfile.lock",
"diff": "GEM\nremote: https://rubygems.org/\nspecs:\n- activesupport (6.0.1)\n- concurrent-ruby (~> 1.0, >= 1.0.2)\n- i18n (>= 0.7, < 2)\n+ activesupport (4.2.9)\n+ i18n (~> 0.7)\nminitest (~> 5.1)\n+ thread_safe (~> 0.3, >= 0.3.4)\ntzinfo (~> 1.1)\n- zeitwerk (~> 2.2)\n- addressable (2.7.0)\n- public_suffix (>= 2.0.2, < 5.0)\n+ addressable (2.5.2)\n+ public_suffix (>= 2.0.2, < 4.0)\ncoffee-script (2.4.1)\ncoffee-script-source\nexecjs\n@@ -16,226 +15,219 @@ GEM\ncolorator (1.1.0)\ncommonmarker (0.17.13)\nruby-enum (~> 0.5)\n- concurrent-ruby (1.1.5)\n- dnsruby (1.61.3)\n- addressable (~> 2.5)\n- em-websocket (0.5.1)\n- eventmachine (>= 0.12.9)\n- http_parser.rb (~> 0.6.0)\n- ethon (0.12.0)\n+ concurrent-ruby (1.0.5)\n+ ethon (0.11.0)\nffi (>= 1.3.0)\n- eventmachine (1.2.7)\nexecjs (2.7.0)\n- faraday (0.17.1)\n+ faraday (0.15.3)\nmultipart-post (>= 1.2, < 3)\n- ffi (1.11.3)\n+ ffi (1.9.25)\nforwardable-extended (2.6.0)\n- gemoji (3.0.1)\n- github-pages (203)\n- github-pages-health-check (= 1.16.1)\n- jekyll (= 3.8.5)\n- jekyll-avatar (= 0.7.0)\n- jekyll-coffeescript (= 1.1.1)\n- jekyll-commonmark-ghpages (= 0.1.6)\n+ gemoji (3.0.0)\n+ github-pages (177)\n+ activesupport (= 4.2.9)\n+ github-pages-health-check (= 1.3.5)\n+ jekyll (= 3.6.2)\n+ jekyll-avatar (= 0.5.0)\n+ jekyll-coffeescript (= 1.0.2)\n+ jekyll-commonmark-ghpages (= 0.1.5)\njekyll-default-layout (= 0.1.4)\n- jekyll-feed (= 0.13.0)\n- jekyll-gist (= 1.5.0)\n- jekyll-github-metadata (= 2.12.1)\n- jekyll-mentions (= 1.5.1)\n- jekyll-optional-front-matter (= 0.3.2)\n+ jekyll-feed (= 0.9.2)\n+ jekyll-gist (= 1.4.1)\n+ jekyll-github-metadata (= 2.9.3)\n+ jekyll-mentions (= 1.2.0)\n+ jekyll-optional-front-matter (= 0.3.0)\njekyll-paginate (= 1.1.0)\n- jekyll-readme-index (= 0.3.0)\n- jekyll-redirect-from (= 0.15.0)\n- jekyll-relative-links (= 0.6.1)\n- jekyll-remote-theme (= 0.4.1)\n- jekyll-sass-converter (= 1.5.2)\n- jekyll-seo-tag (= 2.6.1)\n- jekyll-sitemap (= 1.4.0)\n- jekyll-swiss (= 1.0.0)\n- jekyll-theme-architect (= 0.1.1)\n- jekyll-theme-cayman (= 0.1.1)\n- jekyll-theme-dinky (= 0.1.1)\n- jekyll-theme-hacker (= 0.1.1)\n- jekyll-theme-leap-day (= 0.1.1)\n- jekyll-theme-merlot (= 0.1.1)\n- jekyll-theme-midnight (= 0.1.1)\n- jekyll-theme-minimal (= 0.1.1)\n- jekyll-theme-modernist (= 0.1.1)\n- jekyll-theme-primer (= 0.5.4)\n- jekyll-theme-slate (= 0.1.1)\n- jekyll-theme-tactile (= 0.1.1)\n- jekyll-theme-time-machine (= 0.1.1)\n- jekyll-titles-from-headings (= 0.5.3)\n- jemoji (= 0.11.1)\n- kramdown (= 1.17.0)\n- liquid (= 4.0.3)\n+ jekyll-readme-index (= 0.2.0)\n+ jekyll-redirect-from (= 0.12.1)\n+ jekyll-relative-links (= 0.5.2)\n+ jekyll-remote-theme (= 0.2.3)\n+ jekyll-sass-converter (= 1.5.0)\n+ jekyll-seo-tag (= 2.3.0)\n+ jekyll-sitemap (= 1.1.1)\n+ jekyll-swiss (= 0.4.0)\n+ jekyll-theme-architect (= 0.1.0)\n+ jekyll-theme-cayman (= 0.1.0)\n+ jekyll-theme-dinky (= 0.1.0)\n+ jekyll-theme-hacker (= 0.1.0)\n+ jekyll-theme-leap-day (= 0.1.0)\n+ jekyll-theme-merlot (= 0.1.0)\n+ jekyll-theme-midnight (= 0.1.0)\n+ jekyll-theme-minimal (= 0.1.0)\n+ jekyll-theme-modernist (= 0.1.0)\n+ jekyll-theme-primer (= 0.5.2)\n+ jekyll-theme-slate (= 0.1.0)\n+ jekyll-theme-tactile (= 0.1.0)\n+ jekyll-theme-time-machine (= 0.1.0)\n+ jekyll-titles-from-headings (= 0.5.0)\n+ jemoji (= 0.8.1)\n+ kramdown (= 1.16.2)\n+ liquid (= 4.0.0)\n+ listen (= 3.0.6)\nmercenary (~> 0.3)\n- minima (= 2.5.1)\n- nokogiri (>= 1.10.4, < 2.0)\n- rouge (= 3.13.0)\n+ minima (= 2.1.1)\n+ nokogiri (>= 1.8.1, < 2.0)\n+ rouge (= 2.2.1)\nterminal-table (~> 1.4)\n- github-pages-health-check (1.16.1)\n+ github-pages-health-check (1.3.5)\naddressable (~> 2.3)\n- dnsruby (~> 1.60)\n+ net-dns (~> 0.8)\noctokit (~> 4.0)\n- public_suffix (~> 3.0)\n- typhoeus (~> 1.3)\n- html-pipeline (2.12.2)\n+ public_suffix (~> 2.0)\n+ typhoeus (~> 0.7)\n+ html-pipeline (2.8.4)\nactivesupport (>= 2)\nnokogiri (>= 1.4)\n- http_parser.rb (0.6.0)\ni18n (0.9.5)\nconcurrent-ruby (~> 1.0)\n- jekyll (3.8.5)\n+ jekyll (3.6.2)\naddressable (~> 2.4)\ncolorator (~> 1.0)\n- em-websocket (~> 0.5)\n- i18n (~> 0.7)\njekyll-sass-converter (~> 1.0)\n- jekyll-watch (~> 2.0)\n+ jekyll-watch (~> 1.1)\nkramdown (~> 1.14)\nliquid (~> 4.0)\nmercenary (~> 0.3.3)\npathutil (~> 0.9)\n- rouge (>= 1.7, < 4)\n+ rouge (>= 1.7, < 3)\nsafe_yaml (~> 1.0)\n- jekyll-avatar (0.7.0)\n- jekyll (>= 3.0, < 5.0)\n- jekyll-coffeescript (1.1.1)\n+ jekyll-avatar (0.5.0)\n+ jekyll (~> 3.0)\n+ jekyll-coffeescript (1.0.2)\ncoffee-script (~> 2.2)\ncoffee-script-source (~> 1.11.1)\n- jekyll-commonmark (1.3.1)\n+ jekyll-commonmark (1.2.0)\ncommonmarker (~> 0.14)\n- jekyll (>= 3.7, < 5.0)\n- jekyll-commonmark-ghpages (0.1.6)\n+ jekyll (>= 3.0, < 4.0)\n+ jekyll-commonmark-ghpages (0.1.5)\ncommonmarker (~> 0.17.6)\n- jekyll-commonmark (~> 1.2)\n- rouge (>= 2.0, < 4.0)\n+ jekyll-commonmark (~> 1)\n+ rouge (~> 2)\njekyll-default-layout (0.1.4)\njekyll (~> 3.0)\n- jekyll-feed (0.13.0)\n- jekyll (>= 3.7, < 5.0)\n- jekyll-gist (1.5.0)\n+ jekyll-feed (0.9.2)\n+ jekyll (~> 3.3)\n+ jekyll-gist (1.4.1)\noctokit (~> 4.2)\n- jekyll-github-metadata (2.12.1)\n- jekyll (~> 3.4)\n+ jekyll-github-metadata (2.9.3)\n+ jekyll (~> 3.1)\noctokit (~> 4.0, != 4.4.0)\n- jekyll-mentions (1.5.1)\n+ jekyll-mentions (1.2.0)\n+ activesupport (~> 4.0)\nhtml-pipeline (~> 2.3)\n- jekyll (>= 3.7, < 5.0)\n- jekyll-optional-front-matter (0.3.2)\n- jekyll (>= 3.0, < 5.0)\n+ jekyll (~> 3.0)\n+ jekyll-optional-front-matter (0.3.0)\n+ jekyll (~> 3.0)\njekyll-paginate (1.1.0)\n- jekyll-readme-index (0.3.0)\n- jekyll (>= 3.0, < 5.0)\n- jekyll-redirect-from (0.15.0)\n- jekyll (>= 3.3, < 5.0)\n- jekyll-relative-links (0.6.1)\n- jekyll (>= 3.3, < 5.0)\n- jekyll-remote-theme (0.4.1)\n- addressable (~> 2.0)\n- jekyll (>= 3.5, < 5.0)\n- rubyzip (>= 1.3.0)\n- jekyll-sass-converter (1.5.2)\n+ jekyll-readme-index (0.2.0)\n+ jekyll (~> 3.0)\n+ jekyll-redirect-from (0.12.1)\n+ jekyll (~> 3.3)\n+ jekyll-relative-links (0.5.2)\n+ jekyll (~> 3.3)\n+ jekyll-remote-theme (0.2.3)\n+ jekyll (~> 3.5)\n+ rubyzip (>= 1.2.1, < 3.0)\n+ typhoeus (>= 0.7, < 2.0)\n+ jekyll-sass-converter (1.5.0)\nsass (~> 3.4)\n- jekyll-seo-tag (2.6.1)\n- jekyll (>= 3.3, < 5.0)\n- jekyll-sitemap (1.4.0)\n- jekyll (>= 3.7, < 5.0)\n- jekyll-swiss (1.0.0)\n- jekyll-theme-architect (0.1.1)\n+ jekyll-seo-tag (2.3.0)\n+ jekyll (~> 3.3)\n+ jekyll-sitemap (1.1.1)\n+ jekyll (~> 3.3)\n+ jekyll-swiss (0.4.0)\n+ jekyll-theme-architect (0.1.0)\njekyll (~> 3.5)\njekyll-seo-tag (~> 2.0)\n- jekyll-theme-cayman (0.1.1)\n+ jekyll-theme-cayman (0.1.0)\njekyll (~> 3.5)\njekyll-seo-tag (~> 2.0)\n- jekyll-theme-dinky (0.1.1)\n+ jekyll-theme-dinky (0.1.0)\njekyll (~> 3.5)\njekyll-seo-tag (~> 2.0)\n- jekyll-theme-hacker (0.1.1)\n+ jekyll-theme-hacker (0.1.0)\njekyll (~> 3.5)\njekyll-seo-tag (~> 2.0)\n- jekyll-theme-leap-day (0.1.1)\n+ jekyll-theme-leap-day (0.1.0)\njekyll (~> 3.5)\njekyll-seo-tag (~> 2.0)\n- jekyll-theme-merlot (0.1.1)\n+ jekyll-theme-merlot (0.1.0)\njekyll (~> 3.5)\njekyll-seo-tag (~> 2.0)\n- jekyll-theme-midnight (0.1.1)\n+ jekyll-theme-midnight (0.1.0)\njekyll (~> 3.5)\njekyll-seo-tag (~> 2.0)\n- jekyll-theme-minimal (0.1.1)\n+ jekyll-theme-minimal (0.1.0)\njekyll (~> 3.5)\njekyll-seo-tag (~> 2.0)\n- jekyll-theme-modernist (0.1.1)\n+ jekyll-theme-modernist (0.1.0)\njekyll (~> 3.5)\njekyll-seo-tag (~> 2.0)\n- jekyll-theme-primer (0.5.4)\n- jekyll (> 3.5, < 5.0)\n+ jekyll-theme-primer (0.5.2)\n+ jekyll (~> 3.5)\njekyll-github-metadata (~> 2.9)\n- jekyll-seo-tag (~> 2.0)\n- jekyll-theme-slate (0.1.1)\n+ jekyll-seo-tag (~> 2.2)\n+ jekyll-theme-slate (0.1.0)\njekyll (~> 3.5)\njekyll-seo-tag (~> 2.0)\n- jekyll-theme-tactile (0.1.1)\n+ jekyll-theme-tactile (0.1.0)\njekyll (~> 3.5)\njekyll-seo-tag (~> 2.0)\n- jekyll-theme-time-machine (0.1.1)\n+ jekyll-theme-time-machine (0.1.0)\njekyll (~> 3.5)\njekyll-seo-tag (~> 2.0)\n- jekyll-titles-from-headings (0.5.3)\n- jekyll (>= 3.3, < 5.0)\n- jekyll-watch (2.2.1)\n+ jekyll-titles-from-headings (0.5.0)\n+ jekyll (~> 3.3)\n+ jekyll-watch (1.5.1)\nlisten (~> 3.0)\n- jemoji (0.11.1)\n+ jemoji (0.8.1)\n+ activesupport (~> 4.0, >= 4.2.9)\ngemoji (~> 3.0)\nhtml-pipeline (~> 2.2)\n- jekyll (>= 3.0, < 5.0)\n- kramdown (1.17.0)\n- liquid (4.0.3)\n- listen (3.2.1)\n- rb-fsevent (~> 0.10, >= 0.10.3)\n- rb-inotify (~> 0.9, >= 0.9.10)\n+ jekyll (>= 3.0)\n+ kramdown (1.16.2)\n+ liquid (4.0.0)\n+ listen (3.0.6)\n+ rb-fsevent (>= 0.9.3)\n+ rb-inotify (>= 0.9.7)\nmercenary (0.3.6)\n- mini_portile2 (2.4.0)\n- minima (2.5.1)\n- jekyll (>= 3.5, < 5.0)\n- jekyll-feed (~> 0.9)\n- jekyll-seo-tag (~> 2.1)\n- minitest (5.13.0)\n- multipart-post (2.1.1)\n- nokogiri (1.10.7)\n- mini_portile2 (~> 2.4.0)\n- octokit (4.14.0)\n+ mini_portile2 (2.3.0)\n+ minima (2.1.1)\n+ jekyll (~> 3.3)\n+ minitest (5.11.3)\n+ multipart-post (2.0.0)\n+ net-dns (0.8.0)\n+ nokogiri (1.8.5)\n+ mini_portile2 (~> 2.3.0)\n+ octokit (4.12.0)\nsawyer (~> 0.8.0, >= 0.5.3)\n- pathutil (0.16.2)\n+ pathutil (0.16.1)\nforwardable-extended (~> 2.6)\n- public_suffix (3.1.1)\n+ public_suffix (2.0.5)\nrb-fsevent (0.10.3)\n- rb-inotify (0.10.0)\n- ffi (~> 1.0)\n- rouge (3.13.0)\n+ rb-inotify (0.9.10)\n+ ffi (>= 0.5.0, < 2)\n+ rouge (2.2.1)\nruby-enum (0.7.2)\ni18n\n- rubyzip (2.0.0)\n- safe_yaml (1.0.5)\n- sass (3.7.4)\n+ rubyzip (1.2.2)\n+ safe_yaml (1.0.4)\n+ sass (3.6.0)\nsass-listen (~> 4.0.0)\nsass-listen (4.0.0)\nrb-fsevent (~> 0.9, >= 0.9.4)\nrb-inotify (~> 0.9, >= 0.9.7)\n- sawyer (0.8.2)\n- addressable (>= 2.3.5)\n- faraday (> 0.8, < 2.0)\n+ sawyer (0.8.1)\n+ addressable (>= 2.3.5, < 2.6)\n+ faraday (~> 0.8, < 1.0)\nterminal-table (1.8.0)\nunicode-display_width (~> 1.1, >= 1.1.1)\nthread_safe (0.3.6)\n- typhoeus (1.3.1)\n- ethon (>= 0.9.0)\n+ typhoeus (0.8.0)\n+ ethon (>= 0.8.0)\ntzinfo (1.2.5)\nthread_safe (~> 0.1)\n- unicode-display_width (1.6.0)\n- zeitwerk (2.2.2)\n+ unicode-display_width (1.4.0)\nPLATFORMS\nruby\n@@ -244,4 +236,4 @@ DEPENDENCIES\ngithub-pages\nBUNDLED WITH\n- 1.17.2\n+ 1.16.0\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Don't update the gems. |
687,060 | 12.12.2019 09:49:29 | -39,600 | 6247dfe5ed52a4a1653b33f8127480c34b059d46 | Update the swagger cli. | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/package-lock.json",
"new_path": "docs-v2/package-lock.json",
"diff": "\"safer-buffer\": \"^2.1.0\"\n}\n},\n+ \"emoji-regex\": {\n+ \"version\": \"7.0.3\",\n+ \"resolved\": \"https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz\",\n+ \"integrity\": \"sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==\",\n+ \"dev\": true\n+ },\n\"emojis-list\": {\n\"version\": \"2.1.0\",\n\"resolved\": \"https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz\",\n\"integrity\": \"sha1-T9kss04OnbPInIYi7PUfm5eMbLk=\",\n\"dev\": true\n},\n- \"jsonschema\": {\n- \"version\": \"1.2.4\",\n- \"resolved\": \"https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.4.tgz\",\n- \"integrity\": \"sha512-lz1nOH69GbsVHeVgEdvyavc/33oymY1AZwtePMiMj4HZPMbP5OIKK3zT9INMWjwua/V4Z4yq7wSlBbSG+g4AEw==\",\n- \"dev\": true\n- },\n- \"jsonschema-draft4\": {\n- \"version\": \"1.0.0\",\n- \"resolved\": \"https://registry.npmjs.org/jsonschema-draft4/-/jsonschema-draft4-1.0.0.tgz\",\n- \"integrity\": \"sha1-8K8gBQVPDwrefqIRhhS2ncUS2GU=\",\n- \"dev\": true\n- },\n\"jsprim\": {\n\"version\": \"1.4.1\",\n\"resolved\": \"https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz\",\n}\n},\n\"ono\": {\n- \"version\": \"4.0.11\",\n- \"resolved\": \"https://registry.npmjs.org/ono/-/ono-4.0.11.tgz\",\n- \"integrity\": \"sha512-jQ31cORBFE6td25deYeD80wxKBMj+zBmHTrVxnc6CKhx8gho6ipmWM5zj/oeoqioZ99yqBls9Z/9Nss7J26G2g==\",\n- \"dev\": true,\n- \"requires\": {\n- \"format-util\": \"^1.0.3\"\n- }\n+ \"version\": \"5.1.0\",\n+ \"resolved\": \"https://registry.npmjs.org/ono/-/ono-5.1.0.tgz\",\n+ \"integrity\": \"sha512-GgqRIUWErLX4l9Up0khRtbrlH8Fyj59A0nKv8V6pWEto38aUgnOGOOF7UmgFFLzFnDSc8REzaTXOc0hqEe7yIw==\",\n+ \"dev\": true\n},\n\"openapi-sampler\": {\n\"version\": \"1.0.0-beta.15\",\n\"json-pointer\": \"^0.6.0\"\n}\n},\n- \"openapi-schema-validation\": {\n- \"version\": \"0.4.2\",\n- \"resolved\": \"https://registry.npmjs.org/openapi-schema-validation/-/openapi-schema-validation-0.4.2.tgz\",\n- \"integrity\": \"sha512-K8LqLpkUf2S04p2Nphq9L+3bGFh/kJypxIG2NVGKX0ffzT4NQI9HirhiY6Iurfej9lCu7y4Ndm4tv+lm86Ck7w==\",\n- \"dev\": true,\n- \"requires\": {\n- \"jsonschema\": \"1.2.4\",\n- \"jsonschema-draft4\": \"^1.0.0\",\n- \"swagger-schema-official\": \"2.0.0-bab6bed\"\n- }\n+ \"openapi-schemas\": {\n+ \"version\": \"1.0.3\",\n+ \"resolved\": \"https://registry.npmjs.org/openapi-schemas/-/openapi-schemas-1.0.3.tgz\",\n+ \"integrity\": \"sha512-KtMWcK2VtOS+nD8RKSIyScJsj8JrmVWcIX7Kjx4xEHijFYuvMTDON8WfeKOgeSb4uNG6UsqLj5Na7nKbSav9RQ==\",\n+ \"dev\": true\n+ },\n+ \"openapi-types\": {\n+ \"version\": \"1.3.5\",\n+ \"resolved\": \"https://registry.npmjs.org/openapi-types/-/openapi-types-1.3.5.tgz\",\n+ \"integrity\": \"sha512-11oi4zYorsgvg5yBarZplAqbpev5HkuVNPlZaPTknPDzAynq+lnJdXAmruGWP0s+dNYZS7bjM+xrTpJw7184Fg==\",\n+ \"dev\": true\n},\n\"optimist\": {\n\"version\": \"0.6.1\",\n\"dev\": true\n},\n\"swagger-cli\": {\n- \"version\": \"2.2.0\",\n- \"resolved\": \"https://registry.npmjs.org/swagger-cli/-/swagger-cli-2.2.0.tgz\",\n- \"integrity\": \"sha512-coldykHxE3GRLsWMpY8hq08Bbe/z0IvW7P+c9wkEqrBGD3/byfyOGvXplH92N2KjVSHW9vaPBUafX6p+12eYFw==\",\n+ \"version\": \"2.3.4\",\n+ \"resolved\": \"https://registry.npmjs.org/swagger-cli/-/swagger-cli-2.3.4.tgz\",\n+ \"integrity\": \"sha512-5UV342uGznmKQcMWB3XhkvAc3IFiM28i5hShYXcV/RkUkJD1UCh/nckrcGASaBNu9P0cMgEXUKzof1hMq3O0Uw==\",\n\"dev\": true,\n\"requires\": {\n- \"chalk\": \"^2.4.1\",\n- \"js-yaml\": \"^3.12.0\",\n+ \"chalk\": \"^2.4.2\",\n+ \"js-yaml\": \"^3.13.1\",\n\"mkdirp\": \"^0.5.1\",\n- \"swagger-parser\": \"^6.0.1\",\n- \"yargs\": \"^12.0.2\"\n+ \"swagger-parser\": \"^8.0.3\",\n+ \"yargs\": \"^14.2.0\"\n},\n\"dependencies\": {\n+ \"ansi-regex\": {\n+ \"version\": \"4.1.0\",\n+ \"resolved\": \"https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz\",\n+ \"integrity\": \"sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==\",\n+ \"dev\": true\n+ },\n\"ansi-styles\": {\n\"version\": \"3.2.1\",\n\"resolved\": \"https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz\",\n\"color-convert\": \"^1.9.0\"\n}\n},\n+ \"camelcase\": {\n+ \"version\": \"5.3.1\",\n+ \"resolved\": \"https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz\",\n+ \"integrity\": \"sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==\",\n+ \"dev\": true\n+ },\n\"chalk\": {\n\"version\": \"2.4.2\",\n\"resolved\": \"https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz\",\n\"supports-color\": \"^5.3.0\"\n}\n},\n+ \"cliui\": {\n+ \"version\": \"5.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz\",\n+ \"integrity\": \"sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"string-width\": \"^3.1.0\",\n+ \"strip-ansi\": \"^5.2.0\",\n+ \"wrap-ansi\": \"^5.1.0\"\n+ }\n+ },\n+ \"find-up\": {\n+ \"version\": \"3.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz\",\n+ \"integrity\": \"sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"locate-path\": \"^3.0.0\"\n+ }\n+ },\n+ \"get-caller-file\": {\n+ \"version\": \"2.0.5\",\n+ \"resolved\": \"https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz\",\n+ \"integrity\": \"sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==\",\n+ \"dev\": true\n+ },\n\"has-flag\": {\n\"version\": \"3.0.0\",\n\"resolved\": \"https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz\",\n\"integrity\": \"sha1-tdRU3CGZriJWmfNGfloH87lVuv0=\",\n\"dev\": true\n},\n+ \"is-fullwidth-code-point\": {\n+ \"version\": \"2.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz\",\n+ \"integrity\": \"sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=\",\n+ \"dev\": true\n+ },\n+ \"require-main-filename\": {\n+ \"version\": \"2.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz\",\n+ \"integrity\": \"sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==\",\n+ \"dev\": true\n+ },\n+ \"string-width\": {\n+ \"version\": \"3.1.0\",\n+ \"resolved\": \"https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz\",\n+ \"integrity\": \"sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"emoji-regex\": \"^7.0.1\",\n+ \"is-fullwidth-code-point\": \"^2.0.0\",\n+ \"strip-ansi\": \"^5.1.0\"\n+ }\n+ },\n+ \"strip-ansi\": {\n+ \"version\": \"5.2.0\",\n+ \"resolved\": \"https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz\",\n+ \"integrity\": \"sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"ansi-regex\": \"^4.1.0\"\n+ }\n+ },\n\"supports-color\": {\n\"version\": \"5.5.0\",\n\"resolved\": \"https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz\",\n\"requires\": {\n\"has-flag\": \"^3.0.0\"\n}\n+ },\n+ \"which-module\": {\n+ \"version\": \"2.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz\",\n+ \"integrity\": \"sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=\",\n+ \"dev\": true\n+ },\n+ \"wrap-ansi\": {\n+ \"version\": \"5.1.0\",\n+ \"resolved\": \"https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz\",\n+ \"integrity\": \"sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"ansi-styles\": \"^3.2.0\",\n+ \"string-width\": \"^3.0.0\",\n+ \"strip-ansi\": \"^5.0.0\"\n+ }\n+ },\n+ \"y18n\": {\n+ \"version\": \"4.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz\",\n+ \"integrity\": \"sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==\",\n+ \"dev\": true\n+ },\n+ \"yargs\": {\n+ \"version\": \"14.2.2\",\n+ \"resolved\": \"https://registry.npmjs.org/yargs/-/yargs-14.2.2.tgz\",\n+ \"integrity\": \"sha512-/4ld+4VV5RnrynMhPZJ/ZpOCGSCeghMykZ3BhdFBDa9Wy/RH6uEGNWDJog+aUlq+9OM1CFTgtYRW5Is1Po9NOA==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"cliui\": \"^5.0.0\",\n+ \"decamelize\": \"^1.2.0\",\n+ \"find-up\": \"^3.0.0\",\n+ \"get-caller-file\": \"^2.0.1\",\n+ \"require-directory\": \"^2.1.1\",\n+ \"require-main-filename\": \"^2.0.0\",\n+ \"set-blocking\": \"^2.0.0\",\n+ \"string-width\": \"^3.0.0\",\n+ \"which-module\": \"^2.0.0\",\n+ \"y18n\": \"^4.0.0\",\n+ \"yargs-parser\": \"^15.0.0\"\n+ }\n+ },\n+ \"yargs-parser\": {\n+ \"version\": \"15.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/yargs-parser/-/yargs-parser-15.0.0.tgz\",\n+ \"integrity\": \"sha512-xLTUnCMc4JhxrPEPUYD5IBR1mWCK/aT6+RJ/K29JY2y1vD+FhtgKK0AXRWvI262q3QSffAQuTouFIKUuHX89wQ==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"camelcase\": \"^5.0.0\",\n+ \"decamelize\": \"^1.2.0\"\n+ }\n}\n}\n},\n\"swagger-methods\": {\n- \"version\": \"1.0.8\",\n- \"resolved\": \"https://registry.npmjs.org/swagger-methods/-/swagger-methods-1.0.8.tgz\",\n- \"integrity\": \"sha512-G6baCwuHA+C5jf4FNOrosE4XlmGsdjbOjdBK4yuiDDj/ro9uR4Srj3OR84oQMT8F3qKp00tYNv0YN730oTHPZA==\",\n+ \"version\": \"2.0.2\",\n+ \"resolved\": \"https://registry.npmjs.org/swagger-methods/-/swagger-methods-2.0.2.tgz\",\n+ \"integrity\": \"sha512-/RNqvBZkH8+3S/FqBPejHxJxZenaYq3MrpeXnzi06aDIS39Mqf5YCUNb/ZBjsvFFt8h9FxfKs8EXPtcYdfLiRg==\",\n\"dev\": true\n},\n\"swagger-parser\": {\n- \"version\": \"6.0.5\",\n- \"resolved\": \"https://registry.npmjs.org/swagger-parser/-/swagger-parser-6.0.5.tgz\",\n- \"integrity\": \"sha512-UL47eu4+GRm5y+N7J+W6QQiqAJn2lojyqgMwS0EZgA55dXd5xmpQCsjUmH/Rf0eKDiG1kULc9VS515PxAyTDVw==\",\n+ \"version\": \"8.0.3\",\n+ \"resolved\": \"https://registry.npmjs.org/swagger-parser/-/swagger-parser-8.0.3.tgz\",\n+ \"integrity\": \"sha512-y2gw+rTjn7Z9J+J1qwbBm0UL93k/VREDCveKBK6iGjf7KXC6QGshbnpEmeHL0ZkCgmIghsXzpNzPSbBH91BAEQ==\",\n\"dev\": true,\n\"requires\": {\n\"call-me-maybe\": \"^1.0.1\",\n- \"json-schema-ref-parser\": \"^6.0.3\",\n- \"ono\": \"^4.0.11\",\n- \"openapi-schema-validation\": \"^0.4.2\",\n- \"swagger-methods\": \"^1.0.8\",\n- \"swagger-schema-official\": \"2.0.0-bab6bed\",\n- \"z-schema\": \"^3.24.2\"\n- }\n+ \"json-schema-ref-parser\": \"^7.1.1\",\n+ \"ono\": \"^5.1.0\",\n+ \"openapi-schemas\": \"^1.0.2\",\n+ \"openapi-types\": \"^1.3.5\",\n+ \"swagger-methods\": \"^2.0.1\",\n+ \"z-schema\": \"^4.1.1\"\n},\n- \"swagger-schema-official\": {\n- \"version\": \"2.0.0-bab6bed\",\n- \"resolved\": \"https://registry.npmjs.org/swagger-schema-official/-/swagger-schema-official-2.0.0-bab6bed.tgz\",\n- \"integrity\": \"sha1-cAcEaNbSl3ylI3suUZyn0Gouo/0=\",\n- \"dev\": true\n+ \"dependencies\": {\n+ \"json-schema-ref-parser\": {\n+ \"version\": \"7.1.2\",\n+ \"resolved\": \"https://registry.npmjs.org/json-schema-ref-parser/-/json-schema-ref-parser-7.1.2.tgz\",\n+ \"integrity\": \"sha512-bi2Nns2UqdX7wThX5qSHd+lOxlu9oeJvlCnWGuR3qS4Ex4UZtuwygkyq/43J31GuNGX8xBHeV6zjQztYk/G5VA==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"call-me-maybe\": \"^1.0.1\",\n+ \"js-yaml\": \"^3.13.1\",\n+ \"ono\": \"^5.1.0\"\n+ }\n+ }\n+ }\n},\n\"swagger-ui-dist\": {\n\"version\": \"3.24.3\",\n}\n},\n\"validator\": {\n- \"version\": \"10.11.0\",\n- \"resolved\": \"https://registry.npmjs.org/validator/-/validator-10.11.0.tgz\",\n- \"integrity\": \"sha512-X/p3UZerAIsbBfN/IwahhYaBbY68EN/UQBWHtsbXGT5bfrH/p4NQzUCG1kF/rtKaNpnJ7jAu6NGTdSNtyNIXMw==\",\n+ \"version\": \"11.1.0\",\n+ \"resolved\": \"https://registry.npmjs.org/validator/-/validator-11.1.0.tgz\",\n+ \"integrity\": \"sha512-qiQ5ktdO7CD6C/5/mYV4jku/7qnqzjrxb3C/Q5wR3vGGinHTgJZN/TdFT3ZX4vXhX2R1PXx42fB1cn5W+uJ4lg==\",\n\"dev\": true\n},\n\"verror\": {\n}\n},\n\"z-schema\": {\n- \"version\": \"3.25.1\",\n- \"resolved\": \"https://registry.npmjs.org/z-schema/-/z-schema-3.25.1.tgz\",\n- \"integrity\": \"sha512-7tDlwhrBG+oYFdXNOjILSurpfQyuVgkRe3hB2q8TEssamDHB7BbLWYkYO98nTn0FibfdFroFKDjndbgufAgS/Q==\",\n+ \"version\": \"4.2.2\",\n+ \"resolved\": \"https://registry.npmjs.org/z-schema/-/z-schema-4.2.2.tgz\",\n+ \"integrity\": \"sha512-7bGR7LohxSdlK1EOdvA/OHksvKGE4jTLSjd8dBj9YKT0S43N9pdMZ0Z7GZt9mHrBFhbNTRh3Ky6Eu2MHsPJe8g==\",\n\"dev\": true,\n\"requires\": {\n\"commander\": \"^2.7.1\",\n- \"core-js\": \"^2.5.7\",\n- \"lodash.get\": \"^4.0.0\",\n- \"lodash.isequal\": \"^4.0.0\",\n- \"validator\": \"^10.0.0\"\n- },\n- \"dependencies\": {\n- \"core-js\": {\n- \"version\": \"2.6.11\",\n- \"resolved\": \"https://registry.npmjs.org/core-js/-/core-js-2.6.11.tgz\",\n- \"integrity\": \"sha512-5wjnpaT/3dV+XB4borEsnAYQchn00XSgTAWKDkEqv+K8KevjbzmofK6hfJ9TZIlpj2N0xQpazy7PiRQiWHqzWg==\",\n- \"dev\": true\n- }\n+ \"lodash.get\": \"^4.4.2\",\n+ \"lodash.isequal\": \"^4.5.0\",\n+ \"validator\": \"^11.0.0\"\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/package.json",
"new_path": "docs-v2/package.json",
"diff": "\"postcss-cli\": \"^6.1.3\",\n\"redoc\": \"2.0.0-rc.18\",\n\"shx\": \"0.2.2\",\n- \"swagger-cli\": \"2.2.0\",\n+ \"swagger-cli\": \"2.3.4\",\n\"swagger-ui-dist\": \"3.24.3\",\n\"to\": \"^0.2.9\",\n\"uglify-js\": \"^2.6.1\"\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Update the swagger cli. |
686,936 | 10.01.2020 18:11:59 | 0 | 901ab5b4ceb105b508c3104130bd328b34a788f1 | Fixed - mark all stubs as persistent when /__admin/mappings/save or saveAllMappings() is called so that they are deleted when the corresponding stub is deleted. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"diff": "@@ -240,10 +240,15 @@ public class WireMockApp implements StubServer, Admin {\n@Override\npublic void removeStubMapping(StubMapping stubMapping) {\n- stubMappings.removeMapping(stubMapping);\n- if (stubMapping.shouldBePersisted()) {\n- mappingsSaver.remove(stubMapping);\n+ final Optional<StubMapping> maybeStub = stubMappings.get(stubMapping.getId());\n+ if (maybeStub.isPresent()) {\n+ StubMapping stubToDelete = maybeStub.get();\n+ if (stubToDelete.shouldBePersisted()) {\n+ mappingsSaver.remove(stubToDelete);\n+ }\n}\n+\n+ stubMappings.removeMapping(stubMapping);\n}\n@Override\n@@ -266,6 +271,9 @@ public class WireMockApp implements StubServer, Admin {\n@Override\npublic void saveMappings() {\n+ for (StubMapping stubMapping: stubMappings.getAll()) {\n+ stubMapping.setPersistent(true);\n+ }\nmappingsSaver.save(stubMappings.getAll());\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/SavingMappingsAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/SavingMappingsAcceptanceTest.java",
"diff": "package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.common.SingleRootFileSource;\n+import com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\n+import com.google.common.base.Predicate;\n+import com.google.common.collect.FluentIterable;\n+import org.apache.commons.io.FileUtils;\n+import org.hamcrest.Description;\n+import org.hamcrest.Matcher;\n+import org.hamcrest.TypeSafeDiagnosingMatcher;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n-import org.apache.commons.io.FileUtils;\nimport java.io.File;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\n-import static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.assertThat;\npublic class SavingMappingsAcceptanceTest extends AcceptanceTestBase {\n@@ -80,6 +86,47 @@ public class SavingMappingsAcceptanceTest extends AcceptanceTestBase {\nresponse = testClient.get(\"/some/url\");\nassertThat(response.statusCode(), is(200));\nassertThat(response.content(), is(\"Response to /some/url\"));\n+\n+ assertThat(listAllStubMappings().getMappings(), everyItem(IS_PERSISTENT));\n+ }\n+\n+ @Test\n+ public void savedMappingIsDeletedFromTheDiskOnRemove() {\n+ StubMapping stubMapping = stubFor(get(\"/delete/me\").willReturn(ok()));\n+ saveAllMappings();\n+\n+ assertThat(MAPPINGS_DIRECTORY, containsFileWithNameContaining(stubMapping.getId().toString()));\n+\n+ removeStub(stubMapping);\n+\n+ assertThat(MAPPINGS_DIRECTORY, not(containsFileWithNameContaining(stubMapping.getId().toString())));\n+ }\n+\n+ private static Matcher<File> containsFileWithNameContaining(final String namePart) {\n+ return new TypeSafeDiagnosingMatcher<File>() {\n+ @Override\n+ protected boolean matchesSafely(File directory, Description mismatchDescription) {\n+ boolean found = FluentIterable.from(directory.list()).filter(new Predicate<String>() {\n+ @Override\n+ public boolean apply(String filename) {\n+ return filename.contains(namePart);\n+ }\n+ })\n+ .first()\n+ .isPresent();\n+\n+ if (!found) {\n+ mismatchDescription.appendText(\"file with name containing \" + namePart + \" not found\");\n+ }\n+\n+ return found;\n+ }\n+\n+ @Override\n+ public void describeTo(Description description) {\n+ description.appendText(\"a file whose name contains \" + namePart);\n+ }\n+ };\n}\n@Test\n@@ -118,4 +165,21 @@ public class SavingMappingsAcceptanceTest extends AcceptanceTestBase {\n// Check only one file has been written\nassertThat(MAPPINGS_DIRECTORY.listFiles().length, is(1));\n}\n+\n+ static final TypeSafeDiagnosingMatcher<StubMapping> IS_PERSISTENT = new TypeSafeDiagnosingMatcher<StubMapping>() {\n+ @Override\n+ public void describeTo(Description description) {\n+ description.appendText(\"a stub mapping marked as persistent\");\n+ }\n+\n+ @Override\n+ protected boolean matchesSafely(StubMapping stub, Description mismatchDescription) {\n+ final boolean result = stub.shouldBePersisted();\n+ if (!result) {\n+ mismatchDescription.appendText(stub.getId() + \" not marked as persistent\");\n+ }\n+\n+ return result;\n+ }\n+ };\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/StubLifecycleListenerAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/StubLifecycleListenerAcceptanceTest.java",
"diff": "@@ -23,8 +23,10 @@ import com.github.tomakehurst.wiremock.junit.WireMockRule;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport org.hamcrest.Matchers;\nimport org.junit.Before;\n+import org.junit.ClassRule;\nimport org.junit.Rule;\nimport org.junit.Test;\n+import org.junit.rules.TemporaryFolder;\nimport java.util.ArrayList;\nimport java.util.List;\n@@ -41,9 +43,13 @@ public class StubLifecycleListenerAcceptanceTest {\nTestStubLifecycleListener loggingListener = new TestStubLifecycleListener();\nExceptionThrowingStubLifecycleListener exceptionThrowingListener = new ExceptionThrowingStubLifecycleListener();\n+ @ClassRule\n+ public static TemporaryFolder tempDir = new TemporaryFolder();\n+\n@Rule\npublic WireMockRule wm = new WireMockRule(options()\n.dynamicPort()\n+ .withRootDirectory(tempDir.getRoot().getAbsolutePath())\n.extensions(loggingListener, exceptionThrowingListener));\n@Before\n@@ -88,6 +94,8 @@ public class StubLifecycleListenerAcceptanceTest {\npublic void stubCreationCanBeVetoedWhenExceptionIsThrown() {\nexceptionThrowingListener.throwException = true;\n+ assertTrue(wm.listAllStubMappings().getMappings().isEmpty());\n+\ntry {\nwm.stubFor(get(\"/test\").withName(\"Created\").willReturn(ok()));\nfail(\"Expected an exception to be thrown\");\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/StubMappingPersistenceAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/StubMappingPersistenceAcceptanceTest.java",
"diff": "@@ -162,9 +162,13 @@ public class StubMappingPersistenceAcceptanceTest {\n}\n@Test\n- public void doesNotDeletePersistentStubMappingIfNotFlaggedPersistent() {\n- StubMapping stubMapping = stubFor(get(urlEqualTo(\"/to-not-delete\")));\n- saveAllMappings();\n+ public void doesNotDeleteStubMappingFromDiskIfNotFlaggedPersistent() throws Exception {\n+ UUID id = UUID.randomUUID();\n+ StubMapping stubMapping = get(urlEqualTo(\"/do-not-delete\")).withId(id).build();\n+ Files.write(mappingsDir.resolve(\"do-not-delete.json\"), Json.write(stubMapping).getBytes());\n+ resetToDefault();\n+\n+ assertThat(getSingleStubMapping(id).getRequest().getUrl(), is(\"/do-not-delete\"));\nassertMappingsDirContainsOneFile();\nremoveStub(stubMapping);\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #1240 - mark all stubs as persistent when /__admin/mappings/save or saveAllMappings() is called so that they are deleted when the corresponding stub is deleted. |
686,939 | 17.01.2020 09:29:45 | 0 | b840940f6069d562a32e8259439b66aeb0c82297 | Correct link to standalone JAR
Link to download standalone JAR from Maven central was using HTTP rather than HTTPS.
The HTTP URL now gives a `501` error:
> 501 HTTPS Required.
> Use
>More information at | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/running-standalone.md",
"new_path": "docs-v2/_docs/running-standalone.md",
"diff": "@@ -16,7 +16,7 @@ description: Running WireMock as a standalone mock server.\nThe WireMock server can be run in its own process, and configured via\nthe Java API, JSON over HTTP or JSON files.\n-Once you have [downloaded the standalone JAR](http://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-standalone/{{ site.wiremock_version }}/wiremock-standalone-{{ site.wiremock_version }}.jar) you can run it simply by doing this:\n+Once you have [downloaded the standalone JAR](https://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-standalone/{{ site.wiremock_version }}/wiremock-standalone-{{ site.wiremock_version }}.jar) you can run it simply by doing this:\n```bash\n$ java -jar wiremock-standalone-{{ site.wiremock_version }}.jar\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Correct link to standalone JAR (#1244)
Link to download standalone JAR from Maven central was using HTTP rather than HTTPS.
The HTTP URL now gives a `501` error:
> 501 HTTPS Required.
> Use https://repo1.maven.org/maven2/
>More information at https://links.sonatype.com/central/501-https-required |
686,936 | 29.01.2020 14:06:33 | 0 | f9e64d249889fb346b57bb6ea693b9da7d32de10 | Now uses the wrapped request rather than the raw one as the original request passed to the proxy renderer | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/AbstractRequestHandler.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/AbstractRequestHandler.java",
"diff": "@@ -53,11 +53,13 @@ public abstract class AbstractRequestHandler implements RequestHandler, RequestE\nStopwatch stopwatch = Stopwatch.createStarted();\nServeEvent serveEvent;\n-\n+ Request originalRequest = request;\nif (!requestFilters.isEmpty()) {\nRequestFilterAction requestFilterAction = processFilters(request, requestFilters, RequestFilterAction.continueWith(request));\nif (requestFilterAction instanceof ContinueAction) {\n- serveEvent = handleRequest(((ContinueAction) requestFilterAction).getRequest());\n+ Request wrappedRequest = ((ContinueAction) requestFilterAction).getRequest();\n+ originalRequest = wrappedRequest;\n+ serveEvent = handleRequest(wrappedRequest);\n} else {\nserveEvent = ServeEvent.of(LoggedRequest.createFrom(request), ((StopAction) requestFilterAction).getResponseDefinition());\n}\n@@ -66,7 +68,7 @@ public abstract class AbstractRequestHandler implements RequestHandler, RequestE\n}\nResponseDefinition responseDefinition = serveEvent.getResponseDefinition();\n- responseDefinition.setOriginalRequest(request);\n+ responseDefinition.setOriginalRequest(originalRequest);\nResponse response = responseRenderer.render(serveEvent);\nServeEvent completedServeEvent = serveEvent.complete(response, (int) stopwatch.elapsed(MILLISECONDS));\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/RequestFilterAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/RequestFilterAcceptanceTest.java",
"diff": "@@ -26,6 +26,7 @@ import org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n+import java.net.URI;\nimport java.util.Collections;\nimport java.util.List;\n@@ -133,6 +134,20 @@ public class RequestFilterAcceptanceTest {\nassertThat(admin.statusCode(), is(401));\n}\n+ @Test\n+ public void wrappedRequestsAreUsedWhenProxying() {\n+ WireMockServer proxyTarget = new WireMockServer(wireMockConfig().dynamicPort());\n+ proxyTarget.start();\n+ initialise(new PathModifyingStubFilter());\n+\n+ wm.stubFor(get(anyUrl()).willReturn(aResponse().proxiedFrom(\"http://localhost:\" + proxyTarget.port())));\n+ proxyTarget.stubFor(get(\"/prefix/subpath/item\").willReturn(ok(\"From the proxy\")));\n+\n+ assertThat(client.get(\"/subpath/item\").content(), is(\"From the proxy\"));\n+\n+ proxyTarget.stop();\n+ }\n+\n@Before\npublic void init() {\nurl = \"/\" + RandomStringUtils.randomAlphabetic(5);\n@@ -265,4 +280,25 @@ public class RequestFilterAcceptanceTest {\n}\n}\n+ public static class PathModifyingStubFilter extends StubRequestFilter {\n+\n+ @Override\n+ public RequestFilterAction filter(Request request) {\n+ Request wrappedRequest = RequestWrapper.create().transformAbsoluteUrl(new FieldTransformer<String>() {\n+ @Override\n+ public String transform(String url) {\n+ return url.replace(\"/subpath\", \"/prefix/subpath\");\n+ }\n+ })\n+ .wrap(request);\n+\n+ return RequestFilterAction.continueWith(wrappedRequest);\n+ }\n+\n+ @Override\n+ public String getName() {\n+ return \"path-mod-filter\";\n+ }\n+ }\n+\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Now uses the wrapped request rather than the raw one as the original request passed to the proxy renderer |
686,936 | 30.01.2020 15:26:02 | 0 | 4bf599ed9c0caaad3f4adbdd69e1f5aedb51fd43 | Fixed Ignore meta property on stub mapping collections so that exports can be used as files without modification. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingCollection.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingCollection.java",
"diff": "package com.github.tomakehurst.wiremock.stubbing;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\n+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport java.util.Collections;\nimport java.util.List;\n+@JsonIgnoreProperties({ \"$schema\", \"meta\" })\npublic class StubMappingCollection extends StubMapping {\nprivate List<StubMapping> mappings;\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #1253. Ignore meta property on stub mapping collections so that exports can be used as files without modification. |
686,989 | 30.01.2020 16:45:43 | -3,600 | 14b8226f0bce71676b3903216acc32a36fc0b8b2 | Docs: Fix handlebar syntax in formData example | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/response-templating.md",
"new_path": "docs-v2/_docs/response-templating.md",
"diff": "@@ -425,7 +425,7 @@ indicating that values should be URL decoded. The folowing example will parse th\n{% raw %}\n```\n-{{formData request.body 'form' urlDecode=true}}}{{{form.formField3}}\n+{{formData request.body 'form' urlDecode=true}}{{form.formField3}}\n```\n{% endraw %}\n@@ -433,8 +433,8 @@ If the form submitted has multiple values for a given field, these can be access\n{% raw %}\n```\n-{{formData request.body 'form' urlDecode=true}}}{{{form.multiValueField.1}}, {{{form.multiValueField.2}}\n-{{formData request.body 'form' urlDecode=true}}}{{{form.multiValueField.first}}, {{{form.multiValueField.last}}\n+{{formData request.body 'form' urlDecode=true}}{{form.multiValueField.1}}, {{form.multiValueField.2}}\n+{{formData request.body 'form' urlDecode=true}}{{form.multiValueField.first}}, {{form.multiValueField.last}}\n```\n{% endraw %}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Docs: Fix handlebar syntax in formData example (#1229) |
686,978 | 30.01.2020 16:33:26 | 0 | cf282c16241abb61b5f70c450733b6cddb4f3ed0 | Update tests to handle windows file separators | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/AdminApiTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/AdminApiTest.java",
"diff": "@@ -40,6 +40,7 @@ import org.junit.After;\nimport org.junit.Test;\nimport org.skyscreamer.jsonassert.JSONAssert;\n+import java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\n@@ -628,7 +629,11 @@ public class AdminApiTest extends AcceptanceTestBase {\nWireMockResponse response = testClient.get(\"/__admin/files\");\nassertEquals(200, response.statusCode());\n- assertThat(new String(response.binaryContent()), matches(\"\\\\[ \\\".*/bar.txt\\\", \\\".*zoo.*txt\\\" ]\"));\n+ String pathSeparatorRegex = File.separator;\n+ if( File.separator.equals(\"\\\\\") ) {\n+ pathSeparatorRegex=\"\\\\\\\\\";\n+ }\n+ assertThat(new String(response.binaryContent()), matches(\"\\\\[ \\\".*\"+ pathSeparatorRegex + \"bar.txt\\\", \\\".*zoo.*txt\\\" ]\"));\n}\n@Test\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseTransformerAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseTransformerAcceptanceTest.java",
"diff": "@@ -24,6 +24,8 @@ import com.github.tomakehurst.wiremock.http.Response;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport org.junit.Test;\n+import java.io.File;\n+\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\nimport static com.github.tomakehurst.wiremock.http.HttpHeader.httpHeader;\n@@ -74,7 +76,7 @@ public class ResponseTransformerAcceptanceTest {\nwm.stubFor(get(urlEqualTo(\"/response-transform-with-files\")).willReturn(ok()));\n- assertThat(client.get(\"/response-transform-with-files\").content(), endsWith(\"src/test/resources/__files/plain-example.txt\"));\n+ assertThat(client.get(\"/response-transform-with-files\").content(), endsWith(\"src\" + File.separator + \"test\" + File.separator + \"resources\" + File.separator + \"__files\" + File.separator + \"plain-example.txt\"));\n}\n@SuppressWarnings(\"unchecked\")\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Update tests to handle windows file separators (#1248) |
686,936 | 30.01.2020 17:32:37 | 0 | c4f22df64c4068a3828aac66d199c01bdabbb3c6 | Upgraded to latest Jackson for | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -40,8 +40,8 @@ allprojects {\nhandlebars : '4.0.7',\njetty : '9.2.28.v20190418', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\nguava : '20.0',\n- jackson : '2.10.0',\n- jacksonDatabind: '2.10.0',\n+ jackson : '2.10.2',\n+ jacksonDatabind: '2.10.2',\nxmlUnit : '2.6.2'\n],\njava8: [\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Upgraded to latest Jackson for #1228 |
686,936 | 30.01.2020 18:00:20 | 0 | d1a7833ded0894eee7313c1f5383a10689e709b9 | Fixed - matcher operators are now validated as non-null and for string type | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/ContentPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/ContentPattern.java",
"diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\n+import com.google.common.base.Preconditions;\n@JsonDeserialize(using = ContentPatternDeserialiser.class)\npublic abstract class ContentPattern<T> implements NamedValueMatcher<T> {\n@@ -24,6 +25,7 @@ public abstract class ContentPattern<T> implements NamedValueMatcher<T> {\nprotected final T expectedValue;\npublic ContentPattern(T expectedValue) {\n+ Preconditions.checkNotNull(expectedValue, \"'\" + getName() + \"' expected value cannot be null\");\nthis.expectedValue = expectedValue;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/StringValuePatternJsonDeserializer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/StringValuePatternJsonDeserializer.java",
"diff": "@@ -87,6 +87,9 @@ public class StringValuePatternJsonDeserializer extends JsonDeserializer<StringV\n}\n});\n+ if (!entry.getValue().isTextual()) {\n+ throw new JsonMappingException(entry.getKey() + \" operand must be a string\");\n+ }\nString operand = entry.getValue().textValue();\ntry {\nreturn constructor.newInstance(operand);\n@@ -100,7 +103,12 @@ public class StringValuePatternJsonDeserializer extends JsonDeserializer<StringV\nthrow new JsonMappingException(rootNode.toString() + \" is not a valid match operation\");\n}\n- String operand = rootNode.findValue(\"equalTo\").textValue();\n+ JsonNode equalToNode = rootNode.findValue(\"equalTo\");\n+ if (!equalToNode.isTextual()) {\n+ throw new JsonMappingException(\"equalTo operand must be a string\");\n+ }\n+\n+ String operand = equalToNode.textValue();\nBoolean ignoreCase = fromNullable(rootNode.findValue(\"caseInsensitive\"));\nreturn new EqualToPattern(operand, ignoreCase);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/AdminApiTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/AdminApiTest.java",
"diff": "@@ -554,7 +554,7 @@ public class AdminApiTest extends AcceptanceTestBase {\n@Test\npublic void returnsBadEntityStatusWhenInvalidEqualToXmlSpecified() {\n- WireMockResponse response = testClient.postXml(\"/__admin/mappings\",\n+ WireMockResponse response = testClient.postJson(\"/__admin/mappings\",\n\"{\\n\" +\n\" \\\"request\\\": {\\n\" +\n\" \\\"bodyPatterns\\\": [\\n\" +\n@@ -573,6 +573,90 @@ public class AdminApiTest extends AcceptanceTestBase {\nassertThat(errors.first().getDetail(), is(\"Content is not allowed in prolog.; line 1; column 1\"));\n}\n+ @Test\n+ public void returnsBadEntityStatusWhenContainsOperandIsNull() {\n+ WireMockResponse response = testClient.postJson(\"/__admin/mappings\",\n+ \"{\\n\" +\n+ \" \\\"request\\\": {\\n\" +\n+ \" \\\"bodyPatterns\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"contains\\\": null\\n\" +\n+ \" }\\n\" +\n+ \" ]\\n\" +\n+ \" }\\n\" +\n+ \"}\");\n+\n+ assertThat(response.statusCode(), is(422));\n+\n+ Errors errors = Json.read(response.content(), Errors.class);\n+ assertThat(errors.first().getSource().getPointer(), is(\"/request/bodyPatterns/0\"));\n+ assertThat(errors.first().getTitle(), is(\"Error parsing JSON\"));\n+ assertThat(errors.first().getDetail(), is(\"'contains' expected value cannot be null\"));\n+ }\n+\n+ @Test\n+ public void returnsBadEntityStatusWhenEqualToOperandIsWrongType() {\n+ WireMockResponse response = testClient.postJson(\"/__admin/mappings\",\n+ \"{\\n\" +\n+ \" \\\"request\\\": {\\n\" +\n+ \" \\\"bodyPatterns\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"equalTo\\\": 12\\n\" +\n+ \" }\\n\" +\n+ \" ]\\n\" +\n+ \" }\\n\" +\n+ \"}\");\n+\n+ assertThat(response.statusCode(), is(422));\n+\n+ Errors errors = Json.read(response.content(), Errors.class);\n+ assertThat(errors.first().getSource().getPointer(), is(\"/request/bodyPatterns/0\"));\n+ assertThat(errors.first().getTitle(), is(\"Error parsing JSON\"));\n+ assertThat(errors.first().getDetail(), is(\"equalTo operand must be a string\"));\n+ }\n+\n+ @Test\n+ public void returnsBadEntityStatusWhenContainsOperandIsWrongType() {\n+ WireMockResponse response = testClient.postJson(\"/__admin/mappings\",\n+ \"{\\n\" +\n+ \" \\\"request\\\": {\\n\" +\n+ \" \\\"bodyPatterns\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"contains\\\": 12\\n\" +\n+ \" }\\n\" +\n+ \" ]\\n\" +\n+ \" }\\n\" +\n+ \"}\");\n+\n+ assertThat(response.statusCode(), is(422));\n+\n+ Errors errors = Json.read(response.content(), Errors.class);\n+ assertThat(errors.first().getSource().getPointer(), is(\"/request/bodyPatterns/0\"));\n+ assertThat(errors.first().getTitle(), is(\"Error parsing JSON\"));\n+ assertThat(errors.first().getDetail(), is(\"contains operand must be a string\"));\n+ }\n+\n+ @Test\n+ public void returnsBadEntityStatusWhenMatchesOperandIsWrongType() {\n+ WireMockResponse response = testClient.postJson(\"/__admin/mappings\",\n+ \"{\\n\" +\n+ \" \\\"request\\\": {\\n\" +\n+ \" \\\"bodyPatterns\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"matches\\\": 12\\n\" +\n+ \" }\\n\" +\n+ \" ]\\n\" +\n+ \" }\\n\" +\n+ \"}\");\n+\n+ assertThat(response.statusCode(), is(422));\n+\n+ Errors errors = Json.read(response.content(), Errors.class);\n+ assertThat(errors.first().getSource().getPointer(), is(\"/request/bodyPatterns/0\"));\n+ assertThat(errors.first().getTitle(), is(\"Error parsing JSON\"));\n+ assertThat(errors.first().getDetail(), is(\"matches operand must be a string\"));\n+ }\n+\n@Test\npublic void servesSwaggerSpec() {\nWireMockResponse response = testClient.get(\"/__admin/docs/swagger\");\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #1241 - matcher operators are now validated as non-null and for string type |
686,936 | 30.01.2020 18:18:47 | 0 | 4d00ea2cbbc89436afb245ba0361261c9fd09a38 | Fixed some test failures caused by the non-null validation of matcher operands | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AbsentPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/AbsentPattern.java",
"diff": "@@ -39,4 +39,9 @@ public class AbsentPattern extends StringValuePattern {\npublic String getExpected() {\nreturn \"(absent)\";\n}\n+\n+ @Override\n+ protected boolean isNullValuePermitted() {\n+ return true;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/ContentPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/ContentPattern.java",
"diff": "@@ -25,7 +25,9 @@ public abstract class ContentPattern<T> implements NamedValueMatcher<T> {\nprotected final T expectedValue;\npublic ContentPattern(T expectedValue) {\n+ if (!isNullValuePermitted()) {\nPreconditions.checkNotNull(expectedValue, \"'\" + getName() + \"' expected value cannot be null\");\n+ }\nthis.expectedValue = expectedValue;\n}\n@@ -33,4 +35,8 @@ public abstract class ContentPattern<T> implements NamedValueMatcher<T> {\npublic T getValue() {\nreturn expectedValue;\n}\n+\n+ protected boolean isNullValuePermitted() {\n+ return false;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/StringValuePatternJsonDeserializer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/StringValuePatternJsonDeserializer.java",
"diff": "@@ -88,7 +88,7 @@ public class StringValuePatternJsonDeserializer extends JsonDeserializer<StringV\n});\nif (!entry.getValue().isTextual()) {\n- throw new JsonMappingException(entry.getKey() + \" operand must be a string\");\n+ throw new JsonMappingException(entry.getKey() + \" operand must be a non-null string\");\n}\nString operand = entry.getValue().textValue();\ntry {\n@@ -105,7 +105,7 @@ public class StringValuePatternJsonDeserializer extends JsonDeserializer<StringV\nJsonNode equalToNode = rootNode.findValue(\"equalTo\");\nif (!equalToNode.isTextual()) {\n- throw new JsonMappingException(\"equalTo operand must be a string\");\n+ throw new JsonMappingException(\"equalTo operand must be a non-null string\");\n}\nString operand = equalToNode.textValue();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/AdminApiTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/AdminApiTest.java",
"diff": "@@ -591,7 +591,7 @@ public class AdminApiTest extends AcceptanceTestBase {\nErrors errors = Json.read(response.content(), Errors.class);\nassertThat(errors.first().getSource().getPointer(), is(\"/request/bodyPatterns/0\"));\nassertThat(errors.first().getTitle(), is(\"Error parsing JSON\"));\n- assertThat(errors.first().getDetail(), is(\"'contains' expected value cannot be null\"));\n+ assertThat(errors.first().getDetail(), is(\"contains operand must be a non-null string\"));\n}\n@Test\n@@ -612,7 +612,7 @@ public class AdminApiTest extends AcceptanceTestBase {\nErrors errors = Json.read(response.content(), Errors.class);\nassertThat(errors.first().getSource().getPointer(), is(\"/request/bodyPatterns/0\"));\nassertThat(errors.first().getTitle(), is(\"Error parsing JSON\"));\n- assertThat(errors.first().getDetail(), is(\"equalTo operand must be a string\"));\n+ assertThat(errors.first().getDetail(), is(\"equalTo operand must be a non-null string\"));\n}\n@Test\n@@ -633,7 +633,7 @@ public class AdminApiTest extends AcceptanceTestBase {\nErrors errors = Json.read(response.content(), Errors.class);\nassertThat(errors.first().getSource().getPointer(), is(\"/request/bodyPatterns/0\"));\nassertThat(errors.first().getTitle(), is(\"Error parsing JSON\"));\n- assertThat(errors.first().getDetail(), is(\"contains operand must be a string\"));\n+ assertThat(errors.first().getDetail(), is(\"contains operand must be a non-null string\"));\n}\n@Test\n@@ -654,7 +654,7 @@ public class AdminApiTest extends AcceptanceTestBase {\nErrors errors = Json.read(response.content(), Errors.class);\nassertThat(errors.first().getSource().getPointer(), is(\"/request/bodyPatterns/0\"));\nassertThat(errors.first().getTitle(), is(\"Error parsing JSON\"));\n- assertThat(errors.first().getDetail(), is(\"matches operand must be a string\"));\n+ assertThat(errors.first().getDetail(), is(\"matches operand must be a non-null string\"));\n}\n@Test\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactoryJsonDeserializerTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactoryJsonDeserializerTest.java",
"diff": "@@ -46,8 +46,9 @@ public class RequestBodyPatternFactoryJsonDeserializerTest {\n\" \\\"caseInsensitive\\\": true \\n\" +\n\"} \"\n);\n- EqualToPattern bodyPattern = (EqualToPattern) bodyPatternFactory.forRequest(mockRequest());\n+ EqualToPattern bodyPattern = (EqualToPattern) bodyPatternFactory.forRequest(mockRequest().body(\"this body text\"));\nassertThat(bodyPattern.getCaseInsensitive(), is(true));\n+ assertThat(bodyPattern.getExpected(), is(\"this body text\"));\n}\n@Test\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed some test failures caused by the non-null validation of matcher operands |
686,936 | 05.12.2019 19:26:28 | 0 | 7ead912283b9c89d010eaf523e877ff5a5a5a728 | Switched EqualToJson implementation to use JsonUnit (thanks !) | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -84,16 +84,13 @@ allprojects {\nexclude group: \"org.hamcrest\", module: \"hamcrest-core\"\n}\ncompile 'org.apache.commons:commons-lang3:3.7'\n- compile 'com.flipkart.zjsonpatch:zjsonpatch:0.4.4', {\n- exclude group: 'com.fasterxml.jackson.core', module: 'jackson-databind'\n- exclude group: 'com.fasterxml.jackson.core', module: 'jackson-core'\n- }\ncompile \"com.github.jknack:handlebars:$versions.handlebars\", {\nexclude group: 'org.mozilla', module: 'rhino'\n}\ncompile(\"com.github.jknack:handlebars-helpers:$versions.handlebars\") {\nexclude group: 'org.mozilla', module: 'rhino'\n}\n+ compile 'net.javacrumbs.json-unit:json-unit-core:2.12.0'\ncompile 'commons-fileupload:commons-fileupload:1.4'\n@@ -227,7 +224,7 @@ subprojects {\nrelocate \"com.jayway\", 'wiremock.com.jayway'\nrelocate \"org.objectweb\", 'wiremock.org.objectweb'\nrelocate \"org.custommonkey\", \"wiremock.org.custommonkey\"\n- relocate \"com.flipkart\", \"wiremock.com.flipkart\"\n+ relocate \"net.javacrumbs\", \"wiremock.net.javacrumbs\"\nrelocate \"net.sf\", \"wiremock.net.sf\"\nrelocate \"com.github.jknack\", \"wiremock.com.github.jknack\"\nrelocate \"org.antlr\", \"wiremock.org.antlr\"\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"diff": "-/*\n- * Copyright (C) 2011 Thomas Akehurst\n- *\n- * Licensed under the Apache License, Version 2.0 (the \"License\");\n- * you may not use this file except in compliance with the License.\n- * You may obtain a copy of the License at\n- *\n- * http://www.apache.org/licenses/LICENSE-2.0\n- *\n- * Unless required by applicable law or agreed to in writing, software\n- * distributed under the License is distributed on an \"AS IS\" BASIS,\n- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n- * See the License for the specific language governing permissions and\n- * limitations under the License.\n- */\npackage com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.JsonNode;\n-import com.fasterxml.jackson.databind.node.ArrayNode;\n-import com.flipkart.zjsonpatch.DiffFlags;\n-import com.flipkart.zjsonpatch.JsonDiff;\nimport com.github.tomakehurst.wiremock.common.Json;\n-import com.google.common.base.Function;\n-import com.google.common.base.Splitter;\n-import com.google.common.collect.Iterables;\n-import com.google.common.collect.Lists;\n-\n-import java.util.EnumSet;\n-import java.util.List;\n-import java.util.Objects;\n-\n-import static com.flipkart.zjsonpatch.DiffFlags.OMIT_COPY_OPERATION;\n-import static com.flipkart.zjsonpatch.DiffFlags.OMIT_MOVE_OPERATION;\n-import static com.github.tomakehurst.wiremock.common.Json.deepSize;\n-import static com.github.tomakehurst.wiremock.common.Json.maxDeepSize;\n-import static com.google.common.collect.Iterables.getLast;\n-import static org.apache.commons.lang3.math.NumberUtils.isNumber;\n+import net.javacrumbs.jsonunit.core.Configuration;\n+import net.javacrumbs.jsonunit.core.Option;\n+import net.javacrumbs.jsonunit.core.internal.Diff;\n+import net.javacrumbs.jsonunit.core.listener.Difference;\n+import net.javacrumbs.jsonunit.core.listener.DifferenceContext;\n+import net.javacrumbs.jsonunit.core.listener.DifferenceListener;\npublic class EqualToJsonPattern extends StringValuePattern {\n@@ -64,141 +37,104 @@ public class EqualToJsonPattern extends StringValuePattern {\nthis.serializeAsString = false;\n}\n- @JsonProperty(\"equalToJson\")\n- public Object getSerializedEqualToJson() {\n- return serializeAsString ? getValue() : expected;\n- }\n-\n- public String getEqualToJson() {\n- return expectedValue;\n+ EqualToJsonPattern(String json) {\n+ this(json, false, false);\n}\n- private boolean shouldIgnoreArrayOrder() {\n- return ignoreArrayOrder != null && ignoreArrayOrder;\n- }\n-\n- public Boolean isIgnoreArrayOrder() {\n- return ignoreArrayOrder;\n- }\n-\n- private boolean shouldIgnoreExtraElements() {\n- return ignoreExtraElements != null && ignoreExtraElements;\n- }\n+ @Override\n+ public MatchResult match(String value) {\n+ final CountingDiffListener diffListener = new CountingDiffListener();\n+ Configuration diffConfig = Configuration.empty()\n+ .withDifferenceListener(diffListener);\n- public Boolean isIgnoreExtraElements() {\n- return ignoreExtraElements;\n+ if (shouldIgnoreArrayOrder()) {\n+ diffConfig = diffConfig.withOptions(Option.IGNORING_ARRAY_ORDER);\n}\n- @Override\n- public String getExpected() {\n- return Json.prettyPrint(getValue());\n+ if (shouldIgnoreExtraElements()) {\n+ diffConfig = diffConfig.withOptions(Option.IGNORING_EXTRA_ARRAY_ITEMS, Option.IGNORING_EXTRA_FIELDS);\n}\n- @Override\n- public MatchResult match(String value) {\n+ final JsonNode actual;\n+ final Diff diff;\ntry {\n- final JsonNode actual = Json.read(value, JsonNode.class);\n+ actual = Json.read(value, JsonNode.class);\n+ diff = Diff.create(\n+ expected, // JsonUnit knows how to work with JsonNode\n+ actual,\n+ \"\",\n+ \"\",\n+ diffConfig\n+ );\n+ } catch (Exception e) {\n+ return MatchResult.noMatch();\n+ }\nreturn new MatchResult() {\n@Override\npublic boolean isExactMatch() {\n- // Try to do it the fast way first, then fall back to doing the full diff\n- if (!shouldIgnoreArrayOrder() && !shouldIgnoreExtraElements()) {\n- return Objects.equals(actual, expected);\n- }\n-\n- return getDistance() == 0.0;\n+ return diff.similar();\n}\n@Override\npublic double getDistance() {\n- EnumSet<DiffFlags> flags = EnumSet.of(OMIT_COPY_OPERATION);\n- ArrayNode diff = (ArrayNode) JsonDiff.asJson(expected, actual, flags);\n-\n+ diff.similar();\ndouble maxNodes = maxDeepSize(expected, actual);\n- return diffSize(diff) / maxNodes;\n+ return diffListener.count / maxNodes;\n}\n};\n- } catch (Exception e) {\n- return MatchResult.noMatch();\n- }\n}\n- private int diffSize(ArrayNode diff) {\n- int acc = 0;\n- for (JsonNode child: diff) {\n- String operation = child.findValue(\"op\").textValue();\n- JsonNode pathString = getFromPathString(operation, child);\n- List<String> path = getPath(pathString.textValue());\n- if (!arrayOrderIgnoredAndIsArrayMove(operation, path) && !extraElementsIgnoredAndIsAddition(operation)) {\n- JsonNode valueNode = operation.equals(\"remove\") ? null : child.findValue(\"value\");\n- JsonNode referencedExpectedNode = getNodeAtPath(expected, pathString);\n- if (valueNode == null) {\n- acc += deepSize(referencedExpectedNode);\n- } else {\n- acc += maxDeepSize(referencedExpectedNode, valueNode);\n- }\n- }\n+ @JsonProperty(\"equalToJson\")\n+ public Object getSerializedEqualToJson() {\n+ return serializeAsString ? getValue() : Json.read(getValue(), JsonNode.class);\n}\n- return acc;\n+ public String getEqualToJson() {\n+ return expectedValue;\n}\n- private static JsonNode getFromPathString(String operation, JsonNode node) {\n- if (operation.equals(\"move\")) {\n- return node.findValue(\"from\");\n+ private boolean shouldIgnoreArrayOrder() {\n+ return ignoreArrayOrder != null && ignoreArrayOrder;\n}\n- return node.findValue(\"path\");\n+ public Boolean isIgnoreArrayOrder() {\n+ return ignoreArrayOrder;\n}\n- private boolean extraElementsIgnoredAndIsAddition(String operation) {\n- return operation.equals(\"add\") && shouldIgnoreExtraElements();\n+ private boolean shouldIgnoreExtraElements() {\n+ return ignoreExtraElements != null && ignoreExtraElements;\n}\n- private boolean arrayOrderIgnoredAndIsArrayMove(String operation, List<String> path) {\n- return operation.equals(\"move\") && isNumber(getLast(path)) && shouldIgnoreArrayOrder();\n+ public Boolean isIgnoreExtraElements() {\n+ return ignoreExtraElements;\n}\n- public static JsonNode getNodeAtPath(JsonNode rootNode, JsonNode path) {\n- String pathString = path.toString().equals(\"\\\"/\\\"\") ? \"\\\"\\\"\" : path.toString();\n- return getNode(rootNode, getPath(pathString), 1);\n+ @Override\n+ public String getExpected() {\n+ return Json.prettyPrint(getValue());\n}\n- private static JsonNode getNode(JsonNode ret, List<String> path, int pos) {\n- if (pos >= path.size()) {\n- return ret;\n- }\n+ private static class CountingDiffListener implements DifferenceListener {\n- if (ret == null) {\n- return null;\n- }\n+ public int count = 0;\n- String key = path.get(pos);\n- if (ret.isArray()) {\n- int keyInt = Integer.parseInt(key.replaceAll(\"\\\"\", \"\"));\n- return getNode(ret.get(keyInt), path, ++pos);\n- } else if (ret.isObject()) {\n- if (ret.has(key)) {\n- return getNode(ret.get(key), path, ++pos);\n- }\n- return null;\n- } else {\n- return ret;\n+ @Override\n+ public void diff(Difference difference, DifferenceContext context) {\n+ final int delta = maxDeepSize(difference.getExpected(), difference.getActual());\n+ count += delta == 0 ? 1 : Math.abs(delta);\n}\n}\n- private static List<String> getPath(String path) {\n- List<String> paths = Splitter.on('/').splitToList(path.replaceAll(\"\\\"\", \"\"));\n- return Lists.newArrayList(Iterables.transform(paths, new DecodePathFunction()));\n+ public static int maxDeepSize(Object one, Object two) {\n+ return Math.max(\n+ one != null ? deepSize(one) : 0,\n+ two != null ? deepSize(two) : 0\n+ );\n}\n- private final static class DecodePathFunction implements Function<String, String> {\n-\n- @Override\n- public String apply(String path) {\n- return path.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"); // see http://tools.ietf.org/html/rfc6901#section-4\n- }\n+ private static int deepSize(Object nodeObj) {\n+ JsonNode jsonNode = Json.getObjectMapper().convertValue(nodeObj, JsonNode.class);\n+ return Json.deepSize(jsonNode);\n}\n-\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/SnapshotDslAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/SnapshotDslAcceptanceTest.java",
"diff": "@@ -17,7 +17,6 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\nimport com.github.tomakehurst.wiremock.client.WireMock;\n-import com.github.tomakehurst.wiremock.client.WireMockBuilder;\nimport com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.extension.StubMappingTransformer;\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern2Test.java",
"diff": "+package com.github.tomakehurst.wiremock.matching;\n+\n+import com.github.tomakehurst.wiremock.common.Json;\n+import org.json.JSONException;\n+import org.junit.Test;\n+import org.skyscreamer.jsonassert.JSONAssert;\n+\n+import static org.hamcrest.Matchers.*;\n+import static org.junit.Assert.*;\n+\n+public class EqualToJsonPattern2Test {\n+\n+ @Test\n+ public void returns0DistanceForExactMatchForSingleLevelObject() {\n+ assertThat(new EqualToJsonPattern(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"four\\\": 4 \\n\" +\n+ \"} \\n\"\n+ ).match(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"four\\\": 4 \\n\" +\n+ \"} \\n\"\n+ ).getDistance(), is(0.0));\n+ }\n+\n+ @Test\n+ public void returnsNon0DistanceForPartialMatchForSingleLevelObject() {\n+ assertThat(new EqualToJsonPattern(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"four\\\": 4 \\n\" +\n+ \"} \\n\"\n+ ).match(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": 7, \\n\" +\n+ \" \\\"four\\\": 8 \\n\" +\n+ \"} \\n\"\n+ ).getDistance(), is(0.4));\n+ }\n+\n+ @Test\n+ public void returnsLargeDistanceForTotallyDifferentDocuments() {\n+ assertThat(new EqualToJsonPattern(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"four\\\": 4 \\n\" +\n+ \"} \\n\"\n+ ).match(\n+ \"[1, 2, 3]\"\n+ ).getDistance(), is(1.0));\n+ }\n+\n+ @Test\n+ public void returnsLargeDistanceWhenActualDocIsAnEmptyObject() {\n+ assertThat(new EqualToJsonPattern(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"four\\\": 4 \\n\" +\n+ \"} \\n\"\n+ ).match(\n+ \"{}\"\n+ ).getDistance(), is(0.8));\n+ }\n+\n+ @Test\n+ public void returnsLargeDistanceWhenActualDocIsAnEmptyArray() {\n+ assertThat(new EqualToJsonPattern(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"four\\\": 4 \\n\" +\n+ \"} \\n\"\n+ ).match(\n+ \"[]\"\n+ ).getDistance(), is(1.0));\n+ }\n+\n+ @Test\n+ public void returnsLargeDistanceWhenExpectedDocIsAnEmptyObject() {\n+ assertThat(new EqualToJsonPattern(\n+ \"{}\"\n+ ).match(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"four\\\": 4 \\n\" +\n+ \"} \\n\"\n+ ).getDistance(), is(0.8));\n+ }\n+\n+ @Test\n+ public void returnsLargeDistanceWhenExpectedDocIsAnEmptyArray() {\n+ assertThat(new EqualToJsonPattern(\n+ \"[]\"\n+ ).match(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"four\\\": 4 \\n\" +\n+ \"} \\n\"\n+ ).getDistance(), is(1.0));\n+ }\n+\n+ @Test\n+ public void returnsMediumDistanceWhenSubtreeIsMissingFromActual() {\n+ assertThat(new EqualToJsonPattern(\n+ \"{\\n\" +\n+ \" \\\"one\\\": \\\"GET\\\", \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": { \\n\" +\n+ \" \\\"four\\\": \\\"FOUR\\\", \\n\" +\n+ \" \\\"five\\\": [ \\n\" +\n+ \" { \\n\" +\n+ \" \\\"six\\\": 6, \\n\" +\n+ \" \\\"seven\\\": 7 \\n\" +\n+ \" }, \\n\" +\n+ \" { \\n\" +\n+ \" \\\"eight\\\": 8, \\n\" +\n+ \" \\\"nine\\\": 9 \\n\" +\n+ \" } \\n\" +\n+ \" ] \\n\" +\n+ \" } \\n\" +\n+ \"}\"\n+ ).match(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": \\\"GET\\\", \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": { \\n\" +\n+ \" \\\"four\\\": \\\"FOUR\\\"\\n\" +\n+ \" } \\n\" +\n+ \"} \\n\"\n+ ).getDistance(), closeTo(0.56, 0.01));\n+ }\n+\n+ @Test\n+ public void returnsExactMatchWhenObjectPropertyOrderDiffers() {\n+ assertTrue(new EqualToJsonPattern(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"four\\\": 4 \\n\" +\n+ \"} \\n\"\n+ ).match(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"four\\\": 4 \\n\" +\n+ \"} \\n\"\n+ ).isExactMatch());\n+ }\n+\n+ @Test\n+ public void returnsNonMatchWhenArrayOrderDiffers() {\n+ assertFalse(new EqualToJsonPattern(\n+ \"[1, 2, 3, 4]\"\n+ ).match(\n+ \"[1, 3, 2, 4]\"\n+ ).isExactMatch());\n+ }\n+\n+ @Test\n+ public void ignoresArrayOrderDifferenceWhenConfigured() {\n+ assertTrue(new EqualToJsonPattern(\n+ \"[1, 2, 3, 4]\",\n+ true, false)\n+ .match(\n+ \"[1, 3, 2, 4]\"\n+ ).isExactMatch());\n+ }\n+\n+ @Test\n+ public void ignoresNestedArrayOrderDifferenceWhenConfigured() {\n+ assertTrue(new EqualToJsonPattern(\n+ \"{\\n\" +\n+ \" \\\"one\\\": 1,\\n\" +\n+ \" \\\"two\\\": [\\n\" +\n+ \" { \\\"val\\\": 1 },\\n\" +\n+ \" { \\\"val\\\": 2 },\\n\" +\n+ \" { \\\"val\\\": 3 }\\n\" +\n+ \" ]\\n\" +\n+ \"}\",\n+ true, false)\n+ .match(\n+ \"{\\n\" +\n+ \" \\\"one\\\": 1,\\n\" +\n+ \" \\\"two\\\": [\\n\" +\n+ \" { \\\"val\\\": 3 },\\n\" +\n+ \" { \\\"val\\\": 2 },\\n\" +\n+ \" { \\\"val\\\": 1 }\\n\" +\n+ \" ]\\n\" +\n+ \"}\"\n+ ).isExactMatch());\n+ }\n+\n+ @Test\n+ public void ignoresExtraObjectAttributesWhenConfigured() {\n+ assertTrue(new EqualToJsonPattern(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"four\\\": 4 \\n\" +\n+ \"} \\n\",\n+ false, true\n+ ).match(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"four\\\": 4, \\n\" +\n+ \" \\\"five\\\": 5, \\n\" +\n+ \" \\\"six\\\": 6 \\n\" +\n+ \"} \\n\"\n+ ).isExactMatch());\n+ }\n+\n+ @Test\n+ public void ignoresExtraObjectAttributesAndArrayOrderWhenConfigured() {\n+ assertTrue(new EqualToJsonPattern(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"four\\\": [1, 2, 3] \\n\" +\n+ \"} \\n\",\n+ true, true\n+ ).match(\n+ \"{ \\n\" +\n+ \" \\\"one\\\": 1, \\n\" +\n+ \" \\\"three\\\": 3, \\n\" +\n+ \" \\\"two\\\": 2, \\n\" +\n+ \" \\\"four\\\": [3, 1, 2], \\n\" +\n+ \" \\\"five\\\": 5, \\n\" +\n+ \" \\\"six\\\": 6 \\n\" +\n+ \"} \\n\"\n+ ).isExactMatch());\n+ }\n+\n+ @Test\n+ public void correctlyDeserialisesFromJsonStringWhenAdditionalParamsPresent() {\n+ StringValuePattern pattern = Json.read(\n+ \"{\\n\" +\n+ \" \\\"equalToJson\\\": \\\"2\\\",\\n\" +\n+ \" \\\"ignoreArrayOrder\\\": true,\\n\" +\n+ \" \\\"ignoreExtraElements\\\": true\\n\" +\n+ \"}\",\n+ StringValuePattern.class\n+ );\n+\n+ assertThat(pattern, instanceOf(EqualToJsonPattern.class));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreArrayOrder(), is(true));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreExtraElements(), is(true));\n+ assertThat(pattern.getExpected(), is(\"2\"));\n+ }\n+\n+ @Test\n+ public void correctlyDeserialisesFromJsonValueWhenAdditionalParamsPresent() throws JSONException {\n+ String expectedJson = \"{ \\\"someKey\\\": \\\"someValue\\\" }\";\n+ String serializedJson =\n+ \"{ \\n\" +\n+ \" \\\"equalToJson\\\": \" + expectedJson + \", \\n\" +\n+ \" \\\"ignoreArrayOrder\\\": true, \\n\" +\n+ \" \\\"ignoreExtraElements\\\": true \\n\" +\n+ \"} \";\n+ StringValuePattern pattern = Json.read(serializedJson, StringValuePattern.class);\n+\n+ assertThat(pattern, instanceOf(EqualToJsonPattern.class));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreArrayOrder(), is(true));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreExtraElements(), is(true));\n+ JSONAssert.assertEquals(pattern.getExpected(), expectedJson, false);\n+ }\n+\n+ @Test\n+ public void correctlySerialisesToJsonValueWhenAdditionalParamsPresentAndConstructedWithJsonValue() throws JSONException {\n+ String expectedJson = \"{ \\\"someKey\\\": \\\"someValue\\\" }\";\n+ EqualToJsonPattern pattern = new EqualToJsonPattern(Json.node(expectedJson), true, true);\n+\n+ String serialised = Json.write(pattern);\n+ String expected =\n+ \"{ \\n\" +\n+ \" \\\"equalToJson\\\": \" + expectedJson + \", \\n\" +\n+ \" \\\"ignoreArrayOrder\\\": true, \\n\" +\n+ \" \\\"ignoreExtraElements\\\": true \\n\" +\n+ \"} \";\n+ JSONAssert.assertEquals(expected, serialised, false);\n+ }\n+\n+ @Test\n+ public void correctlySerialisesToJsonWhenAdditionalParamsPresentAndConstructedWithString() throws JSONException {\n+ EqualToJsonPattern pattern = new EqualToJsonPattern(\"4444\", true, true);\n+\n+ String serialised = Json.write(pattern);\n+ JSONAssert.assertEquals(\n+ \"{\\n\" +\n+ \" \\\"equalToJson\\\": \\\"4444\\\",\\n\" +\n+ \" \\\"ignoreArrayOrder\\\": true,\\n\" +\n+ \" \\\"ignoreExtraElements\\\": true\\n\" +\n+ \"}\",\n+ serialised,\n+ false);\n+ }\n+\n+ @Test\n+ public void correctlyDeserialisesFromJsonStringWhenAdditionalParamsAbsent() {\n+ StringValuePattern pattern = Json.read(\n+ \"{\\n\" +\n+ \" \\\"equalToJson\\\": \\\"2\\\"\\n\" +\n+ \"}\",\n+ StringValuePattern.class\n+ );\n+\n+ assertThat(pattern, instanceOf(EqualToJsonPattern.class));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreArrayOrder(), is(nullValue()));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreExtraElements(), is(nullValue()));\n+ assertThat(pattern.getExpected(), is(\"2\"));\n+ }\n+\n+ @Test\n+ public void correctlyDeserialisesFromJsonValueWhenAdditionalParamsAbsent() throws JSONException {\n+ String expectedJson = \"[ 1, 2, \\\"value\\\" ]\";\n+ StringValuePattern pattern = Json.read(\"{ \\\"equalToJson\\\": \" + expectedJson + \" }\", StringValuePattern.class);\n+\n+ assertThat(pattern, instanceOf(EqualToJsonPattern.class));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreArrayOrder(), is(nullValue()));\n+ assertThat(((EqualToJsonPattern) pattern).isIgnoreExtraElements(), is(nullValue()));\n+ JSONAssert.assertEquals(pattern.getExpected(), expectedJson, false);\n+ }\n+\n+ @Test\n+ public void correctlySerialisesToJsonWhenAdditionalParamsAbsentAndConstructedWithJsonValue() throws JSONException {\n+ String expectedJson = \"[ 1, 2, \\\"value\\\" ]\";\n+ EqualToJsonPattern pattern = new EqualToJsonPattern(Json.node(expectedJson), null, null);\n+\n+ String serialised = Json.write(pattern);\n+ JSONAssert.assertEquals(\"{ \\\"equalToJson\\\": \" + expectedJson + \" }\", serialised, false);\n+ }\n+\n+ @Test\n+ public void correctlySerialisesToJsonWhenAdditionalParamsAbsent() throws JSONException {\n+ EqualToJsonPattern pattern = new EqualToJsonPattern(\"4444\", null, null);\n+\n+ String serialised = Json.write(pattern);\n+ JSONAssert.assertEquals(\n+ \"{\\n\" +\n+ \" \\\"equalToJson\\\": \\\"4444\\\"\\n\" +\n+ \"}\",\n+ serialised,\n+ false);\n+ }\n+\n+ @Test\n+ public void returnsNoExactMatchForVerySimilarNestedDocs() {\n+ assertFalse(\n+ new EqualToJsonPattern(\n+ \"{\\n\" +\n+ \" \\\"outer\\\": {\\n\" +\n+ \" \\\"inner:\\\": {\\n\" +\n+ \" \\\"wrong\\\": 1\\n\" +\n+ \" }\\n\" +\n+ \" }\\n\" +\n+ \"}\", false, false\n+ ).match(\n+ \"{\\n\" +\n+ \" \\\"outer\\\": {\\n\" +\n+ \" \\\"inner:\\\": {\\n\" +\n+ \" \\\"thing\\\": 1\\n\" +\n+ \" }\\n\" +\n+ \" }\\n\" +\n+ \"}\"\n+ ).isExactMatch()\n+ );\n+ }\n+\n+ @Test\n+ public void doesNotMatchWhenValueIsNull() {\n+ MatchResult match = new EqualToJsonPattern(\n+ \"{\\n\" +\n+ \" \\\"outer\\\": {\\n\" +\n+ \" \\\"inner:\\\": {\\n\" +\n+ \" \\\"wrong\\\": 1\\n\" +\n+ \" }\\n\" +\n+ \" }\\n\" +\n+ \"}\", false, false\n+ ).match(null);\n+\n+ assertFalse(match.isExactMatch());\n+ assertThat(match.getDistance(), is(1.0));\n+ }\n+\n+ @Test\n+ public void doesNotMatchWhenValueIsEmptyString() {\n+ MatchResult match = new EqualToJsonPattern(\n+ \"{\\n\" +\n+ \" \\\"outer\\\": {\\n\" +\n+ \" \\\"inner:\\\": {\\n\" +\n+ \" \\\"wrong\\\": 1\\n\" +\n+ \" }\\n\" +\n+ \" }\\n\" +\n+ \"}\", false, false\n+ ).match(\"\");\n+\n+ assertFalse(match.isExactMatch());\n+ assertThat(match.getDistance(), is(1.0));\n+ }\n+\n+ @Test\n+ public void doesNotMatchWhenValueIsNotJson() {\n+ MatchResult match = new EqualToJsonPattern(\n+ \"{\\n\" +\n+ \" \\\"outer\\\": {\\n\" +\n+ \" \\\"inner:\\\": {\\n\" +\n+ \" \\\"wrong\\\": 1\\n\" +\n+ \" }\\n\" +\n+ \" }\\n\" +\n+ \"}\", false, false\n+ ).match(\"<some-xml />\");\n+\n+ assertFalse(match.isExactMatch());\n+ assertThat(match.getDistance(), is(1.0));\n+ }\n+\n+ @Test\n+ public void doesNotBreakWhenComparingNestedArraysOfDifferentSizes() {\n+ String expected = \"{\\\"columns\\\": [{\\\"name\\\": \\\"agreementnumber\\\",\\\"a\\\": 1},{\\\"name\\\": \\\"utilizerstatus\\\",\\\"b\\\": 2}]}\";\n+ String actual = \"{\\\"columns\\\": [{\\\"name\\\": \\\"x\\\",\\\"y\\\": 3},{\\\"name\\\": \\\"agreementnumber\\\",\\\"a\\\": 1},{\\\"name\\\": \\\"agreementstatus\\\",\\\"b\\\": 2}]}\";\n+\n+ MatchResult match = new EqualToJsonPattern(expected, false, false).match(actual);\n+\n+ assertFalse(match.isExactMatch());\n+ }\n+\n+ @Test\n+ public void doesNotBreakWhenComparingTopLevelArraysOfDifferentSizesWithCommonElements() {\n+ String expected = \"[ \\n\" +\n+ \" { \\\"one\\\": 1 }, \\n\" +\n+ \" { \\\"two\\\": 2 }, \\n\" +\n+ \" { \\\"three\\\": 3 } \\n\" +\n+ \"]\";\n+ String actual = \"[ \\n\" +\n+ \" { \\\"zero\\\": 0 }, \\n\" +\n+ \" { \\\"one\\\": 1 }, \\n\" +\n+ \" { \\\"two\\\": 2 }, \\n\" +\n+ \" { \\\"four\\\": 4 } \\n\" +\n+ \"]\";\n+\n+ MatchResult match = new EqualToJsonPattern(expected, false, false).match(actual);\n+\n+ assertFalse(match.isExactMatch());\n+ }\n+\n+ @Test\n+ public void ignoresExtraElementsWhenParameterIsPresentsWithoutIgnoreArrayOrder() {\n+ StringValuePattern pattern = Json.read(\n+ \"{\\n\" +\n+ \" \\\"equalToJson\\\": { \\\"one\\\": 1 },\\n\" +\n+ \" \\\"ignoreExtraElements\\\": true\\n\" +\n+ \"}\",\n+ StringValuePattern.class\n+ );\n+\n+ assertThat(pattern.match(\"{\\n\" +\n+ \" \\\"one\\\": 1,\\n\" +\n+ \" \\\"two\\\": 2\\n\" +\n+ \"}\").isExactMatch(), is(true));\n+ }\n+\n+ @Test\n+ public void doesNotMatchEmptyArraysWhenNotIgnoringExtraElements() {\n+ String expected = \"{\\\"client\\\":\\\"AAA\\\",\\\"name\\\":\\\"BBB\\\"}\";\n+ String actual = \"{\\\"client\\\":\\\"AAA\\\", \\\"name\\\":\\\"BBB\\\", \\\"addresses\\\": [ ]}\";\n+\n+ MatchResult match = new EqualToJsonPattern(expected, false, false).match(actual);\n+\n+ assertFalse(match.isExactMatch());\n+ }\n+\n+ @Test\n+ public void doesNotMatchEmptyArrayWhenIgnoringExtraArrayElementsAndNotIgnoringExtraElements() {\n+ String expected = \"{\\\"client\\\":\\\"AAA\\\",\\\"name\\\":\\\"BBB\\\"}\";\n+ String actual = \"{\\\"client\\\":\\\"AAA\\\", \\\"name\\\":\\\"BBB\\\", \\\"addresses\\\": [ ]}\";\n+\n+ MatchResult match = new EqualToJsonPattern(expected, true, false).match(actual);\n+\n+ assertFalse(match.isExactMatch());\n+ }\n+\n+ @Test\n+ public void doesNotMatchEmptyObjectWhenIgnoringExtraArrayElementsAndNotIgnoringExtraElements() {\n+ String expected = \"{\\\"client\\\":\\\"AAA\\\",\\\"name\\\":\\\"BBB\\\"}\";\n+ String actual = \"{\\\"client\\\":\\\"AAA\\\", \\\"name\\\":\\\"BBB\\\", \\\"addresses\\\": { }}\";\n+\n+ MatchResult match = new EqualToJsonPattern(expected, true, false).match(actual);\n+\n+ assertFalse(match.isExactMatch());\n+ }\n+\n+ @Test\n+ public void treatsTwoTopLevelsArraysWithDifferingOrderAsSameWhenIgnoringOrder() {\n+ String expected = \"[\\\"a\\\",\\\"b\\\", \\\"c\\\",\\\"d\\\",\\\"e\\\",\\\"f\\\",\\\"g\\\",\\\"h\\\"]\";\n+ String actual = \"[\\\"b\\\",\\\"a\\\", \\\"d\\\",\\\"c\\\",\\\"e\\\",\\\"f\\\",\\\"g\\\",\\\"h\\\"]\";\n+\n+ EqualToJsonPattern pattern = new EqualToJsonPattern(expected, true, true);\n+ final MatchResult result = pattern.match(actual);\n+\n+ assertTrue(result.isExactMatch());\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"diff": "@@ -269,7 +269,7 @@ public class EqualToJsonTest {\n\" \\\"one\\\": 1, \\n\" +\n\" \\\"three\\\": 3, \\n\" +\n\" \\\"two\\\": 2, \\n\" +\n- \" \\\"four\\\": [2, 1, 2], \\n\" +\n+ \" \\\"four\\\": [2, 1, 3], \\n\" +\n\" \\\"five\\\": 5, \\n\" +\n\" \\\"six\\\": 6 \\n\" +\n\"} \\n\"\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/RequestPatternTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/RequestPatternTest.java",
"diff": "@@ -26,7 +26,6 @@ import org.skyscreamer.jsonassert.JSONAssert;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.client.WireMock.equalTo;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.*;\n-import static com.github.tomakehurst.wiremock.matching.MockMultipart.mockPart;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.newRequestPattern;\nimport static org.hamcrest.Matchers.*;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactoryTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactoryTest.java",
"diff": "@@ -27,7 +27,7 @@ public class RequestBodyEqualToJsonPatternFactoryTest {\n@Test\npublic void withIgnoreArrayOrder() {\nRequestBodyEqualToJsonPatternFactory patternFactory = new RequestBodyEqualToJsonPatternFactory(true, false);\n- EqualToJsonPattern pattern = (EqualToJsonPattern) patternFactory.forRequest(mockRequest().body(\"{}\"));\n+ EqualToJsonPattern pattern = patternFactory.forRequest(mockRequest().body(\"{}\"));\nassertThat(pattern.getEqualToJson(), is(\"{}\"));\nassertThat(pattern.isIgnoreExtraElements(), is(false));\n@@ -37,7 +37,7 @@ public class RequestBodyEqualToJsonPatternFactoryTest {\n@Test\npublic void withIgnoreExtraElements() {\nRequestBodyEqualToJsonPatternFactory patternFactory = new RequestBodyEqualToJsonPatternFactory(false, true);\n- EqualToJsonPattern pattern = (EqualToJsonPattern) patternFactory.forRequest(mockRequest().body(\"{}\"));\n+ EqualToJsonPattern pattern = patternFactory.forRequest(mockRequest().body(\"{}\"));\nassertThat(pattern.getEqualToJson(), is(\"{}\"));\nassertThat(pattern.isIgnoreExtraElements(), is(true));\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Switched EqualToJson implementation to use JsonUnit (thanks @lukas-krecan !) |
686,936 | 31.01.2020 13:30:16 | 0 | 3134d95eb76a01b86159ed61e6d5c1bd5e17a41f | Removed redundant equal to JSON test class | [
{
"change_type": "DELETE",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern2Test.java",
"new_path": null,
"diff": "-package com.github.tomakehurst.wiremock.matching;\n-\n-import com.github.tomakehurst.wiremock.common.Json;\n-import org.json.JSONException;\n-import org.junit.Test;\n-import org.skyscreamer.jsonassert.JSONAssert;\n-\n-import static org.hamcrest.Matchers.*;\n-import static org.junit.Assert.*;\n-\n-public class EqualToJsonPattern2Test {\n-\n- @Test\n- public void returns0DistanceForExactMatchForSingleLevelObject() {\n- assertThat(new EqualToJsonPattern(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"four\\\": 4 \\n\" +\n- \"} \\n\"\n- ).match(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"four\\\": 4 \\n\" +\n- \"} \\n\"\n- ).getDistance(), is(0.0));\n- }\n-\n- @Test\n- public void returnsNon0DistanceForPartialMatchForSingleLevelObject() {\n- assertThat(new EqualToJsonPattern(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"four\\\": 4 \\n\" +\n- \"} \\n\"\n- ).match(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": 7, \\n\" +\n- \" \\\"four\\\": 8 \\n\" +\n- \"} \\n\"\n- ).getDistance(), is(0.4));\n- }\n-\n- @Test\n- public void returnsLargeDistanceForTotallyDifferentDocuments() {\n- assertThat(new EqualToJsonPattern(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"four\\\": 4 \\n\" +\n- \"} \\n\"\n- ).match(\n- \"[1, 2, 3]\"\n- ).getDistance(), is(1.0));\n- }\n-\n- @Test\n- public void returnsLargeDistanceWhenActualDocIsAnEmptyObject() {\n- assertThat(new EqualToJsonPattern(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"four\\\": 4 \\n\" +\n- \"} \\n\"\n- ).match(\n- \"{}\"\n- ).getDistance(), is(0.8));\n- }\n-\n- @Test\n- public void returnsLargeDistanceWhenActualDocIsAnEmptyArray() {\n- assertThat(new EqualToJsonPattern(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"four\\\": 4 \\n\" +\n- \"} \\n\"\n- ).match(\n- \"[]\"\n- ).getDistance(), is(1.0));\n- }\n-\n- @Test\n- public void returnsLargeDistanceWhenExpectedDocIsAnEmptyObject() {\n- assertThat(new EqualToJsonPattern(\n- \"{}\"\n- ).match(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"four\\\": 4 \\n\" +\n- \"} \\n\"\n- ).getDistance(), is(0.8));\n- }\n-\n- @Test\n- public void returnsLargeDistanceWhenExpectedDocIsAnEmptyArray() {\n- assertThat(new EqualToJsonPattern(\n- \"[]\"\n- ).match(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"four\\\": 4 \\n\" +\n- \"} \\n\"\n- ).getDistance(), is(1.0));\n- }\n-\n- @Test\n- public void returnsMediumDistanceWhenSubtreeIsMissingFromActual() {\n- assertThat(new EqualToJsonPattern(\n- \"{\\n\" +\n- \" \\\"one\\\": \\\"GET\\\", \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": { \\n\" +\n- \" \\\"four\\\": \\\"FOUR\\\", \\n\" +\n- \" \\\"five\\\": [ \\n\" +\n- \" { \\n\" +\n- \" \\\"six\\\": 6, \\n\" +\n- \" \\\"seven\\\": 7 \\n\" +\n- \" }, \\n\" +\n- \" { \\n\" +\n- \" \\\"eight\\\": 8, \\n\" +\n- \" \\\"nine\\\": 9 \\n\" +\n- \" } \\n\" +\n- \" ] \\n\" +\n- \" } \\n\" +\n- \"}\"\n- ).match(\n- \"{ \\n\" +\n- \" \\\"one\\\": \\\"GET\\\", \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": { \\n\" +\n- \" \\\"four\\\": \\\"FOUR\\\"\\n\" +\n- \" } \\n\" +\n- \"} \\n\"\n- ).getDistance(), closeTo(0.56, 0.01));\n- }\n-\n- @Test\n- public void returnsExactMatchWhenObjectPropertyOrderDiffers() {\n- assertTrue(new EqualToJsonPattern(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"four\\\": 4 \\n\" +\n- \"} \\n\"\n- ).match(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"four\\\": 4 \\n\" +\n- \"} \\n\"\n- ).isExactMatch());\n- }\n-\n- @Test\n- public void returnsNonMatchWhenArrayOrderDiffers() {\n- assertFalse(new EqualToJsonPattern(\n- \"[1, 2, 3, 4]\"\n- ).match(\n- \"[1, 3, 2, 4]\"\n- ).isExactMatch());\n- }\n-\n- @Test\n- public void ignoresArrayOrderDifferenceWhenConfigured() {\n- assertTrue(new EqualToJsonPattern(\n- \"[1, 2, 3, 4]\",\n- true, false)\n- .match(\n- \"[1, 3, 2, 4]\"\n- ).isExactMatch());\n- }\n-\n- @Test\n- public void ignoresNestedArrayOrderDifferenceWhenConfigured() {\n- assertTrue(new EqualToJsonPattern(\n- \"{\\n\" +\n- \" \\\"one\\\": 1,\\n\" +\n- \" \\\"two\\\": [\\n\" +\n- \" { \\\"val\\\": 1 },\\n\" +\n- \" { \\\"val\\\": 2 },\\n\" +\n- \" { \\\"val\\\": 3 }\\n\" +\n- \" ]\\n\" +\n- \"}\",\n- true, false)\n- .match(\n- \"{\\n\" +\n- \" \\\"one\\\": 1,\\n\" +\n- \" \\\"two\\\": [\\n\" +\n- \" { \\\"val\\\": 3 },\\n\" +\n- \" { \\\"val\\\": 2 },\\n\" +\n- \" { \\\"val\\\": 1 }\\n\" +\n- \" ]\\n\" +\n- \"}\"\n- ).isExactMatch());\n- }\n-\n- @Test\n- public void ignoresExtraObjectAttributesWhenConfigured() {\n- assertTrue(new EqualToJsonPattern(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"four\\\": 4 \\n\" +\n- \"} \\n\",\n- false, true\n- ).match(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"four\\\": 4, \\n\" +\n- \" \\\"five\\\": 5, \\n\" +\n- \" \\\"six\\\": 6 \\n\" +\n- \"} \\n\"\n- ).isExactMatch());\n- }\n-\n- @Test\n- public void ignoresExtraObjectAttributesAndArrayOrderWhenConfigured() {\n- assertTrue(new EqualToJsonPattern(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"four\\\": [1, 2, 3] \\n\" +\n- \"} \\n\",\n- true, true\n- ).match(\n- \"{ \\n\" +\n- \" \\\"one\\\": 1, \\n\" +\n- \" \\\"three\\\": 3, \\n\" +\n- \" \\\"two\\\": 2, \\n\" +\n- \" \\\"four\\\": [3, 1, 2], \\n\" +\n- \" \\\"five\\\": 5, \\n\" +\n- \" \\\"six\\\": 6 \\n\" +\n- \"} \\n\"\n- ).isExactMatch());\n- }\n-\n- @Test\n- public void correctlyDeserialisesFromJsonStringWhenAdditionalParamsPresent() {\n- StringValuePattern pattern = Json.read(\n- \"{\\n\" +\n- \" \\\"equalToJson\\\": \\\"2\\\",\\n\" +\n- \" \\\"ignoreArrayOrder\\\": true,\\n\" +\n- \" \\\"ignoreExtraElements\\\": true\\n\" +\n- \"}\",\n- StringValuePattern.class\n- );\n-\n- assertThat(pattern, instanceOf(EqualToJsonPattern.class));\n- assertThat(((EqualToJsonPattern) pattern).isIgnoreArrayOrder(), is(true));\n- assertThat(((EqualToJsonPattern) pattern).isIgnoreExtraElements(), is(true));\n- assertThat(pattern.getExpected(), is(\"2\"));\n- }\n-\n- @Test\n- public void correctlyDeserialisesFromJsonValueWhenAdditionalParamsPresent() throws JSONException {\n- String expectedJson = \"{ \\\"someKey\\\": \\\"someValue\\\" }\";\n- String serializedJson =\n- \"{ \\n\" +\n- \" \\\"equalToJson\\\": \" + expectedJson + \", \\n\" +\n- \" \\\"ignoreArrayOrder\\\": true, \\n\" +\n- \" \\\"ignoreExtraElements\\\": true \\n\" +\n- \"} \";\n- StringValuePattern pattern = Json.read(serializedJson, StringValuePattern.class);\n-\n- assertThat(pattern, instanceOf(EqualToJsonPattern.class));\n- assertThat(((EqualToJsonPattern) pattern).isIgnoreArrayOrder(), is(true));\n- assertThat(((EqualToJsonPattern) pattern).isIgnoreExtraElements(), is(true));\n- JSONAssert.assertEquals(pattern.getExpected(), expectedJson, false);\n- }\n-\n- @Test\n- public void correctlySerialisesToJsonValueWhenAdditionalParamsPresentAndConstructedWithJsonValue() throws JSONException {\n- String expectedJson = \"{ \\\"someKey\\\": \\\"someValue\\\" }\";\n- EqualToJsonPattern pattern = new EqualToJsonPattern(Json.node(expectedJson), true, true);\n-\n- String serialised = Json.write(pattern);\n- String expected =\n- \"{ \\n\" +\n- \" \\\"equalToJson\\\": \" + expectedJson + \", \\n\" +\n- \" \\\"ignoreArrayOrder\\\": true, \\n\" +\n- \" \\\"ignoreExtraElements\\\": true \\n\" +\n- \"} \";\n- JSONAssert.assertEquals(expected, serialised, false);\n- }\n-\n- @Test\n- public void correctlySerialisesToJsonWhenAdditionalParamsPresentAndConstructedWithString() throws JSONException {\n- EqualToJsonPattern pattern = new EqualToJsonPattern(\"4444\", true, true);\n-\n- String serialised = Json.write(pattern);\n- JSONAssert.assertEquals(\n- \"{\\n\" +\n- \" \\\"equalToJson\\\": \\\"4444\\\",\\n\" +\n- \" \\\"ignoreArrayOrder\\\": true,\\n\" +\n- \" \\\"ignoreExtraElements\\\": true\\n\" +\n- \"}\",\n- serialised,\n- false);\n- }\n-\n- @Test\n- public void correctlyDeserialisesFromJsonStringWhenAdditionalParamsAbsent() {\n- StringValuePattern pattern = Json.read(\n- \"{\\n\" +\n- \" \\\"equalToJson\\\": \\\"2\\\"\\n\" +\n- \"}\",\n- StringValuePattern.class\n- );\n-\n- assertThat(pattern, instanceOf(EqualToJsonPattern.class));\n- assertThat(((EqualToJsonPattern) pattern).isIgnoreArrayOrder(), is(nullValue()));\n- assertThat(((EqualToJsonPattern) pattern).isIgnoreExtraElements(), is(nullValue()));\n- assertThat(pattern.getExpected(), is(\"2\"));\n- }\n-\n- @Test\n- public void correctlyDeserialisesFromJsonValueWhenAdditionalParamsAbsent() throws JSONException {\n- String expectedJson = \"[ 1, 2, \\\"value\\\" ]\";\n- StringValuePattern pattern = Json.read(\"{ \\\"equalToJson\\\": \" + expectedJson + \" }\", StringValuePattern.class);\n-\n- assertThat(pattern, instanceOf(EqualToJsonPattern.class));\n- assertThat(((EqualToJsonPattern) pattern).isIgnoreArrayOrder(), is(nullValue()));\n- assertThat(((EqualToJsonPattern) pattern).isIgnoreExtraElements(), is(nullValue()));\n- JSONAssert.assertEquals(pattern.getExpected(), expectedJson, false);\n- }\n-\n- @Test\n- public void correctlySerialisesToJsonWhenAdditionalParamsAbsentAndConstructedWithJsonValue() throws JSONException {\n- String expectedJson = \"[ 1, 2, \\\"value\\\" ]\";\n- EqualToJsonPattern pattern = new EqualToJsonPattern(Json.node(expectedJson), null, null);\n-\n- String serialised = Json.write(pattern);\n- JSONAssert.assertEquals(\"{ \\\"equalToJson\\\": \" + expectedJson + \" }\", serialised, false);\n- }\n-\n- @Test\n- public void correctlySerialisesToJsonWhenAdditionalParamsAbsent() throws JSONException {\n- EqualToJsonPattern pattern = new EqualToJsonPattern(\"4444\", null, null);\n-\n- String serialised = Json.write(pattern);\n- JSONAssert.assertEquals(\n- \"{\\n\" +\n- \" \\\"equalToJson\\\": \\\"4444\\\"\\n\" +\n- \"}\",\n- serialised,\n- false);\n- }\n-\n- @Test\n- public void returnsNoExactMatchForVerySimilarNestedDocs() {\n- assertFalse(\n- new EqualToJsonPattern(\n- \"{\\n\" +\n- \" \\\"outer\\\": {\\n\" +\n- \" \\\"inner:\\\": {\\n\" +\n- \" \\\"wrong\\\": 1\\n\" +\n- \" }\\n\" +\n- \" }\\n\" +\n- \"}\", false, false\n- ).match(\n- \"{\\n\" +\n- \" \\\"outer\\\": {\\n\" +\n- \" \\\"inner:\\\": {\\n\" +\n- \" \\\"thing\\\": 1\\n\" +\n- \" }\\n\" +\n- \" }\\n\" +\n- \"}\"\n- ).isExactMatch()\n- );\n- }\n-\n- @Test\n- public void doesNotMatchWhenValueIsNull() {\n- MatchResult match = new EqualToJsonPattern(\n- \"{\\n\" +\n- \" \\\"outer\\\": {\\n\" +\n- \" \\\"inner:\\\": {\\n\" +\n- \" \\\"wrong\\\": 1\\n\" +\n- \" }\\n\" +\n- \" }\\n\" +\n- \"}\", false, false\n- ).match(null);\n-\n- assertFalse(match.isExactMatch());\n- assertThat(match.getDistance(), is(1.0));\n- }\n-\n- @Test\n- public void doesNotMatchWhenValueIsEmptyString() {\n- MatchResult match = new EqualToJsonPattern(\n- \"{\\n\" +\n- \" \\\"outer\\\": {\\n\" +\n- \" \\\"inner:\\\": {\\n\" +\n- \" \\\"wrong\\\": 1\\n\" +\n- \" }\\n\" +\n- \" }\\n\" +\n- \"}\", false, false\n- ).match(\"\");\n-\n- assertFalse(match.isExactMatch());\n- assertThat(match.getDistance(), is(1.0));\n- }\n-\n- @Test\n- public void doesNotMatchWhenValueIsNotJson() {\n- MatchResult match = new EqualToJsonPattern(\n- \"{\\n\" +\n- \" \\\"outer\\\": {\\n\" +\n- \" \\\"inner:\\\": {\\n\" +\n- \" \\\"wrong\\\": 1\\n\" +\n- \" }\\n\" +\n- \" }\\n\" +\n- \"}\", false, false\n- ).match(\"<some-xml />\");\n-\n- assertFalse(match.isExactMatch());\n- assertThat(match.getDistance(), is(1.0));\n- }\n-\n- @Test\n- public void doesNotBreakWhenComparingNestedArraysOfDifferentSizes() {\n- String expected = \"{\\\"columns\\\": [{\\\"name\\\": \\\"agreementnumber\\\",\\\"a\\\": 1},{\\\"name\\\": \\\"utilizerstatus\\\",\\\"b\\\": 2}]}\";\n- String actual = \"{\\\"columns\\\": [{\\\"name\\\": \\\"x\\\",\\\"y\\\": 3},{\\\"name\\\": \\\"agreementnumber\\\",\\\"a\\\": 1},{\\\"name\\\": \\\"agreementstatus\\\",\\\"b\\\": 2}]}\";\n-\n- MatchResult match = new EqualToJsonPattern(expected, false, false).match(actual);\n-\n- assertFalse(match.isExactMatch());\n- }\n-\n- @Test\n- public void doesNotBreakWhenComparingTopLevelArraysOfDifferentSizesWithCommonElements() {\n- String expected = \"[ \\n\" +\n- \" { \\\"one\\\": 1 }, \\n\" +\n- \" { \\\"two\\\": 2 }, \\n\" +\n- \" { \\\"three\\\": 3 } \\n\" +\n- \"]\";\n- String actual = \"[ \\n\" +\n- \" { \\\"zero\\\": 0 }, \\n\" +\n- \" { \\\"one\\\": 1 }, \\n\" +\n- \" { \\\"two\\\": 2 }, \\n\" +\n- \" { \\\"four\\\": 4 } \\n\" +\n- \"]\";\n-\n- MatchResult match = new EqualToJsonPattern(expected, false, false).match(actual);\n-\n- assertFalse(match.isExactMatch());\n- }\n-\n- @Test\n- public void ignoresExtraElementsWhenParameterIsPresentsWithoutIgnoreArrayOrder() {\n- StringValuePattern pattern = Json.read(\n- \"{\\n\" +\n- \" \\\"equalToJson\\\": { \\\"one\\\": 1 },\\n\" +\n- \" \\\"ignoreExtraElements\\\": true\\n\" +\n- \"}\",\n- StringValuePattern.class\n- );\n-\n- assertThat(pattern.match(\"{\\n\" +\n- \" \\\"one\\\": 1,\\n\" +\n- \" \\\"two\\\": 2\\n\" +\n- \"}\").isExactMatch(), is(true));\n- }\n-\n- @Test\n- public void doesNotMatchEmptyArraysWhenNotIgnoringExtraElements() {\n- String expected = \"{\\\"client\\\":\\\"AAA\\\",\\\"name\\\":\\\"BBB\\\"}\";\n- String actual = \"{\\\"client\\\":\\\"AAA\\\", \\\"name\\\":\\\"BBB\\\", \\\"addresses\\\": [ ]}\";\n-\n- MatchResult match = new EqualToJsonPattern(expected, false, false).match(actual);\n-\n- assertFalse(match.isExactMatch());\n- }\n-\n- @Test\n- public void doesNotMatchEmptyArrayWhenIgnoringExtraArrayElementsAndNotIgnoringExtraElements() {\n- String expected = \"{\\\"client\\\":\\\"AAA\\\",\\\"name\\\":\\\"BBB\\\"}\";\n- String actual = \"{\\\"client\\\":\\\"AAA\\\", \\\"name\\\":\\\"BBB\\\", \\\"addresses\\\": [ ]}\";\n-\n- MatchResult match = new EqualToJsonPattern(expected, true, false).match(actual);\n-\n- assertFalse(match.isExactMatch());\n- }\n-\n- @Test\n- public void doesNotMatchEmptyObjectWhenIgnoringExtraArrayElementsAndNotIgnoringExtraElements() {\n- String expected = \"{\\\"client\\\":\\\"AAA\\\",\\\"name\\\":\\\"BBB\\\"}\";\n- String actual = \"{\\\"client\\\":\\\"AAA\\\", \\\"name\\\":\\\"BBB\\\", \\\"addresses\\\": { }}\";\n-\n- MatchResult match = new EqualToJsonPattern(expected, true, false).match(actual);\n-\n- assertFalse(match.isExactMatch());\n- }\n-\n- @Test\n- public void treatsTwoTopLevelsArraysWithDifferingOrderAsSameWhenIgnoringOrder() {\n- String expected = \"[\\\"a\\\",\\\"b\\\", \\\"c\\\",\\\"d\\\",\\\"e\\\",\\\"f\\\",\\\"g\\\",\\\"h\\\"]\";\n- String actual = \"[\\\"b\\\",\\\"a\\\", \\\"d\\\",\\\"c\\\",\\\"e\\\",\\\"f\\\",\\\"g\\\",\\\"h\\\"]\";\n-\n- EqualToJsonPattern pattern = new EqualToJsonPattern(expected, true, true);\n- final MatchResult result = pattern.match(actual);\n-\n- assertTrue(result.isExactMatch());\n- }\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"diff": "@@ -534,4 +534,15 @@ public class EqualToJsonTest {\nassertFalse(match.isExactMatch());\n}\n+ @Test\n+ public void treatsTwoTopLevelsArraysWithDifferingOrderAsSameWhenIgnoringOrder() {\n+ String expected = \"[\\\"a\\\",\\\"b\\\", \\\"c\\\",\\\"d\\\",\\\"e\\\",\\\"f\\\",\\\"g\\\",\\\"h\\\"]\";\n+ String actual = \"[\\\"b\\\",\\\"a\\\", \\\"d\\\",\\\"c\\\",\\\"e\\\",\\\"f\\\",\\\"g\\\",\\\"h\\\"]\";\n+\n+ EqualToJsonPattern pattern = new EqualToJsonPattern(expected, true, true);\n+ final MatchResult result = pattern.match(actual);\n+\n+ assertTrue(result.isExactMatch());\n+ }\n+\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Removed redundant equal to JSON test class |
686,936 | 31.01.2020 13:31:11 | 0 | 71adecdd536254eac7a38cd364375c8470de13bd | Removed redundant EqualToJsonPattern constructor | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"diff": "@@ -37,10 +37,6 @@ public class EqualToJsonPattern extends StringValuePattern {\nthis.serializeAsString = false;\n}\n- EqualToJsonPattern(String json) {\n- this(json, false, false);\n- }\n-\n@Override\npublic MatchResult match(String value) {\nfinal CountingDiffListener diffListener = new CountingDiffListener();\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Removed redundant EqualToJsonPattern constructor |
686,936 | 31.01.2020 13:41:34 | 0 | ffe8b58c45441a591f33cb83623fa0b0816c25b1 | Fixed - added tests confirming support for JsonUnit placeholders | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"diff": "@@ -540,9 +540,48 @@ public class EqualToJsonTest {\nString actual = \"[\\\"b\\\",\\\"a\\\", \\\"d\\\",\\\"c\\\",\\\"e\\\",\\\"f\\\",\\\"g\\\",\\\"h\\\"]\";\nEqualToJsonPattern pattern = new EqualToJsonPattern(expected, true, true);\n- final MatchResult result = pattern.match(actual);\n+ MatchResult result = pattern.match(actual);\nassertTrue(result.isExactMatch());\n}\n+ @Test\n+ public void supportsPlaceholders() {\n+ String expected = \"{\\n\" +\n+ \" \\\"id\\\": \\\"${json-unit.any-string}\\\",\\n\" +\n+ \" \\\"name\\\": \\\"Tom\\\"\\n\" +\n+ \"}\";\n+\n+ String actual = \"{\\n\" +\n+ \" \\\"id\\\": \\\"abc123\\\",\\n\" +\n+ \" \\\"name\\\": \\\"Tom\\\"\\n\" +\n+ \"}\";\n+\n+ MatchResult match = new EqualToJsonPattern(expected, false, false).match(actual);\n+ assertThat(match.isExactMatch(), is(true));\n+ }\n+\n+ @Test\n+ public void supportsRegexPlaceholders() {\n+ String expected = \"{\\n\" +\n+ \" \\\"id\\\": \\\"${json-unit.regex}[a-z]+\\\",\\n\" +\n+ \" \\\"name\\\": \\\"Tom\\\"\\n\" +\n+ \"}\";\n+\n+ String actualMatching = \"{\\n\" +\n+ \" \\\"id\\\": \\\"abc\\\",\\n\" +\n+ \" \\\"name\\\": \\\"Tom\\\"\\n\" +\n+ \"}\";\n+ MatchResult match = new EqualToJsonPattern(expected, false, false).match(actualMatching);\n+ assertThat(match.isExactMatch(), is(true));\n+\n+\n+ String actualNonMatching = \"{\\n\" +\n+ \" \\\"id\\\": \\\"123\\\",\\n\" +\n+ \" \\\"name\\\": \\\"Tom\\\"\\n\" +\n+ \"}\";\n+ MatchResult nonMatch = new EqualToJsonPattern(expected, false, false).match(actualNonMatching);\n+ assertThat(nonMatch.isExactMatch(), is(false));\n+ }\n+\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #1121 - added tests confirming support for JsonUnit placeholders |
686,936 | 31.01.2020 14:09:01 | 0 | 13da0c0fce7a836bbf4092072e7a4028258d58c1 | Documented JSON placeholders | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/request-matching.md",
"new_path": "docs-v2/_docs/request-matching.md",
"diff": "@@ -391,6 +391,8 @@ JSON with string literal:\n}\n```\n+#### Less strict matching\n+\nBy default different array orderings and additional object attributes will trigger a non-match. However, both of these conditions can be disabled individually.\nJava:\n@@ -416,6 +418,25 @@ JSON:\n}\n```\n+#### Placeholders\n+\n+JSON equality matching is based on [JsonUnit](https://github.com/lukas-krecan/JsonUnit) and therefore supports placeholders.\n+This allows specific attributes to be treated as wildcards, rather than an exactly value being required for a match.\n+\n+For instance, the following:\n+\n+```json\n+{ \"id\": \"${json-unit.any-string}\" }\n+```\n+\n+would match a request with a JSON body of:\n+\n+```json\n+{ \"id\": \"abc123\" }\n+```\n+\n+It's also possible to use placeholders that constrain the expected value by type or regular expression.\n+See [the JsonUnit placeholders documentation](https://github.com/lukas-krecan/JsonUnit#typeplc) for the full syntax.\n### JSON Path\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Documented JSON placeholders |
686,936 | 31.01.2020 15:14:21 | 0 | c7028449c35d6521accf5d956dc618f7d6cf5b7b | Fixed - added a configuration option to disable logging of request/responses to the notifier, for use in performance tests. | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/running-standalone.md",
"new_path": "docs-v2/_docs/running-standalone.md",
"diff": "@@ -128,6 +128,8 @@ The last of these will cause chunked encoding to be used only when a stub define\n`--disable-gzip`: Prevent response bodies from being gzipped.\n+`--disable-request-logging`: Prevent requests and responses from being sent to the notifier. Use this when performance testing as it will save memory and CPU even when info/verbose logging is not enabled.\n+\n`--permitted-system-keys`: Comma-separated list of regular expressions for names of permitted environment variables and system properties accessible from response templates. Only has any effect when templating is enabled. Defaults to `wiremock.*`.\n`--help`: Show command line help\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"diff": "@@ -71,4 +71,5 @@ public interface Options {\nAsynchronousResponseSettings getAsynchronousResponseSettings();\nChunkedEncodingPolicy getChunkedEncodingPolicy();\nboolean getGzipDisabled();\n+ boolean getStubRequestLoggingDisabled();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"diff": "@@ -161,7 +161,8 @@ public class WireMockApp implements StubServer, Admin {\nthis,\npostServeActions,\nrequestJournal,\n- getStubRequestFilters()\n+ getStubRequestFilters(),\n+ options.getStubRequestLoggingDisabled()\n);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java",
"diff": "@@ -94,6 +94,7 @@ public class WireMockConfiguration implements Options {\nprivate int asynchronousResponseThreads;\nprivate ChunkedEncodingPolicy chunkedEncodingPolicy;\nprivate boolean gzipDisabled = false;\n+ private boolean stubLoggingDisabled = false;\nprivate String permittedSystemKeys = null;\nprivate MappingsSource getMappingsSource() {\n@@ -349,6 +350,11 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n+ public WireMockConfiguration stubRequestLoggingDisabled(boolean disabled) {\n+ this.stubLoggingDisabled = disabled;\n+ return this;\n+ }\n+\n@Override\npublic int portNumber() {\nreturn portNumber;\n@@ -498,4 +504,9 @@ public class WireMockConfiguration implements Options {\npublic boolean getGzipDisabled() {\nreturn gzipDisabled;\n}\n+\n+ @Override\n+ public boolean getStubRequestLoggingDisabled() {\n+ return stubLoggingDisabled;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubRequestHandler.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/StubRequestHandler.java",
"diff": "@@ -34,18 +34,21 @@ public class StubRequestHandler extends AbstractRequestHandler {\nprivate final Admin admin;\nprivate final Map<String, PostServeAction> postServeActions;\nprivate final RequestJournal requestJournal;\n+ private final boolean loggingDisabled;\npublic StubRequestHandler(StubServer stubServer,\nResponseRenderer responseRenderer,\nAdmin admin,\nMap<String, PostServeAction> postServeActions,\nRequestJournal requestJournal,\n- List<RequestFilter> requestFilters) {\n+ List<RequestFilter> requestFilters,\n+ boolean loggingDisabled) {\nsuper(responseRenderer, requestFilters);\nthis.stubServer = stubServer;\nthis.admin = admin;\nthis.postServeActions = postServeActions;\nthis.requestJournal = requestJournal;\n+ this.loggingDisabled = loggingDisabled;\n}\n@Override\n@@ -55,7 +58,7 @@ public class StubRequestHandler extends AbstractRequestHandler {\n@Override\nprotected boolean logRequests() {\n- return true;\n+ return !loggingDisabled;\n}\n@Override\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"diff": "@@ -186,4 +186,9 @@ public class WarConfiguration implements Options {\npublic boolean getGzipDisabled() {\nreturn false;\n}\n+\n+ @Override\n+ public boolean getStubRequestLoggingDisabled() {\n+ return false;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java",
"diff": "@@ -93,8 +93,8 @@ public class CommandLineOptions implements Options {\nprivate static final String USE_CHUNKED_ENCODING = \"use-chunked-encoding\";\nprivate static final String MAX_TEMPLATE_CACHE_ENTRIES = \"max-template-cache-entries\";\nprivate static final String PERMITTED_SYSTEM_KEYS = \"permitted-system-keys\";\n-\nprivate static final String DISABLE_GZIP = \"disable-gzip\";\n+ private static final String DISABLE_REQUEST_LOGGING = \"disable-request-logging\";\nprivate final OptionSet optionSet;\n@@ -143,7 +143,7 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(MAX_TEMPLATE_CACHE_ENTRIES, \"The maximum number of response template fragments that can be cached. Only has any effect when templating is enabled. Defaults to no limit.\").withOptionalArg();\noptionParser.accepts(PERMITTED_SYSTEM_KEYS, \"A list of case-insensitive regular expressions for names of permitted system properties and environment vars. Only has any effect when templating is enabled. Defaults to no limit.\").withOptionalArg().ofType(String.class).withValuesSeparatedBy(\",\");\noptionParser.accepts(DISABLE_GZIP, \"Disable gzipping of request and response bodies\");\n-\n+ optionParser.accepts(DISABLE_REQUEST_LOGGING, \"Disable logging of stub requests and responses to the notifier. Useful when performance testing.\");\noptionParser.accepts(HELP, \"Print this message\");\n@@ -538,6 +538,11 @@ public class CommandLineOptions implements Options {\nreturn optionSet.has(DISABLE_GZIP);\n}\n+ @Override\n+ public boolean getStubRequestLoggingDisabled() {\n+ return optionSet.has(DISABLE_REQUEST_LOGGING);\n+ }\n+\nprivate Long getMaxTemplateCacheEntries() {\nreturn optionSet.has(MAX_TEMPLATE_CACHE_ENTRIES) ?\nLong.valueOf(optionSet.valueOf(MAX_TEMPLATE_CACHE_ENTRIES).toString()) :\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/StubRequestLoggingAcceptanceTest.java",
"diff": "+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.common.Notifier;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\n+import org.junit.Test;\n+\n+import java.util.ArrayList;\n+import java.util.List;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\n+import static com.github.tomakehurst.wiremock.client.WireMock.ok;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\n+import static org.hamcrest.Matchers.*;\n+import static org.junit.Assert.assertThat;\n+\n+public class StubRequestLoggingAcceptanceTest extends AcceptanceTestBase {\n+\n+ @Test\n+ public void logsEventsToNotifierWhenNotDisabled() {\n+ TestNotifier notifier = new TestNotifier();\n+ WireMockServer wm = new WireMockServer(wireMockConfig().dynamicPort().notifier(notifier));\n+ wm.start();\n+ testClient = new WireMockTestClient(wm.port());\n+\n+ wm.stubFor(get(\"/log-me\").willReturn(ok(\"body text\")));\n+\n+ testClient.get(\"/log-me\");\n+ assertThat(notifier.infoMessages.size(), is(1));\n+ assertThat(notifier.infoMessages.get(0), allOf(\n+ containsString(\"Request received:\"),\n+ containsString(\"/log-me\"),\n+ containsString(\"body text\")\n+ ));\n+ }\n+\n+ @Test\n+ public void doesNotLogEventsToNotifierWhenDisabled() {\n+ TestNotifier notifier = new TestNotifier();\n+ WireMockServer wm = new WireMockServer(wireMockConfig()\n+ .dynamicPort()\n+ .stubRequestLoggingDisabled(true)\n+ .notifier(notifier));\n+ wm.start();\n+ testClient = new WireMockTestClient(wm.port());\n+\n+ wm.stubFor(get(\"/log-me\").willReturn(ok(\"body\")));\n+\n+ testClient.get(\"/log-me\");\n+ assertThat(notifier.infoMessages.size(), is(0));\n+ }\n+\n+ public static class TestNotifier implements Notifier {\n+\n+ final List<String> infoMessages = new ArrayList<>();\n+\n+ @Override\n+ public void info(String message) {\n+ infoMessages.add(message);\n+ }\n+\n+ @Override\n+ public void error(String message) {\n+\n+ }\n+\n+ @Override\n+ public void error(String message, Throwable t) {\n+\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServerTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServerTest.java",
"diff": "@@ -60,7 +60,8 @@ public class JettyHttpServerTest {\nadmin,\nCollections.<String, PostServeAction>emptyMap(),\ncontext.mock(RequestJournal.class),\n- Collections.<RequestFilter>emptyList()\n+ Collections.<RequestFilter>emptyList(),\n+ false\n);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"diff": "@@ -450,7 +450,18 @@ public class CommandLineOptionsTest {\npublic void defaultsToGzipEnabled() {\nCommandLineOptions options = new CommandLineOptions();\nassertThat(options.getGzipDisabled(), is(false));\n+ }\n+\n+ @Test\n+ public void disablesRequestLogging() {\n+ CommandLineOptions options = new CommandLineOptions(\"--disable-request-logging\");\n+ assertThat(options.getStubRequestLoggingDisabled(), is(true));\n+ }\n+ @Test\n+ public void defaultsToRequestLoggingEnabled() {\n+ CommandLineOptions options = new CommandLineOptions();\n+ assertThat(options.getStubRequestLoggingDisabled(), is(false));\n}\npublic static class ResponseDefinitionTransformerExt1 extends ResponseDefinitionTransformer {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/StubRequestHandlerTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/stubbing/StubRequestHandlerTest.java",
"diff": "@@ -67,7 +67,7 @@ public class StubRequestHandlerTest {\nadmin = context.mock(Admin.class);\nrequestJournal = context.mock(RequestJournal.class);\n- requestHandler = new StubRequestHandler(stubServer, responseRenderer, admin, Collections.<String, PostServeAction>emptyMap(), requestJournal, Collections.<RequestFilter>emptyList());\n+ requestHandler = new StubRequestHandler(stubServer, responseRenderer, admin, Collections.<String, PostServeAction>emptyMap(), requestJournal, Collections.<RequestFilter>emptyList(), false);\ncontext.checking(new Expectations() {{\nallowing(requestJournal);\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #1255 - added a configuration option to disable logging of request/responses to the notifier, for use in performance tests. |
686,936 | 31.01.2020 17:23:48 | 0 | ef4cf3426e50121b4a8985aa0983fd8f0ba36fd3 | Restricted JsonUnit implementation of EqualToJson to JRE8, since this is the minimum supported version for the library. | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -90,7 +90,11 @@ allprojects {\ncompile(\"com.github.jknack:handlebars-helpers:$versions.handlebars\") {\nexclude group: 'org.mozilla', module: 'rhino'\n}\n- compile 'net.javacrumbs.json-unit:json-unit-core:2.12.0'\n+\n+ compile 'com.flipkart.zjsonpatch:zjsonpatch:0.4.4', {\n+ exclude group: 'com.fasterxml.jackson.core', module: 'jackson-databind'\n+ exclude group: 'com.fasterxml.jackson.core', module: 'jackson-core'\n+ }\ncompile 'commons-fileupload:commons-fileupload:1.4'\n@@ -175,7 +179,18 @@ subprojects {\napply plugin: 'signing'\nsourceSets {\n- main.java.srcDir project(':').sourceSets.main.java\n+// def isJava7 = project.name in ['wiremock', 'java7']\n+// println \"$project.name\"\n+// if (isJava7) {\n+// println \"$project.name: Using Java 7 EqualToJsonPattern\"\n+// main.java.srcDir project(':').sourceSets.main.java\n+// } else {\n+// println \"$project.name: Excluding Java 7 EqualToJsonPattern\"\n+// main.java.srcDir(project(':').sourceSets.main.java.exclude('com/github/tomakehurst/wiremock/matching/EqualToJsonPattern*'))\n+// }\n+\n+ main.java.srcDir project(':').sourceSets.main.java.exclude('com/github/tomakehurst/wiremock/matching/EqualToJsonPattern*')\n+\ntest.java.srcDir project(':').sourceSets.test.java\ntest.scala.srcDir project(':').sourceSets.test.scala\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/request-matching.md",
"new_path": "docs-v2/_docs/request-matching.md",
"diff": "@@ -438,6 +438,10 @@ would match a request with a JSON body of:\nIt's also possible to use placeholders that constrain the expected value by type or regular expression.\nSee [the JsonUnit placeholders documentation](https://github.com/lukas-krecan/JsonUnit#typeplc) for the full syntax.\n+> **note**\n+>\n+> Placeholders are only available in the `jre8` WireMock JARs, as the JsonUnit library requires at least Java 8.\n+\n### JSON Path\nDeems a match if the attribute value is valid JSON and matches the [JSON Path](http://goessner.net/articles/JsonPath/) expression supplied. A JSON body will be considered to match a path expression if the expression returns either a non-null single value (string, integer etc.), or a non-empty object or array.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "java7/src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"diff": "+/*\n+ * Copyright (C) 2011 Thomas Akehurst\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package com.github.tomakehurst.wiremock.matching;\n+\n+import com.fasterxml.jackson.annotation.JsonProperty;\n+import com.fasterxml.jackson.databind.JsonNode;\n+import com.fasterxml.jackson.databind.node.ArrayNode;\n+import com.flipkart.zjsonpatch.DiffFlags;\n+import com.flipkart.zjsonpatch.JsonDiff;\n+import com.github.tomakehurst.wiremock.common.Json;\n+import com.google.common.base.Function;\n+import com.google.common.base.Splitter;\n+import com.google.common.collect.Iterables;\n+import com.google.common.collect.Lists;\n+\n+import java.util.EnumSet;\n+import java.util.List;\n+import java.util.Objects;\n+\n+import static com.flipkart.zjsonpatch.DiffFlags.OMIT_COPY_OPERATION;\n+import static com.flipkart.zjsonpatch.DiffFlags.OMIT_MOVE_OPERATION;\n+import static com.github.tomakehurst.wiremock.common.Json.deepSize;\n+import static com.github.tomakehurst.wiremock.common.Json.maxDeepSize;\n+import static com.google.common.collect.Iterables.getLast;\n+import static org.apache.commons.lang3.math.NumberUtils.isNumber;\n+\n+public class EqualToJsonPattern extends StringValuePattern {\n+\n+ private final JsonNode expected;\n+ private final Boolean ignoreArrayOrder;\n+ private final Boolean ignoreExtraElements;\n+ private final Boolean serializeAsString;\n+\n+ public EqualToJsonPattern(@JsonProperty(\"equalToJson\") String json,\n+ @JsonProperty(\"ignoreArrayOrder\") Boolean ignoreArrayOrder,\n+ @JsonProperty(\"ignoreExtraElements\") Boolean ignoreExtraElements) {\n+ super(json);\n+ expected = Json.read(json, JsonNode.class);\n+ this.ignoreArrayOrder = ignoreArrayOrder;\n+ this.ignoreExtraElements = ignoreExtraElements;\n+ this.serializeAsString = true;\n+ }\n+\n+ public EqualToJsonPattern(JsonNode jsonNode,\n+ Boolean ignoreArrayOrder,\n+ Boolean ignoreExtraElements) {\n+ super(Json.write(jsonNode));\n+ expected = jsonNode;\n+ this.ignoreArrayOrder = ignoreArrayOrder;\n+ this.ignoreExtraElements = ignoreExtraElements;\n+ this.serializeAsString = false;\n+ }\n+\n+ @JsonProperty(\"equalToJson\")\n+ public Object getSerializedEqualToJson() {\n+ return serializeAsString ? getValue() : expected;\n+ }\n+\n+ public String getEqualToJson() {\n+ return expectedValue;\n+ }\n+\n+ private boolean shouldIgnoreArrayOrder() {\n+ return ignoreArrayOrder != null && ignoreArrayOrder;\n+ }\n+\n+ public Boolean isIgnoreArrayOrder() {\n+ return ignoreArrayOrder;\n+ }\n+\n+ private boolean shouldIgnoreExtraElements() {\n+ return ignoreExtraElements != null && ignoreExtraElements;\n+ }\n+\n+ public Boolean isIgnoreExtraElements() {\n+ return ignoreExtraElements;\n+ }\n+\n+ @Override\n+ public String getExpected() {\n+ return Json.prettyPrint(getValue());\n+ }\n+\n+ @Override\n+ public MatchResult match(String value) {\n+ try {\n+ final JsonNode actual = Json.read(value, JsonNode.class);\n+\n+ return new MatchResult() {\n+ @Override\n+ public boolean isExactMatch() {\n+ // Try to do it the fast way first, then fall back to doing the full diff\n+ if (!shouldIgnoreArrayOrder() && !shouldIgnoreExtraElements()) {\n+ return Objects.equals(actual, expected);\n+ }\n+\n+ return getDistance() == 0.0;\n+ }\n+\n+ @Override\n+ public double getDistance() {\n+ EnumSet<DiffFlags> flags = EnumSet.of(OMIT_COPY_OPERATION);\n+ ArrayNode diff = (ArrayNode) JsonDiff.asJson(expected, actual, flags);\n+\n+ double maxNodes = maxDeepSize(expected, actual);\n+ return diffSize(diff) / maxNodes;\n+ }\n+ };\n+ } catch (Exception e) {\n+ return MatchResult.noMatch();\n+ }\n+ }\n+\n+ private int diffSize(ArrayNode diff) {\n+ int acc = 0;\n+ for (JsonNode child: diff) {\n+ String operation = child.findValue(\"op\").textValue();\n+ JsonNode pathString = getFromPathString(operation, child);\n+ List<String> path = getPath(pathString.textValue());\n+ if (!arrayOrderIgnoredAndIsArrayMove(operation, path) && !extraElementsIgnoredAndIsAddition(operation)) {\n+ JsonNode valueNode = operation.equals(\"remove\") ? null : child.findValue(\"value\");\n+ JsonNode referencedExpectedNode = getNodeAtPath(expected, pathString);\n+ if (valueNode == null) {\n+ acc += deepSize(referencedExpectedNode);\n+ } else {\n+ acc += maxDeepSize(referencedExpectedNode, valueNode);\n+ }\n+ }\n+ }\n+\n+ return acc;\n+ }\n+\n+ private static JsonNode getFromPathString(String operation, JsonNode node) {\n+ if (operation.equals(\"move\")) {\n+ return node.findValue(\"from\");\n+ }\n+\n+ return node.findValue(\"path\");\n+ }\n+\n+ private boolean extraElementsIgnoredAndIsAddition(String operation) {\n+ return operation.equals(\"add\") && shouldIgnoreExtraElements();\n+ }\n+\n+ private boolean arrayOrderIgnoredAndIsArrayMove(String operation, List<String> path) {\n+ return operation.equals(\"move\") && isNumber(getLast(path)) && shouldIgnoreArrayOrder();\n+ }\n+\n+ public static JsonNode getNodeAtPath(JsonNode rootNode, JsonNode path) {\n+ String pathString = path.toString().equals(\"\\\"/\\\"\") ? \"\\\"\\\"\" : path.toString();\n+ return getNode(rootNode, getPath(pathString), 1);\n+ }\n+\n+ private static JsonNode getNode(JsonNode ret, List<String> path, int pos) {\n+ if (pos >= path.size()) {\n+ return ret;\n+ }\n+\n+ if (ret == null) {\n+ return null;\n+ }\n+\n+ String key = path.get(pos);\n+ if (ret.isArray()) {\n+ int keyInt = Integer.parseInt(key.replaceAll(\"\\\"\", \"\"));\n+ return getNode(ret.get(keyInt), path, ++pos);\n+ } else if (ret.isObject()) {\n+ if (ret.has(key)) {\n+ return getNode(ret.get(key), path, ++pos);\n+ }\n+ return null;\n+ } else {\n+ return ret;\n+ }\n+ }\n+\n+ private static List<String> getPath(String path) {\n+ List<String> paths = Splitter.on('/').splitToList(path.replaceAll(\"\\\"\", \"\"));\n+ return Lists.newArrayList(Iterables.transform(paths, new DecodePathFunction()));\n+ }\n+\n+ private final static class DecodePathFunction implements Function<String, String> {\n+\n+ @Override\n+ public String apply(String path) {\n+ return path.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"); // see http://tools.ietf.org/html/rfc6901#section-4\n+ }\n+ }\n+\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "java8/build.gradle",
"new_path": "java8/build.gradle",
"diff": "@@ -11,10 +11,8 @@ dependencies {\ncompile \"org.eclipse.jetty:jetty-alpn-server:$jettyVersion\"\ncompile \"org.eclipse.jetty:jetty-alpn-conscrypt-server:$jettyVersion\"\ncompile \"org.eclipse.jetty:jetty-alpn-conscrypt-client:$jettyVersion\"\n+ compile 'net.javacrumbs.json-unit:json-unit-core:2.12.0'\n+\ntestCompile \"org.eclipse.jetty:jetty-client:$jettyVersion\"\ntestCompile \"org.eclipse.jetty.http2:http2-http-client-transport:$jettyVersion\"\n}\n-\n-def getAlpnJarPath() {\n- project.configurations.compile.find { it.name.startsWith(\"alpn-boot-\") }\n-}\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"diff": "+package com.github.tomakehurst.wiremock.matching;\n+\n+import com.fasterxml.jackson.annotation.JsonProperty;\n+import com.fasterxml.jackson.databind.JsonNode;\n+import com.github.tomakehurst.wiremock.common.Json;\n+import net.javacrumbs.jsonunit.core.Configuration;\n+import net.javacrumbs.jsonunit.core.Option;\n+import net.javacrumbs.jsonunit.core.internal.Diff;\n+import net.javacrumbs.jsonunit.core.listener.Difference;\n+import net.javacrumbs.jsonunit.core.listener.DifferenceContext;\n+import net.javacrumbs.jsonunit.core.listener.DifferenceListener;\n+\n+public class EqualToJsonPattern extends StringValuePattern {\n+\n+ private final JsonNode expected;\n+ private final Boolean ignoreArrayOrder;\n+ private final Boolean ignoreExtraElements;\n+ private final Boolean serializeAsString;\n+\n+ public EqualToJsonPattern(@JsonProperty(\"equalToJson\") String json,\n+ @JsonProperty(\"ignoreArrayOrder\") Boolean ignoreArrayOrder,\n+ @JsonProperty(\"ignoreExtraElements\") Boolean ignoreExtraElements) {\n+ super(json);\n+ expected = Json.read(json, JsonNode.class);\n+ this.ignoreArrayOrder = ignoreArrayOrder;\n+ this.ignoreExtraElements = ignoreExtraElements;\n+ this.serializeAsString = true;\n+ }\n+\n+ public EqualToJsonPattern(JsonNode jsonNode,\n+ Boolean ignoreArrayOrder,\n+ Boolean ignoreExtraElements) {\n+ super(Json.write(jsonNode));\n+ expected = jsonNode;\n+ this.ignoreArrayOrder = ignoreArrayOrder;\n+ this.ignoreExtraElements = ignoreExtraElements;\n+ this.serializeAsString = false;\n+ }\n+\n+ @Override\n+ public MatchResult match(String value) {\n+ final CountingDiffListener diffListener = new CountingDiffListener();\n+ Configuration diffConfig = Configuration.empty()\n+ .withDifferenceListener(diffListener);\n+\n+ if (shouldIgnoreArrayOrder()) {\n+ diffConfig = diffConfig.withOptions(Option.IGNORING_ARRAY_ORDER);\n+ }\n+\n+ if (shouldIgnoreExtraElements()) {\n+ diffConfig = diffConfig.withOptions(Option.IGNORING_EXTRA_ARRAY_ITEMS, Option.IGNORING_EXTRA_FIELDS);\n+ }\n+\n+ final JsonNode actual;\n+ final Diff diff;\n+ try {\n+ actual = Json.read(value, JsonNode.class);\n+ diff = Diff.create(\n+ expected, // JsonUnit knows how to work with JsonNode\n+ actual,\n+ \"\",\n+ \"\",\n+ diffConfig\n+ );\n+ } catch (Exception e) {\n+ return MatchResult.noMatch();\n+ }\n+\n+ return new MatchResult() {\n+ @Override\n+ public boolean isExactMatch() {\n+ return diff.similar();\n+ }\n+\n+ @Override\n+ public double getDistance() {\n+ diff.similar();\n+ double maxNodes = maxDeepSize(expected, actual);\n+ return diffListener.count / maxNodes;\n+ }\n+ };\n+ }\n+\n+ @JsonProperty(\"equalToJson\")\n+ public Object getSerializedEqualToJson() {\n+ return serializeAsString ? getValue() : Json.read(getValue(), JsonNode.class);\n+ }\n+\n+ public String getEqualToJson() {\n+ return expectedValue;\n+ }\n+\n+ private boolean shouldIgnoreArrayOrder() {\n+ return ignoreArrayOrder != null && ignoreArrayOrder;\n+ }\n+\n+ public Boolean isIgnoreArrayOrder() {\n+ return ignoreArrayOrder;\n+ }\n+\n+ private boolean shouldIgnoreExtraElements() {\n+ return ignoreExtraElements != null && ignoreExtraElements;\n+ }\n+\n+ public Boolean isIgnoreExtraElements() {\n+ return ignoreExtraElements;\n+ }\n+\n+ @Override\n+ public String getExpected() {\n+ return Json.prettyPrint(getValue());\n+ }\n+\n+ private static class CountingDiffListener implements DifferenceListener {\n+\n+ public int count = 0;\n+\n+ @Override\n+ public void diff(Difference difference, DifferenceContext context) {\n+ final int delta = maxDeepSize(difference.getExpected(), difference.getActual());\n+ count += delta == 0 ? 1 : Math.abs(delta);\n+ }\n+ }\n+\n+ public static int maxDeepSize(Object one, Object two) {\n+ return Math.max(\n+ one != null ? deepSize(one) : 0,\n+ two != null ? deepSize(two) : 0\n+ );\n+ }\n+\n+ private static int deepSize(Object nodeObj) {\n+ JsonNode jsonNode = Json.getObjectMapper().convertValue(nodeObj, JsonNode.class);\n+ return Json.deepSize(jsonNode);\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"diff": "+/*\n+ * Copyright (C) 2011 Thomas Akehurst\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\npackage com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.JsonNode;\n+import com.fasterxml.jackson.databind.node.ArrayNode;\n+import com.flipkart.zjsonpatch.DiffFlags;\n+import com.flipkart.zjsonpatch.JsonDiff;\nimport com.github.tomakehurst.wiremock.common.Json;\n-import net.javacrumbs.jsonunit.core.Configuration;\n-import net.javacrumbs.jsonunit.core.Option;\n-import net.javacrumbs.jsonunit.core.internal.Diff;\n-import net.javacrumbs.jsonunit.core.listener.Difference;\n-import net.javacrumbs.jsonunit.core.listener.DifferenceContext;\n-import net.javacrumbs.jsonunit.core.listener.DifferenceListener;\n+import com.google.common.base.Function;\n+import com.google.common.base.Splitter;\n+import com.google.common.collect.Iterables;\n+import com.google.common.collect.Lists;\n+\n+import java.util.EnumSet;\n+import java.util.List;\n+import java.util.Objects;\n+\n+import static com.flipkart.zjsonpatch.DiffFlags.OMIT_COPY_OPERATION;\n+import static com.flipkart.zjsonpatch.DiffFlags.OMIT_MOVE_OPERATION;\n+import static com.github.tomakehurst.wiremock.common.Json.deepSize;\n+import static com.github.tomakehurst.wiremock.common.Json.maxDeepSize;\n+import static com.google.common.collect.Iterables.getLast;\n+import static org.apache.commons.lang3.math.NumberUtils.isNumber;\npublic class EqualToJsonPattern extends StringValuePattern {\n@@ -37,100 +64,141 @@ public class EqualToJsonPattern extends StringValuePattern {\nthis.serializeAsString = false;\n}\n- @Override\n- public MatchResult match(String value) {\n- final CountingDiffListener diffListener = new CountingDiffListener();\n- Configuration diffConfig = Configuration.empty()\n- .withDifferenceListener(diffListener);\n+ @JsonProperty(\"equalToJson\")\n+ public Object getSerializedEqualToJson() {\n+ return serializeAsString ? getValue() : expected;\n+ }\n- if (shouldIgnoreArrayOrder()) {\n- diffConfig = diffConfig.withOptions(Option.IGNORING_ARRAY_ORDER);\n+ public String getEqualToJson() {\n+ return expectedValue;\n}\n- if (shouldIgnoreExtraElements()) {\n- diffConfig = diffConfig.withOptions(Option.IGNORING_EXTRA_ARRAY_ITEMS, Option.IGNORING_EXTRA_FIELDS);\n+ private boolean shouldIgnoreArrayOrder() {\n+ return ignoreArrayOrder != null && ignoreArrayOrder;\n}\n- final JsonNode actual;\n- final Diff diff;\n- try {\n- actual = Json.read(value, JsonNode.class);\n- diff = Diff.create(\n- expected, // JsonUnit knows how to work with JsonNode\n- actual,\n- \"\",\n- \"\",\n- diffConfig\n- );\n- } catch (Exception e) {\n- return MatchResult.noMatch();\n+ public Boolean isIgnoreArrayOrder() {\n+ return ignoreArrayOrder;\n}\n+ private boolean shouldIgnoreExtraElements() {\n+ return ignoreExtraElements != null && ignoreExtraElements;\n+ }\n+\n+ public Boolean isIgnoreExtraElements() {\n+ return ignoreExtraElements;\n+ }\n+\n+ @Override\n+ public String getExpected() {\n+ return Json.prettyPrint(getValue());\n+ }\n+\n+ @Override\n+ public MatchResult match(String value) {\n+ try {\n+ final JsonNode actual = Json.read(value, JsonNode.class);\n+\nreturn new MatchResult() {\n@Override\npublic boolean isExactMatch() {\n- return diff.similar();\n+ // Try to do it the fast way first, then fall back to doing the full diff\n+ if (!shouldIgnoreArrayOrder() && !shouldIgnoreExtraElements()) {\n+ return Objects.equals(actual, expected);\n+ }\n+\n+ return getDistance() == 0.0;\n}\n@Override\npublic double getDistance() {\n- diff.similar();\n+ EnumSet<DiffFlags> flags = EnumSet.of(OMIT_COPY_OPERATION);\n+ ArrayNode diff = (ArrayNode) JsonDiff.asJson(expected, actual, flags);\n+\ndouble maxNodes = maxDeepSize(expected, actual);\n- return diffListener.count / maxNodes;\n+ return diffSize(diff) / maxNodes;\n}\n};\n+ } catch (Exception e) {\n+ return MatchResult.noMatch();\n+ }\n}\n- @JsonProperty(\"equalToJson\")\n- public Object getSerializedEqualToJson() {\n- return serializeAsString ? getValue() : Json.read(getValue(), JsonNode.class);\n+ private int diffSize(ArrayNode diff) {\n+ int acc = 0;\n+ for (JsonNode child: diff) {\n+ String operation = child.findValue(\"op\").textValue();\n+ JsonNode pathString = getFromPathString(operation, child);\n+ List<String> path = getPath(pathString.textValue());\n+ if (!arrayOrderIgnoredAndIsArrayMove(operation, path) && !extraElementsIgnoredAndIsAddition(operation)) {\n+ JsonNode valueNode = operation.equals(\"remove\") ? null : child.findValue(\"value\");\n+ JsonNode referencedExpectedNode = getNodeAtPath(expected, pathString);\n+ if (valueNode == null) {\n+ acc += deepSize(referencedExpectedNode);\n+ } else {\n+ acc += maxDeepSize(referencedExpectedNode, valueNode);\n+ }\n+ }\n}\n- public String getEqualToJson() {\n- return expectedValue;\n+ return acc;\n}\n- private boolean shouldIgnoreArrayOrder() {\n- return ignoreArrayOrder != null && ignoreArrayOrder;\n+ private static JsonNode getFromPathString(String operation, JsonNode node) {\n+ if (operation.equals(\"move\")) {\n+ return node.findValue(\"from\");\n}\n- public Boolean isIgnoreArrayOrder() {\n- return ignoreArrayOrder;\n+ return node.findValue(\"path\");\n}\n- private boolean shouldIgnoreExtraElements() {\n- return ignoreExtraElements != null && ignoreExtraElements;\n+ private boolean extraElementsIgnoredAndIsAddition(String operation) {\n+ return operation.equals(\"add\") && shouldIgnoreExtraElements();\n}\n- public Boolean isIgnoreExtraElements() {\n- return ignoreExtraElements;\n+ private boolean arrayOrderIgnoredAndIsArrayMove(String operation, List<String> path) {\n+ return operation.equals(\"move\") && isNumber(getLast(path)) && shouldIgnoreArrayOrder();\n}\n- @Override\n- public String getExpected() {\n- return Json.prettyPrint(getValue());\n+ public static JsonNode getNodeAtPath(JsonNode rootNode, JsonNode path) {\n+ String pathString = path.toString().equals(\"\\\"/\\\"\") ? \"\\\"\\\"\" : path.toString();\n+ return getNode(rootNode, getPath(pathString), 1);\n}\n- private static class CountingDiffListener implements DifferenceListener {\n+ private static JsonNode getNode(JsonNode ret, List<String> path, int pos) {\n+ if (pos >= path.size()) {\n+ return ret;\n+ }\n- public int count = 0;\n+ if (ret == null) {\n+ return null;\n+ }\n- @Override\n- public void diff(Difference difference, DifferenceContext context) {\n- final int delta = maxDeepSize(difference.getExpected(), difference.getActual());\n- count += delta == 0 ? 1 : Math.abs(delta);\n+ String key = path.get(pos);\n+ if (ret.isArray()) {\n+ int keyInt = Integer.parseInt(key.replaceAll(\"\\\"\", \"\"));\n+ return getNode(ret.get(keyInt), path, ++pos);\n+ } else if (ret.isObject()) {\n+ if (ret.has(key)) {\n+ return getNode(ret.get(key), path, ++pos);\n+ }\n+ return null;\n+ } else {\n+ return ret;\n}\n}\n- public static int maxDeepSize(Object one, Object two) {\n- return Math.max(\n- one != null ? deepSize(one) : 0,\n- two != null ? deepSize(two) : 0\n- );\n+ private static List<String> getPath(String path) {\n+ List<String> paths = Splitter.on('/').splitToList(path.replaceAll(\"\\\"\", \"\"));\n+ return Lists.newArrayList(Iterables.transform(paths, new DecodePathFunction()));\n}\n- private static int deepSize(Object nodeObj) {\n- JsonNode jsonNode = Json.getObjectMapper().convertValue(nodeObj, JsonNode.class);\n- return Json.deepSize(jsonNode);\n+ private final static class DecodePathFunction implements Function<String, String> {\n+\n+ @Override\n+ public String apply(String path) {\n+ return path.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"); // see http://tools.ietf.org/html/rfc6901#section-4\n+ }\n}\n+\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToJsonTest.java",
"diff": "@@ -17,10 +17,14 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.common.Json;\n+import org.apache.commons.lang3.JavaVersion;\n+import org.apache.commons.lang3.SystemUtils;\nimport org.json.JSONException;\nimport org.junit.Test;\nimport org.skyscreamer.jsonassert.JSONAssert;\n+import static org.apache.commons.lang3.JavaVersion.JAVA_1_8;\n+import static org.apache.commons.lang3.SystemUtils.isJavaVersionAtLeast;\nimport static org.hamcrest.Matchers.closeTo;\nimport static org.hamcrest.Matchers.instanceOf;\nimport static org.hamcrest.Matchers.is;\n@@ -28,6 +32,7 @@ import static org.hamcrest.Matchers.nullValue;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;\n+import static org.junit.Assume.assumeThat;\npublic class EqualToJsonTest {\n@@ -536,6 +541,8 @@ public class EqualToJsonTest {\n@Test\npublic void treatsTwoTopLevelsArraysWithDifferingOrderAsSameWhenIgnoringOrder() {\n+ assumeJava8OrHigher();\n+\nString expected = \"[\\\"a\\\",\\\"b\\\", \\\"c\\\",\\\"d\\\",\\\"e\\\",\\\"f\\\",\\\"g\\\",\\\"h\\\"]\";\nString actual = \"[\\\"b\\\",\\\"a\\\", \\\"d\\\",\\\"c\\\",\\\"e\\\",\\\"f\\\",\\\"g\\\",\\\"h\\\"]\";\n@@ -547,6 +554,8 @@ public class EqualToJsonTest {\n@Test\npublic void supportsPlaceholders() {\n+ assumeJava8OrHigher();\n+\nString expected = \"{\\n\" +\n\" \\\"id\\\": \\\"${json-unit.any-string}\\\",\\n\" +\n\" \\\"name\\\": \\\"Tom\\\"\\n\" +\n@@ -563,6 +572,8 @@ public class EqualToJsonTest {\n@Test\npublic void supportsRegexPlaceholders() {\n+ assumeJava8OrHigher();\n+\nString expected = \"{\\n\" +\n\" \\\"id\\\": \\\"${json-unit.regex}[a-z]+\\\",\\n\" +\n\" \\\"name\\\": \\\"Tom\\\"\\n\" +\n@@ -584,4 +595,7 @@ public class EqualToJsonTest {\nassertThat(nonMatch.isExactMatch(), is(false));\n}\n+ private static void assumeJava8OrHigher() {\n+ assumeThat(isJavaVersionAtLeast(JAVA_1_8), is(true));\n+ }\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Restricted JsonUnit implementation of EqualToJson to JRE8, since this is the minimum supported version for the library. |
686,936 | 11.02.2020 17:18:54 | 0 | 60e14c4c29fe9f85751269178a8a177ff5672690 | Attempt at fixing Travis config so that correct Java version tests are run | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -12,5 +12,5 @@ install:\n- JAVA_HOME=$(jdk_switcher home openjdk8) ./gradlew classes testClasses -x generateApiDocs\nscript:\n- - ./gradlew check --stacktrace --no-daemon\n+ - if [[ $TRAVIS_JDK_VERSION == *\"8\"* ]]; then ./gradlew -c release-settings.gradle :java8:check --stacktrace --no-daemon; else ./gradlew -c release-settings.gradle :java7:check --stacktrace --no-daemon; fi\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Attempt at fixing Travis config so that correct Java version tests are run |
686,936 | 26.02.2020 11:09:46 | 0 | e207c0fc2c8bb9129b7a533ca34c7737fe3c9fab | Improved performance of XPath Handlebars helper by caching the XML document builder and XPath objects | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java",
"diff": "@@ -40,6 +40,26 @@ import static javax.xml.xpath.XPathConstants.NODE;\n*/\npublic class HandlebarsXPathHelper extends HandlebarsHelper<String> {\n+ private static final InheritableThreadLocal<XPath> localXPath = new InheritableThreadLocal<XPath>() {\n+ @Override\n+ protected XPath initialValue() {\n+ final XPathFactory xPathfactory = XPathFactory.newInstance();\n+ return xPathfactory.newXPath();\n+ }\n+ };\n+\n+ private static final InheritableThreadLocal<DocumentBuilder> localDocBuilder = new InheritableThreadLocal<DocumentBuilder>() {\n+ @Override\n+ protected DocumentBuilder initialValue() {\n+ final DocumentBuilderFactory factory = Xml.newDocumentBuilderFactory();\n+ try {\n+ return factory.newDocumentBuilder();\n+ } catch (ParserConfigurationException e) {\n+ return throwUnchecked(e, DocumentBuilder.class);\n+ }\n+ }\n+ };\n+\n@Override\npublic Object apply(final String inputXml, final Options options) throws IOException {\nif (inputXml == null ) {\n@@ -55,20 +75,14 @@ public class HandlebarsXPathHelper extends HandlebarsHelper<String> {\nDocument doc;\ntry (final StringReader reader = new StringReader(inputXml)) {\nInputSource source = new InputSource(reader);\n- final DocumentBuilderFactory factory = Xml.newDocumentBuilderFactory();\n- final DocumentBuilder builder = factory.newDocumentBuilder();\n- doc = builder.parse(source);\n+ doc = localDocBuilder.get().parse(source);\n} catch (SAXException se) {\nreturn handleError(inputXml + \" is not valid XML\");\n- } catch (ParserConfigurationException e) {\n- return throwUnchecked(e, Object.class);\n}\ntry {\n- final XPathFactory xPathfactory = XPathFactory.newInstance();\n- final XPath xpath = xPathfactory.newXPath();\n-\n- Node node = (Node) xpath.evaluate(getXPathPrefix() + xPathInput, doc, NODE);\n+ XPath xPath = localXPath.get();\n+ Node node = (Node) xPath.evaluate(getXPathPrefix() + xPathInput, doc, NODE);\nif (node == null) {\nreturn \"\";\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Improved performance of XPath Handlebars helper by caching the XML document builder and XPath objects |
686,936 | 26.02.2020 13:40:22 | 0 | 92e2e106efabf013f6e753bc832ed79da448fe8b | Optimised the XPath Handlebars helper's performance by caching parsed XML documents and evaluated XPath expressions | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/HandlebarsOptimizedTemplate.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/HandlebarsOptimizedTemplate.java",
"diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.extension.responsetemplating;\nimport java.io.IOException;\n+import com.github.jknack.handlebars.Context;\nimport com.github.jknack.handlebars.Handlebars;\nimport com.github.jknack.handlebars.Template;\nimport com.github.tomakehurst.wiremock.common.Exceptions;\n@@ -56,8 +57,17 @@ public class HandlebarsOptimizedTemplate {\n}\n}\n- public String apply(Object context) throws IOException {\n+ public String apply(Object contextData) throws IOException {\n+ final RenderCache renderCache = new RenderCache();\n+ Context context = Context\n+ .newBuilder(contextData)\n+ .combine(\"renderCache\", renderCache)\n+ .build();\n+\nStringBuilder sb = new StringBuilder();\n- return sb.append(startContent).append(template.apply(context)).append(endContent).toString();\n+ return sb.append(startContent)\n+ .append(template.apply(context))\n+ .append(endContent)\n+ .toString();\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/RenderCache.java",
"diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating;\n+\n+import java.util.HashMap;\n+import java.util.List;\n+import java.util.Map;\n+import java.util.Objects;\n+\n+import static java.util.Arrays.asList;\n+\n+public class RenderCache {\n+\n+ private final Map<Key, Object> cache = new HashMap<>();\n+\n+ public void put(Key key, Object value) {\n+ cache.put(key, value);\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ public <T> T get(Key key) {\n+ return (T) cache.get(key);\n+ }\n+\n+ public static class Key {\n+ private final Class<?> forClass;\n+ private final List<?> elements;\n+\n+ public static Key keyFor(Class<?> forClass, Object... elements) {\n+ return new Key(forClass, asList(elements));\n+ }\n+\n+ private Key(Class<?> forClass, List<?> elements) {\n+ this.forClass = forClass;\n+ this.elements = elements;\n+ }\n+\n+ @Override\n+ public String toString() {\n+ final StringBuilder sb = new StringBuilder(\"Key{\");\n+ sb.append(\"forClass=\").append(forClass);\n+ sb.append(\", elements=\").append(elements);\n+ sb.append('}');\n+ return sb.toString();\n+ }\n+\n+ @Override\n+ public boolean equals(Object o) {\n+ if (this == o) return true;\n+ if (o == null || getClass() != o.getClass()) return false;\n+ Key key = (Key) o;\n+ return forClass.equals(key.forClass) &&\n+ elements.equals(key.elements);\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return Objects.hash(forClass, elements);\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java",
"diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\nimport com.github.jknack.handlebars.Options;\nimport com.github.tomakehurst.wiremock.common.Xml;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.RenderCache;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Node;\nimport org.xml.sax.InputSource;\n@@ -73,16 +74,14 @@ public class HandlebarsXPathHelper extends HandlebarsHelper<String> {\nfinal String xPathInput = options.param(0);\nDocument doc;\n- try (final StringReader reader = new StringReader(inputXml)) {\n- InputSource source = new InputSource(reader);\n- doc = localDocBuilder.get().parse(source);\n+ try {\n+ doc = getDocument(inputXml, options);\n} catch (SAXException se) {\nreturn handleError(inputXml + \" is not valid XML\");\n}\ntry {\n- XPath xPath = localXPath.get();\n- Node node = (Node) xPath.evaluate(getXPathPrefix() + xPathInput, doc, NODE);\n+ Node node = getNode(getXPathPrefix() + xPathInput, doc, options);\nif (node == null) {\nreturn \"\";\n@@ -94,6 +93,38 @@ public class HandlebarsXPathHelper extends HandlebarsHelper<String> {\n}\n}\n+ private Node getNode(String xPathExpression, Document doc, Options options) throws XPathExpressionException {\n+ RenderCache renderCache = getRenderCache(options);\n+ RenderCache.Key cacheKey = RenderCache.Key.keyFor(Document.class, xPathExpression, doc);\n+ Node node = renderCache.get(cacheKey);\n+\n+ if (node == null) {\n+ XPath xPath = localXPath.get();\n+ node = (Node) xPath.evaluate(xPathExpression, doc, NODE);\n+ renderCache.put(cacheKey, node);\n+ }\n+\n+ return node;\n+ }\n+\n+ private Document getDocument(String xml, Options options) throws SAXException, IOException {\n+ RenderCache renderCache = getRenderCache(options);\n+ RenderCache.Key cacheKey = RenderCache.Key.keyFor(Document.class, xml);\n+ Document document = renderCache.get(cacheKey);\n+ if (document == null) {\n+ try (final StringReader reader = new StringReader(xml)) {\n+ InputSource source = new InputSource(reader);\n+ document = localDocBuilder.get().parse(source);\n+ renderCache.put(cacheKey, document);\n+ }\n+ }\n+\n+ return document;\n+ }\n+\n+ private RenderCache getRenderCache(Options options) {\n+ return options.get(\"renderCache\", null);\n+ }\n/**\n* No prefix by default. It allows to extend this class with a specified prefix. Just overwrite this method to do\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelperTestBase.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelperTestBase.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+import com.github.jknack.handlebars.Context;\nimport com.github.jknack.handlebars.Helper;\nimport com.github.jknack.handlebars.Options;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.RenderCache;\nimport org.hamcrest.Matcher;\nimport org.junit.Assert;\n+import org.junit.Before;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport static org.hamcrest.Matchers.is;\n-import static org.hamcrest.Matchers.startsWith;\nimport static org.junit.Assert.assertThat;\npublic abstract class HandlebarsHelperTestBase {\n+ protected RenderCache renderCache;\n+\n+ @Before\n+ public void initRenderCache() {\n+ renderCache = new RenderCache();\n+ }\n+\nprotected static final String FAIL_GRACEFULLY_MSG = \"Handlebars helper should fail gracefully and show the issue directly in the response.\";\n- protected static <T> void testHelperError(Helper<T> helper,\n+ protected <T> void testHelperError(Helper<T> helper,\nT content,\nString pathExpression,\nMatcher<String> expectation) {\ntry {\n- assertThat((String) helper.apply(content, createOptions(pathExpression)), expectation);\n+ assertThat((String) renderHelperValue(helper, content, pathExpression), expectation);\n} catch (final IOException e) {\nAssert.fail(FAIL_GRACEFULLY_MSG);\n}\n}\n- protected static <T> void testHelper(Helper<T> helper,\n+ @SuppressWarnings(\"unchecked\")\n+ protected <R, C> R renderHelperValue(Helper<C> helper, C content, String parameter) throws IOException {\n+ return (R) helper.apply(content, createOptions(parameter));\n+ }\n+\n+ protected <T> void testHelper(Helper<T> helper,\nT content,\nString optionParam,\nString expected) throws IOException {\ntestHelper(helper, content, optionParam, is(expected));\n}\n- protected static <T> void testHelper(Helper<T> helper,\n+ protected <T> void testHelper(Helper<T> helper,\nT content,\nString optionParam,\nMatcher<String> expected) throws IOException {\nassertThat(helper.apply(content, createOptions(optionParam)).toString(), expected);\n}\n- protected static Options createOptions(String optionParam) {\n- return new Options(null, null, null, null, null, null,\n+ protected Options createOptions(String optionParam) {\n+ return createOptions(optionParam, renderCache);\n+ }\n+\n+ protected Options createOptions(String optionParam, RenderCache renderCache) {\n+ Context context = Context.newBuilder(null)\n+ .combine(\"renderCache\", renderCache)\n+ .build();\n+\n+ return new Options(null, null, null, context, null, null,\nnew Object[]{optionParam}, null, new ArrayList<String>(0));\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelperTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelperTest.java",
"diff": "package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.RenderCache;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\nimport com.github.tomakehurst.wiremock.testsupport.WireMatchers;\n+import org.jmock.Expectations;\n+import org.jmock.Mockery;\n+import org.jmock.integration.junit4.JMock;\nimport org.junit.Before;\nimport org.junit.Test;\n+import org.junit.runner.RunWith;\nimport java.io.IOException;\n@@ -30,6 +35,7 @@ import static com.github.tomakehurst.wiremock.testsupport.NoFileSource.noFileSou\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalToXml;\nimport static org.hamcrest.Matchers.is;\nimport static org.hamcrest.Matchers.startsWith;\n+import static org.jmock.Expectations.anything;\nimport static org.junit.Assert.assertThat;\npublic class HandlebarsXPathHelperTest extends HandlebarsHelperTestBase {\n@@ -108,6 +114,31 @@ public class HandlebarsXPathHelperTest extends HandlebarsHelperTestBase {\ntestHelperError(helper, null, \"/test\", is(\"\"));\n}\n+ @Test\n+ public void returnsCorrectResultWhenSameExpressionUsedTwiceOnIdenticalDocuments() throws Exception {\n+ String one = renderHelperValue(helper, \"<test>one</test>\", \"/test/text()\");\n+ String two = renderHelperValue(helper, \"<test>one</test>\", \"/test/text()\");\n+\n+ assertThat(one, is(\"one\"));\n+ assertThat(two, is(\"one\"));\n+ }\n+\n+ @Test\n+ public void returnsCorrectResultWhenSameExpressionUsedTwiceOnDifferentDocuments() throws Exception {\n+ String one = renderHelperValue(helper, \"<test>one</test>\", \"/test/text()\");\n+ String two = renderHelperValue(helper, \"<test>two</test>\", \"/test/text()\");\n+ assertThat(one, is(\"one\"));\n+ assertThat(two, is(\"two\"));\n+ }\n+\n+ @Test\n+ public void returnsCorrectResultWhenDifferentExpressionsUsedOnSameDocument() throws Exception {\n+ String one = renderHelperValue(helper, \"<test><one>1</one><two>2</two></test>\", \"/test/one/text()\");\n+ String two = renderHelperValue(helper, \"<test><one>1</one><two>2</two></test>\", \"/test/two/text()\");\n+\n+ assertThat(one, is(\"1\"));\n+ assertThat(two, is(\"2\"));\n+ }\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Optimised the XPath Handlebars helper's performance by caching parsed XML documents and evaluated XPath expressions |
686,936 | 26.02.2020 14:03:59 | 0 | 618d82517f3180340b7b54ce051dbfd3004addd3 | Improved performance of JsonPath Handlebars helper by caching parsed documents and evaluated expressions | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelper.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelper.java",
"diff": "package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\nimport com.github.jknack.handlebars.Helper;\n+import com.github.jknack.handlebars.Options;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.RenderCache;\nimport java.util.HashSet;\nimport java.util.Set;\n@@ -73,4 +75,8 @@ public abstract class HandlebarsHelper<T> implements Helper<T> {\nprivate String formatMessage(String message) {\nreturn ERROR_PREFIX + message + ERROR_SUFFIX;\n}\n+\n+ protected static RenderCache getRenderCache(Options options) {\n+ return options.get(\"renderCache\", null);\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelper.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelper.java",
"diff": "@@ -17,11 +17,17 @@ package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\nimport com.github.jknack.handlebars.Options;\nimport com.github.tomakehurst.wiremock.common.Json;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.RenderCache;\n+import com.jayway.jsonpath.DocumentContext;\nimport com.jayway.jsonpath.InvalidJsonException;\nimport com.jayway.jsonpath.JsonPath;\nimport com.jayway.jsonpath.JsonPathException;\n+import org.w3c.dom.Document;\n+import org.xml.sax.InputSource;\n+import javax.xml.parsers.DocumentBuilder;\nimport java.io.IOException;\n+import java.io.StringReader;\nimport java.util.Map;\npublic class HandlebarsJsonPathHelper extends HandlebarsHelper<Object> {\n@@ -37,10 +43,10 @@ public class HandlebarsJsonPathHelper extends HandlebarsHelper<Object> {\n}\nfinal String jsonPath = options.param(0);\n+\ntry {\n- Object result = input instanceof String ?\n- JsonPath.read((String) input, jsonPath) :\n- JsonPath.read(input, jsonPath);\n+ final DocumentContext jsonDocument = getJsonDocument(input, options);\n+ Object result = getValue(jsonPath, jsonDocument, options);\nreturn JsonData.create(result);\n} catch (InvalidJsonException e) {\nreturn this.handleError(\n@@ -50,4 +56,30 @@ public class HandlebarsJsonPathHelper extends HandlebarsHelper<Object> {\nreturn this.handleError(jsonPath + \" is not a valid JSONPath expression\", e);\n}\n}\n+\n+ private Object getValue(String jsonPath, DocumentContext jsonDocument, Options options) {\n+ RenderCache renderCache = getRenderCache(options);\n+ RenderCache.Key cacheKey = RenderCache.Key.keyFor(Object.class, jsonPath, jsonDocument);\n+ Object value = renderCache.get(cacheKey);\n+ if (value == null) {\n+ value = jsonDocument.read(jsonPath);\n+ renderCache.put(cacheKey, value);\n+ }\n+\n+ return value;\n+ }\n+\n+ private DocumentContext getJsonDocument(Object json, Options options) {\n+ RenderCache renderCache = getRenderCache(options);\n+ RenderCache.Key cacheKey = RenderCache.Key.keyFor(DocumentContext.class, json);\n+ DocumentContext document = renderCache.get(cacheKey);\n+ if (document == null) {\n+ document = json instanceof String ?\n+ JsonPath.parse((String) json) :\n+ JsonPath.parse(json);\n+ renderCache.put(cacheKey, document);\n+ }\n+\n+ return document;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java",
"diff": "@@ -122,10 +122,6 @@ public class HandlebarsXPathHelper extends HandlebarsHelper<String> {\nreturn document;\n}\n- private RenderCache getRenderCache(Options options) {\n- return options.get(\"renderCache\", null);\n- }\n-\n/**\n* No prefix by default. It allows to extend this class with a specified prefix. Just overwrite this method to do\n* so.\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelperTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelperTest.java",
"diff": "@@ -228,4 +228,42 @@ public class HandlebarsJsonPathHelperTest extends HandlebarsHelperTestBase {\nassertThat(responseDefinition.getBody(), is(\"abc\"));\n}\n+\n+ @Test\n+ public void returnsCorrectResultWhenSameExpressionUsedTwiceOnIdenticalDocuments() throws Exception {\n+ String one = renderHelperValue(helper, \"{\\\"test\\\": \\\"one\\\"}\", \"$.test\");\n+ String two = renderHelperValue(helper, \"{\\\"test\\\": \\\"one\\\"}\", \"$.test\");\n+\n+ assertThat(one, is(\"one\"));\n+ assertThat(two, is(\"one\"));\n+ }\n+\n+ @Test\n+ public void returnsCorrectResultWhenSameExpressionUsedTwiceOnDifferentDocuments() throws Exception {\n+ String one = renderHelperValue(helper, \"{\\\"test\\\": \\\"one\\\"}\", \"$.test\");\n+ String two = renderHelperValue(helper, \"{\\\"test\\\": \\\"two\\\"}\", \"$.test\");\n+\n+ assertThat(one, is(\"one\"));\n+ assertThat(two, is(\"two\"));\n+ }\n+\n+ @Test\n+ public void returnsCorrectResultWhenDifferentExpressionsUsedOnSameDocument() throws Exception {\n+ int one = renderHelperValue(helper, \"{\\n\" +\n+ \" \\\"test\\\": {\\n\" +\n+ \" \\\"one\\\": 1,\\n\" +\n+ \" \\\"two\\\": 2\\n\" +\n+ \" }\\n\" +\n+ \"}\", \"$.test.one\");\n+ int two = renderHelperValue(helper, \"{\\n\" +\n+ \" \\\"test\\\": {\\n\" +\n+ \" \\\"one\\\": 1,\\n\" +\n+ \" \\\"two\\\": 2\\n\" +\n+ \" }\\n\" +\n+ \"}\", \"$.test.two\");\n+\n+ assertThat(one, is(1));\n+ assertThat(two, is(2));\n+ }\n+\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Improved performance of JsonPath Handlebars helper by caching parsed documents and evaluated expressions |
687,033 | 26.02.2020 07:02:14 | 28,800 | ec9219a73b9b8ce46238cf866a1bc8faf87c6065 | Bugfix / http-disabled flag
Fix logic to display dynamically chosen port number when HTTPS only is enabled | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/WireMockServerRunner.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/WireMockServerRunner.java",
"diff": "@@ -74,7 +74,8 @@ public class WireMockServerRunner {\ntry {\nwireMockServer.start();\n- options.setResultingPort(wireMockServer.port());\n+ boolean https = options.httpsSettings().enabled();\n+ options.setResultingPort(https ? wireMockServer.httpsPort() : wireMockServer.port());\nif (!options.bannerDisabled()){\nout.println(BANNER);\nout.println();\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Bugfix / http-disabled flag (#1257)
Fix logic to display dynamically chosen port number when HTTPS only is enabled |
686,936 | 02.03.2020 13:53:33 | 0 | 117472c0cabcdf18c3863330707cf68018dbf077 | Added --stacktrace parameter to release build tasks | [
{
"change_type": "MODIFY",
"old_path": "go",
"new_path": "go",
"diff": "@@ -50,10 +50,10 @@ test-java11() {\nrelease() {\nuse-java7\n- ./gradlew -c release-settings.gradle clean :java7:release\n+ ./gradlew -c release-settings.gradle clean :java7:release --stacktrace\nuse-java8\n- ./gradlew -c release-settings.gradle clean :java8:release\n+ ./gradlew -c release-settings.gradle clean :java8:release --stacktrace\n}\nrelease-local() {\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added --stacktrace parameter to release build tasks |
686,936 | 02.03.2020 13:56:33 | 0 | 6971f180588746bb9b517c7ce592fda42ca533fb | Fixed - NPE when attempting to directly call the JsonPath or XPath handlebars helpers | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelper.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelper.java",
"diff": "@@ -77,6 +77,6 @@ public abstract class HandlebarsHelper<T> implements Helper<T> {\n}\nprotected static RenderCache getRenderCache(Options options) {\n- return options.get(\"renderCache\", null);\n+ return options.get(\"renderCache\", new RenderCache());\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelperTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelperTest.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+import com.github.jknack.handlebars.Context;\n+import com.github.jknack.handlebars.Options;\nimport com.github.tomakehurst.wiremock.common.ConsoleNotifier;\nimport com.github.tomakehurst.wiremock.common.FileSource;\nimport com.github.tomakehurst.wiremock.common.LocalNotifier;\n@@ -27,6 +29,7 @@ import org.junit.Before;\nimport org.junit.Test;\nimport java.io.IOException;\n+import java.util.ArrayList;\nimport java.util.Map;\nimport static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n@@ -266,4 +269,16 @@ public class HandlebarsJsonPathHelperTest extends HandlebarsHelperTestBase {\nassertThat(two, is(2));\n}\n+ @Test\n+ public void helperCanBeCalledDirectlyWithoutSupplyingRenderCache() throws Exception {\n+ Context context = Context.newBuilder(null).build();\n+ Options options = new Options(null, null, null, context, null, null,\n+ new Object[] { \"$.stuff\" }, null, new ArrayList<String>(0));\n+\n+ Object result = helper.apply(\"{\\\"stuff\\\":1}\", options);\n+\n+ assertThat(result, instanceOf(Integer.class));\n+ assertThat((Integer) result, is(1));\n+ }\n+\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #1277 - NPE when attempting to directly call the JsonPath or XPath handlebars helpers |
686,936 | 05.03.2020 20:10:42 | 0 | 6e12577cf73567c70b501d9bb399263a62115dc1 | Fixed bug causing multiple Access-Control-* response headers being sent when proxying to a CORS-enabled target. Enabled CORS for stubs. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java",
"diff": "@@ -48,6 +48,11 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nprivate static final String CONTENT_ENCODING = \"content-encoding\";\nprivate static final String CONTENT_LENGTH = \"content-length\";\nprivate static final String HOST_HEADER = \"host\";\n+ public static final ImmutableList<String> FORBIDDEN_HEADERS = ImmutableList.of(\n+ CONTENT_LENGTH,\n+ TRANSFER_ENCODING,\n+ \"connection\"\n+ );\nprivate final HttpClient client;\nprivate final boolean preserveHostHeader;\n@@ -93,8 +98,10 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nprivate HttpHeaders headersFrom(HttpResponse httpResponse, ResponseDefinition responseDefinition) {\nList<HttpHeader> httpHeaders = new LinkedList<HttpHeader>();\nfor (Header header : httpResponse.getAllHeaders()) {\n+ if (responseHeaderShouldBeTransferred(header.getName())) {\nhttpHeaders.add(new HttpHeader(header.getName(), header.getValue()));\n}\n+ }\nif (responseDefinition.getHeaders() != null) {\nhttpHeaders.addAll(responseDefinition.getHeaders().all());\n@@ -112,7 +119,7 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nprivate void addRequestHeaders(HttpRequest httpRequest, ResponseDefinition response) {\nRequest originalRequest = response.getOriginalRequest();\nfor (String key: originalRequest.getAllHeaderKeys()) {\n- if (headerShouldBeTransferred(key)) {\n+ if (requestHeaderShouldBeTransferred(key)) {\nif (!HOST_HEADER.equalsIgnoreCase(key) || preserveHostHeader) {\nList<String> values = originalRequest.header(key).values();\nfor (String value: values) {\n@@ -135,8 +142,13 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n}\n}\n- private static boolean headerShouldBeTransferred(String key) {\n- return !ImmutableList.of(CONTENT_LENGTH, TRANSFER_ENCODING, \"connection\").contains(key.toLowerCase());\n+ private static boolean requestHeaderShouldBeTransferred(String key) {\n+ return !FORBIDDEN_HEADERS.contains(key.toLowerCase());\n+ }\n+\n+ private static boolean responseHeaderShouldBeTransferred(String key) {\n+ final String lowerCaseKey = key.toLowerCase();\n+ return !FORBIDDEN_HEADERS.contains(lowerCaseKey) && !lowerCaseKey.startsWith(\"access-control\");\n}\nprivate static void addBodyIfPostPutOrPatch(HttpRequest httpRequest, ResponseDefinition response) throws UnsupportedEncodingException {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"diff": "@@ -397,6 +397,8 @@ public class JettyHttpServer implements HttpServer {\nmockServiceContext.addFilter(ContentTypeSettingFilter.class, FILES_URL_MATCH, EnumSet.of(DispatcherType.FORWARD));\nmockServiceContext.addFilter(TrailingSlashFilter.class, FILES_URL_MATCH, EnumSet.allOf(DispatcherType.class));\n+ addCorsFilter(mockServiceContext);\n+\nreturn mockServiceContext;\n}\n@@ -432,16 +434,23 @@ public class JettyHttpServer implements HttpServer {\nadminContext.setAttribute(MultipartRequestConfigurer.KEY, buildMultipartRequestConfigurer());\n+ addCorsFilter(adminContext);\n+\n+ return adminContext;\n+ }\n+\n+ private void addCorsFilter(ServletContextHandler context) {\n+ context.addFilter(buildCorsFilter(), \"/*\", EnumSet.of(DispatcherType.REQUEST));\n+ }\n+\n+ private FilterHolder buildCorsFilter() {\nFilterHolder filterHolder = new FilterHolder(CrossOriginFilter.class);\nfilterHolder.setInitParameters(ImmutableMap.of(\n\"chainPreflight\", \"false\",\n\"allowedOrigins\", \"*\",\n- \"allowedHeaders\", \"X-Requested-With,Content-Type,Accept,Origin,Authorization\",\n+ \"allowedHeaders\", \"*\",\n\"allowedMethods\", \"OPTIONS,GET,POST,PUT,PATCH,DELETE\"));\n-\n- adminContext.addFilter(filterHolder, \"/*\", EnumSet.of(DispatcherType.REQUEST));\n-\n- return adminContext;\n+ return filterHolder;\n}\n// Override this for platform-specific impls\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/AdminCrossOriginTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/CrossOriginTest.java",
"diff": "@@ -18,14 +18,15 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport org.junit.Test;\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader;\nimport static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\n-public class AdminCrossOriginTest extends AcceptanceTestBase {\n+public class CrossOriginTest extends AcceptanceTestBase {\n@Test\n- public void sendsCorsHeadersInResponseToOPTIONSQuery() {\n+ public void sendsCorsHeadersInResponseToAdminOPTIONSQuery() {\nWireMockResponse response = testClient.options(\"/__admin/\",\nwithHeader(\"Origin\", \"http://my.corp.com\"),\nwithHeader(\"Access-Control-Request-Method\", \"POST\")\n@@ -35,4 +36,18 @@ public class AdminCrossOriginTest extends AcceptanceTestBase {\nassertThat(response.firstHeader(\"Access-Control-Allow-Origin\"), is(\"http://my.corp.com\"));\nassertThat(response.firstHeader(\"Access-Control-Allow-Methods\"), is(\"OPTIONS,GET,POST,PUT,PATCH,DELETE\"));\n}\n+\n+ @Test\n+ public void sendsCorsHeadersInResponseToStubOPTIONSQuery() {\n+ wm.stubFor(any(urlEqualTo(\"/cors\")).willReturn(ok()));\n+\n+ WireMockResponse response = testClient.options(\"/cors\",\n+ withHeader(\"Origin\", \"http://my.corp.com\"),\n+ withHeader(\"Access-Control-Request-Method\", \"POST\")\n+ );\n+\n+ assertThat(response.statusCode(), is(200));\n+ assertThat(response.firstHeader(\"Access-Control-Allow-Origin\"), is(\"http://my.corp.com\"));\n+ assertThat(response.firstHeader(\"Access-Control-Allow-Methods\"), is(\"OPTIONS,GET,POST,PUT,PATCH,DELETE\"));\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ProxyAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ProxyAcceptanceTest.java",
"diff": "@@ -20,6 +20,7 @@ import java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.InetSocketAddress;\nimport java.util.Arrays;\n+import java.util.Collection;\nimport java.util.concurrent.TimeUnit;\nimport com.github.tomakehurst.wiremock.client.WireMock;\n@@ -149,7 +150,7 @@ public class ProxyAcceptanceTest {\n.withAdditionalRequestHeader(\"a\", \"b\")));\nWireMockResponse response = testClient.get(\"/proxied/resource?param=value\",\n- TestHttpHeader.withHeader(\"a\", \"doh\"));\n+ withHeader(\"a\", \"doh\"));\nassertThat(response.content(), is(\"Proxied content\"));\n}\n@@ -479,6 +480,21 @@ public class ProxyAcceptanceTest {\nassertThat(stopwatch.elapsed(MILLISECONDS), greaterThanOrEqualTo(300L));\n}\n+ @Test\n+ public void stripsCorsHeadersFromTheTarget() {\n+ initWithDefaultConfig();\n+\n+ proxyingServiceAdmin.register(any(anyUrl())\n+ .willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n+\n+ targetServiceAdmin.register(any(urlPathEqualTo(\"/cors\")).willReturn(ok()));\n+\n+ WireMockResponse response = testClient.get(\"/cors\", withHeader(\"Origin\", \"http://somewhere.com\"));\n+\n+ Collection<String> allowOriginHeaderValues = response.headers().get(\"Access-Control-Allow-Origin\");\n+ assertThat(allowOriginHeaderValues.size(), is(1));\n+ }\n+\nprivate void register200StubOnProxyAndTarget(String url) {\ntargetServiceAdmin.register(get(urlEqualTo(url)).willReturn(aResponse().withStatus(200)));\nproxyingServiceAdmin.register(get(urlEqualTo(url)).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed bug causing multiple Access-Control-* response headers being sent when proxying to a CORS-enabled target. Enabled CORS for stubs. |
686,936 | 05.03.2020 20:37:38 | 0 | 21b8a4f859d8da2d3606679731b96790c64da404 | Fixed printing of http and https ports on command-line startup. Fixes | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java",
"diff": "@@ -102,7 +102,8 @@ public class CommandLineOptions implements Options {\nprivate final MappingsSource mappingsSource;\nprivate String helpText;\n- private Optional<Integer> resultingPort;\n+ private Integer actualHttpPort;\n+ private Integer actualHttpsPort;\npublic CommandLineOptions(String... args) {\nOptionParser optionParser = new OptionParser();\n@@ -154,7 +155,7 @@ public class CommandLineOptions implements Options {\nfileSource = new SingleRootFileSource((String) optionSet.valueOf(ROOT_DIR));\nmappingsSource = new JsonFileMappingsSource(fileSource.child(MAPPINGS_ROOT));\n- resultingPort = Optional.absent();\n+ actualHttpPort = null;\n}\nprivate void validate() {\n@@ -241,8 +242,12 @@ public class CommandLineOptions implements Options {\nreturn optionSet.has(DISABLE_HTTP);\n}\n- public void setResultingPort(int port) {\n- resultingPort = Optional.of(port);\n+ public void setActualHttpPort(int port) {\n+ actualHttpPort = port;\n+ }\n+\n+ public void setActualHttpsPort(int port) {\n+ actualHttpsPort = port;\n}\n@Override\n@@ -452,12 +457,17 @@ public class CommandLineOptions implements Options {\n@Override\npublic String toString() {\nImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();\n- int port = resultingPort.isPresent() ? resultingPort.get() : portNumber();\n- builder.put(PORT, port);\n+\n+ if (actualHttpPort != null) {\n+ builder.put(PORT, actualHttpPort);\n+ }\n+\n+ if (actualHttpsPort != null) {\n+ builder.put(HTTPS_PORT, actualHttpsPort);\n+ }\nif (httpsSettings().enabled()) {\n- builder.put(HTTPS_PORT, nullToString(httpsSettings().port()))\n- .put(HTTPS_KEYSTORE, nullToString(httpsSettings().keyStorePath()));\n+ builder.put(HTTPS_KEYSTORE, nullToString(httpsSettings().keyStorePath()));\n}\nif (!(proxyVia() == NO_PROXY)) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/WireMockServerRunner.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/WireMockServerRunner.java",
"diff": "@@ -75,7 +75,15 @@ public class WireMockServerRunner {\ntry {\nwireMockServer.start();\nboolean https = options.httpsSettings().enabled();\n- options.setResultingPort(https ? wireMockServer.httpsPort() : wireMockServer.port());\n+\n+ if (!options.getHttpDisabled()) {\n+ options.setActualHttpPort(wireMockServer.port());\n+ }\n+\n+ if (https) {\n+ options.setActualHttpsPort(wireMockServer.httpsPort());\n+ }\n+\nif (!options.bannerDisabled()){\nout.println(BANNER);\nout.println();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"diff": "@@ -22,7 +22,6 @@ import com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\n-import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.HandlebarsHelper;\nimport com.github.tomakehurst.wiremock.http.CaseInsensitiveKey;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n@@ -34,9 +33,12 @@ import com.google.common.base.Optional;\nimport org.junit.Test;\nimport java.util.Map;\n+import java.util.regex.Pattern;\n-import static com.github.tomakehurst.wiremock.common.ProxySettings.NO_PROXY;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\n+import static com.github.tomakehurst.wiremock.testsupport.WireMatchers.matchesMultiLine;\n+import static java.util.regex.Pattern.DOTALL;\n+import static java.util.regex.Pattern.MULTILINE;\nimport static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.assertThat;\n@@ -401,15 +403,6 @@ public class CommandLineOptionsTest {\nassertThat(options.getAsynchronousResponseSettings().getThreads(), is(10));\n}\n- @Test\n- public void usesPortInToString() {\n- CommandLineOptions options = new CommandLineOptions(\"--port\", \"1337\");\n- assertThat(options.toString(), allOf(containsString(\"1337\")));\n-\n- options.setResultingPort(1338);\n- assertThat(options.toString(), allOf(containsString(\"1338\")));\n- }\n-\n@Test\npublic void configuresMaxTemplateCacheEntriesIfSpecified() {\nCommandLineOptions options = new CommandLineOptions(\"--global-response-templating\", \"--max-template-cache-entries\", \"5\");\n@@ -464,6 +457,29 @@ public class CommandLineOptionsTest {\nassertThat(options.getStubRequestLoggingDisabled(), is(false));\n}\n+ @Test\n+ public void printsTheActualPortOnlyWhenHttpsDisabled() {\n+ CommandLineOptions options = new CommandLineOptions();\n+ options.setActualHttpPort(5432);\n+\n+ String dump = options.toString();\n+\n+ assertThat(dump, matchesMultiLine(\".*port:.*5432.*\"));\n+ assertThat(dump, not(containsString(\"https-port\")));\n+ }\n+\n+ @Test\n+ public void printsBothActualPortsOnlyWhenHttpsEnabled() {\n+ CommandLineOptions options = new CommandLineOptions();\n+ options.setActualHttpPort(5432);\n+ options.setActualHttpsPort(2345);\n+\n+ String dump = options.toString();\n+\n+ assertThat(dump, matchesMultiLine(\".*port:.*5432.*\"));\n+ assertThat(dump, matchesMultiLine(\".*https-port:.*2345.*\"));\n+ }\n+\npublic static class ResponseDefinitionTransformerExt1 extends ResponseDefinitionTransformer {\n@Override\npublic ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource files, Parameters parameters) { return null; }\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMatchers.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMatchers.java",
"diff": "@@ -45,12 +45,15 @@ import java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.List;\n+import java.util.regex.Pattern;\nimport static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.google.common.collect.Iterables.*;\nimport static java.lang.System.lineSeparator;\nimport static java.util.Arrays.asList;\n+import static java.util.regex.Pattern.DOTALL;\n+import static java.util.regex.Pattern.MULTILINE;\npublic class WireMatchers {\n@@ -134,6 +137,23 @@ public class WireMatchers {\n};\n}\n+ public static Matcher<String> matchesMultiLine(final String regex) {\n+ return new TypeSafeMatcher<String>() {\n+\n+ @Override\n+ public void describeTo(Description description) {\n+ description.appendText(\"Should match \" + regex);\n+\n+ }\n+\n+ @Override\n+ public boolean matchesSafely(String actual) {\n+ return Pattern.compile(regex, MULTILINE + DOTALL).matcher(actual).matches();\n+ }\n+\n+ };\n+ }\n+\npublic static <T> Matcher<Iterable<T>> hasExactly(final Matcher<T>... items) {\nreturn new TypeSafeMatcher<Iterable<T>>() {\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed printing of http and https ports on command-line startup. Fixes #1278. |
686,936 | 05.03.2020 21:04:13 | 0 | 214a3a8f89bd7d6ecafd80118a2c6f10aad70241 | Fixed - exception thrown when characters not considered valid by java.net.URI are present unescaped in request URL | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyUtils.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyUtils.java",
"diff": "@@ -82,18 +82,9 @@ public class JettyUtils {\n}\n}\n- public static URI getUri(Request request) {\n- HttpURI httpUri = getHttpUri(request);\n-\n- URI uri;\n- try {\n- Method getUriMethod = HttpURI.class.getDeclaredMethod(\"toURI\");\n- uri = (URI) getUriMethod.invoke(httpUri);\n- } catch (NoSuchMethodException | SecurityException | IllegalAccessException | InvocationTargetException e) {\n- uri = URI.create(httpUri.toString());\n- }\n-\n- return uri;\n+ public static boolean uriIsAbsolute(Request request) {\n+ HttpURI uri = getHttpUri(request);\n+ return uri.getScheme() != null;\n}\nprivate static HttpURI getHttpUri(Request request) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/UrlPathPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/UrlPathPattern.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock.matching;\n-import java.net.URI;\n+import com.github.tomakehurst.wiremock.common.Urls;\npublic class UrlPathPattern extends UrlPattern {\n@@ -29,7 +29,7 @@ public class UrlPathPattern extends UrlPattern {\nreturn MatchResult.noMatch();\n}\n- String path = URI.create(url).getRawPath();\n+ String path = Urls.getPath(url);\nreturn super.match(path);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHttpServletRequestAdapter.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WireMockHttpServletRequestAdapter.java",
"diff": "@@ -254,7 +254,7 @@ public class WireMockHttpServletRequestAdapter implements Request {\n}\nif (request instanceof org.eclipse.jetty.server.Request) {\norg.eclipse.jetty.server.Request jettyRequest = (org.eclipse.jetty.server.Request) request;\n- return JettyUtils.getUri(jettyRequest).isAbsolute();\n+ return JettyUtils.uriIsAbsolute(jettyRequest);\n}\nreturn false;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingAcceptanceTest.java",
"diff": "@@ -33,7 +33,11 @@ import org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\n+import java.io.IOException;\n+import java.net.HttpURLConnection;\nimport java.net.SocketException;\n+import java.net.URL;\n+import java.net.URLConnection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.UUID;\n@@ -685,6 +689,36 @@ public class StubbingAcceptanceTest extends AcceptanceTestBase {\nassertThat(response.statusCode(), is(HTTP_OK));\n}\n+ @Test\n+ public void copesWithRequestCharactersThatReallyShouldBeEscapedWhenMatchingOnWholeUrlRegex() throws Exception {\n+ stubFor(get(urlMatching(\"/dodgy-chars.*\")).willReturn(ok()));\n+\n+ String url = \"http://localhost:\" + wireMockServer.port() + \"/dodgy-chars?filter={\\\"accountid\\\":\\\"1\\\"}\";\n+ int code = getStatusCodeUsingJavaUrlConnection(url);\n+\n+ assertThat(code, is(200));\n+ }\n+\n+ @Test\n+ public void copesWithRequestCharactersThatReallyShouldBeEscapedWhenMatchingOnExactUrlPath() throws Exception {\n+ stubFor(get(urlPathEqualTo(\"/dodgy-chars\")).willReturn(ok()));\n+\n+ String url = \"http://localhost:\" + wireMockServer.port() + \"/dodgy-chars?filter={\\\"accountid\\\":\\\"1\\\"}\";\n+ int code = getStatusCodeUsingJavaUrlConnection(url);\n+\n+ assertThat(code, is(200));\n+ }\n+\n+ private int getStatusCodeUsingJavaUrlConnection(String url) throws IOException {\n+ HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();\n+ connection.setRequestMethod(\"GET\");\n+ connection.connect();\n+ int code = connection.getResponseCode();\n+ connection.disconnect();\n+ return code;\n+ }\n+\n+\nprivate Matcher<StubMapping> named(final String name) {\nreturn new TypeSafeMatcher<StubMapping>() {\n@Override\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #1259 - exception thrown when characters not considered valid by java.net.URI are present unescaped in request URL |
686,936 | 06.03.2020 10:26:56 | 0 | 6b6d058b27e9660fbf3e04dc27b14b2ab377599b | Fixed - added example certificate conf file accidentally excluded | [
{
"change_type": "MODIFY",
"old_path": ".gitignore",
"new_path": ".gitignore",
"diff": "@@ -59,5 +59,6 @@ src/main/resources/swagger/wiremock-admin-api.json\nsrc/main/resources/assets/swagger-ui/swagger-ui-dist\nscripts/client-cert.*\n+!scripts/client-cert.conf\nnotes.txt\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/client-cert.conf",
"diff": "+[CA_default]\n+copy_extensions = copy\n+\n+[req]\n+default_bits = 4096\n+prompt = no\n+default_md = sha256\n+distinguished_name = req_distinguished_name\n+x509_extensions = v3_ca\n+\n+[req_distinguished_name]\n+C = GB\n+ST = London\n+O = WireMock\n+emailAddress = tom@wiremock.org\n+CN = localhost\n+\n+[v3_ca]\n+basicConstraints = CA:FALSE\n+keyUsage = digitalSignature, keyEncipherment\n+subjectAltName = @alternate_names\n+\n+[alternate_names]\n+DNS.1 = localhost\n+IP.1 = 127.0.0.1\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #1279 - added example certificate conf file accidentally excluded |
686,936 | 06.03.2020 16:54:39 | 0 | 1a025e9d8ce927f749895d9c066dc8c068912906 | Upgraded to latest Jackson version | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -35,21 +35,23 @@ allprojects {\nmavenCentral()\n}\n+ def jacksonVersion = '2.10.3'\n+\ndef versionSets = [\njava7: [\nhandlebars : '4.0.7',\njetty : '9.2.28.v20190418', // Please don't raise PRs upgrading this to the latest version as it drops Java 7 support. See https://github.com/tomakehurst/wiremock/issues/407 and https://github.com/tomakehurst/wiremock/pull/887 for details\nguava : '20.0',\n- jackson : '2.10.2',\n- jacksonDatabind: '2.10.2',\n+ jackson : jacksonVersion,\n+ jacksonDatabind: jacksonVersion,\nxmlUnit : '2.6.2'\n],\njava8: [\nhandlebars : '4.1.2',\njetty : '9.4.20.v20190813',\nguava : '27.0.1-jre',\n- jackson : '2.10.0',\n- jacksonDatabind: '2.10.0',\n+ jackson : jacksonVersion,\n+ jacksonDatabind: jacksonVersion,\nxmlUnit : '2.6.2'\n]\n]\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Upgraded to latest Jackson version |
686,936 | 11.03.2020 15:09:23 | 0 | 682e8eeab3c3e8925180081462eac10b867bad02 | Changed the standalone download link in the docs to point to the jre8 version | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/download-and-installation.md",
"new_path": "docs-v2/_docs/download-and-installation.md",
"diff": "@@ -93,4 +93,4 @@ testCompile \"com.github.tomakehurst:wiremock-jre8-standalone:{{ site.wiremock_ve\n## Direct download\nIf you want to run WireMock as a standalone process you can [download the standalone JAR from\n-here](https://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-standalone/{{ site.wiremock_version }}/wiremock-standalone-{{ site.wiremock_version }}.jar).\n+here](https://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-jre8-standalone/{{ site.wiremock_version }}/wiremock-jre8-standalone-{{ site.wiremock_version }}.jar).\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Changed the standalone download link in the docs to point to the jre8 version |
686,936 | 12.03.2020 12:09:27 | 0 | 07dbb61cf689aac7239bb009becb39ede079be7f | Added link to Pivotal Spring SSO blog post | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/spring-boot.md",
"new_path": "docs-v2/_docs/spring-boot.md",
"diff": "@@ -8,5 +8,8 @@ description: Running WireMock with Spring Boot.\nThe team behind Spring Cloud Contract have created a library to support running WireMock using the \"ambient\" HTTP server.\nIt also simplifies some aspects of configuration and eliminates some common issues that occur when running Spring Boot and WireMock together.\n-\nSee [Spring Cloud Contract WireMock](https://cloud.spring.io/spring-cloud-contract/reference/html/project-features.html#features-wiremock) for details.\n+\n+\n+The article [Faking OAuth2 Single Sign-on in Spring](https://engineering.pivotal.io/post/faking_oauth_sso/)\n+from Pivotal's blog shows how WireMock and MockLab can be used to test Spring apps that use 3rd party OAuth2 login.\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added link to Pivotal Spring SSO blog post |
686,936 | 14.05.2020 16:08:44 | -3,600 | 4b72751cd455b2b659f5f73d0faac468dca9475b | Added a test-java8 task to the go script | [
{
"change_type": "MODIFY",
"old_path": "go",
"new_path": "go",
"diff": "@@ -13,6 +13,7 @@ help() {\necho -e\necho -e \"Common commands: \"\necho -e \" test Run all tests against Java 7 and 8\"\n+ echo -e \" test-java8 Run all tests against Java 8\"\necho -e \" test-java11 Run all tests against Java 11\"\necho -e \" release Release to Maven Central (via Sonatype)\"\necho -e \" release-local Release to ~/.m2/repository\"\n@@ -43,6 +44,11 @@ test() {\n./gradlew -c release-settings.gradle :java8:test --rerun-tasks -x generateApiDocs\n}\n+test-java8() {\n+ use-java8\n+ ./gradlew -c release-settings.gradle :java8:test --rerun-tasks -x generateApiDocs\n+}\n+\ntest-java11() {\nuse-java11\n./gradlew -c release-settings.gradle :java8:test --rerun-tasks -x generateApiDocs\n@@ -65,7 +71,7 @@ release-local() {\n}\n-if [[ $1 =~ ^(help|test|test-java11|release|release-local|use-java7|use-java8)$ ]]; then\n+if [[ $1 =~ ^(help|test|test-java8|test-java11|release|release-local|use-java7|use-java8)$ ]]; then\nCOMMAND=$1\nshift\n$COMMAND \"$@\"\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added a test-java8 task to the go script |
686,936 | 14.05.2020 16:21:45 | -3,600 | 9a8a9b23d488e110a5b30d97cfabec461ab509f5 | Upgraded JDK8 variant to latest Jetty version | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -48,7 +48,7 @@ allprojects {\n],\njava8: [\nhandlebars : '4.1.2',\n- jetty : '9.4.20.v20190813',\n+ jetty : '9.4.28.v20200408',\nguava : '27.0.1-jre',\njackson : jacksonVersion,\njacksonDatabind: jacksonVersion,\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"diff": "@@ -392,7 +392,8 @@ public class JettyHttpServer implements HttpServer {\nmockServiceContext.setMimeTypes(mimeTypes);\nmockServiceContext.setWelcomeFiles(new String[]{\"index.json\", \"index.html\", \"index.xml\", \"index.txt\"});\n- mockServiceContext.setErrorHandler(new NotFoundHandler());\n+ NotFoundHandler errorHandler = new NotFoundHandler(mockServiceContext);\n+ mockServiceContext.setErrorHandler(errorHandler);\nmockServiceContext.addFilter(ContentTypeSettingFilter.class, FILES_URL_MATCH, EnumSet.of(DispatcherType.FORWARD));\nmockServiceContext.addFilter(TrailingSlashFilter.class, FILES_URL_MATCH, EnumSet.allOf(DispatcherType.class));\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/NotFoundHandler.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/NotFoundHandler.java",
"diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.jetty9;\nimport org.eclipse.jetty.server.Dispatcher;\nimport org.eclipse.jetty.server.Request;\n+import org.eclipse.jetty.server.handler.ContextHandler;\nimport org.eclipse.jetty.server.handler.ErrorHandler;\nimport javax.servlet.ServletContext;\n@@ -31,10 +32,17 @@ public class NotFoundHandler extends ErrorHandler {\nprivate final ErrorHandler DEFAULT_HANDLER = new ErrorHandler();\n+ private final ContextHandler mockServiceHandler;\n+\n+ public NotFoundHandler(ContextHandler mockServiceHandler) {\n+ this.mockServiceHandler = mockServiceHandler;\n+ }\n+\n@Override\npublic void handle(String target, final Request baseRequest, final HttpServletRequest request, HttpServletResponse response) throws IOException {\nif (response.getStatus() == 404) {\n- ServletContext adminContext = request.getServletContext().getContext(\"/__admin\");\n+\n+ ServletContext adminContext = mockServiceHandler.getServletContext().getContext(\"/__admin\");\nDispatcher requestDispatcher = (Dispatcher) adminContext.getRequestDispatcher(\"/not-matched\");\ntry {\n@@ -43,7 +51,15 @@ public class NotFoundHandler extends ErrorHandler {\nthrowUnchecked(e);\n}\n} else {\n+ try {\nDEFAULT_HANDLER.handle(target, baseRequest, request, response);\n+ } catch (Exception e) {\n+ if (e instanceof IOException) {\n+ throw (IOException) e;\n+ }\n+\n+ throwUnchecked(e);\n+ }\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java",
"diff": "@@ -705,6 +705,26 @@ public class ResponseTemplateTransformerTest {\nassertThat(body, is(\"3\"));\n}\n+ @Test\n+ public void squareBracketedRequestParameters1() {\n+ String body = transform(\n+ mockRequest().url(\"/stuff?things[1]=one&things[2]=two&things[3]=three\"),\n+ ok(\"{{lookup request.query 'things[2]'}}\"))\n+ .getBody();\n+\n+ assertThat(body, is(\"two\"));\n+ }\n+\n+ @Test\n+ public void squareBracketedRequestParameters2() {\n+ String body = transform(\n+ mockRequest().url(\"/stuff?filter[order_id]=123\"),\n+ ok(\"Order ID: {{lookup request.query 'filter[order_id]'}}\"))\n+ .getBody();\n+\n+ assertThat(body, is(\"Order ID: 123\"));\n+ }\n+\n@Test\npublic void correctlyRendersWhenContentExistsEitherSideOfTemplate() {\nString body = transform(\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Upgraded JDK8 variant to latest Jetty version |
686,936 | 14.05.2020 16:24:23 | -3,600 | cd85809195d3fba3283f9e6149a3c3587006d757 | Upgraded to Handlebars 4.2.0 | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -47,7 +47,7 @@ allprojects {\nxmlUnit : '2.6.2'\n],\njava8: [\n- handlebars : '4.1.2',\n+ handlebars : '4.2.0',\njetty : '9.4.28.v20200408',\nguava : '27.0.1-jre',\njackson : jacksonVersion,\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Upgraded to Handlebars 4.2.0 |
686,936 | 14.05.2020 16:26:37 | -3,600 | f7a692d355191bab6a91fb2e0eb54667b3c7b992 | Upgraded JDK8 variant to latest Guava | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -49,7 +49,7 @@ allprojects {\njava8: [\nhandlebars : '4.2.0',\njetty : '9.4.28.v20200408',\n- guava : '27.0.1-jre',\n+ guava : '29.0-jre',\njackson : jacksonVersion,\njacksonDatabind: jacksonVersion,\nxmlUnit : '2.6.2'\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Upgraded JDK8 variant to latest Guava |
686,936 | 14.05.2020 16:33:30 | -3,600 | b67371fc0c11072849f4e0c2adfaa28e62f33717 | Upgraded to Apache HTTPClient 4.5.12 | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -70,7 +70,7 @@ allprojects {\ncompile \"com.fasterxml.jackson.core:jackson-core:$versions.jackson\",\n\"com.fasterxml.jackson.core:jackson-annotations:$versions.jackson\",\n\"com.fasterxml.jackson.core:jackson-databind:$versions.jacksonDatabind\"\n- compile \"org.apache.httpcomponents:httpclient:4.5.6\"\n+ compile \"org.apache.httpcomponents:httpclient:4.5.12\"\ncompile \"org.xmlunit:xmlunit-core:$versions.xmlUnit\"\ncompile \"org.xmlunit:xmlunit-legacy:$versions.xmlUnit\", {\nexclude group: 'junit', module: 'junit'\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Upgraded to Apache HTTPClient 4.5.12 |
686,940 | 14.05.2020 21:11:57 | -19,080 | cd27ad87e2a1a3242f1d39074485ad7ee500ecf4 | Add request details to VerificationException | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/client/VerificationException.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/client/VerificationException.java",
"diff": "@@ -89,7 +89,8 @@ public class VerificationException extends AssertionError {\npublic static VerificationException forUnmatchedRequests(List<LoggedRequest> unmatchedRequests) {\nif (unmatchedRequests.size() == 1) {\n- return new VerificationException(String.format(\"A request was unmatched by any stub mapping. Request was: \",\n+ return new VerificationException(String.format(\"A request was unmatched by any stub \"\n+ + \"mapping. Request was: %s\",\nunmatchedRequests.get(0)));\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/junit/WireMockRuleFailOnUnmatchedRequestsTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/junit/WireMockRuleFailOnUnmatchedRequestsTest.java",
"diff": "@@ -64,7 +64,6 @@ public class WireMockRuleFailOnUnmatchedRequestsTest {\nclient = new WireMockTestClient(wm.port());\n}\n-\n@Test\npublic void singleUnmatchedRequestShouldThrowVerificationException() {\nexpectedException.expect(VerificationException.class);\n@@ -104,6 +103,10 @@ public class WireMockRuleFailOnUnmatchedRequestsTest {\npublic void unmatchedRequestWithoutStubShouldThrowVerificationException() {\nexpectedException.expect(VerificationException.class);\nexpectedException.expectMessage(containsString(\"A request was unmatched by any stub mapping.\"));\n+\n+ // Check that url details are part of the output error\n+ expectedException.expectMessage(containsString(\"\\\"url\\\" : \\\"/miss\\\"\"));\n+\nclient.get(\"/miss\");\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Add request details to VerificationException (#1287) |
686,999 | 14.05.2020 19:23:49 | -7,200 | 9b4b3851556e749375f0533a5c0216709d842f25 | Added clarification for proxy authentication. | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/running-standalone.md",
"new_path": "docs-v2/_docs/running-standalone.md",
"diff": "@@ -80,7 +80,8 @@ creating stub mappings that proxy to other hosts), route via another\nproxy server (useful when inside a corporate network that only permits\ninternet access via an opaque proxy). e.g.\n`--proxy-via webproxy.mycorp.com` (defaults to port 80) or\n-`--proxy-via webproxy.mycorp.com:8080`\n+`--proxy-via webproxy.mycorp.com:8080`. Also supports proxy authentication,\n+e.g. `--proxy-via http://username:password@webproxy.mycorp.com:8080/`.\n`--enable-browser-proxying`: Run as a browser proxy. See\nbrowser-proxying.\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Added clarification for proxy authentication. (#1294) |
686,936 | 15.05.2020 12:47:07 | -3,600 | 514627553c8600d4d230a6ceb5bfcd7f26eed37c | Improved performance, particularly when requests go unmatched by memoizing match results and only calculating near misses once (originally this happened twice - once in the response renderer, once for logging) | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"diff": "@@ -67,7 +67,6 @@ public class WireMockApp implements StubServer, Admin {\nprivate final Container container;\nprivate final MappingsSaver mappingsSaver;\nprivate final NearMissCalculator nearMissCalculator;\n- private final PlainTextDiffRenderer diffRenderer;\nprivate final Recorder recorder;\nprivate final List<GlobalSettingsListener> globalSettingsListeners;\n@@ -95,7 +94,6 @@ public class WireMockApp implements StubServer, Admin {\nImmutableList.copyOf(options.extensionsOfType(StubLifecycleListener.class).values())\n);\nnearMissCalculator = new NearMissCalculator(stubMappings, requestJournal);\n- diffRenderer = new PlainTextDiffRenderer(customMatchers);\nrecorder = new Recorder(this);\nglobalSettingsListeners = ImmutableList.copyOf(options.extensionsOfType(GlobalSettingsListener.class).values());\n@@ -122,7 +120,6 @@ public class WireMockApp implements StubServer, Admin {\nstubMappings = new InMemoryStubMappings(requestMatchers, transformers, rootFileSource, Collections.<StubLifecycleListener>emptyList());\nthis.container = container;\nnearMissCalculator = new NearMissCalculator(stubMappings, requestJournal);\n- diffRenderer = new PlainTextDiffRenderer(requestMatchers);\nrecorder = new Recorder(this);\nglobalSettingsListeners = Collections.emptyList();\nloadDefaultMappings();\n@@ -209,24 +206,11 @@ public class WireMockApp implements StubServer, Admin {\nif (request.isBrowserProxyRequest() && browserProxyingEnabled) {\nreturn ServeEvent.of(loggedRequest, ResponseDefinition.browserProxy(request));\n}\n-\n- logUnmatchedRequest(loggedRequest);\n}\nreturn serveEvent;\n}\n- private void logUnmatchedRequest(LoggedRequest request) {\n- List<NearMiss> nearest = nearMissCalculator.findNearestTo(request);\n- String message;\n- if (!nearest.isEmpty()) {\n- message = diffRenderer.render(nearest.get(0).getDiff());\n- } else {\n- message = \"Request was not matched as there were no stubs registered:\\n\" + request;\n- }\n- notifier().error(message);\n- }\n-\n@Override\npublic void addStubMapping(StubMapping stubMapping) {\nif (stubMapping.getId() == null) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java",
"diff": "@@ -31,13 +31,12 @@ import java.util.List;\nimport java.util.Objects;\nimport static com.flipkart.zjsonpatch.DiffFlags.OMIT_COPY_OPERATION;\n-import static com.flipkart.zjsonpatch.DiffFlags.OMIT_MOVE_OPERATION;\nimport static com.github.tomakehurst.wiremock.common.Json.deepSize;\nimport static com.github.tomakehurst.wiremock.common.Json.maxDeepSize;\nimport static com.google.common.collect.Iterables.getLast;\nimport static org.apache.commons.lang3.math.NumberUtils.isNumber;\n-public class EqualToJsonPattern extends StringValuePattern {\n+public class EqualToJsonPattern extends MemoizingStringValuePattern {\nprivate final JsonNode expected;\nprivate final Boolean ignoreArrayOrder;\n@@ -95,7 +94,7 @@ public class EqualToJsonPattern extends StringValuePattern {\n}\n@Override\n- public MatchResult match(String value) {\n+ protected MatchResult calculateMatch(String value) {\ntry {\nfinal JsonNode actual = Json.read(value, JsonNode.class);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToPattern.java",
"diff": "@@ -21,7 +21,7 @@ import java.util.Objects;\nimport static org.apache.commons.lang3.StringUtils.getLevenshteinDistance;\n-public class EqualToPattern extends StringValuePattern {\n+public class EqualToPattern extends MemoizingStringValuePattern {\nprivate final Boolean caseInsensitive;\n@@ -46,7 +46,7 @@ public class EqualToPattern extends StringValuePattern {\n}\n@Override\n- public MatchResult match(final String value) {\n+ protected MatchResult calculateMatch(final String value) {\nreturn new MatchResult() {\n@Override\npublic boolean isExactMatch() {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java",
"diff": "@@ -20,7 +20,6 @@ import com.github.tomakehurst.wiremock.common.Xml;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n-import org.w3c.dom.Document;\nimport org.w3c.dom.Node;\nimport org.xmlunit.XMLUnitException;\nimport org.xmlunit.builder.DiffBuilder;\n@@ -37,7 +36,7 @@ import static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\nimport static com.google.common.base.Strings.isNullOrEmpty;\nimport static org.xmlunit.diff.ComparisonType.*;\n-public class EqualToXmlPattern extends StringValuePattern {\n+public class EqualToXmlPattern extends MemoizingStringValuePattern {\nprivate static List<ComparisonType> COUNTED_COMPARISONS = ImmutableList.of(\nELEMENT_TAG_NAME,\n@@ -55,7 +54,6 @@ public class EqualToXmlPattern extends StringValuePattern {\nATTR_NAME_LOOKUP\n);\n- private final Document xmlDocument;\nprivate final Boolean enablePlaceholders;\nprivate final String placeholderOpeningDelimiterRegex;\nprivate final String placeholderClosingDelimiterRegex;\n@@ -70,7 +68,7 @@ public class EqualToXmlPattern extends StringValuePattern {\n@JsonProperty(\"placeholderOpeningDelimiterRegex\") String placeholderOpeningDelimiterRegex,\n@JsonProperty(\"placeholderClosingDelimiterRegex\") String placeholderClosingDelimiterRegex) {\nsuper(expectedValue);\n- xmlDocument = Xml.read(expectedValue);\n+ Xml.read(expectedValue); // Throw an exception if we can't parse the document\nthis.enablePlaceholders = enablePlaceholders;\nthis.placeholderOpeningDelimiterRegex = placeholderOpeningDelimiterRegex;\nthis.placeholderClosingDelimiterRegex = placeholderClosingDelimiterRegex;\n@@ -104,7 +102,7 @@ public class EqualToXmlPattern extends StringValuePattern {\n}\n@Override\n- public MatchResult match(final String value) {\n+ protected MatchResult calculateMatch(final String value) {\nreturn new MatchResult() {\n@Override\npublic boolean isExactMatch() {\n@@ -140,7 +138,7 @@ public class EqualToXmlPattern extends StringValuePattern {\nfinal AtomicInteger totalComparisons = new AtomicInteger(0);\nfinal AtomicInteger differences = new AtomicInteger(0);\n- Diff diff = null;\n+ Diff diff;\ntry {\ndiff = DiffBuilder.compare(Input.from(expectedValue))\n.withTest(value)\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchResult.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchResult.java",
"diff": "@@ -88,6 +88,7 @@ public abstract class MatchResult implements Comparable<MatchResult> {\npublic abstract boolean isExactMatch();\npublic abstract double getDistance();\n+\n@Override\npublic int compareTo(MatchResult other) {\nreturn Double.compare(other.getDistance(), getDistance());\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MemoizingMatchResult.java",
"diff": "+package com.github.tomakehurst.wiremock.matching;\n+\n+import com.google.common.base.Supplier;\n+import com.google.common.base.Suppliers;\n+\n+public class MemoizingMatchResult extends MatchResult {\n+\n+ private final Supplier<Double> memoizedDistance = Suppliers.memoize(new Supplier<Double>() {\n+ @Override\n+ public Double get() {\n+ return target.getDistance();\n+ }\n+ });\n+\n+ private final Supplier<Boolean> memoizedExactMatch = Suppliers.memoize(new Supplier<Boolean>() {\n+ @Override\n+ public Boolean get() {\n+ return target.isExactMatch();\n+ }\n+ });\n+\n+ private final MatchResult target;\n+\n+ public MemoizingMatchResult(MatchResult target) {\n+ this.target = target;\n+ }\n+\n+ @Override\n+ public boolean isExactMatch() {\n+ return memoizedExactMatch.get();\n+ }\n+\n+ @Override\n+ public double getDistance() {\n+ return memoizedDistance.get();\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MemoizingStringValuePattern.java",
"diff": "+package com.github.tomakehurst.wiremock.matching;\n+\n+import com.google.common.cache.CacheBuilder;\n+import com.google.common.cache.CacheLoader;\n+import com.google.common.cache.LoadingCache;\n+\n+import java.util.concurrent.ExecutionException;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+\n+public abstract class MemoizingStringValuePattern extends StringValuePattern {\n+\n+ private final LoadingCache<String, MatchResult> cache = CacheBuilder.newBuilder()\n+ .build(new CacheLoader<String, MatchResult>() {\n+ @Override\n+ public MatchResult load(String value) {\n+ return new MemoizingMatchResult(calculateMatch(value));\n+ }\n+ });\n+\n+ public MemoizingStringValuePattern(String expectedValue) {\n+ super(expectedValue);\n+ }\n+\n+ @Override\n+ public final MatchResult match(String value) {\n+ if (value == null) {\n+ return MatchResult.noMatch();\n+ }\n+\n+ try {\n+ return cache.get(value);\n+ } catch (ExecutionException e) {\n+ return throwUnchecked(e, MatchResult.class);\n+ }\n+ }\n+\n+ protected abstract MatchResult calculateMatch(String value);\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/PathPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/PathPattern.java",
"diff": "@@ -19,7 +19,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore;\nimport java.util.Objects;\n-public abstract class PathPattern extends StringValuePattern {\n+public abstract class PathPattern extends MemoizingStringValuePattern {\nprotected final StringValuePattern valuePattern;\n@@ -38,7 +38,7 @@ public abstract class PathPattern extends StringValuePattern {\n}\n@Override\n- public MatchResult match(String value) {\n+ protected MatchResult calculateMatch(String value) {\nif (isSimple()) {\nreturn isSimpleMatch(value);\n}\n@@ -60,6 +60,6 @@ public abstract class PathPattern extends StringValuePattern {\n@Override\npublic int hashCode() {\n- return Objects.hash(super.hashCode(), getValuePattern());\n+ return Objects.hash(super.hashCode(), valuePattern);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/notmatched/PlainTextStubNotMatchedRenderer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/notmatched/PlainTextStubNotMatchedRenderer.java",
"diff": "@@ -28,6 +28,7 @@ import com.github.tomakehurst.wiremock.verification.diff.PlainTextDiffRenderer;\nimport java.util.List;\nimport java.util.Map;\n+import static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\npublic class PlainTextStubNotMatchedRenderer extends NotMatchedRenderer {\n@@ -54,6 +55,8 @@ public class PlainTextStubNotMatchedRenderer extends NotMatchedRenderer {\nbody = diffRenderer.render(firstDiff);\n}\n+ notifier().error(body);\n+\nreturn ResponseDefinitionBuilder.responseDefinition()\n.withStatus(404)\n.withHeader(CONTENT_TYPE, \"text/plain\")\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/AdminApiTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/AdminApiTest.java",
"diff": "@@ -55,8 +55,10 @@ import static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.matches;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalsMultiLine;\nimport static org.apache.http.entity.ContentType.TEXT_PLAIN;\n+import static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.*;\n-import static org.junit.Assert.*;\n+import static org.junit.Assert.assertEquals;\n+import static org.junit.Assert.assertFalse;\npublic class AdminApiTest extends AcceptanceTestBase {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ProxyAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ProxyAcceptanceTest.java",
"diff": "@@ -71,14 +71,17 @@ public class ProxyAcceptanceTest {\nWireMockTestClient testClient;\nvoid init(WireMockConfiguration proxyingServiceOptions) {\n- targetService = new WireMockServer(wireMockConfig().dynamicPort().dynamicHttpsPort());\n+ targetService = new WireMockServer(wireMockConfig()\n+ .dynamicPort()\n+ .dynamicHttpsPort()\n+ .bindAddress(\"127.0.0.1\"));\ntargetService.start();\ntargetServiceAdmin = WireMock.create().host(\"localhost\").port(targetService.port()).build();\ntargetServiceBaseUrl = \"http://localhost:\" + targetService.port();\ntargetServiceBaseHttpsUrl = \"https://localhost:\" + targetService.httpsPort();\n- proxyingServiceOptions.dynamicPort();\n+ proxyingServiceOptions.dynamicPort().bindAddress(\"127.0.0.1\");\nproxyingService = new WireMockServer(proxyingServiceOptions);\nproxyingService.start();\nproxyingServiceAdmin = WireMock.create().port(proxyingService.port()).build();\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/ignored/MassiveNearMissTest.java",
"diff": "+package ignored;\n+\n+import com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\n+import com.google.common.base.Joiner;\n+import com.google.common.base.Stopwatch;\n+import org.junit.Before;\n+import org.junit.Rule;\n+import org.junit.Test;\n+\n+import java.util.ArrayList;\n+import java.util.List;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\n+import static java.util.concurrent.TimeUnit.MILLISECONDS;\n+\n+public class MassiveNearMissTest {\n+\n+ @Rule\n+ public WireMockRule wm = new WireMockRule(options().dynamicPort(), false);\n+\n+ WireMockTestClient client;\n+\n+ @Before\n+ public void setup() {\n+ client = new WireMockTestClient(wm.port());\n+ }\n+\n+ @Test\n+ public void timeToCalculateBigNearMissDiffXml() {\n+ final int stubs = 1000;\n+ for (int i = 0; i < stubs; i++) {\n+ wm.stubFor(post(urlPathMatching(\"/things/.*/\" + i))\n+ .withRequestBody(equalToXml(requestXml(i)))\n+ .willReturn(ok(\"i: \" + i)));\n+ }\n+\n+ final int drop = 2;\n+ final int reps = 30;\n+ List<Long> times = new ArrayList<>(reps);\n+ long sum = 0;\n+ for (int i = 0; i < reps; i++) {\n+ Stopwatch stopwatch = Stopwatch.createStarted();\n+ client.postXml(\"/things/blah123/\" + (stubs / 2), \"<?xml version=\\\"1.0\\\"?><things />\");\n+ stopwatch.stop();\n+ long time = stopwatch.elapsed(MILLISECONDS);\n+ times.add(time);\n+ if (i > drop) sum += time;\n+ }\n+\n+ System.out.printf(\"Times:\\n%s\\n\", Joiner.on(\"\\n\").join(times));\n+ long mean = sum / (reps - drop);\n+ System.out.printf(\"Mean: %dms\\n\", mean);\n+ }\n+\n+ private static String requestXml(int i) {\n+ return String.format(\"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"\\n\" +\n+ \"<things id=\\\"%d\\\">\\n\" +\n+ \" <stuff id=\\\"1\\\"/>\\n\" +\n+ \" <fluff id=\\\"2\\\"/>\\n\" +\n+ \"\\n\" +\n+ \" <inside>\\n\" +\n+ \" <deep-inside level=\\\"3\\\">\\n\" +\n+ \" <one/>\\n\" +\n+ \" <two/>\\n\" +\n+ \" <three/>\\n\" +\n+ \" <four/>\\n\" +\n+ \" <one/>\\n\" +\n+ \" <text subject=\\\"JWT\\\">\\n\" +\n+ \" JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.\\n\" +\n+ \" </text>\\n\" +\n+ \" </deep-inside>\\n\" +\n+ \" </inside>\\n\" +\n+ \"\\n\" +\n+ \"</things>\", i);\n+ }\n+\n+ @Test\n+ public void timeToCalculateBigNearMissDiffJson() {\n+ final int stubs = 1000;\n+ for (int i = 0; i < stubs; i++) {\n+ wm.stubFor(post(urlPathMatching(\"/things/.*/\" + i))\n+ .withRequestBody(equalToJson(requestJson(i)))\n+ .willReturn(ok(\"i: \" + i)));\n+ }\n+\n+ final int drop = 2;\n+ final int reps = 30;\n+ List<Long> times = new ArrayList<>(reps);\n+ long sum = 0;\n+ for (int i = 0; i < reps; i++) {\n+ Stopwatch stopwatch = Stopwatch.createStarted();\n+ client.postJson(\"/things/blah123/\" + (stubs / 2), \"{ \\\"wrong\\\": [1,2,3]}\");\n+ stopwatch.stop();\n+ long time = stopwatch.elapsed(MILLISECONDS);\n+ times.add(time);\n+ if (i > drop) sum += time;\n+ }\n+\n+ System.out.printf(\"Times:\\n%s\\n\", Joiner.on(\"\\n\").join(times));\n+ long mean = sum / (reps - drop);\n+ System.out.printf(\"Mean: %dms\\n\", mean);\n+ }\n+\n+ private String requestJson(int i) {\n+ return \"{\\n\" +\n+ \" \\\"children\\\": [\\n\" +\n+ \" {\\n\" +\n+ \" \\\"id\\\": \\\"9010946\\\",\\n\" +\n+ \" \\\"age\\\": 1,\\n\" +\n+ \" \\\"isRegistered\\\": false\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"id\\\": \\\"9405762\\\",\\n\" +\n+ \" \\\"age\\\": 1,\\n\" +\n+ \" \\\"isRegistered\\\": true\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"id\\\": \\\"9166586\\\",\\n\" +\n+ \" \\\"age\\\": 1,\\n\" +\n+ \" \\\"isRegistered\\\": false\\n\" +\n+ \" },\\n\" +\n+ \" {\\n\" +\n+ \" \\\"id\\\": \\\"7537984\\\",\\n\" +\n+ \" \\\"age\\\": 1,\\n\" +\n+ \" \\\"isRegistered\\\": true\\n\" +\n+ \" }\\n\" +\n+ \" ],\\n\" +\n+ \" \\\"category\\\": \\\"060\\\",\\n\" +\n+ \" \\\"id\\\": \\\"\" + i + \"\\\",\\n\" +\n+ \" \\\"isRegistered\\\": true,\\n\" +\n+ \" \\\"date\\\": \\\"20200312\\\"\\n\" +\n+ \"}\";\n+ }\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Improved performance, particularly when requests go unmatched by memoizing match results and only calculating near misses once (originally this happened twice - once in the response renderer, once for logging) |
686,936 | 15.05.2020 15:50:29 | -3,600 | d429d81906ab088c745062fcd0861fba76022206 | Fixed by putting stub CORS headers under a config switch, disabled by default to restore backwards compatibility. | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/configuration.md",
"new_path": "docs-v2/_docs/configuration.md",
"diff": "@@ -172,3 +172,13 @@ Valid values are:\nThis might put a lot of strain on the garbage collector if you're using large response bodies.\n* `BODY_FILE` - Use chunked encoding for body files but calculate a `Content-Length` for directly configured bodies.\n* `ALWAYS` - Always use chunk encoding - the default.\n+\n+\n+## Cross-origin response headers (CORS)\n+\n+WireMock always sends CORS headers with admin API responses, but not by default with stub responses.\n+To enable automatic sending of CORS headers on stub responses, do the following:\n+\n+```java\n+.stubCorsEnabled(true)\n+```\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/running-standalone.md",
"new_path": "docs-v2/_docs/running-standalone.md",
"diff": "@@ -133,6 +133,8 @@ The last of these will cause chunked encoding to be used only when a stub define\n`--permitted-system-keys`: Comma-separated list of regular expressions for names of permitted environment variables and system properties accessible from response templates. Only has any effect when templating is enabled. Defaults to `wiremock.*`.\n+`--enable-stub-cors`: Enable automatic sending of cross-origin (CORS) response headers. Defaults to off.\n+\n`--help`: Show command line help\n## Configuring WireMock using the Java client\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"diff": "@@ -72,4 +72,5 @@ public interface Options {\nChunkedEncodingPolicy getChunkedEncodingPolicy();\nboolean getGzipDisabled();\nboolean getStubRequestLoggingDisabled();\n+ boolean getStubCorsEnabled();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java",
"diff": "@@ -97,6 +97,8 @@ public class WireMockConfiguration implements Options {\nprivate boolean stubLoggingDisabled = false;\nprivate String permittedSystemKeys = null;\n+ private boolean stubCorsEnabled = false;\n+\nprivate MappingsSource getMappingsSource() {\nif (mappingsSource == null) {\nmappingsSource = new JsonFileMappingsSource(filesRoot.child(MAPPINGS_ROOT));\n@@ -355,6 +357,11 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n+ public WireMockConfiguration stubCorsEnabled(boolean enabled) {\n+ this.stubCorsEnabled = enabled;\n+ return this;\n+ }\n+\n@Override\npublic int portNumber() {\nreturn portNumber;\n@@ -509,4 +516,9 @@ public class WireMockConfiguration implements Options {\npublic boolean getStubRequestLoggingDisabled() {\nreturn stubLoggingDisabled;\n}\n+\n+ @Override\n+ public boolean getStubCorsEnabled() {\n+ return stubCorsEnabled;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"diff": "@@ -115,6 +115,7 @@ public class JettyHttpServer implements HttpServer {\noptions.filesRoot(),\noptions.getAsynchronousResponseSettings(),\noptions.getChunkedEncodingPolicy(),\n+ options.getStubCorsEnabled(),\nnotifier\n);\n@@ -335,14 +336,11 @@ public class JettyHttpServer implements HttpServer {\n2,\nconnectionFactories\n);\n- connector.setPort(port);\n+ connector.setPort(port);\nconnector.addNetworkTrafficListener(listener);\n-\nsetJettySettings(jettySettings, connector);\n-\nconnector.setHost(bindAddress);\n-\nreturn connector;\n}\n@@ -358,6 +356,7 @@ public class JettyHttpServer implements HttpServer {\nFileSource fileSource,\nAsynchronousResponseSettings asynchronousResponseSettings,\nOptions.ChunkedEncodingPolicy chunkedEncodingPolicy,\n+ boolean stubCorsEnabled,\nNotifier notifier\n) {\nServletContextHandler mockServiceContext = new ServletContextHandler(jettyServer, \"/\");\n@@ -398,7 +397,9 @@ public class JettyHttpServer implements HttpServer {\nmockServiceContext.addFilter(ContentTypeSettingFilter.class, FILES_URL_MATCH, EnumSet.of(DispatcherType.FORWARD));\nmockServiceContext.addFilter(TrailingSlashFilter.class, FILES_URL_MATCH, EnumSet.allOf(DispatcherType.class));\n+ if (stubCorsEnabled) {\naddCorsFilter(mockServiceContext);\n+ }\nreturn mockServiceContext;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"diff": "@@ -191,4 +191,9 @@ public class WarConfiguration implements Options {\npublic boolean getStubRequestLoggingDisabled() {\nreturn false;\n}\n+\n+ @Override\n+ public boolean getStubCorsEnabled() {\n+ return false;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java",
"diff": "@@ -95,7 +95,7 @@ public class CommandLineOptions implements Options {\nprivate static final String PERMITTED_SYSTEM_KEYS = \"permitted-system-keys\";\nprivate static final String DISABLE_GZIP = \"disable-gzip\";\nprivate static final String DISABLE_REQUEST_LOGGING = \"disable-request-logging\";\n-\n+ private static final String ENABLE_STUB_CORS = \"enable-stub-cors\";\nprivate final OptionSet optionSet;\nprivate final FileSource fileSource;\n@@ -145,6 +145,7 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(PERMITTED_SYSTEM_KEYS, \"A list of case-insensitive regular expressions for names of permitted system properties and environment vars. Only has any effect when templating is enabled. Defaults to no limit.\").withOptionalArg().ofType(String.class).withValuesSeparatedBy(\",\");\noptionParser.accepts(DISABLE_GZIP, \"Disable gzipping of request and response bodies\");\noptionParser.accepts(DISABLE_REQUEST_LOGGING, \"Disable logging of stub requests and responses to the notifier. Useful when performance testing.\");\n+ optionParser.accepts(ENABLE_STUB_CORS, \"Enable automatic sending of CORS headers with stub responses.\");\noptionParser.accepts(HELP, \"Print this message\");\n@@ -553,6 +554,11 @@ public class CommandLineOptions implements Options {\nreturn optionSet.has(DISABLE_REQUEST_LOGGING);\n}\n+ @Override\n+ public boolean getStubCorsEnabled() {\n+ return optionSet.has(ENABLE_STUB_CORS);\n+ }\n+\nprivate Long getMaxTemplateCacheEntries() {\nreturn optionSet.has(MAX_TEMPLATE_CACHE_ENTRIES) ?\nLong.valueOf(optionSet.valueOf(MAX_TEMPLATE_CACHE_ENTRIES).toString()) :\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/CrossOriginTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/CrossOriginTest.java",
"diff": "*/\npackage com.github.tomakehurst.wiremock;\n+import com.github.tomakehurst.wiremock.junit.WireMockRule;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\n+import org.junit.Before;\n+import org.junit.Rule;\nimport org.junit.Test;\n+import org.junit.experimental.runners.Enclosed;\n+import org.junit.runner.RunWith;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\nimport static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader;\nimport static org.hamcrest.Matchers.is;\nimport static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.nullValue;\n-public class CrossOriginTest extends AcceptanceTestBase {\n+@RunWith(Enclosed.class)\n+public class CrossOriginTest {\n+\n+ public static class Enabled {\n+\n+ @Rule\n+ public WireMockRule wm = new WireMockRule(wireMockConfig().dynamicPort().stubCorsEnabled(true));\n+\n+ WireMockTestClient testClient;\n+\n+ @Before\n+ public void init() {\n+ testClient = new WireMockTestClient(wm.port());\n+ }\n@Test\npublic void sendsCorsHeadersInResponseToAdminOPTIONSQuery() {\n@@ -51,3 +72,30 @@ public class CrossOriginTest extends AcceptanceTestBase {\nassertThat(response.firstHeader(\"Access-Control-Allow-Methods\"), is(\"OPTIONS,GET,POST,PUT,PATCH,DELETE\"));\n}\n}\n+\n+ public static class Disabled {\n+\n+ @Rule\n+ public WireMockRule wm = new WireMockRule(wireMockConfig().dynamicPort());\n+\n+ WireMockTestClient testClient;\n+\n+ @Before\n+ public void init() {\n+ testClient = new WireMockTestClient(wm.port());\n+ }\n+\n+ @Test\n+ public void doesNotSendCorsHeadersInResponseToStubOPTIONSQuery() {\n+ wm.stubFor(any(urlEqualTo(\"/cors\")).willReturn(ok()));\n+\n+ WireMockResponse response = testClient.options(\"/cors\",\n+ withHeader(\"Origin\", \"http://my.corp.com\"),\n+ withHeader(\"Access-Control-Request-Method\", \"POST\")\n+ );\n+\n+ assertThat(response.statusCode(), is(200));\n+ assertThat(response.firstHeader(\"Access-Control-Allow-Origin\"), nullValue());\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ProxyAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ProxyAcceptanceTest.java",
"diff": "@@ -74,7 +74,7 @@ public class ProxyAcceptanceTest {\ntargetService = new WireMockServer(wireMockConfig()\n.dynamicPort()\n.dynamicHttpsPort()\n- .bindAddress(\"127.0.0.1\"));\n+ .bindAddress(\"127.0.0.1\").stubCorsEnabled(true));\ntargetService.start();\ntargetServiceAdmin = WireMock.create().host(\"localhost\").port(targetService.port()).build();\n@@ -490,12 +490,14 @@ public class ProxyAcceptanceTest {\nproxyingServiceAdmin.register(any(anyUrl())\n.willReturn(aResponse().proxiedFrom(targetServiceBaseUrl)));\n- targetServiceAdmin.register(any(urlPathEqualTo(\"/cors\")).willReturn(ok()));\n+ targetServiceAdmin.register(any(urlPathEqualTo(\"/cors\"))\n+ .withName(\"Target with CORS\")\n+ .willReturn(ok()));\nWireMockResponse response = testClient.get(\"/cors\", withHeader(\"Origin\", \"http://somewhere.com\"));\nCollection<String> allowOriginHeaderValues = response.headers().get(\"Access-Control-Allow-Origin\");\n- assertThat(allowOriginHeaderValues.size(), is(1));\n+ assertThat(allowOriginHeaderValues.size(), is(0));\n}\nprivate void register200StubOnProxyAndTarget(String url) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"diff": "@@ -468,6 +468,18 @@ public class CommandLineOptionsTest {\nassertThat(dump, not(containsString(\"https-port\")));\n}\n+ @Test\n+ public void enablesStubCors() {\n+ CommandLineOptions options = new CommandLineOptions(\"--enable-stub-cors\");\n+ assertThat(options.getStubCorsEnabled(), is(true));\n+ }\n+\n+ @Test\n+ public void defaultsToNoStubCors() {\n+ CommandLineOptions options = new CommandLineOptions();\n+ assertThat(options.getStubCorsEnabled(), is(false));\n+ }\n+\n@Test\npublic void printsBothActualPortsOnlyWhenHttpsEnabled() {\nCommandLineOptions options = new CommandLineOptions();\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed #1283 by putting stub CORS headers under a config switch, disabled by default to restore backwards compatibility. |
686,936 | 15.05.2020 18:54:47 | -3,600 | 766ae5d2e016f79fff992e2c1ea93e9c7e142abf | Fixed bug causing an exception to be thrown when attempting to use the JUnit rule with HTTP disabled | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/WireMockServer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/WireMockServer.java",
"diff": "@@ -62,7 +62,7 @@ public class WireMockServer implements Container, Stubbing, Admin {\nprivate final HttpServer httpServer;\nprivate final Notifier notifier;\n- private final Options options;\n+ protected final Options options;\nprotected final WireMock client;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/junit/WireMockRule.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/junit/WireMockRule.java",
"diff": "@@ -67,7 +67,13 @@ public class WireMockRule extends WireMockServer implements MethodRule, TestRule\n@Override\npublic void evaluate() throws Throwable {\nstart();\n+\n+ if (options.getHttpDisabled()) {\n+ WireMock.configureFor(\"https\", \"localhost\", httpsPort());\n+ } else {\nWireMock.configureFor(\"localhost\", port());\n+ }\n+\ntry {\nbefore();\nbase.evaluate();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/WireMockJUnitRuleTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/WireMockJUnitRuleTest.java",
"diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.common.ConsoleNotifier;\n+import com.github.tomakehurst.wiremock.http.HttpClientFactory;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.RequestListener;\nimport com.github.tomakehurst.wiremock.http.Response;\n@@ -25,6 +26,9 @@ import com.github.tomakehurst.wiremock.junit.WireMockClassRule;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\nimport com.github.tomakehurst.wiremock.testsupport.Network;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\n+import org.apache.http.HttpResponse;\n+import org.apache.http.client.HttpClient;\n+import org.apache.http.client.methods.HttpGet;\nimport org.junit.Before;\nimport org.junit.ClassRule;\nimport org.junit.Rule;\n@@ -35,13 +39,7 @@ import org.junit.runner.RunWith;\nimport java.util.ArrayList;\nimport java.util.List;\n-import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n-import static com.github.tomakehurst.wiremock.client.WireMock.get;\n-import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;\n-import static com.github.tomakehurst.wiremock.client.WireMock.givenThat;\n-import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;\n-import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;\n-import static com.github.tomakehurst.wiremock.client.WireMock.verify;\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\nimport static org.hamcrest.Matchers.equalTo;\nimport static org.hamcrest.Matchers.is;\n@@ -280,6 +278,24 @@ public class WireMockJUnitRuleTest {\n}\n}\n+ public static class HttpsOnly {\n+\n+ @Rule\n+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicHttpsPort().httpDisabled(true));\n+\n+ @Test\n+ public void exposesHttpsOnly() throws Exception {\n+ wireMockRule.stubFor(any(anyUrl()).willReturn(ok()));\n+\n+ HttpClient client = HttpClientFactory.createClient();\n+\n+ HttpGet request = new HttpGet(\"https://localhost:\" + wireMockRule.httpsPort() + \"/anything\");\n+ HttpResponse response = client.execute(request);\n+\n+ assertThat(response.getStatusLine().getStatusCode(), is(200));\n+ }\n+ }\n+\nprivate static void assertNoPreviousRequestsReceived() {\nverify(0, getRequestedFor(urlMatching(\".*\")));\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fixed bug causing an exception to be thrown when attempting to use the JUnit rule with HTTP disabled |
686,936 | 18.05.2020 10:46:45 | -3,600 | 35e1dc5fcf9fb75c6579f5dd9d268661c79d1466 | Upgraded Java versions used in the go script | [
{
"change_type": "MODIFY",
"old_path": "go",
"new_path": "go",
"diff": "set -eo pipefail\nexport JAVA7_HOME=~/.sdkman/candidates/java/7.0.181-zulu\n-export JAVA8_HOME=~/.sdkman/candidates/java/8.0.181-zulu\n-export JAVA11_HOME=~/.sdkman/candidates/java/11.0.1-open\n+export JAVA8_HOME=~/.sdkman/candidates/java/8.0.252-zulu\n+export JAVA11_HOME=~/.sdkman/candidates/java/11.0.7-zulu\nhelp() {\necho -e \"Usage: go <command>\"\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Upgraded Java versions used in the go script |
686,981 | 20.05.2020 11:15:50 | -3,600 | fde8d69bd53ee8ea4962626429c6a5dc82ba5795 | Always use an HTTP proxy
Changing the scheme of the proxy depending on the scheme of the requested
target doesn't make sense; an HTTP proxy can forward HTTPS over a CONNECT
tunnel anyway. | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java",
"diff": "@@ -102,7 +102,7 @@ public class WireMockTestClient {\npublic WireMockResponse getViaProxy(String url, int proxyPort) {\nURI targetUri = URI.create(url);\n- HttpHost proxy = new HttpHost(address, proxyPort, targetUri.getScheme());\n+ HttpHost proxy = new HttpHost(address, proxyPort);\nHttpClient httpClientUsingProxy = HttpClientBuilder.create()\n.disableAuthCaching()\n.disableAutomaticRetries()\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Always use an HTTP proxy
Changing the scheme of the proxy depending on the scheme of the requested
target doesn't make sense; an HTTP proxy can forward HTTPS over a CONNECT
tunnel anyway. |
686,981 | 20.05.2020 11:17:39 | -3,600 | 908d6395204bc6f0926b9443e3f5fea131a0b2d3 | Add ignored failing test for https forward proxying | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/BrowserProxyAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/BrowserProxyAcceptanceTest.java",
"diff": "@@ -27,7 +27,10 @@ import static org.hamcrest.MatcherAssert.assertThat;\npublic class BrowserProxyAcceptanceTest {\n@ClassRule\n- public static WireMockClassRule target = new WireMockClassRule(wireMockConfig().dynamicPort());\n+ public static WireMockClassRule target = new WireMockClassRule(wireMockConfig()\n+ .dynamicPort()\n+ .dynamicHttpsPort()\n+ );\n@Rule\npublic WireMockClassRule instanceRule = target;\n@@ -59,6 +62,13 @@ public class BrowserProxyAcceptanceTest {\nassertThat(testClient.getViaProxy(url(\"/whatever\"), proxy.port()).content(), is(\"Got it\"));\n}\n+ @Test @Ignore\n+ public void canProxyHttps() throws Exception {\n+ target.stubFor(get(urlEqualTo(\"/whatever\")).willReturn(aResponse().withBody(\"Got it\")));\n+\n+ assertThat(testClient.getViaProxy(httpsUrl(\"/whatever\"), proxy.port()).content(), is(\"Got it\"));\n+ }\n+\n@Test\npublic void passesQueryParameters() {\ntarget.stubFor(get(urlEqualTo(\"/search?q=things&limit=10\")).willReturn(aResponse().withStatus(200)));\n@@ -70,4 +80,8 @@ public class BrowserProxyAcceptanceTest {\nreturn \"http://localhost:\" + target.port() + pathAndQuery;\n}\n+ private String httpsUrl(String pathAndQuery) {\n+ return \"https://localhost:\" + target.httpsPort() + pathAndQuery;\n+ }\n+\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Add ignored failing test for https forward proxying |
686,936 | 19.05.2020 10:46:51 | -3,600 | 708a97a1956b641d117c930ddea9ac68c457e338 | Upgraded XMLUnit to 2.7.0 | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -44,7 +44,7 @@ allprojects {\nguava : '20.0',\njackson : jacksonVersion,\njacksonDatabind: jacksonVersion,\n- xmlUnit : '2.6.2'\n+ xmlUnit : '2.7.0'\n],\njava8: [\nhandlebars : '4.2.0',\n@@ -52,7 +52,7 @@ allprojects {\nguava : '29.0-jre',\njackson : jacksonVersion,\njacksonDatabind: jacksonVersion,\n- xmlUnit : '2.6.2'\n+ xmlUnit : '2.7.0'\n]\n]\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Upgraded XMLUnit to 2.7.0 |
686,936 | 22.05.2020 18:21:27 | -3,600 | 29798296b0e4dbff8dcd83c7e0316df229a7d020 | Created XmlDocument and XmlNode classes as wrappers around their DOM equivalents and embedding XPath functionality. Eventually these should completely replace most of the static methods on the Xml class. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ClientError.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ClientError.java",
"diff": "@@ -26,6 +26,11 @@ public class ClientError extends RuntimeException {\nthis.errors = errors;\n}\n+ protected ClientError(Throwable cause, Errors errors) {\n+ super(Json.write(errors), cause);\n+ this.errors = errors;\n+ }\n+\npublic static ClientError fromErrors(Errors errors) {\nInteger errorCode = errors.first().getCode();\nswitch (errorCode) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ContentTypes.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ContentTypes.java",
"diff": "package com.github.tomakehurst.wiremock.common;\nimport com.fasterxml.jackson.databind.JsonNode;\n+import com.github.tomakehurst.wiremock.common.xml.Xml;\nimport com.github.tomakehurst.wiremock.http.ContentTypeHeader;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\n@@ -26,7 +27,6 @@ import java.util.Map;\nimport static com.github.tomakehurst.wiremock.common.Strings.stringFromBytes;\nimport static com.github.tomakehurst.wiremock.common.TextType.JSON;\n-import static com.github.tomakehurst.wiremock.common.TextType.XML;\nimport static com.google.common.collect.Iterables.any;\nimport static java.util.Arrays.asList;\nimport static org.apache.commons.lang3.StringUtils.substringAfterLast;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/InvalidInputException.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/InvalidInputException.java",
"diff": "@@ -20,4 +20,8 @@ public class InvalidInputException extends ClientError {\npublic InvalidInputException(Errors errors) {\nsuper(errors);\n}\n+\n+ protected InvalidInputException(Throwable cause, Errors errors) {\n+ super(cause, errors);\n+ }\n}\n"
},
{
"change_type": "RENAME",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Xml.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/Xml.java",
"diff": "* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n-package com.github.tomakehurst.wiremock.common;\n+package com.github.tomakehurst.wiremock.common.xml;\n+import com.github.tomakehurst.wiremock.common.Errors;\n+import com.github.tomakehurst.wiremock.common.SilentErrorHandler;\nimport org.custommonkey.xmlunit.XMLUnit;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Node;\n@@ -140,10 +142,27 @@ public class Xml {\n}\n}\n+ public static DocumentBuilder getDocumentBuilder() {\n+ try {\n+ return newDocumentBuilderFactory().newDocumentBuilder();\n+ } catch (ParserConfigurationException e) {\n+ return throwUnchecked(e, DocumentBuilder.class);\n+ }\n+ }\n+\npublic static DocumentBuilderFactory newDocumentBuilderFactory() {\nreturn new SkipResolvingEntitiesDocumentBuilderFactory();\n}\n+ public static XmlDocument parse(String xml) {\n+ try {\n+ InputSource source = new InputSource(new StringReader(xml));\n+ return new XmlDocument(getDocumentBuilder().parse(source));\n+ } catch (SAXException | IOException e) {\n+ throw new XmlException(Errors.single(50, e.getMessage()));\n+ }\n+ }\n+\nprivate static class SkipResolvingEntitiesDocumentBuilderFactory extends DocumentBuilderFactory {\nprivate static final ThreadLocal<DocumentBuilderFactory> DBF_CACHE = new ThreadLocal<DocumentBuilderFactory>() {\n@@ -164,7 +183,9 @@ public class Xml {\n@Override\nprotected DocumentBuilder initialValue() {\ntry {\n- return DBF_CACHE.get().newDocumentBuilder();\n+ DocumentBuilder documentBuilder = DBF_CACHE.get().newDocumentBuilder();\n+ documentBuilder.setErrorHandler(new SilentErrorHandler());\n+ return documentBuilder;\n} catch (ParserConfigurationException e) {\nreturn throwUnchecked(e, DocumentBuilder.class);\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/XmlDocument.java",
"diff": "+package com.github.tomakehurst.wiremock.common.xml;\n+\n+import com.github.tomakehurst.wiremock.common.ListOrSingle;\n+import org.w3c.dom.Document;\n+import org.w3c.dom.NodeList;\n+\n+import javax.xml.transform.Transformer;\n+import javax.xml.transform.dom.DOMSource;\n+import javax.xml.transform.stream.StreamResult;\n+import javax.xml.xpath.XPathExpressionException;\n+\n+import java.io.StringWriter;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static javax.xml.xpath.XPathConstants.NODESET;\n+\n+public class XmlDocument extends XmlNode {\n+\n+ private final Document document;\n+\n+ public XmlDocument(Document document) {\n+ super(document);\n+ this.document = document;\n+ }\n+\n+ public ListOrSingle<XmlNode> findNodes(String xpathExpression) {\n+ try {\n+ NodeList nodeSet = (NodeList) XPATH_CACHE.get().evaluate(xpathExpression, document, NODESET);\n+ return toListOrSingle(nodeSet);\n+ } catch (XPathExpressionException e) {\n+ throw XmlException.fromXPathException(e);\n+ }\n+ }\n+\n+}\n"
},
{
"change_type": "RENAME",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/XmlException.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/XmlException.java",
"diff": "* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n-package com.github.tomakehurst.wiremock.common;\n+package com.github.tomakehurst.wiremock.common.xml;\n+import com.github.tomakehurst.wiremock.common.Errors;\n+import com.github.tomakehurst.wiremock.common.InvalidInputException;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n+import javax.xml.xpath.XPathExpressionException;\n+\npublic class XmlException extends InvalidInputException {\nprotected XmlException(Errors errors) {\nsuper(errors);\n}\n+ protected XmlException(Throwable cause, Errors errors) {\n+ super(cause, errors);\n+ }\n+\n+ public static XmlException fromXPathException(XPathExpressionException e) {\n+ return new XmlException(e, Errors.single(51, e.getMessage()));\n+ }\n+\npublic static XmlException fromSaxException(SAXException e) {\nif (e instanceof SAXParseException) {\nSAXParseException spe = (SAXParseException) e;\n@@ -31,6 +43,6 @@ public class XmlException extends InvalidInputException {\nreturn new XmlException(Errors.singleWithDetail(50, e.getMessage(), detail));\n}\n- return new XmlException(Errors.single(50, e.getMessage()));\n+ return new XmlException(e, Errors.single(50, e.getMessage()));\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/XmlNode.java",
"diff": "+package com.github.tomakehurst.wiremock.common.xml;\n+\n+import com.github.tomakehurst.wiremock.common.ListOrSingle;\n+import com.google.common.collect.ImmutableMap;\n+import com.sun.org.apache.xalan.internal.xsltc.trax.DOM2SAX;\n+import org.w3c.dom.NamedNodeMap;\n+import org.w3c.dom.Node;\n+import org.w3c.dom.NodeList;\n+\n+import javax.xml.transform.Source;\n+import javax.xml.transform.Transformer;\n+import javax.xml.transform.TransformerConfigurationException;\n+import javax.xml.transform.TransformerFactory;\n+import javax.xml.transform.dom.DOMSource;\n+import javax.xml.transform.sax.SAXSource;\n+import javax.xml.transform.stream.StreamResult;\n+import javax.xml.xpath.XPath;\n+import javax.xml.xpath.XPathFactory;\n+import java.io.StringWriter;\n+import java.util.Collections;\n+import java.util.Map;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static javax.xml.transform.OutputKeys.INDENT;\n+import static javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION;\n+\n+public class XmlNode {\n+\n+ protected static final InheritableThreadLocal<XPath> XPATH_CACHE = new InheritableThreadLocal<XPath>() {\n+ @Override\n+ protected XPath initialValue() {\n+ final XPathFactory xPathfactory = XPathFactory.newInstance();\n+ return xPathfactory.newXPath();\n+ }\n+ };\n+\n+ protected static final InheritableThreadLocal<Transformer> TRANSFORMER_CACHE = new InheritableThreadLocal<Transformer>() {\n+ @Override\n+ protected Transformer initialValue() {\n+ TransformerFactory transformerFactory;\n+ try {\n+ transformerFactory = (TransformerFactory) Class.forName(\"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl\").newInstance();\n+ transformerFactory.setAttribute(\"indent-number\", 2);\n+ } catch (Exception e) {\n+ transformerFactory = TransformerFactory.newInstance();\n+ }\n+\n+ try {\n+ Transformer transformer = transformerFactory.newTransformer();\n+ transformer.setOutputProperty(INDENT, \"yes\");\n+ transformer.setOutputProperty(OMIT_XML_DECLARATION, \"yes\");\n+ return transformer;\n+ } catch (TransformerConfigurationException e) {\n+ return throwUnchecked(e, Transformer.class);\n+ }\n+ }\n+ };\n+\n+ private static final boolean DOM2SAX_AVAILABLE = getDom2SaxAvailability();\n+ private static boolean getDom2SaxAvailability() {\n+ try {\n+ Class.forName(\"com.sun.org.apache.xalan.internal.xsltc.trax.DOM2SAX\");\n+ return true;\n+ } catch (ClassNotFoundException e) {\n+ return false;\n+ }\n+ }\n+\n+ private final Node domNode;\n+ private final Map<String, String> attributes;\n+\n+ public XmlNode(Node domNode) {\n+ this.domNode = domNode;\n+ attributes = domNode.hasAttributes() ?\n+ convertAttributeMap(domNode.getAttributes()) :\n+ Collections.<String, String>emptyMap();\n+ }\n+\n+ private static Map<String, String> convertAttributeMap(NamedNodeMap namedNodeMap) {\n+ ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();\n+ for (int i = 0; i < namedNodeMap.getLength(); i++) {\n+ Node node = namedNodeMap.item(i);\n+ builder.put(node.getNodeName(), node.getNodeValue());\n+ }\n+\n+ return builder.build();\n+ }\n+\n+ public Map<String, String> getAttributes() {\n+ return attributes;\n+ }\n+\n+ protected static ListOrSingle<XmlNode> toListOrSingle(NodeList nodeList) {\n+ ListOrSingle<XmlNode> nodes = new ListOrSingle<>();\n+ for (int i = 0; i < nodeList.getLength(); i++) {\n+ nodes.add(new XmlNode(nodeList.item(i)));\n+ }\n+\n+ return nodes;\n+ }\n+\n+ @Override\n+ public String toString() {\n+ switch (domNode.getNodeType()) {\n+ case Node.TEXT_NODE:\n+ case Node.ATTRIBUTE_NODE:\n+ return domNode.getTextContent();\n+ case Node.DOCUMENT_NODE:\n+ case Node.ELEMENT_NODE:\n+ return render();\n+ default:\n+ return domNode.toString();\n+ }\n+ }\n+\n+ private String render() {\n+ try {\n+ Transformer transformer = TRANSFORMER_CACHE.get();\n+ StreamResult result = new StreamResult(new StringWriter());\n+ Source source = getSourceForTransform(domNode);\n+ transformer.transform(source, result);\n+ return result.getWriter().toString();\n+ } catch (Exception e) {\n+ return throwUnchecked(e, String.class);\n+ }\n+ }\n+\n+ // This nasty little hack attempts to ensure no exception is thrown when attempting to print an XML node with\n+ // unbound namespace prefixes (which can happen when you've selected an element via XPath whose namespaces are declared in a parent element).\n+ // For some reason Transformer is happy to do this with a SAX source, but not a DOM source.\n+ private static Source getSourceForTransform(Node node) {\n+ if (DOM2SAX_AVAILABLE) {\n+ DOM2SAX dom2SAX = new DOM2SAX(node);\n+ SAXSource saxSource = new SAXSource();\n+ saxSource.setXMLReader(dom2SAX);\n+ return saxSource;\n+ }\n+\n+ return new DOMSource(node);\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"diff": "@@ -19,7 +19,7 @@ import com.github.tomakehurst.wiremock.admin.AdminRoutes;\nimport com.github.tomakehurst.wiremock.admin.LimitAndOffsetPaginator;\nimport com.github.tomakehurst.wiremock.admin.model.*;\nimport com.github.tomakehurst.wiremock.common.FileSource;\n-import com.github.tomakehurst.wiremock.common.Xml;\n+import com.github.tomakehurst.wiremock.common.xml.Xml;\nimport com.github.tomakehurst.wiremock.extension.*;\nimport com.github.tomakehurst.wiremock.extension.requestfilter.RequestFilter;\nimport com.github.tomakehurst.wiremock.global.GlobalSettings;\n@@ -32,7 +32,6 @@ import com.github.tomakehurst.wiremock.recording.*;\nimport com.github.tomakehurst.wiremock.standalone.MappingsLoader;\nimport com.github.tomakehurst.wiremock.stubbing.*;\nimport com.github.tomakehurst.wiremock.verification.*;\n-import com.github.tomakehurst.wiremock.verification.diff.PlainTextDiffRenderer;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\n@@ -44,7 +43,6 @@ import java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n-import static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\nimport static com.github.tomakehurst.wiremock.stubbing.ServeEvent.NOT_MATCHED;\nimport static com.github.tomakehurst.wiremock.stubbing.ServeEvent.TO_LOGGED_REQUEST;\nimport static com.google.common.base.MoreObjects.firstNonNull;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java",
"diff": "package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\nimport com.github.jknack.handlebars.Options;\n-import com.github.tomakehurst.wiremock.common.Xml;\n+import com.github.tomakehurst.wiremock.common.xml.Xml;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.RenderCache;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Node;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java",
"diff": "package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonProperty;\n-import com.github.tomakehurst.wiremock.common.Xml;\n+import com.github.tomakehurst.wiremock.common.xml.Xml;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesXPathPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesXPathPattern.java",
"diff": "@@ -19,7 +19,7 @@ import com.fasterxml.jackson.annotation.JsonGetter;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonSerialize;\nimport com.github.tomakehurst.wiremock.common.SilentErrorHandler;\n-import com.github.tomakehurst.wiremock.common.Xml;\n+import com.github.tomakehurst.wiremock.common.xml.Xml;\nimport com.google.common.collect.ImmutableMap;\nimport org.custommonkey.xmlunit.NamespaceContext;\nimport org.custommonkey.xmlunit.SimpleNamespaceContext;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java",
"diff": "@@ -17,7 +17,7 @@ package com.github.tomakehurst.wiremock.verification.diff;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.common.Urls;\n-import com.github.tomakehurst.wiremock.common.Xml;\n+import com.github.tomakehurst.wiremock.common.xml.Xml;\nimport com.github.tomakehurst.wiremock.http.*;\nimport com.github.tomakehurst.wiremock.matching.*;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/common/xml/XmlTest.java",
"diff": "+package com.github.tomakehurst.wiremock.common.xml;\n+\n+import com.github.tomakehurst.wiremock.common.ListOrSingle;\n+import com.sun.org.apache.xalan.internal.xsltc.trax.DOM2SAX;\n+import org.junit.Ignore;\n+import org.junit.Test;\n+import org.w3c.dom.Document;\n+import org.w3c.dom.Node;\n+\n+import javax.xml.transform.Transformer;\n+import javax.xml.transform.TransformerFactory;\n+import javax.xml.transform.sax.SAXSource;\n+import javax.xml.transform.stream.StreamResult;\n+import javax.xml.xpath.XPath;\n+import javax.xml.xpath.XPathFactory;\n+import java.io.StringWriter;\n+\n+import static javax.xml.transform.OutputKeys.INDENT;\n+import static javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION;\n+import static javax.xml.xpath.XPathConstants.NODE;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.is;\n+\n+public class XmlTest {\n+\n+ @Test\n+ public void findsSimpleXmlNodesByXPath() {\n+ String xml = \"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<things>\\n\" +\n+ \" <thing>1</thing>\\n\" +\n+ \" <thing>2</thing>\\n\" +\n+ \"</things>\";\n+\n+ XmlDocument xmlDocument = Xml.parse(xml);\n+\n+ ListOrSingle<XmlNode> nodes = xmlDocument.findNodes(\"//things/thing/text()\");\n+\n+ assertThat(nodes.size(), is(2));\n+ assertThat(nodes.get(0).toString(), is(\"1\"));\n+ assertThat(nodes.get(1).toString(), is(\"2\"));\n+ }\n+\n+ @Test\n+ public void findsNamespacedXmlNodeByXPath() {\n+ String xml = \"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<things xmlns:s=\\\"https://stuff.biz\\\" id=\\\"1\\\">\\n\" +\n+ \" <stuff id=\\\"1\\\"/>\\n\" +\n+ \" <fl:fluff xmlns:fl=\\\"https://fluff.abc\\\" id=\\\"2\\\" fl:group=\\\"555\\\">\\n\" +\n+ \" <fl:inner id=\\\"123\\\" fl:code=\\\"D1\\\">Innards</fl:inner>\\n\" +\n+ \" <fl:inner>More Innards</fl:inner>\\n\" +\n+ \" </fl:fluff>\\n\" +\n+ \"</things>\";\n+\n+ XmlDocument xmlDocument = Xml.parse(xml);\n+\n+ ListOrSingle<XmlNode> nodes = xmlDocument.findNodes(\"/things/fluff\");\n+\n+ assertThat(nodes.size(), is(1));\n+ assertThat(nodes.get(0).getAttributes().get(\"id\"), is(\"2\"));\n+ assertThat(nodes.get(0).getAttributes().get(\"fl:group\"), is(\"555\"));\n+ }\n+\n+ @Test\n+ public void prettyPrintsDocument() {\n+ String xml = \"<one><two><three name='3'/></two></one>\";\n+\n+ XmlDocument xmlDocument = Xml.parse(xml);\n+\n+ assertThat(xmlDocument.toString(), is(\"<one>\\n\" +\n+ \" <two>\\n\" +\n+ \" <three name=\\\"3\\\"/>\\n\" +\n+ \" </two>\\n\" +\n+ \"</one>\\n\"));\n+ }\n+\n+ @Test\n+ public void prettyPrintsNodeAttributeValue() {\n+ String xml = \"<one><two><three name='3'/></two></one>\";\n+\n+ XmlDocument xmlDocument = Xml.parse(xml);\n+ ListOrSingle<XmlNode> nodes = xmlDocument.findNodes(\"//three/@name\");\n+\n+ assertThat(nodes.getFirst().toString(), is(\"3\"));\n+ }\n+\n+ @Test\n+ public void prettyPrintsNodeTextValue() {\n+ String xml = \"<one><two>2</two></one>\";\n+\n+ XmlDocument xmlDocument = Xml.parse(xml);\n+ ListOrSingle<XmlNode> nodes = xmlDocument.findNodes(\"/one/two/text()\");\n+\n+ assertThat(nodes.getFirst().toString(), is(\"2\"));\n+ }\n+\n+ @Test\n+ public void prettyPrintsNodeXml() {\n+ String xml = \"<one><two><three name=\\\"3\\\"/></two></one>\";\n+\n+ XmlDocument xmlDocument = Xml.parse(xml);\n+ ListOrSingle<XmlNode> nodes = xmlDocument.findNodes(\"/one/two\");\n+\n+ assertThat(nodes.getFirst().toString(), is(\"<two>\\n\" +\n+ \" <three name=\\\"3\\\"/>\\n\" +\n+ \"</two>\"));\n+ }\n+\n+ @Test\n+ public void printsNamespacedXmlWhenPrefixDeclarationNotInScope() {\n+ String xml = \"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<things xmlns:s=\\\"https://stuff.biz\\\" id=\\\"1\\\">\\n\" +\n+ \" <stuff id=\\\"1\\\"/>\\n\" +\n+ \" <fl:fluff xmlns:fl=\\\"https://fluff.abc\\\" id=\\\"2\\\">\\n\" +\n+ \" <fl:inner id=\\\"123\\\" fl:code=\\\"D1\\\">Innards</fl:inner>\\n\" +\n+ \" <fl:inner>More Innards</fl:inner>\\n\" +\n+ \" </fl:fluff>\\n\" +\n+ \"</things>\";\n+\n+ XmlDocument xmlDocument = Xml.parse(xml);\n+ ListOrSingle<XmlNode> xmlNodes = xmlDocument.findNodes(\"/things/fluff/inner[@id=\\\"123\\\"]\");\n+\n+ assertThat(xmlNodes.toString(), is(\"<fl:inner fl:code=\\\"D1\\\" id=\\\"123\\\">Innards</fl:inner>\"));\n+ }\n+\n+ @Ignore\n+ @Test\n+ public void tmp() throws Exception {\n+ String xml = \"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<things xmlns:s=\\\"https://stuff.biz\\\" id=\\\"1\\\">\\n\" +\n+ \" <stuff id=\\\"1\\\"/>\\n\" +\n+ \" <fl:fluff xmlns:fl=\\\"https://fluff.abc\\\" id=\\\"2\\\">\\n\" +\n+ \" <fl:inner id=\\\"123\\\" fl:code=\\\"D1\\\">Innards</fl:inner>\\n\" +\n+ \" <fl:inner>More Innards</fl:inner>\\n\" +\n+ \" </fl:fluff>\\n\" +\n+ \"</things>\";\n+\n+ final Document doc = Xml.read(xml);\n+ XPath xPath = XPathFactory.newInstance().newXPath();\n+ Node node = (Node) xPath.evaluate(\"/things/fluff/inner\", doc, NODE);\n+ StringWriter sw = new StringWriter();\n+ final TransformerFactory transformerFactory = TransformerFactory.newInstance();\n+ Transformer transformer = transformerFactory.newTransformer();\n+ transformer.setOutputProperty(OMIT_XML_DECLARATION, \"yes\");\n+ transformer.setOutputProperty(INDENT, \"yes\");\n+ final DOM2SAX dom2SAX = new DOM2SAX(node);\n+ final SAXSource saxSource = new SAXSource();\n+ saxSource.setXMLReader(dom2SAX);\n+ transformer.transform(saxSource, new StreamResult(sw));\n+ System.out.println(sw.toString());\n+ }\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Created XmlDocument and XmlNode classes as wrappers around their DOM equivalents and embedding XPath functionality. Eventually these should completely replace most of the static methods on the Xml class. |
686,936 | 22.05.2020 19:07:47 | -3,600 | f3e263176c709010cafcfaff8e33b3605ea0c310 | Switched MatchesXPathPattern to use new XmlDocument and XmlNode | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/XPathException.java",
"diff": "+/*\n+ * Copyright (C) 2011 Thomas Akehurst\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package com.github.tomakehurst.wiremock.common.xml;\n+\n+import com.github.tomakehurst.wiremock.common.Errors;\n+import com.github.tomakehurst.wiremock.common.InvalidInputException;\n+import org.xml.sax.SAXException;\n+import org.xml.sax.SAXParseException;\n+\n+import javax.xml.xpath.XPathExpressionException;\n+\n+public class XPathException extends InvalidInputException {\n+\n+ protected XPathException(Throwable cause, Errors errors) {\n+ super(cause, errors);\n+ }\n+\n+ public static XPathException fromXPathException(XPathExpressionException e) {\n+ return new XPathException(e, Errors.single(51, e.getMessage()));\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/XmlDocument.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/XmlDocument.java",
"diff": "package com.github.tomakehurst.wiremock.common.xml;\nimport com.github.tomakehurst.wiremock.common.ListOrSingle;\n+import org.custommonkey.xmlunit.SimpleNamespaceContext;\n+import org.custommonkey.xmlunit.jaxp13.XMLUnitNamespaceContext2Jaxp13;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.NodeList;\n+import org.xmlunit.util.Convert;\n+import javax.xml.XMLConstants;\n+import javax.xml.namespace.NamespaceContext;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n+import javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathExpressionException;\nimport java.io.StringWriter;\n+import java.util.HashMap;\n+import java.util.Iterator;\n+import java.util.Map;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static javax.xml.xpath.XPathConstants.NODESET;\n@@ -23,13 +32,48 @@ public class XmlDocument extends XmlNode {\nthis.document = document;\n}\n- public ListOrSingle<XmlNode> findNodes(String xpathExpression) {\n+ public ListOrSingle<XmlNode> findNodes(String xPathExpression) {\n+ return findNodes(xPathExpression, null);\n+ }\n+\n+ public ListOrSingle<XmlNode> findNodes(String xPathExpression, Map<String, String> namespaces) {\ntry {\n- NodeList nodeSet = (NodeList) XPATH_CACHE.get().evaluate(xpathExpression, document, NODESET);\n+ final XPath xPath = XPATH_CACHE.get();\n+ xPath.reset();\n+\n+ NodeList nodeSet;\n+ if (namespaces != null) {\n+ Map<String, String> fullNamespaces = addStandardNamespaces(namespaces);\n+ NamespaceContext namespaceContext = Convert.toNamespaceContext(fullNamespaces);\n+ xPath.setNamespaceContext(namespaceContext);\n+ nodeSet = (NodeList) xPath.evaluate(xPathExpression, Convert.toInputSource(new DOMSource(document)), NODESET);\n+ } else {\n+ nodeSet = (NodeList) xPath.evaluate(xPathExpression, document, NODESET);\n+ }\n+\nreturn toListOrSingle(nodeSet);\n} catch (XPathExpressionException e) {\n- throw XmlException.fromXPathException(e);\n+ throw XPathException.fromXPathException(e);\n}\n}\n+ private static Map<String, String> addStandardNamespaces(Map<String, String> namespaces) {\n+ Map<String, String> result = new HashMap<String, String>();\n+ for (String prefix: namespaces.keySet()) {\n+ String uri = namespaces.get(prefix);\n+ // according to the Javadocs only the constants defined in\n+ // XMLConstants are allowed as prefixes for the following\n+ // two URIs\n+ if (!XMLConstants.XML_NS_URI.equals(uri)\n+ && !XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri)) {\n+ result.put(prefix, uri);\n+ }\n+ }\n+ result.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);\n+ result.put(XMLConstants.XMLNS_ATTRIBUTE,\n+ XMLConstants.XMLNS_ATTRIBUTE_NS_URI);\n+\n+ return result;\n+ }\n+\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/XmlException.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/XmlException.java",
"diff": "@@ -32,10 +32,6 @@ public class XmlException extends InvalidInputException {\nsuper(cause, errors);\n}\n- public static XmlException fromXPathException(XPathExpressionException e) {\n- return new XmlException(e, Errors.single(51, e.getMessage()));\n- }\n-\npublic static XmlException fromSaxException(SAXException e) {\nif (e instanceof SAXParseException) {\nSAXParseException spe = (SAXParseException) e;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/XmlNode.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/XmlNode.java",
"diff": "@@ -2,10 +2,10 @@ package com.github.tomakehurst.wiremock.common.xml;\nimport com.github.tomakehurst.wiremock.common.ListOrSingle;\nimport com.google.common.collect.ImmutableMap;\n-import com.sun.org.apache.xalan.internal.xsltc.trax.DOM2SAX;\nimport org.w3c.dom.NamedNodeMap;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\n+import org.xml.sax.XMLReader;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\n@@ -17,6 +17,8 @@ import javax.xml.transform.stream.StreamResult;\nimport javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathFactory;\nimport java.io.StringWriter;\n+import java.lang.reflect.Constructor;\n+import java.lang.reflect.InvocationTargetException;\nimport java.util.Collections;\nimport java.util.Map;\n@@ -56,13 +58,12 @@ public class XmlNode {\n}\n};\n- private static final boolean DOM2SAX_AVAILABLE = getDom2SaxAvailability();\n- private static boolean getDom2SaxAvailability() {\n+ private static final Class<XMLReader> DOM2SAX_XMLREADER_CLASS = getDom2SaxAvailability();\n+ private static Class<XMLReader> getDom2SaxAvailability() {\ntry {\n- Class.forName(\"com.sun.org.apache.xalan.internal.xsltc.trax.DOM2SAX\");\n- return true;\n+ return (Class<XMLReader>) Class.forName(\"com.sun.org.apache.xalan.internal.xsltc.trax.DOM2SAX\");\n} catch (ClassNotFoundException e) {\n- return false;\n+ return null;\n}\n}\n@@ -129,11 +130,16 @@ public class XmlNode {\n// unbound namespace prefixes (which can happen when you've selected an element via XPath whose namespaces are declared in a parent element).\n// For some reason Transformer is happy to do this with a SAX source, but not a DOM source.\nprivate static Source getSourceForTransform(Node node) {\n- if (DOM2SAX_AVAILABLE) {\n- DOM2SAX dom2SAX = new DOM2SAX(node);\n+ if (DOM2SAX_XMLREADER_CLASS != null) {\n+ try {\n+ Constructor<XMLReader> constructor = DOM2SAX_XMLREADER_CLASS.getConstructor(Node.class);\n+ XMLReader dom2SAX = constructor.newInstance(node);\nSAXSource saxSource = new SAXSource();\nsaxSource.setXMLReader(dom2SAX);\nreturn saxSource;\n+ } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {\n+ return new DOMSource(node);\n+ }\n}\nreturn new DOMSource(node);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesXPathPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesXPathPattern.java",
"diff": "@@ -18,27 +18,14 @@ package com.github.tomakehurst.wiremock.matching;\nimport com.fasterxml.jackson.annotation.JsonGetter;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonSerialize;\n-import com.github.tomakehurst.wiremock.common.SilentErrorHandler;\n-import com.github.tomakehurst.wiremock.common.xml.Xml;\n+import com.github.tomakehurst.wiremock.common.ListOrSingle;\n+import com.github.tomakehurst.wiremock.common.xml.*;\nimport com.google.common.collect.ImmutableMap;\n-import org.custommonkey.xmlunit.NamespaceContext;\n-import org.custommonkey.xmlunit.SimpleNamespaceContext;\n-import org.custommonkey.xmlunit.XMLUnit;\n-import org.custommonkey.xmlunit.XpathEngine;\n-import org.custommonkey.xmlunit.exceptions.XpathException;\n-import org.w3c.dom.Document;\n-import org.w3c.dom.Node;\n-import org.w3c.dom.NodeList;\n-import org.xml.sax.SAXException;\n-\n-import javax.xml.parsers.DocumentBuilder;\n-import java.io.IOException;\n-import java.io.StringReader;\n+\nimport java.util.Collections;\nimport java.util.Map;\nimport java.util.SortedSet;\n-import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\nimport static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.collect.Sets.newTreeSet;\n@@ -86,57 +73,43 @@ public class MatchesXPathPattern extends PathPattern {\n@Override\nprotected MatchResult isSimpleMatch(String value) {\n- NodeList nodeList = findXmlNodesMatching(value);\n-\n- return MatchResult.of(nodeList != null && nodeList.getLength() > 0);\n+ ListOrSingle<XmlNode> nodeList = findXmlNodes(value);\n+ return MatchResult.of(nodeList != null && nodeList.size() > 0);\n}\n@Override\nprotected MatchResult isAdvancedMatch(String value) {\n- NodeList nodeList = findXmlNodesMatching(value);\n- if (nodeList == null || nodeList.getLength() == 0) {\n+ ListOrSingle<XmlNode> nodeList = findXmlNodes(value);\n+ if (nodeList == null || nodeList.size() == 0) {\nreturn MatchResult.noMatch();\n}\nSortedSet<MatchResult> results = newTreeSet();\n- for (int i = 0; i < nodeList.getLength(); i++) {\n- Node node = nodeList.item(i);\n- String nodeValue = Xml.toStringValue(node);\n- results.add(valuePattern.match(nodeValue));\n+ for (XmlNode node: nodeList) {\n+ results.add(valuePattern.match(node.toString()));\n}\nreturn results.last();\n}\n- private NodeList findXmlNodesMatching(String value) {\n+ private ListOrSingle<XmlNode> findXmlNodes(String value) {\n// For performance reason, don't try to parse non XML value\nif (value == null || !value.trim().startsWith(\"<\")) {\nnotifier().info(String.format(\n\"Warning: failed to parse the XML document\\nXML: %s\", value));\nreturn null;\n}\n+\ntry {\n- DocumentBuilder documentBuilder = Xml.newDocumentBuilderFactory().newDocumentBuilder();\n- documentBuilder.setErrorHandler(new SilentErrorHandler());\n- Document inDocument = XMLUnit.buildDocument(documentBuilder, new StringReader(value));\n- XpathEngine simpleXpathEngine = XMLUnit.newXpathEngine();\n- if (xpathNamespaces != null) {\n- NamespaceContext namespaceContext = new SimpleNamespaceContext(xpathNamespaces);\n- simpleXpathEngine.setNamespaceContext(namespaceContext);\n- }\n- return simpleXpathEngine.getMatchingNodes(expectedValue, inDocument);\n- } catch (SAXException e) {\n+ XmlDocument xmlDocument = Xml.parse(value);\n+ return xmlDocument.findNodes(expectedValue, xpathNamespaces);\n+ } catch (XmlException e) {\nnotifier().info(String.format(\n\"Warning: failed to parse the XML document. Reason: %s\\nXML: %s\", e.getMessage(), value));\nreturn null;\n- } catch (IOException e) {\n- notifier().info(e.getMessage());\n- return null;\n- } catch (XpathException e) {\n+ } catch (XPathException e) {\nnotifier().info(\"Warning: failed to evaluate the XPath expression \" + expectedValue);\nreturn null;\n- } catch (Exception e) {\n- return throwUnchecked(e, NodeList.class);\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/common/xml/XmlTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/common/xml/XmlTest.java",
"diff": "package com.github.tomakehurst.wiremock.common.xml;\nimport com.github.tomakehurst.wiremock.common.ListOrSingle;\n-import com.sun.org.apache.xalan.internal.xsltc.trax.DOM2SAX;\n-import org.junit.Ignore;\nimport org.junit.Test;\n-import org.w3c.dom.Document;\n-import org.w3c.dom.Node;\n-\n-import javax.xml.transform.Transformer;\n-import javax.xml.transform.TransformerFactory;\n-import javax.xml.transform.sax.SAXSource;\n-import javax.xml.transform.stream.StreamResult;\n-import javax.xml.xpath.XPath;\n-import javax.xml.xpath.XPathFactory;\n-import java.io.StringWriter;\n-\n-import static javax.xml.transform.OutputKeys.INDENT;\n-import static javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION;\n-import static javax.xml.xpath.XPathConstants.NODE;\n+\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.is;\n@@ -121,31 +106,4 @@ public class XmlTest {\nassertThat(xmlNodes.toString(), is(\"<fl:inner fl:code=\\\"D1\\\" id=\\\"123\\\">Innards</fl:inner>\"));\n}\n-\n- @Ignore\n- @Test\n- public void tmp() throws Exception {\n- String xml = \"<?xml version=\\\"1.0\\\"?>\\n\" +\n- \"<things xmlns:s=\\\"https://stuff.biz\\\" id=\\\"1\\\">\\n\" +\n- \" <stuff id=\\\"1\\\"/>\\n\" +\n- \" <fl:fluff xmlns:fl=\\\"https://fluff.abc\\\" id=\\\"2\\\">\\n\" +\n- \" <fl:inner id=\\\"123\\\" fl:code=\\\"D1\\\">Innards</fl:inner>\\n\" +\n- \" <fl:inner>More Innards</fl:inner>\\n\" +\n- \" </fl:fluff>\\n\" +\n- \"</things>\";\n-\n- final Document doc = Xml.read(xml);\n- XPath xPath = XPathFactory.newInstance().newXPath();\n- Node node = (Node) xPath.evaluate(\"/things/fluff/inner\", doc, NODE);\n- StringWriter sw = new StringWriter();\n- final TransformerFactory transformerFactory = TransformerFactory.newInstance();\n- Transformer transformer = transformerFactory.newTransformer();\n- transformer.setOutputProperty(OMIT_XML_DECLARATION, \"yes\");\n- transformer.setOutputProperty(INDENT, \"yes\");\n- final DOM2SAX dom2SAX = new DOM2SAX(node);\n- final SAXSource saxSource = new SAXSource();\n- saxSource.setXMLReader(dom2SAX);\n- transformer.transform(saxSource, new StreamResult(sw));\n- System.out.println(sw.toString());\n- }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MatchesXPathPatternTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MatchesXPathPatternTest.java",
"diff": "@@ -88,12 +88,22 @@ public class MatchesXPathPatternTest {\n}\n@Test\n- public void matchesNamespacedXmlExactly() {\n+ public void matchesNamespacedXmlWhenNamespacesSpecified() {\nString xml = \"<t:thing xmlns:t='http://things' xmlns:s='http://subthings'><s:subThing>The stuff</s:subThing></t:thing>\";\nStringValuePattern pattern = WireMock.matchingXPath(\n- \"//s:subThing[.='The stuff']\",\n- ImmutableMap.of(\"s\", \"http://subthings\", \"t\", \"http://things\"));\n+ \"//sub:subThing[.='The stuff']\",\n+ ImmutableMap.of(\"sub\", \"http://subthings\", \"t\", \"http://things\"));\n+\n+ MatchResult match = pattern.match(xml);\n+ assertTrue(match.isExactMatch());\n+ }\n+\n+ @Test\n+ public void matchesNamespacedXmlFromLocalNames() {\n+ String xml = \"<t:thing xmlns:t='http://things' xmlns:s='http://subthings'><s:subThing>The stuff</s:subThing></t:thing>\";\n+\n+ StringValuePattern pattern = WireMock.matchingXPath(\"/thing/subThing[.='The stuff']\");\nMatchResult match = pattern.match(xml);\nassertTrue(match.isExactMatch());\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Switched MatchesXPathPattern to use new XmlDocument and XmlNode |
686,957 | 23.05.2020 17:12:00 | -7,200 | 7067b9af59b3c78e43ff9cb799e778aefaa2e289 | Changed to RequestTemplateModel adaptedHeaders to TreeMap with CASE_INSENSITIVE_ORDER to ignore case for headers in response templating | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/RequestTemplateModel.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/RequestTemplateModel.java",
"diff": "@@ -22,6 +22,7 @@ import com.github.tomakehurst.wiremock.http.Request;\nimport com.google.common.base.Function;\nimport com.google.common.collect.Maps;\nimport java.util.Map;\n+import java.util.TreeMap;\npublic class RequestTemplateModel {\n@@ -40,12 +41,13 @@ public class RequestTemplateModel {\npublic static RequestTemplateModel from(final Request request) {\nRequestLine requestLine = RequestLine.fromRequest(request);\n- Map<String, ListOrSingle<String>> adaptedHeaders = Maps.toMap(request.getAllHeaderKeys(), new Function<String, ListOrSingle<String>>() {\n+ Map<String, ListOrSingle<String>> adaptedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);\n+ adaptedHeaders.putAll(Maps.toMap(request.getAllHeaderKeys(), new Function<String, ListOrSingle<String>>() {\n@Override\npublic ListOrSingle<String> apply(String input) {\nreturn ListOrSingle.of(request.header(input).values());\n}\n- });\n+ }));\nMap<String, ListOrSingle<String>> adaptedCookies = Maps.transformValues(request.getCookies(), new Function<Cookie, ListOrSingle<String>>() {\n@Override\npublic ListOrSingle<String> apply(Cookie cookie) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java",
"diff": "@@ -24,6 +24,7 @@ import com.github.tomakehurst.wiremock.common.ClasspathFileSource;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+import org.hamcrest.CoreMatchers;\nimport org.junit.Before;\nimport org.junit.Test;\n@@ -89,6 +90,21 @@ public class ResponseTemplateTransformerTest {\n));\n}\n+ @Test\n+ public void requestHeadersCaseInsensitive() {\n+ ResponseDefinition transformedResponseDef = transform(mockRequest()\n+ .url(\"/things\")\n+ .header(\"Case-KEY-123\", \"foundit\"),\n+ aResponse().withBody(\n+ \"Case key header: {{request.headers.case-key-123}}, With brackets: {{request.headers.[case-key-123]}}\"\n+ )\n+ );\n+\n+ assertThat(transformedResponseDef.getBody(), CoreMatchers.is(\n+ \"Case key header: foundit, With brackets: foundit\"\n+ ));\n+ }\n+\n@Test\npublic void cookies() {\nResponseDefinition transformedResponseDef = transform(mockRequest()\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Changed to RequestTemplateModel adaptedHeaders to TreeMap with CASE_INSENSITIVE_ORDER to ignore case for headers in response templating (#1314) |
686,981 | 25.05.2020 10:22:20 | -3,600 | 57d932b97a983b5b25aeba02ddd82a34c288f5c7 | Allow WireMockClassRule to work when HTTP is disabled | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/junit/WireMockClassRule.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/junit/WireMockClassRule.java",
"diff": "@@ -64,7 +64,12 @@ public class WireMockClassRule extends WireMockServer implements MethodRule, Tes\n}\n} else {\nstart();\n- WireMock.configureFor(\"localhost\", port());\n+ if (options.getHttpDisabled()) {\n+ WireMock.configureFor(\"https\", \"localhost\", httpsPort());\n+ } else {\n+ WireMock.configureFor(\"http\", \"localhost\", port());\n+ }\n+\ntry {\nbefore();\nbase.evaluate();\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Allow WireMockClassRule to work when HTTP is disabled |
686,981 | 25.05.2020 10:43:19 | -3,600 | 37fb1abff86aba3d58e5bf4722677cacb5d72aa9 | Allow stubbing & recording of forward proxy https traffic
This allows WireMock to act as a forward (browser) proxy for HTTPS as well as
HTTP origins whilst stubbing & recording.
Step towards implementing | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -54,3 +54,19 @@ To build both JARs (thin and standalone):\nThe built JAR will be placed under ``java8/build/libs``.\n+Developing on IntelliJ IDEA\n+---------------------------\n+\n+IntelliJ can't import the gradle build script correctly automatically, so run\n+```bash\n+./gradlew -c release-settings.gradle :java8:idea\n+```\n+\n+Make sure you have no `.idea` directory, the plugin generates old style .ipr,\n+.iml & .iws metadata files.\n+\n+You may have to then set up your project SDK to point at your Java 8\n+installation.\n+\n+Then edit the module settings. Remove the \"null\" Source & Test source folders\n+from all modules. Add `wiremock` as a module dependency to Java 7 & Java 8.\n"
},
{
"change_type": "MODIFY",
"old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java",
"new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java",
"diff": "@@ -12,7 +12,13 @@ import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory;\nimport org.eclipse.jetty.http2.HTTP2Cipher;\nimport org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;\nimport org.eclipse.jetty.io.NetworkTrafficListener;\n-import org.eclipse.jetty.server.*;\n+import org.eclipse.jetty.server.HttpConfiguration;\n+import org.eclipse.jetty.server.HttpConnectionFactory;\n+import org.eclipse.jetty.server.SecureRequestCustomizer;\n+import org.eclipse.jetty.server.Server;\n+import org.eclipse.jetty.server.ServerConnector;\n+import org.eclipse.jetty.server.SslConnectionFactory;\n+import org.eclipse.jetty.server.handler.HandlerCollection;\nimport org.eclipse.jetty.util.ssl.SslContextFactory;\npublic class Jetty94HttpServer extends JettyHttpServer {\n@@ -27,39 +33,45 @@ public class Jetty94HttpServer extends JettyHttpServer {\n}\n@Override\n- protected ServerConnector createHttpsConnector(Server server, String bindAddress, HttpsSettings httpsSettings, JettySettings jettySettings, NetworkTrafficListener listener) {\n- SslContextFactory.Server http2SslContextFactory = buildHttp2SslContextFactory(httpsSettings);\n-\n- HttpConfiguration httpConfig = createHttpConfig(jettySettings);\n- httpConfig.setSecureScheme(\"https\");\n- httpConfig.setSecurePort(httpsSettings.port());\n- httpConfig.setSendXPoweredBy(false);\n- httpConfig.setSendServerVersion(false);\n- httpConfig.addCustomizer(new SecureRequestCustomizer());\n+ protected ServerConnector createHttpConnector(String bindAddress, int port, JettySettings jettySettings, NetworkTrafficListener listener) {\n- HttpConnectionFactory http = new HttpConnectionFactory(httpConfig);\n- HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(httpConfig);\n-\n- ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();\n+ ConnectionFactories connectionFactories = buildConnectionFactories(jettySettings, 0);\n+ return createServerConnector(\n+ bindAddress,\n+ jettySettings,\n+ port,\n+ listener,\n+ // http needs to be the first (the default)\n+ connectionFactories.http,\n+ // alpn & h2 are included so that HTTPS forward proxying can find them\n+ connectionFactories.alpn,\n+ connectionFactories.h2\n+ );\n+ }\n- SslConnectionFactory ssl = new SslConnectionFactory(http2SslContextFactory, alpn.getProtocol());\n+ @Override\n+ protected ServerConnector createHttpsConnector(Server server, String bindAddress, HttpsSettings httpsSettings, JettySettings jettySettings, NetworkTrafficListener listener) {\n- ConnectionFactory[] connectionFactories = new ConnectionFactory[] {\n- ssl,\n- alpn,\n- h2,\n- http\n- };\n+ ConnectionFactories connectionFactories = buildConnectionFactories(jettySettings, httpsSettings.port());\n+ SslConnectionFactory ssl = sslConnectionFactory(httpsSettings);\nreturn createServerConnector(\nbindAddress,\njettySettings,\nhttpsSettings.port(),\nlistener,\n- connectionFactories\n+ ssl,\n+ connectionFactories.alpn,\n+ connectionFactories.h2,\n+ connectionFactories.http\n);\n}\n+ private SslConnectionFactory sslConnectionFactory(HttpsSettings httpsSettings) {\n+ SslContextFactory.Server http2SslContextFactory = buildHttp2SslContextFactory(httpsSettings);\n+ return new SslConnectionFactory(http2SslContextFactory, \"alpn\");\n+ }\n+\nprivate SslContextFactory.Server buildHttp2SslContextFactory(HttpsSettings httpsSettings) {\nSslContextFactory.Server sslContextFactory = new SslContextFactory.Server();\n@@ -75,4 +87,56 @@ public class Jetty94HttpServer extends JettyHttpServer {\nsslContextFactory.setProvider(\"Conscrypt\");\nreturn sslContextFactory;\n}\n+\n+ @Override\n+ protected HttpConfiguration createHttpConfig(JettySettings jettySettings) {\n+ HttpConfiguration httpConfig = super.createHttpConfig(jettySettings);\n+ httpConfig.setSendXPoweredBy(false);\n+ httpConfig.setSendServerVersion(false);\n+ httpConfig.addCustomizer(new SecureRequestCustomizer());\n+ return httpConfig;\n+ }\n+\n+ @Override\n+ protected HandlerCollection createHandler(\n+ Options options,\n+ AdminRequestHandler adminRequestHandler,\n+ StubRequestHandler stubRequestHandler\n+ ) {\n+ HandlerCollection handler = super.createHandler(options, adminRequestHandler, stubRequestHandler);\n+\n+ ManInTheMiddleSslConnectHandler manInTheMiddleSslConnectHandler = new ManInTheMiddleSslConnectHandler(\n+ sslConnectionFactory(options.httpsSettings())\n+ );\n+\n+ handler.addHandler(manInTheMiddleSslConnectHandler);\n+\n+ return handler;\n+ }\n+\n+ private ConnectionFactories buildConnectionFactories(\n+ JettySettings jettySettings,\n+ int securePort\n+ ) {\n+ HttpConfiguration httpConfig = createHttpConfig(jettySettings);\n+ httpConfig.setSecurePort(securePort);\n+\n+ HttpConnectionFactory http = new HttpConnectionFactory(httpConfig);\n+ HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(httpConfig);\n+ ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();\n+\n+ return new ConnectionFactories(http, h2, alpn);\n+ }\n+\n+ private static class ConnectionFactories {\n+ private final HttpConnectionFactory http;\n+ private final HTTP2ServerConnectionFactory h2;\n+ private final ALPNServerConnectionFactory alpn;\n+\n+ private ConnectionFactories(HttpConnectionFactory http, HTTP2ServerConnectionFactory h2, ALPNServerConnectionFactory alpn) {\n+ this.http = http;\n+ this.h2 = h2;\n+ this.alpn = alpn;\n+ }\n+ }\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/ManInTheMiddleSslConnectHandler.java",
"diff": "+package com.github.tomakehurst.wiremock.jetty94;\n+\n+import org.eclipse.jetty.io.Connection;\n+import org.eclipse.jetty.io.EndPoint;\n+import org.eclipse.jetty.server.HttpConnection;\n+import org.eclipse.jetty.server.Request;\n+import org.eclipse.jetty.server.SslConnectionFactory;\n+import org.eclipse.jetty.server.handler.AbstractHandler;\n+\n+import javax.servlet.http.HttpServletRequest;\n+import javax.servlet.http.HttpServletResponse;\n+import java.io.IOException;\n+\n+import static org.eclipse.jetty.http.HttpMethod.CONNECT;\n+\n+/**\n+ * A Handler for the HTTP CONNECT method that, instead of opening up a\n+ * TCP tunnel between the downstream and upstream sockets,\n+ * 1) captures the\n+ * and\n+ * 2) turns the connection into an SSL connection allowing this server to handle\n+ * it.\n+ *\n+ *\n+ */\n+class ManInTheMiddleSslConnectHandler extends AbstractHandler {\n+\n+ private final SslConnectionFactory sslConnectionFactory;\n+\n+ ManInTheMiddleSslConnectHandler(SslConnectionFactory sslConnectionFactory) {\n+ this.sslConnectionFactory = sslConnectionFactory;\n+ }\n+\n+ @Override\n+ protected void doStart() throws Exception {\n+ super.doStart();\n+ sslConnectionFactory.start();\n+ }\n+\n+ @Override\n+ protected void doStop() throws Exception {\n+ super.doStop();\n+ sslConnectionFactory.stop();\n+ }\n+\n+ @Override\n+ public void handle(\n+ String target,\n+ Request baseRequest,\n+ HttpServletRequest request,\n+ HttpServletResponse response\n+ ) throws IOException {\n+ if (CONNECT.is(request.getMethod())) {\n+ baseRequest.setHandled(true);\n+ handleConnect(baseRequest, response);\n+ }\n+ }\n+\n+ private void handleConnect(\n+ Request baseRequest,\n+ HttpServletResponse response\n+ ) throws IOException {\n+ sendConnectResponse(response);\n+ final HttpConnection transport = (HttpConnection) baseRequest.getHttpChannel().getHttpTransport();\n+ EndPoint endpoint = transport.getEndPoint();\n+ Connection connection = sslConnectionFactory.newConnection(transport.getConnector(), endpoint);\n+ endpoint.setConnection(connection);\n+ connection.onOpen();\n+ }\n+\n+ private void sendConnectResponse(HttpServletResponse response) throws IOException {\n+ response.setStatus(HttpServletResponse.SC_OK);\n+ response.getOutputStream().close();\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/Http2BrowserProxyAcceptanceTest.java",
"diff": "+/*\n+ * Copyright (C) 2011 Thomas Akehurst\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.common.SingleRootFileSource;\n+import com.github.tomakehurst.wiremock.junit.WireMockClassRule;\n+import com.github.tomakehurst.wiremock.testsupport.TestFiles;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\n+import org.junit.After;\n+import org.junit.Before;\n+import org.junit.ClassRule;\n+import org.junit.Rule;\n+import org.junit.Test;\n+\n+import java.io.File;\n+import java.io.IOException;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static com.github.tomakehurst.wiremock.core.WireMockApp.FILES_ROOT;\n+import static com.github.tomakehurst.wiremock.core.WireMockApp.MAPPINGS_ROOT;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.is;\n+\n+public class Http2BrowserProxyAcceptanceTest {\n+\n+ private static final String CERTIFICATE_NOT_TRUSTED_BY_TEST_CLIENT = TestFiles.KEY_STORE_PATH;\n+\n+ @ClassRule\n+ public static WireMockClassRule target = new WireMockClassRule(wireMockConfig()\n+ .httpDisabled(true)\n+ .keystorePath(CERTIFICATE_NOT_TRUSTED_BY_TEST_CLIENT)\n+ .dynamicHttpsPort()\n+ );\n+\n+ @Rule\n+ public WireMockClassRule instanceRule = target;\n+\n+ private WireMockServer proxy;\n+ private WireMockTestClient testClient;\n+\n+ @Before\n+ public void addAResourceToProxy() {\n+ testClient = new WireMockTestClient(target.httpsPort());\n+\n+ proxy = new WireMockServer(wireMockConfig()\n+ .dynamicPort()\n+ .fileSource(new SingleRootFileSource(setupTempFileRoot()))\n+ .enableBrowserProxying(true));\n+ proxy.start();\n+ }\n+\n+ @After\n+ public void stopServer() {\n+ if (proxy.isRunning()) {\n+ proxy.stop();\n+ }\n+ }\n+\n+ @Test\n+ public void canProxyHttpsInBrowserProxyMode() throws Exception {\n+ target.stubFor(get(urlEqualTo(\"/whatever\")).willReturn(aResponse().withBody(\"Got it\")));\n+\n+ assertThat(testClient.getViaProxy(target.url(\"/whatever\"), proxy.port()).content(), is(\"Got it\"));\n+ }\n+\n+ @Test\n+ public void canStubHttpsInBrowserProxyMode() throws Exception {\n+ target.stubFor(get(urlEqualTo(\"/stubbed\")).willReturn(aResponse().withBody(\"Should Not Be Returned\")));\n+ proxy.stubFor(get(urlEqualTo(\"/stubbed\")).willReturn(aResponse().withBody(\"Stubbed Value\")));\n+ target.stubFor(get(urlEqualTo(\"/not_stubbed\")).willReturn(aResponse().withBody(\"Should be served from target\")));\n+\n+ assertThat(testClient.getViaProxy(target.url(\"/stubbed\"), proxy.port()).content(), is(\"Stubbed Value\"));\n+ assertThat(testClient.getViaProxy(target.url(\"/not_stubbed\"), proxy.port()).content(), is(\"Should be served from target\"));\n+ }\n+\n+ @Test\n+ public void canRecordHttpsInBrowserProxyMode() throws Exception {\n+\n+ // given\n+ proxy.startRecording(target.baseUrl());\n+ String recordedEndpoint = target.url(\"/record_me\");\n+\n+ // and\n+ target.stubFor(get(urlEqualTo(\"/record_me\")).willReturn(aResponse().withBody(\"Target response\")));\n+\n+ // then\n+ assertThat(testClient.getViaProxy(recordedEndpoint, proxy.port()).content(), is(\"Target response\"));\n+\n+ // when\n+ proxy.stopRecording();\n+\n+ // and\n+ target.stop();\n+\n+ // then\n+ assertThat(testClient.getViaProxy(recordedEndpoint, proxy.port()).content(), is(\"Target response\"));\n+ }\n+\n+ private static File setupTempFileRoot() {\n+ try {\n+ File root = java.nio.file.Files.createTempDirectory(\"wiremock\").toFile();\n+ new File(root, MAPPINGS_ROOT).mkdirs();\n+ new File(root, FILES_ROOT).mkdirs();\n+ return root;\n+ } catch (IOException e) {\n+ return throwUnchecked(e, File.class);\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java",
"diff": "@@ -30,7 +30,6 @@ import com.google.common.io.Resources;\nimport org.apache.commons.lang3.ArrayUtils;\nimport org.eclipse.jetty.http.MimeTypes;\nimport org.eclipse.jetty.io.NetworkTrafficListener;\n-import org.eclipse.jetty.proxy.ConnectHandler;\nimport org.eclipse.jetty.server.*;\nimport org.eclipse.jetty.server.handler.HandlerCollection;\nimport org.eclipse.jetty.server.handler.HandlerWrapper;\n@@ -129,8 +128,6 @@ public class JettyHttpServer implements HttpServer {\naddGZipHandler(mockServiceContext, handlers);\n}\n- handlers.addHandler(new ConnectHandler());\n-\nreturn handlers;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/BrowserProxyAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/BrowserProxyAcceptanceTest.java",
"diff": "@@ -27,10 +27,7 @@ import static org.hamcrest.MatcherAssert.assertThat;\npublic class BrowserProxyAcceptanceTest {\n@ClassRule\n- public static WireMockClassRule target = new WireMockClassRule(wireMockConfig()\n- .dynamicPort()\n- .dynamicHttpsPort()\n- );\n+ public static WireMockClassRule target = new WireMockClassRule(wireMockConfig().dynamicPort());\n@Rule\npublic WireMockClassRule instanceRule = target;\n@@ -62,13 +59,6 @@ public class BrowserProxyAcceptanceTest {\nassertThat(testClient.getViaProxy(url(\"/whatever\"), proxy.port()).content(), is(\"Got it\"));\n}\n- @Test\n- public void canProxyHttps() throws Exception {\n- target.stubFor(get(urlEqualTo(\"/whatever\")).willReturn(aResponse().withBody(\"Got it\")));\n-\n- assertThat(testClient.getViaProxy(httpsUrl(\"/whatever\"), proxy.port()).content(), is(\"Got it\"));\n- }\n-\n@Test\npublic void passesQueryParameters() {\ntarget.stubFor(get(urlEqualTo(\"/search?q=things&limit=10\")).willReturn(aResponse().withStatus(200)));\n@@ -80,8 +70,4 @@ public class BrowserProxyAcceptanceTest {\nreturn \"http://localhost:\" + target.port() + pathAndQuery;\n}\n- private String httpsUrl(String pathAndQuery) {\n- return \"https://localhost:\" + target.httpsPort() + pathAndQuery;\n- }\n-\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java",
"diff": "@@ -26,6 +26,8 @@ import org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\n+import java.io.IOException;\n+\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.core.Options.DYNAMIC_PORT;\nimport static org.hamcrest.Matchers.*;\n@@ -45,8 +47,11 @@ public class ResponseDribbleAcceptanceTest {\nprivate HttpClient httpClient;\n@Before\n- public void init() {\n+ public void init() throws IOException {\n+ stubFor(get(\"/warmup\").willReturn(ok()));\nhttpClient = HttpClientFactory.createClient(SOCKET_TIMEOUT_MILLISECONDS);\n+ // Warm up the server\n+ httpClient.execute(new HttpGet(String.format(\"http://localhost:%d/warmup\", wireMockRule.port())));\n}\n@Test\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java",
"diff": "@@ -113,7 +113,7 @@ public class WireMockTestClient {\n.disableAutomaticRetries()\n.disableCookieManagement()\n.disableRedirectHandling()\n- .setSSLContext(buildAllowAnythingSSLContext())\n+ .setSSLContext(buildTrustWireMockDefaultCertificateSSLContext())\n.setSSLHostnameVerifier(new NoopHostnameVerifier())\n.setProxy(proxy)\n.build();\n@@ -324,12 +324,12 @@ public class WireMockTestClient {\n.build();\n}\n- private static SSLContext buildAllowAnythingSSLContext() {\n+ private static SSLContext buildTrustWireMockDefaultCertificateSSLContext() {\ntry {\nreturn SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {\n@Override\npublic boolean isTrusted(X509Certificate[] chain, String authType) {\n- return true;\n+ return \"CN=Tom Akehurst, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown\".equals(chain[0].getSubjectDN().getName());\n}\n}).build();\n} catch (Exception e) {\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Allow stubbing & recording of forward proxy https traffic
This allows WireMock to act as a forward (browser) proxy for HTTPS as well as
HTTP origins whilst stubbing & recording.
Step towards implementing #401. |
686,981 | 25.05.2020 10:47:13 | -3,600 | 75d00c8901dd1226b20f73c92153cc259253c593 | Finish half written JavaDoc | [
{
"change_type": "MODIFY",
"old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/ManInTheMiddleSslConnectHandler.java",
"new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/ManInTheMiddleSslConnectHandler.java",
"diff": "@@ -15,13 +15,8 @@ import static org.eclipse.jetty.http.HttpMethod.CONNECT;\n/**\n* A Handler for the HTTP CONNECT method that, instead of opening up a\n- * TCP tunnel between the downstream and upstream sockets,\n- * 1) captures the\n- * and\n- * 2) turns the connection into an SSL connection allowing this server to handle\n- * it.\n- *\n- *\n+ * TCP tunnel between the downstream and upstream sockets, turns the connection\n+ * into an SSL connection allowing this server to handle it.\n*/\nclass ManInTheMiddleSslConnectHandler extends AbstractHandler {\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Finish half written JavaDoc |
686,981 | 26.05.2020 16:54:06 | -3,600 | c7b540308c34f92f462f8a65fc9b481cb5b89a82 | Simplify code & prove it works over https
But not over http2 | [
{
"change_type": "MODIFY",
"old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/ManInTheMiddleSslConnectHandler.java",
"new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/ManInTheMiddleSslConnectHandler.java",
"diff": "@@ -2,7 +2,8 @@ package com.github.tomakehurst.wiremock.jetty94;\nimport org.eclipse.jetty.io.Connection;\nimport org.eclipse.jetty.io.EndPoint;\n-import org.eclipse.jetty.server.HttpConnection;\n+import org.eclipse.jetty.server.Connector;\n+import org.eclipse.jetty.server.HttpChannel;\nimport org.eclipse.jetty.server.Request;\nimport org.eclipse.jetty.server.SslConnectionFactory;\nimport org.eclipse.jetty.server.handler.AbstractHandler;\n@@ -56,10 +57,16 @@ class ManInTheMiddleSslConnectHandler extends AbstractHandler {\nHttpServletResponse response\n) throws IOException {\nsendConnectResponse(response);\n- final HttpConnection transport = (HttpConnection) baseRequest.getHttpChannel().getHttpTransport();\n- EndPoint endpoint = transport.getEndPoint();\n- Connection connection = sslConnectionFactory.newConnection(transport.getConnector(), endpoint);\n+\n+ HttpChannel httpChannel = baseRequest.getHttpChannel();\n+ Connector connector = httpChannel.getConnector();\n+ EndPoint endpoint = httpChannel.getEndPoint();\n+ endpoint.setConnection(null);\n+\n+ Connection connection = sslConnectionFactory.newConnection(connector, endpoint);\nendpoint.setConnection(connection);\n+\n+ endpoint.onOpen();\nconnection.onOpen();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/Http2BrowserProxyAcceptanceTest.java",
"new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/Http2BrowserProxyAcceptanceTest.java",
"diff": "@@ -18,10 +18,17 @@ package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.common.SingleRootFileSource;\nimport com.github.tomakehurst.wiremock.junit.WireMockClassRule;\nimport com.github.tomakehurst.wiremock.testsupport.TestFiles;\n+import com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\n+import org.eclipse.jetty.client.HttpClient;\n+import org.eclipse.jetty.client.HttpProxy;\n+import org.eclipse.jetty.client.Origin;\n+import org.eclipse.jetty.client.ProxyConfiguration;\n+import org.eclipse.jetty.client.api.ContentResponse;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.ClassRule;\n+import org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\n@@ -59,6 +66,7 @@ public class Http2BrowserProxyAcceptanceTest {\nproxy = new WireMockServer(wireMockConfig()\n.dynamicPort()\n+ .dynamicHttpsPort()\n.fileSource(new SingleRootFileSource(setupTempFileRoot()))\n.enableBrowserProxying(true));\nproxy.start();\n@@ -78,6 +86,28 @@ public class Http2BrowserProxyAcceptanceTest {\nassertThat(testClient.getViaProxy(target.url(\"/whatever\"), proxy.port()).content(), is(\"Got it\"));\n}\n+ @Test\n+ public void canProxyHttpsInBrowserHttpsProxyMode() throws Exception {\n+ target.stubFor(get(urlEqualTo(\"/whatever\")).willReturn(aResponse().withBody(\"Got it\")));\n+\n+ WireMockResponse response = testClient.getViaProxy(target.url(\"/whatever\"), proxy.httpsPort(), \"https\");\n+ assertThat(response.content(), is(\"Got it\"));\n+ }\n+\n+ @Test @Ignore(\"Jetty doesn't yet support proxying via HTTP2\")\n+ public void canProxyHttpsUsingHttp2InBrowserHttpsProxyMode() throws Exception {\n+\n+ HttpClient httpClient = Http2ClientFactory.create();\n+ ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration();\n+ HttpProxy httpProxy = new HttpProxy(new Origin.Address(\"localhost\", proxy.httpsPort()), true);\n+ proxyConfig.getProxies().add(httpProxy);\n+\n+ target.stubFor(get(urlEqualTo(\"/whatever\")).willReturn(aResponse().withBody(\"Got it\")));\n+\n+ ContentResponse response = httpClient.GET(target.url(\"/whatever\"));\n+ assertThat(response.getContentAsString(), is(\"Got it\"));\n+ }\n+\n@Test\npublic void canStubHttpsInBrowserProxyMode() throws Exception {\ntarget.stubFor(get(urlEqualTo(\"/stubbed\")).willReturn(aResponse().withBody(\"Should Not Be Returned\")));\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java",
"diff": "@@ -106,8 +106,12 @@ public class WireMockTestClient {\n}\npublic WireMockResponse getViaProxy(String url, int proxyPort) {\n+ return getViaProxy(url, proxyPort, HttpHost.DEFAULT_SCHEME_NAME);\n+ }\n+\n+ public WireMockResponse getViaProxy(String url, int proxyPort, String scheme) {\nURI targetUri = URI.create(url);\n- HttpHost proxy = new HttpHost(address, proxyPort);\n+ HttpHost proxy = new HttpHost(address, proxyPort, scheme);\nHttpClient httpClientUsingProxy = HttpClientBuilder.create()\n.disableAuthCaching()\n.disableAutomaticRetries()\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Simplify code & prove it works over https
But not over http2 |
686,936 | 28.05.2020 11:22:27 | -3,600 | be8934c1c2b0be0be372cb86a537d99654ee29bc | Marked two methods as private in the Xml class now that they are not used anywhere else | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/Xml.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/Xml.java",
"diff": "@@ -129,7 +129,7 @@ public class Xml {\n}\n}\n- public static String render(Node node) {\n+ private static String render(Node node) {\ntry {\nStringWriter sw = new StringWriter();\nTransformer transformer = TransformerFactory.newInstance().newTransformer();\n@@ -142,7 +142,16 @@ public class Xml {\n}\n}\n- public static DocumentBuilder getDocumentBuilder() {\n+ public static XmlDocument parse(String xml) {\n+ try {\n+ InputSource source = new InputSource(new StringReader(xml));\n+ return new XmlDocument(getDocumentBuilder().parse(source));\n+ } catch (SAXException | IOException e) {\n+ throw new XmlException(Errors.single(50, e.getMessage()));\n+ }\n+ }\n+\n+ private static DocumentBuilder getDocumentBuilder() {\ntry {\nreturn newDocumentBuilderFactory().newDocumentBuilder();\n} catch (ParserConfigurationException e) {\n@@ -154,15 +163,6 @@ public class Xml {\nreturn new SkipResolvingEntitiesDocumentBuilderFactory();\n}\n- public static XmlDocument parse(String xml) {\n- try {\n- InputSource source = new InputSource(new StringReader(xml));\n- return new XmlDocument(getDocumentBuilder().parse(source));\n- } catch (SAXException | IOException e) {\n- throw new XmlException(Errors.single(50, e.getMessage()));\n- }\n- }\n-\nprivate static class SkipResolvingEntitiesDocumentBuilderFactory extends DocumentBuilderFactory {\nprivate static final ThreadLocal<DocumentBuilderFactory> DBF_CACHE = new ThreadLocal<DocumentBuilderFactory>() {\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Marked two methods as private in the Xml class now that they are not used anywhere else |
686,936 | 28.05.2020 11:48:16 | -3,600 | a295984f19053d43c03cfa29941b59dc434bef69 | Refactored the XPath helper to use XmlDocument and XmlNode | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java",
"diff": "package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\nimport com.github.jknack.handlebars.Options;\n-import com.github.tomakehurst.wiremock.common.xml.Xml;\n+import com.github.tomakehurst.wiremock.common.ListOrSingle;\n+import com.github.tomakehurst.wiremock.common.xml.*;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.RenderCache;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Node;\n@@ -41,26 +42,6 @@ import static javax.xml.xpath.XPathConstants.NODE;\n*/\npublic class HandlebarsXPathHelper extends HandlebarsHelper<String> {\n- private static final InheritableThreadLocal<XPath> localXPath = new InheritableThreadLocal<XPath>() {\n- @Override\n- protected XPath initialValue() {\n- final XPathFactory xPathfactory = XPathFactory.newInstance();\n- return xPathfactory.newXPath();\n- }\n- };\n-\n- private static final InheritableThreadLocal<DocumentBuilder> localDocBuilder = new InheritableThreadLocal<DocumentBuilder>() {\n- @Override\n- protected DocumentBuilder initialValue() {\n- final DocumentBuilderFactory factory = Xml.newDocumentBuilderFactory();\n- try {\n- return factory.newDocumentBuilder();\n- } catch (ParserConfigurationException e) {\n- return throwUnchecked(e, DocumentBuilder.class);\n- }\n- }\n- };\n-\n@Override\npublic Object apply(final String inputXml, final Options options) throws IOException {\nif (inputXml == null ) {\n@@ -73,51 +54,48 @@ public class HandlebarsXPathHelper extends HandlebarsHelper<String> {\nfinal String xPathInput = options.param(0);\n- Document doc;\n+ XmlDocument xmlDocument;\ntry {\n- doc = getDocument(inputXml, options);\n- } catch (SAXException se) {\n+ xmlDocument = getXmlDocument(inputXml, options);\n+ } catch (XmlException e) {\nreturn handleError(inputXml + \" is not valid XML\");\n}\ntry {\n- Node node = getNode(getXPathPrefix() + xPathInput, doc, options);\n+ XmlNode xmlNode = getXmlNode(getXPathPrefix() + xPathInput, xmlDocument, options);\n- if (node == null) {\n+ if (xmlNode == null) {\nreturn \"\";\n}\n- return Xml.toStringValue(node);\n- } catch (XPathExpressionException e) {\n+ return xmlNode.toString();\n+ } catch (XPathException e) {\nreturn handleError(xPathInput + \" is not a valid XPath expression\", e);\n}\n}\n- private Node getNode(String xPathExpression, Document doc, Options options) throws XPathExpressionException {\n+ private XmlNode getXmlNode(String xPathExpression, XmlDocument doc, Options options) {\nRenderCache renderCache = getRenderCache(options);\n- RenderCache.Key cacheKey = RenderCache.Key.keyFor(Document.class, xPathExpression, doc);\n- Node node = renderCache.get(cacheKey);\n+ RenderCache.Key cacheKey = RenderCache.Key.keyFor(XmlDocument.class, xPathExpression, doc);\n+ XmlNode node = renderCache.get(cacheKey);\nif (node == null) {\n- XPath xPath = localXPath.get();\n- node = (Node) xPath.evaluate(xPathExpression, doc, NODE);\n+ ListOrSingle<XmlNode> nodes = doc.findNodes(xPathExpression);\n+ node = nodes.isEmpty() ? null : nodes.getFirst();\nrenderCache.put(cacheKey, node);\n}\nreturn node;\n}\n- private Document getDocument(String xml, Options options) throws SAXException, IOException {\n+ private XmlDocument getXmlDocument(String xml, Options options) {\nRenderCache renderCache = getRenderCache(options);\n- RenderCache.Key cacheKey = RenderCache.Key.keyFor(Document.class, xml);\n- Document document = renderCache.get(cacheKey);\n+ RenderCache.Key cacheKey = RenderCache.Key.keyFor(XmlDocument.class, xml);\n+ XmlDocument document = renderCache.get(cacheKey);\nif (document == null) {\n- try (final StringReader reader = new StringReader(xml)) {\n- InputSource source = new InputSource(reader);\n- document = localDocBuilder.get().parse(source);\n+ document = Xml.parse(xml);\nrenderCache.put(cacheKey, document);\n}\n- }\nreturn document;\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Refactored the XPath helper to use XmlDocument and XmlNode |
686,936 | 28.05.2020 13:19:07 | -3,600 | 19e0f03125c96fe347f0b0ededaf0ff9b209bf15 | XPath handlebars helper now returns lists of nodes that can be iterated over, attributes read etc. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/XmlNode.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/xml/XmlNode.java",
"diff": "@@ -100,6 +100,14 @@ public class XmlNode {\nreturn nodes;\n}\n+ public String getName() {\n+ return domNode.getNodeName();\n+ }\n+\n+ public String getText() {\n+ return domNode.getTextContent();\n+ }\n+\n@Override\npublic String toString() {\nswitch (domNode.getNodeType()) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelper.java",
"diff": "@@ -19,22 +19,8 @@ import com.github.jknack.handlebars.Options;\nimport com.github.tomakehurst.wiremock.common.ListOrSingle;\nimport com.github.tomakehurst.wiremock.common.xml.*;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.RenderCache;\n-import org.w3c.dom.Document;\n-import org.w3c.dom.Node;\n-import org.xml.sax.InputSource;\n-import org.xml.sax.SAXException;\n-\n-import javax.xml.parsers.DocumentBuilder;\n-import javax.xml.parsers.DocumentBuilderFactory;\n-import javax.xml.parsers.ParserConfigurationException;\n-import javax.xml.xpath.XPath;\n-import javax.xml.xpath.XPathExpressionException;\n-import javax.xml.xpath.XPathFactory;\n-import java.io.IOException;\n-import java.io.StringReader;\n-import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n-import static javax.xml.xpath.XPathConstants.NODE;\n+import java.io.IOException;\n/**\n* This class uses javax.xml.xpath.* for reading a xml via xPath so that the result can be used for response\n@@ -62,30 +48,29 @@ public class HandlebarsXPathHelper extends HandlebarsHelper<String> {\n}\ntry {\n- XmlNode xmlNode = getXmlNode(getXPathPrefix() + xPathInput, xmlDocument, options);\n+ ListOrSingle<XmlNode> xmlNodes = getXmlNodes(getXPathPrefix() + xPathInput, xmlDocument, options);\n- if (xmlNode == null) {\n+ if (xmlNodes == null || xmlNodes.isEmpty()) {\nreturn \"\";\n}\n- return xmlNode.toString();\n+ return xmlNodes;\n} catch (XPathException e) {\nreturn handleError(xPathInput + \" is not a valid XPath expression\", e);\n}\n}\n- private XmlNode getXmlNode(String xPathExpression, XmlDocument doc, Options options) {\n+ private ListOrSingle<XmlNode> getXmlNodes(String xPathExpression, XmlDocument doc, Options options) {\nRenderCache renderCache = getRenderCache(options);\nRenderCache.Key cacheKey = RenderCache.Key.keyFor(XmlDocument.class, xPathExpression, doc);\n- XmlNode node = renderCache.get(cacheKey);\n+ ListOrSingle<XmlNode> nodes = renderCache.get(cacheKey);\n- if (node == null) {\n- ListOrSingle<XmlNode> nodes = doc.findNodes(xPathExpression);\n- node = nodes.isEmpty() ? null : nodes.getFirst();\n- renderCache.put(cacheKey, node);\n+ if (nodes == null) {\n+ nodes = doc.findNodes(xPathExpression);\n+ renderCache.put(cacheKey, nodes);\n}\n- return node;\n+ return nodes;\n}\nprivate XmlDocument getXmlDocument(String xml, Options options) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelperTestBase.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsHelperTestBase.java",
"diff": "@@ -19,6 +19,7 @@ import com.github.jknack.handlebars.Context;\nimport com.github.jknack.handlebars.Helper;\nimport com.github.jknack.handlebars.Options;\nimport com.github.tomakehurst.wiremock.extension.responsetemplating.RenderCache;\n+import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\nimport org.hamcrest.Matcher;\nimport org.junit.Assert;\nimport org.junit.Before;\n@@ -31,10 +32,12 @@ import static org.hamcrest.MatcherAssert.assertThat;\npublic abstract class HandlebarsHelperTestBase {\n+ protected ResponseTemplateTransformer transformer;\nprotected RenderCache renderCache;\n@Before\npublic void initRenderCache() {\n+ transformer = new ResponseTemplateTransformer(true);\nrenderCache = new RenderCache();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelperTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsJsonPathHelperTest.java",
"diff": "@@ -42,13 +42,10 @@ import static org.hamcrest.MatcherAssert.assertThat;\npublic class HandlebarsJsonPathHelperTest extends HandlebarsHelperTestBase {\nprivate HandlebarsJsonPathHelper helper;\n- private ResponseTemplateTransformer transformer;\n@Before\npublic void init() {\nhelper = new HandlebarsJsonPathHelper();\n- transformer = new ResponseTemplateTransformer(true);\n-\nLocalNotifier.set(new ConsoleNotifier(true));\n}\n@@ -99,8 +96,7 @@ public class HandlebarsJsonPathHelperTest extends HandlebarsHelperTestBase {\n\" ]\\n\" +\n\"}\"),\naResponse()\n- .withBody(\"\" +\n- \"{{#each (jsonPath request.body '$.items') as |item|}}{{item.name}} {{/each}}\")\n+ .withBody(\"{{#each (jsonPath request.body '$.items') as |item|}}{{item.name}} {{/each}}\")\n.build(),\nnoFileSource(),\nParameters.empty());\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelperTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HandlebarsXPathHelperTest.java",
"diff": "package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\n-import com.github.tomakehurst.wiremock.extension.responsetemplating.RenderCache;\n-import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n-import com.github.tomakehurst.wiremock.testsupport.WireMatchers;\n-import org.jmock.Expectations;\n-import org.jmock.Mockery;\n-import org.jmock.integration.junit4.JMock;\nimport org.junit.Before;\nimport org.junit.Test;\n-import org.junit.runner.RunWith;\nimport java.io.IOException;\n@@ -33,20 +26,17 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static com.github.tomakehurst.wiremock.testsupport.NoFileSource.noFileSource;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalToXml;\n+import static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.is;\nimport static org.hamcrest.Matchers.startsWith;\n-import static org.jmock.Expectations.anything;\n-import static org.hamcrest.MatcherAssert.assertThat;\npublic class HandlebarsXPathHelperTest extends HandlebarsHelperTestBase {\nprivate HandlebarsXPathHelper helper;\n- private ResponseTemplateTransformer transformer;\n@Before\npublic void init() {\nhelper = new HandlebarsXPathHelper();\n- this.transformer = new ResponseTemplateTransformer(true);\n}\n@Test\n@@ -116,8 +106,8 @@ public class HandlebarsXPathHelperTest extends HandlebarsHelperTestBase {\n@Test\npublic void returnsCorrectResultWhenSameExpressionUsedTwiceOnIdenticalDocuments() throws Exception {\n- String one = renderHelperValue(helper, \"<test>one</test>\", \"/test/text()\");\n- String two = renderHelperValue(helper, \"<test>one</test>\", \"/test/text()\");\n+ String one = renderHelperValue(helper, \"<test>one</test>\", \"/test/text()\").toString();\n+ String two = renderHelperValue(helper, \"<test>one</test>\", \"/test/text()\").toString();\nassertThat(one, is(\"one\"));\nassertThat(two, is(\"one\"));\n@@ -125,8 +115,8 @@ public class HandlebarsXPathHelperTest extends HandlebarsHelperTestBase {\n@Test\npublic void returnsCorrectResultWhenSameExpressionUsedTwiceOnDifferentDocuments() throws Exception {\n- String one = renderHelperValue(helper, \"<test>one</test>\", \"/test/text()\");\n- String two = renderHelperValue(helper, \"<test>two</test>\", \"/test/text()\");\n+ String one = renderHelperValue(helper, \"<test>one</test>\", \"/test/text()\").toString();\n+ String two = renderHelperValue(helper, \"<test>two</test>\", \"/test/text()\").toString();\nassertThat(one, is(\"one\"));\nassertThat(two, is(\"two\"));\n@@ -134,11 +124,117 @@ public class HandlebarsXPathHelperTest extends HandlebarsHelperTestBase {\n@Test\npublic void returnsCorrectResultWhenDifferentExpressionsUsedOnSameDocument() throws Exception {\n- String one = renderHelperValue(helper, \"<test><one>1</one><two>2</two></test>\", \"/test/one/text()\");\n- String two = renderHelperValue(helper, \"<test><one>1</one><two>2</two></test>\", \"/test/two/text()\");\n+ String one = renderHelperValue(helper, \"<test><one>1</one><two>2</two></test>\", \"/test/one/text()\").toString();\n+ String two = renderHelperValue(helper, \"<test><one>1</one><two>2</two></test>\", \"/test/two/text()\").toString();\nassertThat(one, is(\"1\"));\nassertThat(two, is(\"2\"));\n}\n+ @Test\n+ public void rendersXmlWhenElementIsSelected() throws Exception {\n+ String one = renderHelperValue(helper, \"<test><one>1</one><two>2</two></test>\", \"/test/one\").toString();\n+ assertThat(one, is(\"<one>1</one>\"));\n+ }\n+\n+ @Test\n+ public void supportsIterationOverNodeListWithEachHelper() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest()\n+ .body(\"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<stuff>\\n\" +\n+ \" <thing>One</thing>\\n\" +\n+ \" <thing>Two</thing>\\n\" +\n+ \" <thing>Three</thing>\\n\" +\n+ \"</stuff>\"),\n+ aResponse()\n+ .withBody(\"{{#each (xPath request.body '/stuff/thing/text()') as |thing|}}{{thing}} {{/each}}\")\n+ .build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ assertThat(responseDefinition.getBody(), is(\"One Two Three \"));\n+ }\n+\n+ @Test\n+ public void supportsIterationOverElementsWithAttributes() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest()\n+ .body(\"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<stuff>\\n\" +\n+ \" <thing id=\\\"1\\\">One</thing>\\n\" +\n+ \" <thing id=\\\"2\\\">Two</thing>\\n\" +\n+ \" <thing id=\\\"3\\\">Three</thing>\\n\" +\n+ \"</stuff>\"),\n+ aResponse()\n+ .withBody(\"{{#each (xPath request.body '/stuff/thing') as |thing|}}{{{thing.attributes.id}}} {{/each}}\")\n+ .build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ assertThat(responseDefinition.getBody(), is(\"1 2 3 \"));\n+ }\n+\n+ @Test\n+ public void supportsIterationOverNamespacedElements() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest()\n+ .body(\"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<stuff xmlns:th=\\\"https://thing.com\\\">\\n\" +\n+ \" <th:thing>One</th:thing>\\n\" +\n+ \" <th:thing>Two</th:thing>\\n\" +\n+ \" <th:thing>Three</th:thing>\\n\" +\n+ \"</stuff>\"),\n+ aResponse()\n+ .withBody(\"{{#each (xPath request.body '/stuff/thing') as |thing|}}{{{thing.text}}} {{/each}}\")\n+ .build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ assertThat(responseDefinition.getBody(), is(\"One Two Three \"));\n+ }\n+\n+ @Test\n+ public void rendersNamespacedElement() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest()\n+ .body(\"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<stuff xmlns:th=\\\"https://thing.com\\\">\\n\" +\n+ \" <th:thing>One</th:thing>\\n\" +\n+ \" <th:thing>Two</th:thing>\\n\" +\n+ \" <th:thing>Three</th:thing>\\n\" +\n+ \"</stuff>\"),\n+ aResponse()\n+ .withBody(\"{{{xPath request.body '/stuff'}}}\")\n+ .build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ assertThat(responseDefinition.getBody(), is(\n+ \"<stuff xmlns:th=\\\"https://thing.com\\\">\\n\" +\n+ \" <th:thing>One</th:thing>\\n\" +\n+ \" <th:thing>Two</th:thing>\\n\" +\n+ \" <th:thing>Three</th:thing>\\n\" +\n+ \"</stuff>\"));\n+ }\n+\n+ @Test\n+ public void rendersElementNames() {\n+ final ResponseDefinition responseDefinition = this.transformer.transform(\n+ mockRequest()\n+ .body(\"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<stuff>\\n\" +\n+ \" <one>1</one>\\n\" +\n+ \" <two>2</two>\\n\" +\n+ \" <three>3</three>\\n\" +\n+ \"</stuff>\"),\n+ aResponse()\n+ .withBody(\"{{#each (xPath request.body '/stuff/*') as |thing|}}{{{thing.name}}} {{/each}}\")\n+ .build(),\n+ noFileSource(),\n+ Parameters.empty());\n+\n+ assertThat(responseDefinition.getBody(), is(\"one two three \"));\n+ }\n+\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | XPath handlebars helper now returns lists of nodes that can be iterated over, attributes read etc. |
686,936 | 28.05.2020 15:01:19 | -3,600 | 461dd85e2248d2ebe84599f93da60d3631fca6ba | Switched out deprecated assertions in EqualToXmlPatternTest | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPatternTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPatternTest.java",
"diff": "@@ -34,6 +34,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.equalToXml;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.hamcrest.CoreMatchers.not;\n+import static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.*;\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Switched out deprecated assertions in EqualToXmlPatternTest |
686,981 | 28.05.2020 17:17:22 | -3,600 | 3545fa1ef91ce96fab8102ca3721c22de581771d | Rename poorly named test | [
{
"change_type": "RENAME",
"old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/Http2BrowserProxyAcceptanceTest.java",
"new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java",
"diff": "@@ -43,7 +43,7 @@ import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMoc\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.is;\n-public class Http2BrowserProxyAcceptanceTest {\n+public class HttpsBrowserProxyAcceptanceTest {\nprivate static final String CERTIFICATE_NOT_TRUSTED_BY_TEST_CLIENT = TestFiles.KEY_STORE_PATH;\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Rename poorly named test |
686,981 | 25.05.2020 15:26:20 | -3,600 | 3d7ad8a00b747f8e74af9e93e55879fb9114625f | Prove no validation of origin certificates | [
{
"change_type": "MODIFY",
"old_path": "java8/build.gradle",
"new_path": "java8/build.gradle",
"diff": "@@ -11,6 +11,7 @@ dependencies {\ncompile \"org.eclipse.jetty:jetty-alpn-server:$jettyVersion\"\ncompile \"org.eclipse.jetty:jetty-alpn-conscrypt-server:$jettyVersion\"\ncompile \"org.eclipse.jetty:jetty-alpn-conscrypt-client:$jettyVersion\"\n+ compile 'org.conscrypt:conscrypt-openjdk-uber:2.4.0'\ncompile 'net.javacrumbs.json-unit:json-unit-core:2.12.0'\ntestCompile \"org.eclipse.jetty:jetty-client:$jettyVersion\"\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/CertificateSpecification.java",
"diff": "+package com.github.tomakehurst.wiremock.crypto;\n+\n+import java.security.InvalidKeyException;\n+import java.security.KeyPair;\n+import java.security.SignatureException;\n+import java.security.cert.CertificateException;\n+import java.security.cert.X509Certificate;\n+\n+public interface CertificateSpecification {\n+ X509Certificate certificateFor(KeyPair keyPair) throws CertificateException, InvalidKeyException, SignatureException;\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/InMemoryKeyStore.java",
"diff": "+package com.github.tomakehurst.wiremock.crypto;\n+\n+import java.io.File;\n+import java.io.FileOutputStream;\n+import java.io.IOException;\n+import java.security.InvalidKeyException;\n+import java.security.KeyPair;\n+import java.security.KeyStore;\n+import java.security.KeyStoreException;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.SignatureException;\n+import java.security.cert.Certificate;\n+import java.security.cert.CertificateException;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static java.util.Objects.requireNonNull;\n+\n+public class InMemoryKeyStore {\n+\n+ public enum KeyStoreType {\n+ JKS(\"jks\");\n+\n+ private final String type;\n+\n+ KeyStoreType(String type) {\n+ this.type = type;\n+ }\n+ }\n+\n+ private final Secret password;\n+ private final KeyStore keyStore;\n+\n+ public InMemoryKeyStore(\n+ KeyStoreType type,\n+ Secret password\n+ ) {\n+ this.password = requireNonNull(password, \"password\");\n+ this.keyStore = initialise(requireNonNull(type, \"type\"));\n+ }\n+\n+ private KeyStore initialise(KeyStoreType type) {\n+ try {\n+ KeyStore keyStore = KeyStore.getInstance(type.type);\n+ keyStore.load(null, password.getValue());\n+ return keyStore;\n+ } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+\n+ public void addPrivateKey(String alias, KeyPair keyPair, CertificateSpecification specification) throws KeyStoreException, CertificateException, InvalidKeyException, SignatureException {\n+ Certificate cert = specification.certificateFor(keyPair);\n+ keyStore.setKeyEntry(alias, keyPair.getPrivate(), password.getValue(), new Certificate[] { cert });\n+ }\n+\n+ public void saveAs(File file) throws IOException {\n+ try (FileOutputStream fos = new FileOutputStream(file)) {\n+ try {\n+ keyStore.store(fos, password.getValue());\n+ } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) {\n+ throwUnchecked(e);\n+ }\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/Secret.java",
"diff": "+package com.github.tomakehurst.wiremock.crypto;\n+\n+import java.util.Arrays;\n+\n+import static java.util.Arrays.copyOf;\n+import static java.util.Arrays.fill;\n+import static java.util.Objects.requireNonNull;\n+\n+public class Secret implements AutoCloseable {\n+\n+ private static final char[] EMPTY_VALUE = new char[0];\n+ private volatile char[] value;\n+\n+ public Secret(char[] value) {\n+ requireNonNull(value, \"Secret value may not be null\");\n+\n+ this.value = copyOf(value, value.length);\n+ }\n+\n+ public Secret(String value) {\n+ this(null == value ? null : value.toCharArray());\n+ }\n+\n+ public char[] getValue() {\n+ return Arrays.copyOf(value, value.length);\n+ }\n+\n+ @Override\n+ public void close() {\n+ if (EMPTY_VALUE == value)\n+ return;\n+\n+ char[] tempValue = value;\n+ value = EMPTY_VALUE;\n+\n+ fill(tempValue, (char) 0x00);\n+ }\n+\n+ public boolean compareTo(String password) {\n+ if (password == null) {\n+ return false;\n+ }\n+\n+ return Arrays.equals(password.toCharArray(), value);\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/X509CertificateSpecification.java",
"diff": "+package com.github.tomakehurst.wiremock.crypto;\n+\n+import sun.security.x509.AlgorithmId;\n+import sun.security.x509.CertificateAlgorithmId;\n+import sun.security.x509.CertificateSerialNumber;\n+import sun.security.x509.CertificateValidity;\n+import sun.security.x509.CertificateX509Key;\n+import sun.security.x509.X500Name;\n+import sun.security.x509.X509CertImpl;\n+import sun.security.x509.X509CertInfo;\n+\n+import java.io.IOException;\n+import java.math.BigInteger;\n+import java.security.InvalidKeyException;\n+import java.security.KeyPair;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.NoSuchProviderException;\n+import java.security.SecureRandom;\n+import java.security.SignatureException;\n+import java.security.cert.CertificateException;\n+import java.security.cert.X509Certificate;\n+import java.util.Date;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static java.util.Objects.requireNonNull;\n+\n+public class X509CertificateSpecification implements CertificateSpecification {\n+\n+ private final X509CertificateVersion version;\n+ private final String subject;\n+ private final String issuer;\n+ // java.time is JDK8 on\n+ private final Date notBefore;\n+ private final Date notAfter;\n+\n+ public X509CertificateSpecification(\n+ X509CertificateVersion version,\n+ String subject,\n+ String issuer,\n+ Date notBefore,\n+ Date notAfter\n+ ) {\n+ this.version = requireNonNull(version);\n+ this.subject = requireNonNull(subject);\n+ this.issuer = requireNonNull(issuer);\n+ this.notBefore = requireNonNull(notBefore);\n+ this.notAfter = requireNonNull(notAfter);\n+ }\n+\n+ @Override\n+ public X509Certificate certificateFor(KeyPair keyPair) throws CertificateException, InvalidKeyException, SignatureException {\n+ try {\n+ SecureRandom random = new SecureRandom();\n+\n+ X509CertInfo info = new X509CertInfo();\n+ info.set(X509CertInfo.VERSION, version.getVersion());\n+ info.set(X509CertInfo.SUBJECT, new X500Name(subject));\n+ info.set(X509CertInfo.ISSUER, new X500Name(issuer));\n+ info.set(X509CertInfo.VALIDITY, new CertificateValidity(notBefore, notAfter));\n+\n+ info.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));\n+ info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(64, random)));\n+ info.set(X509CertInfo.ALGORITHM_ID,\n+ new CertificateAlgorithmId(new AlgorithmId(AlgorithmId.sha1WithRSAEncryption_oid)));\n+\n+ // Sign the cert to identify the algorithm that's used.\n+ X509CertImpl cert = new X509CertImpl(info);\n+ cert.sign(keyPair.getPrivate(), \"SHA256withRSA\");\n+\n+ // Update the algorithm and sign again.\n+ info.set(CertificateAlgorithmId.NAME + '.' + CertificateAlgorithmId.ALGORITHM, cert.get(X509CertImpl.SIG_ALG));\n+ cert = new X509CertImpl(info);\n+ cert.sign(keyPair.getPrivate(), \"SHA256withRSA\");\n+ cert.verify(keyPair.getPublic());\n+\n+ return cert;\n+ } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException e) {\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/X509CertificateVersion.java",
"diff": "+package com.github.tomakehurst.wiremock.crypto;\n+\n+import sun.security.x509.CertificateVersion;\n+\n+import java.io.IOException;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+\n+public enum X509CertificateVersion {\n+\n+ V1(CertificateVersion.V1),\n+ V2(CertificateVersion.V2),\n+ V3(CertificateVersion.V3);\n+\n+ private final CertificateVersion version;\n+\n+ X509CertificateVersion(int version) {\n+ this.version = getVersion(version);\n+ }\n+\n+ private static CertificateVersion getVersion(int version) {\n+ try {\n+ return new CertificateVersion(version);\n+ } catch (IOException e) {\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+\n+ public CertificateVersion getVersion() {\n+ return version;\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java",
"diff": "+package com.github.tomakehurst.wiremock.http;\n+\n+import com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.common.ProxySettings;\n+import com.github.tomakehurst.wiremock.crypto.InMemoryKeyStore;\n+import com.github.tomakehurst.wiremock.crypto.Secret;\n+import com.github.tomakehurst.wiremock.crypto.X509CertificateSpecification;\n+import com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\n+import com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n+import com.github.tomakehurst.wiremock.stubbing.StubMapping;\n+import com.github.tomakehurst.wiremock.verification.LoggedRequest;\n+import org.junit.Rule;\n+import org.junit.Test;\n+import sun.security.x509.X500Name;\n+\n+import java.io.File;\n+import java.security.KeyPair;\n+import java.security.KeyPairGenerator;\n+import java.security.NoSuchAlgorithmException;\n+import java.util.Date;\n+import java.util.HashMap;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\n+import static com.github.tomakehurst.wiremock.crypto.X509CertificateVersion.V3;\n+import static org.junit.Assert.assertEquals;\n+\n+public class ProxyResponseRendererTest {\n+\n+ @Rule\n+ public WireMockRule origin = new WireMockRule(options()\n+ .httpDisabled(true)\n+ .dynamicHttpsPort()\n+ .keystorePath(generateKeystore().getAbsolutePath())\n+ );\n+\n+ @Test\n+ public void acceptsAnyCertificateForStandardProxying() {\n+\n+ origin.stubFor(get(\"/proxied\").willReturn(aResponse().withBody(\"Result\")));\n+\n+ ProxyResponseRenderer proxyResponseRenderer = new ProxyResponseRenderer(\n+ ProxySettings.NO_PROXY,\n+ KeyStoreSettings.NO_STORE,\n+ /* preserveHostHeader = */ false,\n+ /* hostHeaderValue = */ null,\n+ new GlobalSettingsHolder()\n+ );\n+\n+ ServeEvent serveEvent = reverseProxyServeEvent(\"/proxied\");\n+\n+ Response response = proxyResponseRenderer.render(serveEvent);\n+\n+ assertEquals(response.getBodyAsString(), \"Result\");\n+ }\n+\n+ private ServeEvent reverseProxyServeEvent(String path) {\n+ LoggedRequest loggedRequest = new LoggedRequest(\n+ /* url = */path,\n+ /* absoluteUrl = */origin.url(path),\n+ /* method = */ RequestMethod.GET,\n+ /* clientIp = */\"127.0.0.1\",\n+ /* headers = */new HttpHeaders(),\n+ /* cookies = */new HashMap<String, Cookie>(),\n+ /* isBrowserProxyRequest = */false,\n+ /* loggedDate = */new Date(),\n+ /* body = */new byte[0],\n+ /* multiparts = */null\n+ );\n+ ResponseDefinition responseDefinition = aResponse().proxiedFrom(origin.baseUrl()).build();\n+ responseDefinition.setOriginalRequest(loggedRequest);\n+\n+ return ServeEvent.of(\n+ loggedRequest,\n+ responseDefinition,\n+ new StubMapping()\n+ );\n+ }\n+\n+ private File generateKeystore() throws Exception {\n+\n+ InMemoryKeyStore ks = new InMemoryKeyStore(InMemoryKeyStore.KeyStoreType.JKS, new Secret(\"password\"));\n+\n+ ks.addPrivateKey(\"wiremock\", generateKeyPair(), new X509CertificateSpecification(\n+ /* version = */V3,\n+ /* subject = */\"CN=wiremock.org\",\n+ /* issuer = */\"CN=wiremock.org\",\n+ /* notBefore = */new Date(),\n+ /* notAfter = */new Date(System.currentTimeMillis() + (365L * 24 * 60 * 60 * 1000))\n+ ));\n+\n+ File keystoreFile = File.createTempFile(\"wiremock-test\", \"keystore\");\n+\n+ ks.saveAs(keystoreFile);\n+\n+ return keystoreFile;\n+ }\n+\n+ private KeyPair generateKeyPair() throws NoSuchAlgorithmException {\n+ KeyPairGenerator keyGen = KeyPairGenerator.getInstance(\"RSA\");\n+ keyGen.initialize(1024);\n+ return keyGen.generateKeyPair();\n+ }\n+\n+ // Just exists to make the compiler happy by having the throws clause\n+ public ProxyResponseRendererTest() throws Exception {}\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Prove no validation of origin certificates |
686,981 | 28.05.2020 17:17:56 | -3,600 | be285b87a6c17f58cfa2a9243d7ef95e2d758276 | Add failing test proving we don't validate certs on forward proxy | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java",
"diff": "@@ -10,9 +10,10 @@ import com.github.tomakehurst.wiremock.junit.WireMockRule;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.verification.LoggedRequest;\n+import org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\n-import sun.security.x509.X500Name;\n+import org.junit.function.ThrowingRunnable;\nimport java.io.File;\nimport java.security.KeyPair;\n@@ -26,6 +27,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\nimport static com.github.tomakehurst.wiremock.crypto.X509CertificateVersion.V3;\nimport static org.junit.Assert.assertEquals;\n+import static org.junit.Assert.assertThrows;\npublic class ProxyResponseRendererTest {\n@@ -36,12 +38,7 @@ public class ProxyResponseRendererTest {\n.keystorePath(generateKeystore().getAbsolutePath())\n);\n- @Test\n- public void acceptsAnyCertificateForStandardProxying() {\n-\n- origin.stubFor(get(\"/proxied\").willReturn(aResponse().withBody(\"Result\")));\n-\n- ProxyResponseRenderer proxyResponseRenderer = new ProxyResponseRenderer(\n+ private final ProxyResponseRenderer proxyResponseRenderer = new ProxyResponseRenderer(\nProxySettings.NO_PROXY,\nKeyStoreSettings.NO_STORE,\n/* preserveHostHeader = */ false,\n@@ -49,6 +46,11 @@ public class ProxyResponseRendererTest {\nnew GlobalSettingsHolder()\n);\n+ @Test\n+ public void acceptsAnyCertificateForStandardProxying() {\n+\n+ origin.stubFor(get(\"/proxied\").willReturn(aResponse().withBody(\"Result\")));\n+\nServeEvent serveEvent = reverseProxyServeEvent(\"/proxied\");\nResponse response = proxyResponseRenderer.render(serveEvent);\n@@ -56,7 +58,32 @@ public class ProxyResponseRendererTest {\nassertEquals(response.getBodyAsString(), \"Result\");\n}\n+ @Test @Ignore(\"Not yet implemented\")\n+ public void rejectsSelfSignedCertificateForReverseProxying() {\n+\n+ origin.stubFor(get(\"/proxied\").willReturn(aResponse().withBody(\"Result\")));\n+\n+ final ServeEvent serveEvent = forwardProxyServeEvent(\"/proxied\");\n+\n+ Exception e = assertThrows(Exception.class, new ThrowingRunnable() {\n+ @Override\n+ public void run() {\n+ proxyResponseRenderer.render(serveEvent);\n+ }\n+ });\n+\n+ assertEquals(\"\", e.getMessage());\n+ }\n+\nprivate ServeEvent reverseProxyServeEvent(String path) {\n+ return serveEvent(path, false);\n+ }\n+\n+ private ServeEvent forwardProxyServeEvent(String path) {\n+ return serveEvent(path, true);\n+ }\n+\n+ private ServeEvent serveEvent(String path, boolean isBrowserProxyRequest) {\nLoggedRequest loggedRequest = new LoggedRequest(\n/* url = */path,\n/* absoluteUrl = */origin.url(path),\n@@ -64,7 +91,7 @@ public class ProxyResponseRendererTest {\n/* clientIp = */\"127.0.0.1\",\n/* headers = */new HttpHeaders(),\n/* cookies = */new HashMap<String, Cookie>(),\n- /* isBrowserProxyRequest = */false,\n+ /* isBrowserProxyRequest = */isBrowserProxyRequest,\n/* loggedDate = */new Date(),\n/* body = */new byte[0],\n/* multiparts = */null\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Add failing test proving we don't validate certs on forward proxy |
686,936 | 28.05.2020 18:11:55 | -3,600 | 0643425187d36805941a0c5e168009e11e279e4f | Implemented - Support for exempting comparison types in equalToXml | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/client/WireMock.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/client/WireMock.java",
"diff": "@@ -192,16 +192,16 @@ public class WireMock {\nreturn new MatchesJsonPathPattern(value, valuePattern);\n}\n- public static StringValuePattern equalToXml(String value) {\n+ public static EqualToXmlPattern equalToXml(String value) {\nreturn new EqualToXmlPattern(value);\n}\npublic static EqualToXmlPattern equalToXml(String value, boolean enablePlaceholders) {\n- return new EqualToXmlPattern(value, enablePlaceholders, null, null);\n+ return new EqualToXmlPattern(value, enablePlaceholders, null, null, null);\n}\npublic static EqualToXmlPattern equalToXml(String value, boolean enablePlaceholders, String placeholderOpeningDelimiterRegex, String placeholderClosingDelimiterRegex) {\n- return new EqualToXmlPattern(value, enablePlaceholders, placeholderOpeningDelimiterRegex, placeholderClosingDelimiterRegex);\n+ return new EqualToXmlPattern(value, enablePlaceholders, placeholderOpeningDelimiterRegex, placeholderClosingDelimiterRegex, null);\n}\npublic static MatchesXPathPattern matchingXPath(String value) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java",
"diff": "@@ -20,6 +20,8 @@ import com.github.tomakehurst.wiremock.common.xml.Xml;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n+import com.google.common.collect.ImmutableSet;\n+import com.google.common.collect.Sets;\nimport org.w3c.dom.Node;\nimport org.xmlunit.XMLUnitException;\nimport org.xmlunit.builder.DiffBuilder;\n@@ -27,18 +29,17 @@ import org.xmlunit.builder.Input;\nimport org.xmlunit.diff.*;\nimport org.xmlunit.placeholder.PlaceholderDifferenceEvaluator;\n-import java.util.Comparator;\n-import java.util.List;\n-import java.util.Map;\n+import java.util.*;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\n+import static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.base.Strings.isNullOrEmpty;\nimport static org.xmlunit.diff.ComparisonType.*;\npublic class EqualToXmlPattern extends MemoizingStringValuePattern {\n- private static List<ComparisonType> COUNTED_COMPARISONS = ImmutableList.of(\n+ private static Set<ComparisonType> COUNTED_COMPARISONS = ImmutableSet.of(\nELEMENT_TAG_NAME,\nSCHEMA_LOCATION,\nNO_NAMESPACE_SCHEMA_LOCATION,\n@@ -58,25 +59,31 @@ public class EqualToXmlPattern extends MemoizingStringValuePattern {\nprivate final String placeholderOpeningDelimiterRegex;\nprivate final String placeholderClosingDelimiterRegex;\nprivate final DifferenceEvaluator diffEvaluator;\n+ private final Set<ComparisonType> exemptedComparisons;\npublic EqualToXmlPattern(@JsonProperty(\"equalToXml\") String expectedValue) {\n- this(expectedValue, null, null, null);\n+ this(expectedValue, null, null, null, null);\n}\npublic EqualToXmlPattern(@JsonProperty(\"equalToXml\") String expectedValue,\n@JsonProperty(\"enablePlaceholders\") Boolean enablePlaceholders,\n@JsonProperty(\"placeholderOpeningDelimiterRegex\") String placeholderOpeningDelimiterRegex,\n- @JsonProperty(\"placeholderClosingDelimiterRegex\") String placeholderClosingDelimiterRegex) {\n+ @JsonProperty(\"placeholderClosingDelimiterRegex\") String placeholderClosingDelimiterRegex,\n+ @JsonProperty(\"exemptedComparisons\") Set<ComparisonType> exemptedComparisons) {\n+\nsuper(expectedValue);\nXml.read(expectedValue); // Throw an exception if we can't parse the document\nthis.enablePlaceholders = enablePlaceholders;\nthis.placeholderOpeningDelimiterRegex = placeholderOpeningDelimiterRegex;\nthis.placeholderClosingDelimiterRegex = placeholderClosingDelimiterRegex;\n+ this.exemptedComparisons = exemptedComparisons;\n+\n+ IgnoreUncountedDifferenceEvaluator baseDifferenceEvaluator = new IgnoreUncountedDifferenceEvaluator(exemptedComparisons);\nif (enablePlaceholders != null && enablePlaceholders) {\n- diffEvaluator = DifferenceEvaluators.chain(IGNORE_UNCOUNTED_COMPARISONS,\n+ diffEvaluator = DifferenceEvaluators.chain(baseDifferenceEvaluator,\nnew PlaceholderDifferenceEvaluator(placeholderOpeningDelimiterRegex, placeholderClosingDelimiterRegex));\n} else {\n- diffEvaluator = IGNORE_UNCOUNTED_COMPARISONS;\n+ diffEvaluator = baseDifferenceEvaluator;\n}\n}\n@@ -101,6 +108,10 @@ public class EqualToXmlPattern extends MemoizingStringValuePattern {\nreturn placeholderClosingDelimiterRegex;\n}\n+ public Set<ComparisonType> getExemptedComparisons() {\n+ return exemptedComparisons;\n+ }\n+\n@Override\nprotected MatchResult calculateMatch(final String value) {\nreturn new MatchResult() {\n@@ -174,17 +185,34 @@ public class EqualToXmlPattern extends MemoizingStringValuePattern {\n};\n}\n- private static final DifferenceEvaluator IGNORE_UNCOUNTED_COMPARISONS = new DifferenceEvaluator() {\n+ private static class IgnoreUncountedDifferenceEvaluator implements DifferenceEvaluator {\n+\n+ private final Set<ComparisonType> finalCountedComparisons;\n+\n+ public IgnoreUncountedDifferenceEvaluator(Set<ComparisonType> exemptedComparisons) {\n+ finalCountedComparisons = exemptedComparisons != null ?\n+ Sets.difference(COUNTED_COMPARISONS, exemptedComparisons) :\n+ COUNTED_COMPARISONS;\n+ }\n+\n@Override\npublic ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) {\n- if (COUNTED_COMPARISONS.contains(comparison.getType()) && comparison.getControlDetails().getValue() != null) {\n+ if (finalCountedComparisons.contains(comparison.getType()) && comparison.getControlDetails().getValue() != null) {\nreturn outcome;\n}\nreturn ComparisonResult.EQUAL;\n}\n- };\n+ }\n+ public EqualToXmlPattern exemptingComparisons(ComparisonType... comparisons) {\n+ return new EqualToXmlPattern(\n+ expectedValue,\n+ enablePlaceholders,\n+ placeholderOpeningDelimiterRegex,\n+ placeholderClosingDelimiterRegex,\n+ ImmutableSet.copyOf(comparisons));\n+ }\nprivate static final class OrderInvariantNodeMatcher extends DefaultNodeMatcher {\n@Override\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/StringValuePatternJsonDeserializer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/StringValuePatternJsonDeserializer.java",
"diff": "@@ -25,12 +25,15 @@ import com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n+import com.google.common.collect.ImmutableSet;\n+import org.xmlunit.diff.ComparisonType;\nimport java.io.IOException;\nimport java.lang.reflect.Constructor;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.Map;\n+import java.util.Set;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.google.common.collect.Iterables.tryFind;\n@@ -142,8 +145,9 @@ public class StringValuePatternJsonDeserializer extends JsonDeserializer<StringV\nBoolean enablePlaceholders = fromNullable(rootNode.findValue(\"enablePlaceholders\"));\nString placeholderOpeningDelimiterRegex = fromNullableTextNode(rootNode.findValue(\"placeholderOpeningDelimiterRegex\"));\nString placeholderClosingDelimiterRegex = fromNullableTextNode(rootNode.findValue(\"placeholderClosingDelimiterRegex\"));\n+ Set<ComparisonType> exemptedComparisons = comparisonTypeSetFromArray(rootNode.findValue(\"exemptedComparisons\"));\n- return new EqualToXmlPattern(operand.textValue(), enablePlaceholders, placeholderOpeningDelimiterRegex, placeholderClosingDelimiterRegex);\n+ return new EqualToXmlPattern(operand.textValue(), enablePlaceholders, placeholderOpeningDelimiterRegex, placeholderClosingDelimiterRegex, exemptedComparisons);\n}\nprivate MatchesJsonPathPattern deserialiseMatchesJsonPathPattern(JsonNode rootNode) throws JsonMappingException {\n@@ -210,6 +214,19 @@ public class StringValuePatternJsonDeserializer extends JsonDeserializer<StringV\nreturn node == null ? null : node.asText();\n}\n+ private static Set<ComparisonType> comparisonTypeSetFromArray(JsonNode node) {\n+ if (node == null || !node.isArray()) {\n+ return null;\n+ }\n+\n+ ImmutableSet.Builder<ComparisonType> builder = ImmutableSet.builder();\n+ for (JsonNode itemNode: node) {\n+ builder.add(ComparisonType.valueOf(itemNode.textValue()));\n+ }\n+\n+ return builder.build();\n+ }\n+\n@SuppressWarnings(\"unchecked\")\nprivate static Constructor<? extends StringValuePattern> findConstructor(Class<? extends StringValuePattern> clazz) {\nOptional<Constructor<?>> optionalConstructor =\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPatternTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPatternTest.java",
"diff": "@@ -21,14 +21,18 @@ import com.github.tomakehurst.wiremock.common.LocalNotifier;\nimport com.github.tomakehurst.wiremock.common.Notifier;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\nimport com.github.tomakehurst.wiremock.testsupport.WireMatchers;\n+import com.google.common.collect.ImmutableSet;\n+import org.hamcrest.Matchers;\nimport org.jmock.Expectations;\nimport org.jmock.Mockery;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\n+import org.xmlunit.diff.ComparisonType;\nimport java.util.Locale;\n+import java.util.Set;\nimport static com.github.tomakehurst.wiremock.client.WireMock.equalToXml;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\n@@ -37,6 +41,7 @@ import static org.hamcrest.CoreMatchers.not;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.*;\n+import static org.xmlunit.diff.ComparisonType.*;\npublic class EqualToXmlPatternTest {\n@@ -328,7 +333,7 @@ public class EqualToXmlPatternTest {\npublic void returnsMatchWhenTextNodeIsIgnored() {\nString expectedXml = \"<a>#{xmlunit.ignore}</a>\";\nString actualXml = \"<a>123</a>\";\n- EqualToXmlPattern pattern = new EqualToXmlPattern(expectedXml, true, \"#\\\\{\", \"}\");\n+ EqualToXmlPattern pattern = new EqualToXmlPattern(expectedXml, true, \"#\\\\{\", \"}\", null);\nMatchResult matchResult = pattern.match(actualXml);\nassertTrue(matchResult.isExactMatch());\n@@ -339,7 +344,7 @@ public class EqualToXmlPatternTest {\npublic void returnsMatchWhenTextNodeIsIgnored_DefaultDelimiters() {\nString expectedXml = \"<a>${xmlunit.ignore}</a>\";\nString actualXml = \"<a>123</a>\";\n- EqualToXmlPattern pattern = new EqualToXmlPattern(expectedXml, true, null, null);\n+ EqualToXmlPattern pattern = new EqualToXmlPattern(expectedXml, true, null, null, null);\nMatchResult matchResult = pattern.match(actualXml);\nassertTrue(matchResult.isExactMatch());\n@@ -347,7 +352,23 @@ public class EqualToXmlPatternTest {\n}\n@Test\n- public void deserializesEqualToXmlWithPlaceholder() {\n+ public void deserializesEqualToXmlWithMinimalParameters() {\n+ String patternJson =\n+ \"{\" +\n+ \"\\\"equalToXml\\\" : \\\"<a/>\\\"\" +\n+ \"}\";\n+ StringValuePattern stringValuePattern = Json.read(patternJson, StringValuePattern.class);\n+\n+ assertTrue(stringValuePattern instanceof EqualToXmlPattern);\n+ EqualToXmlPattern equalToXmlPattern = (EqualToXmlPattern) stringValuePattern;\n+ assertThat(equalToXmlPattern.isEnablePlaceholders(), nullValue());\n+ assertThat(equalToXmlPattern.getPlaceholderOpeningDelimiterRegex(), nullValue());\n+ assertThat(equalToXmlPattern.getPlaceholderClosingDelimiterRegex(), nullValue());\n+ assertThat(equalToXmlPattern.getExemptedComparisons(), nullValue());\n+ }\n+\n+ @Test\n+ public void deserializesEqualToXmlWithAllParameters() {\nBoolean enablePlaceholders = Boolean.TRUE;\nString placeholderOpeningDelimiterRegex = \"theOpeningDelimiterRegex\";\nString placeholderClosingDelimiterRegex = \"theClosingDelimiterRegex\";\n@@ -355,7 +376,8 @@ public class EqualToXmlPatternTest {\n\"\\\"equalToXml\\\" : \\\"<a/>\\\", \" +\n\"\\\"enablePlaceholders\\\" : \" + enablePlaceholders + \", \" +\n\"\\\"placeholderOpeningDelimiterRegex\\\" : \\\"\" + placeholderOpeningDelimiterRegex + \"\\\", \" +\n- \"\\\"placeholderClosingDelimiterRegex\\\" : \\\"\" + placeholderClosingDelimiterRegex + \"\\\"}\";\n+ \"\\\"placeholderClosingDelimiterRegex\\\" : \\\"\" + placeholderClosingDelimiterRegex + \"\\\", \" +\n+ \"\\\"exemptedComparisons\\\": [\\\"SCHEMA_LOCATION\\\", \\\"NAMESPACE_URI\\\", \\\"ATTR_VALUE\\\"] }\";\nStringValuePattern stringValuePattern = Json.read(patternJson, StringValuePattern.class);\nassertTrue(stringValuePattern instanceof EqualToXmlPattern);\n@@ -363,10 +385,12 @@ public class EqualToXmlPatternTest {\nassertEquals(enablePlaceholders, equalToXmlPattern.isEnablePlaceholders());\nassertEquals(placeholderOpeningDelimiterRegex, equalToXmlPattern.getPlaceholderOpeningDelimiterRegex());\nassertEquals(placeholderClosingDelimiterRegex, equalToXmlPattern.getPlaceholderClosingDelimiterRegex());\n+ assertThat(equalToXmlPattern.getExemptedComparisons(),\n+ Matchers.<Set<ComparisonType>>is(ImmutableSet.of(SCHEMA_LOCATION, NAMESPACE_URI, ATTR_VALUE)));\n}\n@Test\n- public void serializesEqualToXmlWithPlaceholder() {\n+ public void serializesEqualToXmlWithAllParameters() {\nString xml = \"<stuff />\";\nBoolean enablePlaceholders = Boolean.TRUE;\nString placeholderOpeningDelimiterRegex = \"[\";\n@@ -376,7 +400,8 @@ public class EqualToXmlPatternTest {\nxml,\nenablePlaceholders,\nplaceholderOpeningDelimiterRegex,\n- placeholderClosingDelimiterRegex\n+ placeholderClosingDelimiterRegex,\n+ ImmutableSet.of(SCHEMA_LOCATION, NAMESPACE_URI, ATTR_VALUE)\n);\nString json = Json.write(pattern);\n@@ -385,7 +410,46 @@ public class EqualToXmlPatternTest {\n\" \\\"equalToXml\\\": \\\"<stuff />\\\",\\n\" +\n\" \\\"enablePlaceholders\\\": true,\\n\" +\n\" \\\"placeholderOpeningDelimiterRegex\\\": \\\"[\\\",\\n\" +\n- \" \\\"placeholderClosingDelimiterRegex\\\": \\\"]\\\"\\n\" +\n+ \" \\\"placeholderClosingDelimiterRegex\\\": \\\"]\\\",\\n\" +\n+ \" \\\"exemptedComparisons\\\": [\\\"SCHEMA_LOCATION\\\", \\\"NAMESPACE_URI\\\", \\\"ATTR_VALUE\\\"]\\n\" +\n\"}\"));\n}\n+\n+ @Test\n+ public void namespaceComparisonCanBeExcluded() {\n+ String expected = \"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<stuff xmlns:th=\\\"https://thing.com\\\">\\n\" +\n+ \" <th:thing>Match this</th:thing>\\n\" +\n+ \"</stuff>\";\n+\n+ String actual = \"<?xml version=\\\"1.0\\\"?>\\n\" +\n+ \"<stuff xmlns:st=\\\"https://stuff.com\\\">\\n\" +\n+ \" <st:thing>Match this</st:thing>\\n\" +\n+ \"</stuff>\";\n+\n+ MatchResult matchResult = equalToXml(expected).match(actual);\n+\n+ assertTrue(matchResult.isExactMatch());\n+ }\n+\n+ @Test\n+ public void namespaceComparisonCanBeExcluded2() {\n+ String expected = \"<ns2:GetValue\\n\" +\n+ \" xmlns=\\\"http://CIS/BIR/PUBL/2014/07/DataContract\\\"\\n\" +\n+ \" xmlns:ns2=\\\"http://CIS/BIR/2014/07\\\" \\n\" +\n+ \" xmlns:ns3=\\\"http://CIS/BIR/PUBL/2014/07\\\" \\n\" +\n+ \" xmlns:ns4=\\\"http://schemas.microsoft.com/2003/10/Serializa \\n\" +\n+ \" tion/\\\"/>\";\n+\n+ String actual = \"<ns3:GetValue\\n\" +\n+ \" xmlns=\\\"http://CIS/BIR/PUBL/2014/07\\\"\\n\" +\n+ \" xmlns:ns2=\\\"http://CIS/BIR/PUBL/2014/07/DataContract\\\"\\n\" +\n+ \" xmlns:ns3=\\\"http://CIS/BIR/2014/07\\\"\\n\" +\n+ \" xmlns:ns4=\\\"http://schemas.microsoft.com/2003/10/Serializa\\n\" +\n+ \" tion/\\\"/>\";\n+\n+ StringValuePattern pattern = equalToXml(expected).exemptingComparisons(NAMESPACE_URI);\n+\n+ assertTrue(pattern.match(actual).isExactMatch());\n+ }\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Implemented #1150 - Support for exempting comparison types in equalToXml |
686,981 | 29.05.2020 08:14:26 | -3,600 | e1ff9cb6f996e3519a18d87cf3bdd1b268d15012 | Validate certs by default on forward proxy
Provide an option `--trust-all` to allow turning this behaviour off. | [
{
"change_type": "MODIFY",
"old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java",
"new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java",
"diff": "@@ -68,7 +68,9 @@ public class HttpsBrowserProxyAcceptanceTest {\n.dynamicPort()\n.dynamicHttpsPort()\n.fileSource(new SingleRootFileSource(setupTempFileRoot()))\n- .enableBrowserProxying(true));\n+ .enableBrowserProxying(true)\n+ .trustAll(true)\n+ );\nproxy.start();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"diff": "@@ -73,4 +73,5 @@ public interface Options {\nboolean getGzipDisabled();\nboolean getStubRequestLoggingDisabled();\nboolean getStubCorsEnabled();\n+ boolean trustAll();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"diff": "@@ -150,7 +150,9 @@ public class WireMockApp implements StubServer, Admin {\noptions.httpsSettings().trustStore(),\noptions.shouldPreserveHostHeader(),\noptions.proxyHostHeader(),\n- globalSettingsHolder),\n+ globalSettingsHolder,\n+ options.trustAll()\n+ ),\nImmutableList.copyOf(options.extensionsOfType(ResponseTransformer.class).values())\n),\nthis,\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java",
"diff": "@@ -98,6 +98,7 @@ public class WireMockConfiguration implements Options {\nprivate String permittedSystemKeys = null;\nprivate boolean stubCorsEnabled = false;\n+ private boolean trustAll = false;\nprivate MappingsSource getMappingsSource() {\nif (mappingsSource == null) {\n@@ -362,6 +363,11 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n+ public WireMockConfiguration trustAll(boolean enabled) {\n+ this.trustAll = enabled;\n+ return this;\n+ }\n+\n@Override\npublic int portNumber() {\nreturn portNumber;\n@@ -521,4 +527,9 @@ public class WireMockConfiguration implements Options {\npublic boolean getStubCorsEnabled() {\nreturn stubCorsEnabled;\n}\n+\n+ @Override\n+ public boolean trustAll() {\n+ return trustAll;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"diff": "@@ -26,6 +26,7 @@ import org.apache.http.client.config.RequestConfig;\nimport org.apache.http.client.methods.*;\nimport org.apache.http.config.SocketConfig;\nimport org.apache.http.conn.ssl.AllowAllHostnameVerifier;\n+import org.apache.http.conn.ssl.SSLContextBuilder;\nimport org.apache.http.conn.ssl.SSLContexts;\nimport org.apache.http.conn.ssl.TrustSelfSignedStrategy;\nimport org.apache.http.conn.ssl.TrustStrategy;\n@@ -55,7 +56,8 @@ public class HttpClientFactory {\nint maxConnections,\nint timeoutMilliseconds,\nProxySettings proxySettings,\n- KeyStoreSettings trustStoreSettings) {\n+ KeyStoreSettings trustStoreSettings,\n+ boolean trustSelfSignedCertificates) {\nHttpClientBuilder builder = HttpClientBuilder.create()\n.disableAuthCaching()\n@@ -83,21 +85,32 @@ public class HttpClientFactory {\n}\nif (trustStoreSettings != NO_STORE) {\n- builder.setSslcontext(buildSSLContextWithTrustStore(trustStoreSettings));\n- } else {\n+ builder.setSslcontext(buildSSLContextWithTrustStore(trustStoreSettings, trustSelfSignedCertificates));\n+ } else if (trustSelfSignedCertificates) {\nbuilder.setSslcontext(buildAllowAnythingSSLContext());\n}\nreturn builder.build();\n}\n- private static SSLContext buildSSLContextWithTrustStore(KeyStoreSettings trustStoreSettings) {\n+ public static CloseableHttpClient createClient(\n+ int maxConnections,\n+ int timeoutMilliseconds,\n+ ProxySettings proxySettings,\n+ KeyStoreSettings trustStoreSettings) {\n+ return createClient(maxConnections, timeoutMilliseconds, proxySettings, trustStoreSettings, true);\n+ }\n+\n+ private static SSLContext buildSSLContextWithTrustStore(KeyStoreSettings trustStoreSettings, boolean trustSelfSignedCertificates) {\ntry {\nKeyStore trustStore = trustStoreSettings.loadStore();\n- return SSLContexts.custom()\n- .loadTrustMaterial(null, new TrustSelfSignedStrategy())\n+ SSLContextBuilder sslContextBuilder = SSLContexts.custom()\n.loadKeyMaterial(trustStore, trustStoreSettings.password().toCharArray())\n- .useTLS()\n+ .useTLS();\n+ if (trustSelfSignedCertificates) {\n+ sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());\n+ }\n+ return sslContextBuilder\n.build();\n} catch (Exception e) {\nreturn throwUnchecked(e, SSLContext.class);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java",
"diff": "@@ -35,6 +35,7 @@ import java.net.URI;\nimport java.util.LinkedList;\nimport java.util.List;\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.common.HttpClientUtils.getEntityAsByteArrayAndCloseStream;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.POST;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.PUT;\n@@ -55,13 +56,24 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n);\nprivate final HttpClient client;\n+ private final HttpClient scepticalClient;\nprivate final boolean preserveHostHeader;\nprivate final String hostHeaderValue;\nprivate final GlobalSettingsHolder globalSettingsHolder;\n-\n- public ProxyResponseRenderer(ProxySettings proxySettings, KeyStoreSettings trustStoreSettings, boolean preserveHostHeader, String hostHeaderValue, GlobalSettingsHolder globalSettingsHolder) {\n+ private final boolean trustAll;\n+\n+ public ProxyResponseRenderer(\n+ ProxySettings proxySettings,\n+ KeyStoreSettings trustStoreSettings,\n+ boolean preserveHostHeader,\n+ String hostHeaderValue,\n+ GlobalSettingsHolder globalSettingsHolder,\n+ boolean trustAll\n+ ) {\nthis.globalSettingsHolder = globalSettingsHolder;\n- client = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings);\n+ this.trustAll = trustAll;\n+ client = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, true);\n+ scepticalClient = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, false);\nthis.preserveHostHeader = preserveHostHeader;\nthis.hostHeaderValue = hostHeaderValue;\n@@ -75,6 +87,7 @@ public class ProxyResponseRenderer implements ResponseRenderer {\ntry {\naddBodyIfPostPutOrPatch(httpRequest, responseDefinition);\n+ HttpClient client = buildClient(serveEvent.getRequest().isBrowserProxyRequest());\nHttpResponse httpResponse = client.execute(httpRequest);\nreturn response()\n@@ -91,7 +104,15 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n.chunkedDribbleDelay(responseDefinition.getChunkedDribbleDelay())\n.build();\n} catch (IOException e) {\n- throw new RuntimeException(e);\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+\n+ private HttpClient buildClient(boolean browserProxyRequest) {\n+ if (browserProxyRequest && !trustAll) {\n+ return scepticalClient;\n+ } else {\n+ return this.client;\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"diff": "@@ -196,4 +196,9 @@ public class WarConfiguration implements Options {\npublic boolean getStubCorsEnabled() {\nreturn false;\n}\n+\n+ @Override\n+ public boolean trustAll() {\n+ return false;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java",
"diff": "@@ -96,6 +96,7 @@ public class CommandLineOptions implements Options {\nprivate static final String DISABLE_GZIP = \"disable-gzip\";\nprivate static final String DISABLE_REQUEST_LOGGING = \"disable-request-logging\";\nprivate static final String ENABLE_STUB_CORS = \"enable-stub-cors\";\n+ private static final String TRUST_ALL = \"trust-all\";\nprivate final OptionSet optionSet;\nprivate final FileSource fileSource;\n@@ -146,6 +147,7 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(DISABLE_GZIP, \"Disable gzipping of request and response bodies\");\noptionParser.accepts(DISABLE_REQUEST_LOGGING, \"Disable logging of stub requests and responses to the notifier. Useful when performance testing.\");\noptionParser.accepts(ENABLE_STUB_CORS, \"Enable automatic sending of CORS headers with stub responses.\");\n+ optionParser.accepts(TRUST_ALL, \"Trust all certificates presented by origins when browser proxying\");\noptionParser.accepts(HELP, \"Print this message\");\n@@ -559,6 +561,11 @@ public class CommandLineOptions implements Options {\nreturn optionSet.has(ENABLE_STUB_CORS);\n}\n+ @Override\n+ public boolean trustAll() {\n+ return optionSet.has(TRUST_ALL);\n+ }\n+\nprivate Long getMaxTemplateCacheEntries() {\nreturn optionSet.has(MAX_TEMPLATE_CACHE_ENTRIES) ?\nLong.valueOf(optionSet.valueOf(MAX_TEMPLATE_CACHE_ENTRIES).toString()) :\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java",
"diff": "@@ -10,11 +10,11 @@ import com.github.tomakehurst.wiremock.junit.WireMockRule;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.verification.LoggedRequest;\n-import org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.function.ThrowingRunnable;\n+import javax.net.ssl.SSLHandshakeException;\nimport java.io.File;\nimport java.security.KeyPair;\nimport java.security.KeyPairGenerator;\n@@ -26,6 +26,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\nimport static com.github.tomakehurst.wiremock.client.WireMock.get;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\nimport static com.github.tomakehurst.wiremock.crypto.X509CertificateVersion.V3;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.core.StringContains.containsString;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertThrows;\n@@ -38,13 +40,7 @@ public class ProxyResponseRendererTest {\n.keystorePath(generateKeystore().getAbsolutePath())\n);\n- private final ProxyResponseRenderer proxyResponseRenderer = new ProxyResponseRenderer(\n- ProxySettings.NO_PROXY,\n- KeyStoreSettings.NO_STORE,\n- /* preserveHostHeader = */ false,\n- /* hostHeaderValue = */ null,\n- new GlobalSettingsHolder()\n- );\n+ private final ProxyResponseRenderer proxyResponseRenderer = buildProxyResponseRenderer(false);\n@Test\npublic void acceptsAnyCertificateForStandardProxying() {\n@@ -58,21 +54,35 @@ public class ProxyResponseRendererTest {\nassertEquals(response.getBodyAsString(), \"Result\");\n}\n- @Test @Ignore(\"Not yet implemented\")\n+ @Test\npublic void rejectsSelfSignedCertificateForReverseProxying() {\norigin.stubFor(get(\"/proxied\").willReturn(aResponse().withBody(\"Result\")));\nfinal ServeEvent serveEvent = forwardProxyServeEvent(\"/proxied\");\n- Exception e = assertThrows(Exception.class, new ThrowingRunnable() {\n+ SSLHandshakeException e = assertThrows(SSLHandshakeException.class, new ThrowingRunnable() {\n@Override\npublic void run() {\nproxyResponseRenderer.render(serveEvent);\n}\n});\n- assertEquals(\"\", e.getMessage());\n+ assertThat(e.getMessage(), containsString(\"unable to find valid certification path to requested target\"));\n+ }\n+\n+ @Test\n+ public void acceptsSelfSignedCertificateForReverseProxyingIfTrustAll() {\n+\n+ final ProxyResponseRenderer trustAllProxyResponseRenderer = buildProxyResponseRenderer(true);\n+\n+ origin.stubFor(get(\"/proxied\").willReturn(aResponse().withBody(\"Result\")));\n+\n+ final ServeEvent serveEvent = forwardProxyServeEvent(\"/proxied\");\n+\n+ Response response = trustAllProxyResponseRenderer.render(serveEvent);\n+\n+ assertEquals(response.getBodyAsString(), \"Result\");\n}\nprivate ServeEvent reverseProxyServeEvent(String path) {\n@@ -131,6 +141,17 @@ public class ProxyResponseRendererTest {\nreturn keyGen.generateKeyPair();\n}\n+ private ProxyResponseRenderer buildProxyResponseRenderer(boolean trustAll) {\n+ return new ProxyResponseRenderer(\n+ ProxySettings.NO_PROXY,\n+ KeyStoreSettings.NO_STORE,\n+ /* preserveHostHeader = */ false,\n+ /* hostHeaderValue = */ null,\n+ new GlobalSettingsHolder(),\n+ trustAll\n+ );\n+ }\n+\n// Just exists to make the compiler happy by having the throws clause\npublic ProxyResponseRendererTest() throws Exception {}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"diff": "@@ -480,6 +480,18 @@ public class CommandLineOptionsTest {\nassertThat(options.getStubCorsEnabled(), is(false));\n}\n+ @Test\n+ public void trustsAll() {\n+ CommandLineOptions options = new CommandLineOptions(\"--trust-all\");\n+ assertThat(options.trustAll(), is(true));\n+ }\n+\n+ @Test\n+ public void defaultsToNotTrustingAll() {\n+ CommandLineOptions options = new CommandLineOptions();\n+ assertThat(options.trustAll(), is(false));\n+ }\n+\n@Test\npublic void printsBothActualPortsOnlyWhenHttpsEnabled() {\nCommandLineOptions options = new CommandLineOptions();\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Validate certs by default on forward proxy
Provide an option `--trust-all` to allow turning this behaviour off. |
686,981 | 29.05.2020 08:38:09 | -3,600 | c18ded1f2236653e818436d613ef9371295c36b2 | Document `--trust-all` & HTTPS forward proxying | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/proxying.md",
"new_path": "docs-v2/_docs/proxying.md",
"diff": "@@ -132,6 +132,11 @@ stubFor(get(urlEqualTo(\"/users/12345.json\"))\n.withStatus(503)));\n```\n+wiremock-jre8 allows forward proxying, stubbing & recording of HTTPS traffic. By default, this will verify the origin certificates; this behaviour can be turned to trusting all as follows:\n+```bash\n+$ java -jar wiremock-jre8-standalone-{{ site.wiremock_version }}.jar --enable-browser-proxying --trust-all\n+```\n+\n## Proxying via another proxy server\nIf you're inside a network that only permits HTTP traffic out to the\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/running-standalone.md",
"new_path": "docs-v2/_docs/running-standalone.md",
"diff": "@@ -86,6 +86,9 @@ e.g. `--proxy-via http://username:password@webproxy.mycorp.com:8080/`.\n`--enable-browser-proxying`: Run as a browser proxy. See\nbrowser-proxying.\n+`--trust-all`: Trust all remote certificates when running as a browser proxy and\n+proxying HTTPS traffic.\n+\n`--no-request-journal`: Disable the request journal, which records\nincoming requests for later verification. This allows WireMock to be run\n(and serve stubs) for long periods (without resetting) without\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Document `--trust-all` & HTTPS forward proxying |
686,981 | 29.05.2020 08:53:57 | -3,600 | d3dc53e2ed045e5758f15957701f720dd92a123a | Fix java7 build | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/X509CertificateSpecification.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/X509CertificateSpecification.java",
"diff": "@@ -2,7 +2,9 @@ package com.github.tomakehurst.wiremock.crypto;\nimport sun.security.x509.AlgorithmId;\nimport sun.security.x509.CertificateAlgorithmId;\n+import sun.security.x509.CertificateIssuerName;\nimport sun.security.x509.CertificateSerialNumber;\n+import sun.security.x509.CertificateSubjectName;\nimport sun.security.x509.CertificateValidity;\nimport sun.security.x509.CertificateX509Key;\nimport sun.security.x509.X500Name;\n@@ -27,9 +29,9 @@ import static java.util.Objects.requireNonNull;\npublic class X509CertificateSpecification implements CertificateSpecification {\nprivate final X509CertificateVersion version;\n- private final String subject;\n- private final String issuer;\n- // java.time is JDK8 on\n+ private final X500Name subject;\n+ private final X500Name issuer;\n+ // java.time is JDK8 only\nprivate final Date notBefore;\nprivate final Date notAfter;\n@@ -39,10 +41,10 @@ public class X509CertificateSpecification implements CertificateSpecification {\nString issuer,\nDate notBefore,\nDate notAfter\n- ) {\n+ ) throws IOException {\nthis.version = requireNonNull(version);\n- this.subject = requireNonNull(subject);\n- this.issuer = requireNonNull(issuer);\n+ this.subject = new X500Name(requireNonNull(subject));\n+ this.issuer = new X500Name(requireNonNull(issuer));\nthis.notBefore = requireNonNull(notBefore);\nthis.notAfter = requireNonNull(notAfter);\n}\n@@ -54,8 +56,23 @@ public class X509CertificateSpecification implements CertificateSpecification {\nX509CertInfo info = new X509CertInfo();\ninfo.set(X509CertInfo.VERSION, version.getVersion());\n- info.set(X509CertInfo.SUBJECT, new X500Name(subject));\n- info.set(X509CertInfo.ISSUER, new X500Name(issuer));\n+\n+ // On Java <= 1.7 it has to be a `CertificateSubjectName`\n+ // On Java >= 1.8 it has to be an `X500Name`\n+ try {\n+ info.set(X509CertInfo.SUBJECT, subject);\n+ } catch (CertificateException ignore) {\n+ info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(subject));\n+ }\n+\n+ // On Java <= 1.7 it has to be a `CertificateIssuerName`\n+ // On Java >= 1.8 it has to be an `X500Name`\n+ try {\n+ info.set(X509CertInfo.ISSUER, issuer);\n+ } catch (CertificateException ignore) {\n+ info.set(X509CertInfo.ISSUER, new CertificateIssuerName(issuer));\n+ }\n+\ninfo.set(X509CertInfo.VALIDITY, new CertificateValidity(notBefore, notAfter));\ninfo.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fix java7 build |
686,936 | 29.05.2020 17:31:13 | -3,600 | daa4454a141c59336bb07baa2941e3b435adf6e8 | Documented XML equality comparison type exemption | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/request-matching.md",
"new_path": "docs-v2/_docs/request-matching.md",
"diff": "@@ -685,7 +685,9 @@ The XMLUnit [placeholders](https://github.com/xmlunit/user-guide/wiki/Placeholde\nJava:\n```java\n-.withRequestBody(equalToXml(\"<message><id>${xmlunit.ignore}</id><content>Hello</content></message>\", true))\n+.withRequestBody(\n+ equalToXml(\"<message><id>${xmlunit.ignore}</id><content>Hello</content></message>\", true)\n+)\n```\nJSON:\n@@ -711,7 +713,13 @@ If the default placeholder delimiters `${` and `}` can not be used, you can spec\nJava:\n```java\n-.withRequestBody(equalToXml(\"<message><id>[[xmlunit.ignore]]</id><content>Hello</content></message>\", true, \"\\\\[\\\\[\", \"]]\"))\n+.withRequestBody(\n+ equalToXml(\"<message><id>[[xmlunit.ignore]]</id><content>Hello</content></message>\",\n+ true,\n+ \"\\\\[\\\\[\",\n+ \"]]\"\n+ )\n+)\n```\nJSON:\n@@ -732,6 +740,56 @@ JSON:\n}\n```\n+#### Excluding specific types of comparison\n+\n+You can further tune how XML documents are compared for equality by disabling specific [XMLUnit comparison types](https://www.xmlunit.org/api/java/2.7.0/org/xmlunit/diff/ComparisonType.html).\n+\n+Java:\n+\n+\n+```java\n+import static org.xmlunit.diff.ComparisonType.*;\n+\n+...\n+\n+.withRequestBody(equalToXml(\"<thing>Hello</thing>\")\n+ .exemptingComparisons(NAMESPACE_URI, ELEMENT_TAG_NAME)\n+)\n+```\n+\n+JSON:\n+\n+```json\n+{\n+ \"request\": {\n+ ...\n+ \"bodyPatterns\" : [ {\n+ \"equalToXml\" : \"<thing>Hello</thing>\",\n+ \"exemptedComparisons\": [\"NAMESPACE_URI\", \"ELEMENT_TAG_NAME\"]\n+ } ]\n+ ...\n+ },\n+ ...\n+}\n+```\n+\n+The full list of comparison types used by default is as follows:\n+\n+`ELEMENT_TAG_NAME`\n+`SCHEMA_LOCATION`\n+`NO_NAMESPACE_SCHEMA_LOCATION`\n+`NODE_TYPE`\n+`NAMESPACE_URI`\n+`TEXT_VALUE`\n+`PROCESSING_INSTRUCTION_TARGET`\n+`PROCESSING_INSTRUCTION_DATA`\n+`ELEMENT_NUM_ATTRIBUTES`\n+`ATTR_VALUE`\n+`CHILD_NODELIST_LENGTH`\n+`CHILD_LOOKUP`\n+`ATTR_NAME_LOOKUP`\n+\n+\n### XPath\nDeems a match if the attribute value is valid XML and matches the XPath expression supplied. An XML document will be considered to match if any elements are returned by the XPath evaluation. WireMock delegates to Java's in-built XPath engine (via XMLUnit), therefore up to (at least) Java 8 it supports XPath version 1.0.\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Documented XML equality comparison type exemption |
686,936 | 29.05.2020 17:58:08 | -3,600 | 61a92dfc26e52e8617d219103da4f478b2bef067 | Documented change to XPath behaviour when matching namespaced XML documents | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/request-matching.md",
"new_path": "docs-v2/_docs/request-matching.md",
"diff": "@@ -815,7 +815,10 @@ JSON:\n}\n```\n-The above example will only work with non-namespaced XML. If you need to match a namespaced document with it is necessary to declare the namespaces:\n+The above example will select elements based on their local name if used with a namespaced XML document.\n+\n+If you need to be able to select elements based on their namespace in addition to their name you can declare the prefix\n+to namespace URI mappings and use them in your XPath expression:\nJava:\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Documented change to XPath behaviour when matching namespaced XML documents |
686,936 | 29.05.2020 17:58:32 | -3,600 | d7cdd27836185883effdf130f689f6fb664f6726 | Documented enhancement to XPath helper permitting use of results in further helpers | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/response-templating.md",
"new_path": "docs-v2/_docs/response-templating.md",
"diff": "@@ -321,6 +321,32 @@ The following will render \"success\" in the output:\n{% endraw %}\n+### Using the output of `xPath` in other helpers\n+\n+Since version 2.27.0 the XPath helper returns collections of node objects rather than a single string, meaning that the result\n+can be used in further helpers.\n+\n+The returned node objects have the following properties:\n+\n+`name` - the local XML element name.\n+\n+`text` - the text content of the element.\n+\n+`attributes` - a map of the element's attributes (name: value)\n+\n+Referring to the node itself will cause it to be printed.\n+\n+\n+A common use case for returned node objects is to iterate over the collection with the `each` helper:\n+\n+{% raw %}\n+```\n+{{#each (xPath request.body '/things/item') as |node|}}\n+ name: {{node.name}}, text: {{node.text}}, ID attribute: {{node.attributes.id}}\n+{{/each}}\n+```\n+{% endraw %}\n+\n## JSONPath helper\nIt is similarly possible to extract JSON values or sub documents via JSONPath using the `jsonPath` helper. Given the JSON\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Documented enhancement to XPath helper permitting use of results in further helpers |
686,981 | 01.06.2020 10:32:02 | -3,600 | 03d29c3c54c7a19927272577ff7e79a23c502365 | Rename trust-all to trust-all-proxy-targets
More explicit name. | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/proxying.md",
"new_path": "docs-v2/_docs/proxying.md",
"diff": "@@ -134,7 +134,7 @@ stubFor(get(urlEqualTo(\"/users/12345.json\"))\nwiremock-jre8 allows forward proxying, stubbing & recording of HTTPS traffic. By default, this will verify the origin certificates; this behaviour can be turned to trusting all as follows:\n```bash\n-$ java -jar wiremock-jre8-standalone-{{ site.wiremock_version }}.jar --enable-browser-proxying --trust-all\n+$ java -jar wiremock-jre8-standalone-{{ site.wiremock_version }}.jar --enable-browser-proxying --trust-all-proxy-targets\n```\n## Proxying via another proxy server\n"
},
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/running-standalone.md",
"new_path": "docs-v2/_docs/running-standalone.md",
"diff": "@@ -86,7 +86,7 @@ e.g. `--proxy-via http://username:password@webproxy.mycorp.com:8080/`.\n`--enable-browser-proxying`: Run as a browser proxy. See\nbrowser-proxying.\n-`--trust-all`: Trust all remote certificates when running as a browser proxy and\n+`--trust-all-proxy-targets`: Trust all remote certificates when running as a browser proxy and\nproxying HTTPS traffic.\n`--no-request-journal`: Disable the request journal, which records\n"
},
{
"change_type": "MODIFY",
"old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java",
"new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java",
"diff": "@@ -69,7 +69,7 @@ public class HttpsBrowserProxyAcceptanceTest {\n.dynamicHttpsPort()\n.fileSource(new SingleRootFileSource(setupTempFileRoot()))\n.enableBrowserProxying(true)\n- .trustAll(true)\n+ .trustAllProxyTargets(true)\n);\nproxy.start();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java",
"diff": "@@ -73,5 +73,5 @@ public interface Options {\nboolean getGzipDisabled();\nboolean getStubRequestLoggingDisabled();\nboolean getStubCorsEnabled();\n- boolean trustAll();\n+ boolean trustAllProxyTargets();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java",
"diff": "@@ -151,7 +151,7 @@ public class WireMockApp implements StubServer, Admin {\noptions.shouldPreserveHostHeader(),\noptions.proxyHostHeader(),\nglobalSettingsHolder,\n- options.trustAll()\n+ options.trustAllProxyTargets()\n),\nImmutableList.copyOf(options.extensionsOfType(ResponseTransformer.class).values())\n),\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java",
"diff": "@@ -98,7 +98,7 @@ public class WireMockConfiguration implements Options {\nprivate String permittedSystemKeys = null;\nprivate boolean stubCorsEnabled = false;\n- private boolean trustAll = false;\n+ private boolean trustAllProxyTargets = false;\nprivate MappingsSource getMappingsSource() {\nif (mappingsSource == null) {\n@@ -363,8 +363,8 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n- public WireMockConfiguration trustAll(boolean enabled) {\n- this.trustAll = enabled;\n+ public WireMockConfiguration trustAllProxyTargets(boolean enabled) {\n+ this.trustAllProxyTargets = enabled;\nreturn this;\n}\n@@ -529,7 +529,7 @@ public class WireMockConfiguration implements Options {\n}\n@Override\n- public boolean trustAll() {\n- return trustAll;\n+ public boolean trustAllProxyTargets() {\n+ return trustAllProxyTargets;\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java",
"diff": "@@ -60,7 +60,7 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nprivate final boolean preserveHostHeader;\nprivate final String hostHeaderValue;\nprivate final GlobalSettingsHolder globalSettingsHolder;\n- private final boolean trustAll;\n+ private final boolean trustAllProxyTargets;\npublic ProxyResponseRenderer(\nProxySettings proxySettings,\n@@ -68,10 +68,10 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nboolean preserveHostHeader,\nString hostHeaderValue,\nGlobalSettingsHolder globalSettingsHolder,\n- boolean trustAll\n+ boolean trustAllProxyTargets\n) {\nthis.globalSettingsHolder = globalSettingsHolder;\n- this.trustAll = trustAll;\n+ this.trustAllProxyTargets = trustAllProxyTargets;\nclient = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, true);\nscepticalClient = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, false);\n@@ -109,7 +109,7 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n}\nprivate HttpClient buildClient(boolean browserProxyRequest) {\n- if (browserProxyRequest && !trustAll) {\n+ if (browserProxyRequest && !trustAllProxyTargets) {\nreturn scepticalClient;\n} else {\nreturn this.client;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java",
"diff": "@@ -198,7 +198,7 @@ public class WarConfiguration implements Options {\n}\n@Override\n- public boolean trustAll() {\n+ public boolean trustAllProxyTargets() {\nreturn false;\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java",
"diff": "@@ -96,7 +96,7 @@ public class CommandLineOptions implements Options {\nprivate static final String DISABLE_GZIP = \"disable-gzip\";\nprivate static final String DISABLE_REQUEST_LOGGING = \"disable-request-logging\";\nprivate static final String ENABLE_STUB_CORS = \"enable-stub-cors\";\n- private static final String TRUST_ALL = \"trust-all\";\n+ private static final String TRUST_ALL_PROXY_TARGETS = \"trust-all-proxy-targets\";\nprivate final OptionSet optionSet;\nprivate final FileSource fileSource;\n@@ -147,7 +147,7 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(DISABLE_GZIP, \"Disable gzipping of request and response bodies\");\noptionParser.accepts(DISABLE_REQUEST_LOGGING, \"Disable logging of stub requests and responses to the notifier. Useful when performance testing.\");\noptionParser.accepts(ENABLE_STUB_CORS, \"Enable automatic sending of CORS headers with stub responses.\");\n- optionParser.accepts(TRUST_ALL, \"Trust all certificates presented by origins when browser proxying\");\n+ optionParser.accepts(TRUST_ALL_PROXY_TARGETS, \"Trust all certificates presented by origins when browser proxying\");\noptionParser.accepts(HELP, \"Print this message\");\n@@ -562,8 +562,8 @@ public class CommandLineOptions implements Options {\n}\n@Override\n- public boolean trustAll() {\n- return optionSet.has(TRUST_ALL);\n+ public boolean trustAllProxyTargets() {\n+ return optionSet.has(TRUST_ALL_PROXY_TARGETS);\n}\nprivate Long getMaxTemplateCacheEntries() {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java",
"diff": "@@ -72,7 +72,7 @@ public class ProxyResponseRendererTest {\n}\n@Test\n- public void acceptsSelfSignedCertificateForReverseProxyingIfTrustAll() {\n+ public void acceptsSelfSignedCertificateForReverseProxyingIfTrustAllProxyTargets() {\nfinal ProxyResponseRenderer trustAllProxyResponseRenderer = buildProxyResponseRenderer(true);\n@@ -141,14 +141,14 @@ public class ProxyResponseRendererTest {\nreturn keyGen.generateKeyPair();\n}\n- private ProxyResponseRenderer buildProxyResponseRenderer(boolean trustAll) {\n+ private ProxyResponseRenderer buildProxyResponseRenderer(boolean trustAllProxyTargets) {\nreturn new ProxyResponseRenderer(\nProxySettings.NO_PROXY,\nKeyStoreSettings.NO_STORE,\n/* preserveHostHeader = */ false,\n/* hostHeaderValue = */ null,\nnew GlobalSettingsHolder(),\n- trustAll\n+ trustAllProxyTargets\n);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java",
"diff": "@@ -33,12 +33,9 @@ import com.google.common.base.Optional;\nimport org.junit.Test;\nimport java.util.Map;\n-import java.util.regex.Pattern;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.matchesMultiLine;\n-import static java.util.regex.Pattern.DOTALL;\n-import static java.util.regex.Pattern.MULTILINE;\nimport static org.hamcrest.Matchers.*;\nimport static org.hamcrest.MatcherAssert.assertThat;\n@@ -482,14 +479,14 @@ public class CommandLineOptionsTest {\n@Test\npublic void trustsAll() {\n- CommandLineOptions options = new CommandLineOptions(\"--trust-all\");\n- assertThat(options.trustAll(), is(true));\n+ CommandLineOptions options = new CommandLineOptions(\"--trust-all-proxy-targets\");\n+ assertThat(options.trustAllProxyTargets(), is(true));\n}\n@Test\npublic void defaultsToNotTrustingAll() {\nCommandLineOptions options = new CommandLineOptions();\n- assertThat(options.trustAll(), is(false));\n+ assertThat(options.trustAllProxyTargets(), is(false));\n}\n@Test\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Rename trust-all to trust-all-proxy-targets
More explicit name. |
686,981 | 01.06.2020 10:34:52 | -3,600 | 46da3df242228308eef9fc864f15ef7361b7ea75 | Fix misnamed tests
They are testing forward proxying, not reverse proxying. | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java",
"diff": "@@ -55,7 +55,7 @@ public class ProxyResponseRendererTest {\n}\n@Test\n- public void rejectsSelfSignedCertificateForReverseProxying() {\n+ public void rejectsSelfSignedCertificateForForwardProxyingByDefault() {\norigin.stubFor(get(\"/proxied\").willReturn(aResponse().withBody(\"Result\")));\n@@ -72,7 +72,7 @@ public class ProxyResponseRendererTest {\n}\n@Test\n- public void acceptsSelfSignedCertificateForReverseProxyingIfTrustAllProxyTargets() {\n+ public void acceptsSelfSignedCertificateForForwardProxyingIfTrustAllProxyTargets() {\nfinal ProxyResponseRenderer trustAllProxyResponseRenderer = buildProxyResponseRenderer(true);\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fix misnamed tests
They are testing forward proxying, not reverse proxying. |
686,936 | 01.06.2020 10:50:13 | -3,600 | c327c5b20033d7b53bf108eb3f264799c147d65f | Started caching expected XML in EqualToXmlPattern as a Document to reduce repeated parsing | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java",
"diff": "@@ -22,6 +22,7 @@ import com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\n+import org.w3c.dom.Document;\nimport org.w3c.dom.Node;\nimport org.xmlunit.XMLUnitException;\nimport org.xmlunit.builder.DiffBuilder;\n@@ -60,6 +61,7 @@ public class EqualToXmlPattern extends MemoizingStringValuePattern {\nprivate final String placeholderClosingDelimiterRegex;\nprivate final DifferenceEvaluator diffEvaluator;\nprivate final Set<ComparisonType> exemptedComparisons;\n+ private final Document expectedXmlDoc;\npublic EqualToXmlPattern(@JsonProperty(\"equalToXml\") String expectedValue) {\nthis(expectedValue, null, null, null, null);\n@@ -72,7 +74,7 @@ public class EqualToXmlPattern extends MemoizingStringValuePattern {\n@JsonProperty(\"exemptedComparisons\") Set<ComparisonType> exemptedComparisons) {\nsuper(expectedValue);\n- Xml.read(expectedValue); // Throw an exception if we can't parse the document\n+ expectedXmlDoc = Xml.read(expectedValue); // Throw an exception if we can't parse the document\nthis.enablePlaceholders = enablePlaceholders;\nthis.placeholderOpeningDelimiterRegex = placeholderOpeningDelimiterRegex;\nthis.placeholderClosingDelimiterRegex = placeholderClosingDelimiterRegex;\n@@ -121,7 +123,7 @@ public class EqualToXmlPattern extends MemoizingStringValuePattern {\nreturn false;\n}\ntry {\n- Diff diff = DiffBuilder.compare(Input.from(expectedValue))\n+ Diff diff = DiffBuilder.compare(Input.from(expectedXmlDoc))\n.withTest(value)\n.withComparisonController(ComparisonControllers.StopWhenDifferent)\n.ignoreWhitespace()\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Started caching expected XML in EqualToXmlPattern as a Document to reduce repeated parsing |
686,936 | 01.06.2020 15:29:36 | -3,600 | e584b16253d487ffb6dde1e444d4920e05ec3d0d | Flattened the response template request model to save keystrokes and sanity. Also fixed the distinction between path and url (path + query string). | [
{
"change_type": "MODIFY",
"old_path": "docs-v2/_docs/response-templating.md",
"new_path": "docs-v2/_docs/response-templating.md",
"diff": "@@ -116,7 +116,7 @@ The body file for a response can be selected dynamically by templating the file\n```java\nwm.stubFor(get(urlPathMatching(\"/static/.*\"))\n.willReturn(ok()\n- .withBodyFile(\"files/{{request.requestLine.pathSegments.[1]}}\")));\n+ .withBodyFile(\"files/{{request.pathSegments.[1]}}\")));\n```\n{% endraw %}\n@@ -132,7 +132,7 @@ wm.stubFor(get(urlPathMatching(\"/static/.*\"))\n},\n\"response\" : {\n\"status\" : 200,\n- \"bodyFileName\" : \"files/{{request.requestLine.pathSegments.[1]}}\"\n+ \"bodyFileName\" : \"files/{{request.pathSegments.[1]}}\"\n}\n}\n```\n@@ -143,23 +143,23 @@ The model of the request is supplied to the header and body templates. The follo\n`request.url` - URL path and query\n-`request.requestLine.path` - URL path\n+`request.path` - URL path\n-`request.requestLine.pathSegments.[<n>]`- URL path segment (zero indexed) e.g. `request.requestLine.pathSegments.[2]`\n+`request.pathSegments.[<n>]`- URL path segment (zero indexed) e.g. `request.pathSegments.[2]`\n-`request.requestLine.query.<key>`- First value of a query parameter e.g. `request.query.search`\n+`request.query.<key>`- First value of a query parameter e.g. `request.query.search`\n-`request.requestLine.query.<key>.[<n>]`- nth value of a query parameter (zero indexed) e.g. `request.query.search.[5]`\n+`request.query.<key>.[<n>]`- nth value of a query parameter (zero indexed) e.g. `request.query.search.[5]`\n-`request.requestLine.method`- request method e.g. `POST`\n+`request.method`- request method e.g. `POST`\n-`request.requestLine.host`- hostname part of the URL e.g. `my.example.com`\n+`request.host`- hostname part of the URL e.g. `my.example.com`\n-`request.requestLine.port`- port number e.g. `8080`\n+`request.port`- port number e.g. `8080`\n-`request.requestLine.scheme`- protocol part of the URL e.g. `https`\n+`request.scheme`- protocol part of the URL e.g. `https`\n-`request.requestLine.baseUrl`- URL up to the start of the path e.g. `https://my.example.com:8080`\n+`request.baseUrl`- URL up to the start of the path e.g. `https://my.example.com:8080`\n`request.headers.<key>`- First value of a request header e.g. `request.headers.X-Request-Id`\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/RequestLine.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/RequestLine.java",
"diff": "@@ -27,20 +27,24 @@ import com.google.common.collect.Maps;\nimport java.net.URI;\nimport java.util.Map;\n+@Deprecated\n+/**\n+ * @deprecated Use the accessors on {@link RequestTemplateModel}\n+ */\npublic class RequestLine {\nprivate final RequestMethod method;\nprivate final String scheme;\nprivate final String host;\nprivate final int port;\nprivate final Map<String, ListOrSingle<String>> query;\n- private final String path;\n+ private final String url;\n- private RequestLine(RequestMethod method, String scheme, String host, int port, String path, Map<String, ListOrSingle<String>> query) {\n+ private RequestLine(RequestMethod method, String scheme, String host, int port, String url, Map<String, ListOrSingle<String>> query) {\nthis.method = method;\nthis.scheme = scheme;\nthis.host = host;\nthis.port = port;\n- this.path = path;\n+ this.url = url;\nthis.query = query;\n}\n@@ -56,11 +60,15 @@ public class RequestLine {\n}\npublic UrlPath getPathSegments() {\n- return new UrlPath(path);\n+ return new UrlPath(url);\n}\npublic String getPath() {\n- return path;\n+ return getPathSegments().toString();\n+ }\n+\n+ public String getUrl() {\n+ return url;\n}\npublic Map<String, ListOrSingle<String>> getQuery() {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/RequestTemplateModel.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/RequestTemplateModel.java",
"diff": "package com.github.tomakehurst.wiremock.extension.responsetemplating;\nimport com.github.tomakehurst.wiremock.common.ListOrSingle;\n-import com.github.tomakehurst.wiremock.common.Urls;\nimport com.github.tomakehurst.wiremock.http.Cookie;\nimport com.github.tomakehurst.wiremock.http.Request;\n+import com.github.tomakehurst.wiremock.http.RequestMethod;\nimport com.google.common.base.Function;\nimport com.google.common.collect.Maps;\nimport java.util.Map;\n@@ -67,30 +67,42 @@ public class RequestTemplateModel {\nreturn requestLine;\n}\n- /**\n- * @deprecated use requestLine to access information about the request\n- */\n- @Deprecated\n- public String getUrl() {\n- return requestLine.getPath();\n+ public RequestMethod getMethod() {\n+ return requestLine.getMethod();\n+ }\n+\n+ public UrlPath getPathSegments() {\n+ return requestLine.getPathSegments();\n}\n- /**\n- * @deprecated use requestLine to access information about the request\n- */\n- @Deprecated\npublic UrlPath getPath() {\nreturn requestLine.getPathSegments();\n}\n- /**\n- * @deprecated use requestLine to access information about the request\n- */\n- @Deprecated\n+ public String getUrl() {\n+ return requestLine.getUrl();\n+ }\n+\npublic Map<String, ListOrSingle<String>> getQuery() {\nreturn requestLine.getQuery();\n}\n+ public String getScheme() {\n+ return requestLine.getScheme();\n+ }\n+\n+ public String getHost() {\n+ return requestLine.getHost();\n+ }\n+\n+ public int getPort() {\n+ return requestLine.getPort();\n+ }\n+\n+ public String getBaseUrl() {\n+ return requestLine.getBaseUrl();\n+ }\n+\npublic Map<String, ListOrSingle<String>> getHeaders() {\nreturn headers;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java",
"diff": "@@ -466,7 +466,24 @@ public class ResponseTemplateTransformerTest {\n.port(8080)\n.url(\"/the/entire/path?query1=one&query2=two\"),\naResponse().withBody(\n- \"path: {{{request.requestLine.path}}}\"\n+ \"path: {{{request.path}}}\"\n+ )\n+ );\n+\n+ assertThat(transformedResponseDef.getBody(), is(\n+ \"path: /the/entire/path\"\n+ ));\n+ }\n+\n+ @Test\n+ public void requestLineUrl() {\n+ ResponseDefinition transformedResponseDef = transform(mockRequest()\n+ .scheme(\"https\")\n+ .host(\"my.domain.io\")\n+ .port(8080)\n+ .url(\"/the/entire/path?query1=one&query2=two\"),\n+ aResponse().withBody(\n+ \"path: {{{request.url}}}\"\n)\n);\n@@ -483,7 +500,7 @@ public class ResponseTemplateTransformerTest {\n.port(8080)\n.url(\"/the/entire/path?query1=one&query2=two\"),\naResponse().withBody(\n- \"baseUrl: {{{request.requestLine.baseUrl}}}\"\n+ \"baseUrl: {{{request.baseUrl}}}\"\n)\n);\n@@ -500,7 +517,7 @@ public class ResponseTemplateTransformerTest {\n.port(80)\n.url(\"/the/entire/path?query1=one&query2=two\"),\naResponse().withBody(\n- \"baseUrl: {{{request.requestLine.baseUrl}}}\"\n+ \"baseUrl: {{{request.baseUrl}}}\"\n)\n);\n@@ -517,7 +534,7 @@ public class ResponseTemplateTransformerTest {\n.port(443)\n.url(\"/the/entire/path?query1=one&query2=two\"),\naResponse().withBody(\n- \"baseUrl: {{{request.requestLine.baseUrl}}}\"\n+ \"baseUrl: {{{request.baseUrl}}}\"\n)\n);\n@@ -534,7 +551,7 @@ public class ResponseTemplateTransformerTest {\n.port(8080)\n.url(\"/the/entire/path?query1=one&query2=two\"),\naResponse().withBody(\n- \"path segments: {{{request.requestLine.pathSegments}}}\"\n+ \"path segments: {{{request.pathSegments}}}\"\n)\n);\n@@ -551,7 +568,7 @@ public class ResponseTemplateTransformerTest {\n.port(8080)\n.url(\"/the/entire/path?query1=one&query2=two\"),\naResponse().withBody(\n- \"path segments 0: {{{request.requestLine.pathSegments.[0]}}}\"\n+ \"path segments 0: {{{request.pathSegments.[0]}}}\"\n)\n);\n@@ -565,7 +582,7 @@ public class ResponseTemplateTransformerTest {\nResponseDefinition transformedResponseDef = transform(mockRequest()\n.url(\"/things?multi_param=one&multi_param=two&single-param=1234\"),\naResponse().withBody(\n- \"Multi 1: {{request.requestLine.query.multi_param.[0]}}, Multi 2: {{request.requestLine.query.multi_param.[1]}}, Single 1: {{request.requestLine.query.single-param}}\"\n+ \"Multi 1: {{request.query.multi_param.[0]}}, Multi 2: {{request.query.multi_param.[1]}}, Single 1: {{request.query.single-param}}\"\n)\n);\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Flattened the response template request model to save keystrokes and sanity. Also fixed the distinction between path and url (path + query string). |
686,981 | 29.05.2020 09:23:33 | -3,600 | c77f79b7256a71dafcbc355d063d1c0c9627d3ba | Fix the simple to fix deprecation warnings | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"diff": "@@ -20,24 +20,21 @@ import com.github.tomakehurst.wiremock.common.ProxySettings;\nimport org.apache.http.HttpHost;\nimport org.apache.http.auth.AuthScope;\nimport org.apache.http.auth.UsernamePasswordCredentials;\n-import org.apache.http.client.AuthenticationStrategy;\n-import org.apache.http.client.CredentialsProvider;\nimport org.apache.http.client.config.RequestConfig;\nimport org.apache.http.client.methods.*;\nimport org.apache.http.config.SocketConfig;\n-import org.apache.http.conn.ssl.AllowAllHostnameVerifier;\n-import org.apache.http.conn.ssl.SSLContextBuilder;\n-import org.apache.http.conn.ssl.SSLContexts;\n+import org.apache.http.conn.ssl.NoopHostnameVerifier;\nimport org.apache.http.conn.ssl.TrustSelfSignedStrategy;\nimport org.apache.http.conn.ssl.TrustStrategy;\nimport org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.ProxyAuthenticationStrategy;\n+import org.apache.http.ssl.SSLContextBuilder;\n+import org.apache.http.ssl.SSLContexts;\nimport javax.net.ssl.SSLContext;\nimport java.security.KeyStore;\n-import java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n@@ -69,7 +66,7 @@ public class HttpClientFactory {\n.setDefaultRequestConfig(RequestConfig.custom().setStaleConnectionCheckEnabled(true).build())\n.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeoutMilliseconds).build())\n.useSystemProperties()\n- .setHostnameVerifier(new AllowAllHostnameVerifier());\n+ .setSSLHostnameVerifier(new NoopHostnameVerifier());\nif (proxySettings != NO_PROXY) {\nHttpHost proxyHost = new HttpHost(proxySettings.host(), proxySettings.port());\n@@ -85,9 +82,9 @@ public class HttpClientFactory {\n}\nif (trustStoreSettings != NO_STORE) {\n- builder.setSslcontext(buildSSLContextWithTrustStore(trustStoreSettings, trustSelfSignedCertificates));\n+ builder.setSSLContext(buildSSLContextWithTrustStore(trustStoreSettings, trustSelfSignedCertificates));\n} else if (trustSelfSignedCertificates) {\n- builder.setSslcontext(buildAllowAnythingSSLContext());\n+ builder.setSSLContext(buildAllowAnythingSSLContext());\n}\nreturn builder.build();\n@@ -106,7 +103,7 @@ public class HttpClientFactory {\nKeyStore trustStore = trustStoreSettings.loadStore();\nSSLContextBuilder sslContextBuilder = SSLContexts.custom()\n.loadKeyMaterial(trustStore, trustStoreSettings.password().toCharArray())\n- .useTLS();\n+ .setProtocol(\"TLS\");\nif (trustSelfSignedCertificates) {\nsslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());\n}\n@@ -121,7 +118,7 @@ public class HttpClientFactory {\ntry {\nreturn SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {\n@Override\n- public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n+ public boolean isTrusted(X509Certificate[] chain, String authType) {\nreturn true;\n}\n}).build();\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Fix the simple to fix deprecation warnings |
686,981 | 01.06.2020 11:36:35 | -3,600 | 16394dd8605b614a335dc0313cd118772c046205 | Add failing tests for per-host certificate validation | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"diff": "@@ -36,6 +36,8 @@ import org.apache.http.ssl.SSLContexts;\nimport javax.net.ssl.SSLContext;\nimport java.security.KeyStore;\nimport java.security.cert.X509Certificate;\n+import java.util.Collections;\n+import java.util.List;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.common.KeyStoreSettings.NO_STORE;\n@@ -54,7 +56,8 @@ public class HttpClientFactory {\nint timeoutMilliseconds,\nProxySettings proxySettings,\nKeyStoreSettings trustStoreSettings,\n- boolean trustSelfSignedCertificates) {\n+ boolean trustSelfSignedCertificates,\n+ final List<String> trustedHosts) {\nHttpClientBuilder builder = HttpClientBuilder.create()\n.disableAuthCaching()\n@@ -95,7 +98,7 @@ public class HttpClientFactory {\nint timeoutMilliseconds,\nProxySettings proxySettings,\nKeyStoreSettings trustStoreSettings) {\n- return createClient(maxConnections, timeoutMilliseconds, proxySettings, trustStoreSettings, true);\n+ return createClient(maxConnections, timeoutMilliseconds, proxySettings, trustStoreSettings, true, Collections.<String>emptyList());\n}\nprivate static SSLContext buildSSLContextWithTrustStore(KeyStoreSettings trustStoreSettings, boolean trustSelfSignedCertificates) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java",
"diff": "@@ -32,6 +32,7 @@ import java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URI;\n+import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n@@ -72,8 +73,8 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n) {\nthis.globalSettingsHolder = globalSettingsHolder;\nthis.trustAllProxyTargets = trustAllProxyTargets;\n- client = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, true);\n- scepticalClient = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, false);\n+ client = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, true, Collections.<String>emptyList());\n+ scepticalClient = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, false, Collections.<String>emptyList());\nthis.preserveHostHeader = preserveHostHeader;\nthis.hostHeaderValue = hostHeaderValue;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/InMemoryKeyStore.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/InMemoryKeyStore.java",
"diff": "@@ -48,9 +48,12 @@ public class InMemoryKeyStore {\n}\n}\n- public void addPrivateKey(String alias, KeyPair keyPair, CertificateSpecification specification) throws KeyStoreException, CertificateException, InvalidKeyException, SignatureException {\n- Certificate cert = specification.certificateFor(keyPair);\n- keyStore.setKeyEntry(alias, keyPair.getPrivate(), password.getValue(), new Certificate[] { cert });\n+ public void addPrivateKey(String alias, KeyPair keyPair, Certificate... certs) throws KeyStoreException {\n+ keyStore.setKeyEntry(alias, keyPair.getPrivate(), password.getValue(), certs);\n+ }\n+\n+ public void addCertificate(String alias, Certificate cert) throws KeyStoreException {\n+ keyStore.setCertificateEntry(alias, cert);\n}\npublic void saveAs(File file) throws IOException {\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryAcceptsTrustedCertificatesTest.java",
"diff": "+package com.github.tomakehurst.wiremock.http;\n+\n+import org.apache.http.HttpResponse;\n+import org.apache.http.client.methods.HttpGet;\n+import org.junit.Test;\n+import org.junit.runner.RunWith;\n+import org.junit.runners.Parameterized;\n+import org.junit.runners.Parameterized.Parameters;\n+\n+import java.util.Collection;\n+import java.util.List;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\n+import static com.github.tomakehurst.wiremock.common.HttpClientUtils.getEntityAsStringAndCloseStream;\n+import static java.util.Arrays.asList;\n+import static java.util.Collections.singletonList;\n+import static org.junit.Assert.assertEquals;\n+\n+@RunWith(Parameterized.class)\n+public class HttpClientFactoryAcceptsTrustedCertificatesTest extends HttpClientFactoryCertificateVerificationTest {\n+\n+ @Parameters(name = \"{index}: trusted={0}, certificateCN={1}, validCertificate={2}\")\n+ public static Collection<Object[]> data() {\n+ return asList(new Object[][] {\n+ // trusted certificateCN validCertificate?\n+ { TRUST_NOBODY, \"localhost\", true },\n+ { singletonList(\"other.com\"), \"localhost\", true },\n+ { singletonList(\"localhost\"), \"other.com\", true },\n+ { singletonList(\"localhost\"), \"other.com\", false },\n+ { singletonList(\"localhost\"), \"localhost\", true },\n+ { singletonList(\"localhost\"), \"localhost\", false },\n+ });\n+ }\n+\n+ @Test\n+ public void certificatesAreAccepted() throws Exception {\n+\n+ server.stubFor(get(\"/whatever\").willReturn(aResponse().withBody(\"Hello World\")));\n+\n+ HttpResponse response = client.execute(new HttpGet(server.url(\"/whatever\")));\n+\n+ String result = getEntityAsStringAndCloseStream(response);\n+\n+ assertEquals(\"Hello World\", result);\n+ }\n+\n+ public HttpClientFactoryAcceptsTrustedCertificatesTest(\n+ List<String> trustedHosts,\n+ String certificateCN,\n+ boolean validCertificate\n+ ) {\n+ super(trustedHosts, certificateCN, validCertificate);\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryCertificateVerificationTest.java",
"diff": "+package com.github.tomakehurst.wiremock.http;\n+\n+import com.github.tomakehurst.wiremock.WireMockServer;\n+import com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.crypto.CertificateSpecification;\n+import com.github.tomakehurst.wiremock.crypto.InMemoryKeyStore;\n+import com.github.tomakehurst.wiremock.crypto.Secret;\n+import com.github.tomakehurst.wiremock.crypto.X509CertificateSpecification;\n+import org.apache.http.client.HttpClient;\n+import org.junit.After;\n+import org.junit.Before;\n+\n+import java.io.File;\n+import java.security.KeyPair;\n+import java.security.KeyPairGenerator;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.cert.Certificate;\n+import java.util.Date;\n+import java.util.List;\n+\n+import static com.github.tomakehurst.wiremock.common.ProxySettings.NO_PROXY;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\n+import static com.github.tomakehurst.wiremock.crypto.InMemoryKeyStore.KeyStoreType.JKS;\n+import static com.github.tomakehurst.wiremock.crypto.X509CertificateVersion.V3;\n+import static java.util.Collections.emptyList;\n+\n+public abstract class HttpClientFactoryCertificateVerificationTest {\n+\n+ protected static final List<String> TRUST_NOBODY = emptyList();\n+\n+ private final List<String> trustedHosts;\n+ private final String certificateCN;\n+ private final boolean validCertificate;\n+ protected WireMockServer server = null;\n+ protected HttpClient client;\n+\n+ protected HttpClientFactoryCertificateVerificationTest(\n+ List<String> trustedHosts,\n+ String certificateCN,\n+ boolean validCertificate\n+ ) {\n+ this.trustedHosts = trustedHosts;\n+ this.certificateCN = certificateCN;\n+ this.validCertificate = validCertificate;\n+ }\n+\n+ @Before\n+ public void startServerAndBuildClient() throws Exception {\n+\n+ InMemoryKeyStore ks = new InMemoryKeyStore(JKS, new Secret(\"password\"));\n+\n+ KeyPair keyPair = generateKeyPair();\n+\n+ CertificateSpecification certificateSpecification = new X509CertificateSpecification(\n+ /* version = */V3,\n+ /* subject = */\"CN=\" + certificateCN,\n+ /* issuer = */\"CN=wiremock.org\",\n+ /* notBefore = */new Date(),\n+ /* notAfter = */new Date(System.currentTimeMillis() + (365L * 24 * 60 * 60 * 1000))\n+ );\n+\n+ Certificate certificate = certificateSpecification.certificateFor(keyPair);\n+\n+ ks.addPrivateKey(\"wiremock\", keyPair, certificate);\n+\n+ File serverKeyStoreFile = File.createTempFile(\"wiremock-server\", \"jks\");\n+\n+ ks.saveAs(serverKeyStoreFile);\n+\n+ server = new WireMockServer(options()\n+ .httpDisabled(true)\n+ .dynamicHttpsPort()\n+ .keystorePath(serverKeyStoreFile.getAbsolutePath())\n+ );\n+ server.start();\n+\n+\n+ InMemoryKeyStore clientTrustStore = new InMemoryKeyStore(JKS, new Secret(\"password\"));\n+ if (validCertificate) {\n+ clientTrustStore.addCertificate(\"wiremock\", certificate);\n+ }\n+ File clientTrustStoreFile = File.createTempFile(\"wiremock-client\", \"jks\");\n+ clientTrustStore.saveAs(clientTrustStoreFile);\n+ KeyStoreSettings clientTrustStoreSettings = new KeyStoreSettings(clientTrustStoreFile.getAbsolutePath(), \"password\");\n+\n+ client = HttpClientFactory.createClient(\n+ 1000,\n+ 5 * 1000 * 60,\n+ NO_PROXY,\n+ clientTrustStoreSettings,\n+ /* trustSelfSignedCertificates = */false,\n+ trustedHosts\n+ );\n+ }\n+\n+ @After\n+ public void stopServer() {\n+ if (server != null) {\n+ server.stop();\n+ }\n+ }\n+\n+ private KeyPair generateKeyPair() throws NoSuchAlgorithmException {\n+ KeyPairGenerator keyGen = KeyPairGenerator.getInstance(\"RSA\");\n+ keyGen.initialize(1024);\n+ return keyGen.generateKeyPair();\n+ }\n+\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryRejectsUntrustedCertificatesTest.java",
"diff": "+package com.github.tomakehurst.wiremock.http;\n+\n+import org.apache.http.client.methods.HttpGet;\n+import org.junit.Test;\n+import org.junit.function.ThrowingRunnable;\n+import org.junit.runner.RunWith;\n+import org.junit.runners.Parameterized;\n+import org.junit.runners.Parameterized.Parameters;\n+\n+import javax.net.ssl.SSLException;\n+import java.util.Collection;\n+import java.util.List;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\n+import static java.util.Arrays.asList;\n+import static java.util.Collections.singletonList;\n+import static org.junit.Assert.assertThrows;\n+\n+@RunWith(Parameterized.class)\n+public class HttpClientFactoryRejectsUntrustedCertificatesTest extends HttpClientFactoryCertificateVerificationTest {\n+\n+ @Parameters(name = \"{index}: trusted={0}, certificateCN={1}, validCertificate={2}\")\n+ public static Collection<Object[]> data() {\n+ return asList(new Object[][] {\n+ // trusted certificateCN validCertificate?\n+ { TRUST_NOBODY, \"other.com\", true },\n+ { TRUST_NOBODY, \"other.com\", false },\n+ { TRUST_NOBODY, \"localhost\", false },\n+ { singletonList(\"other.com\"), \"other.com\", true },\n+ { singletonList(\"other.com\"), \"other.com\", false },\n+ { singletonList(\"other.com\"), \"localhost\", false }\n+ });\n+ }\n+\n+ @Test\n+ public void certificatesAreRejectedAsExpected() {\n+\n+ server.stubFor(get(\"/whatever\").willReturn(aResponse().withBody(\"Hello World\")));\n+\n+ assertThrows(SSLException.class, new ThrowingRunnable() {\n+ @Override\n+ public void run() throws Exception {\n+ client.execute(new HttpGet(server.url(\"/whatever\")));\n+ }\n+ });\n+ }\n+\n+ public HttpClientFactoryRejectsUntrustedCertificatesTest(\n+ List<String> trustedHosts,\n+ String certificateCN,\n+ boolean validCertificate\n+ ) {\n+ super(trustedHosts, certificateCN, validCertificate);\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java",
"diff": "@@ -2,6 +2,7 @@ package com.github.tomakehurst.wiremock.http;\nimport com.github.tomakehurst.wiremock.common.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\n+import com.github.tomakehurst.wiremock.crypto.CertificateSpecification;\nimport com.github.tomakehurst.wiremock.crypto.InMemoryKeyStore;\nimport com.github.tomakehurst.wiremock.crypto.Secret;\nimport com.github.tomakehurst.wiremock.crypto.X509CertificateSpecification;\n@@ -120,13 +121,15 @@ public class ProxyResponseRendererTest {\nInMemoryKeyStore ks = new InMemoryKeyStore(InMemoryKeyStore.KeyStoreType.JKS, new Secret(\"password\"));\n- ks.addPrivateKey(\"wiremock\", generateKeyPair(), new X509CertificateSpecification(\n+ CertificateSpecification certificateSpecification = new X509CertificateSpecification(\n/* version = */V3,\n/* subject = */\"CN=wiremock.org\",\n/* issuer = */\"CN=wiremock.org\",\n/* notBefore = */new Date(),\n/* notAfter = */new Date(System.currentTimeMillis() + (365L * 24 * 60 * 60 * 1000))\n- ));\n+ );\n+ KeyPair keyPair = generateKeyPair();\n+ ks.addPrivateKey(\"wiremock\", keyPair, certificateSpecification.certificateFor(keyPair));\nFile keystoreFile = File.createTempFile(\"wiremock-test\", \"keystore\");\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Add failing tests for per-host certificate validation |
686,981 | 01.06.2020 12:04:36 | -3,600 | a51d523a24bea6e23838d168f2b1c8e5d3bdbab0 | Use a fork of the Apache SSLContextBuilder
We need to make changes to the way the SSL context is built. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"diff": "@@ -30,8 +30,6 @@ import org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.ProxyAuthenticationStrategy;\n-import org.apache.http.ssl.SSLContextBuilder;\n-import org.apache.http.ssl.SSLContexts;\nimport javax.net.ssl.SSLContext;\nimport java.security.KeyStore;\n@@ -104,7 +102,7 @@ public class HttpClientFactory {\nprivate static SSLContext buildSSLContextWithTrustStore(KeyStoreSettings trustStoreSettings, boolean trustSelfSignedCertificates) {\ntry {\nKeyStore trustStore = trustStoreSettings.loadStore();\n- SSLContextBuilder sslContextBuilder = SSLContexts.custom()\n+ SSLContextBuilder sslContextBuilder = SSLContextBuilder.create()\n.loadKeyMaterial(trustStore, trustStoreSettings.password().toCharArray())\n.setProtocol(\"TLS\");\nif (trustSelfSignedCertificates) {\n@@ -119,7 +117,7 @@ public class HttpClientFactory {\nprivate static SSLContext buildAllowAnythingSSLContext() {\ntry {\n- return SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {\n+ return SSLContextBuilder.create().loadTrustMaterial(null, new TrustStrategy() {\n@Override\npublic boolean isTrusted(X509Certificate[] chain, String authType) {\nreturn true;\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/SSLContextBuilder.java",
"diff": "+/*\n+ * ====================================================================\n+ * Licensed to the Apache Software Foundation (ASF) under one\n+ * or more contributor license agreements. See the NOTICE file\n+ * distributed with this work for additional information\n+ * regarding copyright ownership. The ASF licenses this file\n+ * to you under the Apache License, Version 2.0 (the\n+ * \"License\"); you may not use this file except in compliance\n+ * with the License. You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing,\n+ * software distributed under the License is distributed on an\n+ * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+ * KIND, either express or implied. See the License for the\n+ * specific language governing permissions and limitations\n+ * under the License.\n+ * ====================================================================\n+ *\n+ * This software consists of voluntary contributions made by many\n+ * individuals on behalf of the Apache Software Foundation. For more\n+ * information on the Apache Software Foundation, please see\n+ * <http://www.apache.org/>.\n+ *\n+ */\n+\n+package com.github.tomakehurst.wiremock.http;\n+\n+import org.apache.http.ssl.PrivateKeyDetails;\n+import org.apache.http.ssl.PrivateKeyStrategy;\n+import org.apache.http.ssl.TrustStrategy;\n+import org.apache.http.util.Args;\n+\n+import javax.net.ssl.KeyManager;\n+import javax.net.ssl.KeyManagerFactory;\n+import javax.net.ssl.SSLContext;\n+import javax.net.ssl.SSLEngine;\n+import javax.net.ssl.TrustManager;\n+import javax.net.ssl.TrustManagerFactory;\n+import javax.net.ssl.X509ExtendedKeyManager;\n+import javax.net.ssl.X509TrustManager;\n+import java.io.File;\n+import java.io.FileInputStream;\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.net.Socket;\n+import java.net.URL;\n+import java.security.KeyManagementException;\n+import java.security.KeyStore;\n+import java.security.KeyStoreException;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.Principal;\n+import java.security.PrivateKey;\n+import java.security.Provider;\n+import java.security.SecureRandom;\n+import java.security.Security;\n+import java.security.UnrecoverableKeyException;\n+import java.security.cert.CertificateException;\n+import java.security.cert.X509Certificate;\n+import java.util.Collection;\n+import java.util.HashMap;\n+import java.util.LinkedHashSet;\n+import java.util.Map;\n+import java.util.Set;\n+\n+import static java.util.Collections.addAll;\n+\n+/**\n+ * Builder for {@link SSLContext} instances.\n+ * <p>\n+ * Please note: the default Oracle JSSE implementation of {@link SSLContext#init(KeyManager[], TrustManager[], SecureRandom)}\n+ * accepts multiple key and trust managers, however only only first matching type is ever used.\n+ * See for example:\n+ * <a href=\"http://docs.oracle.com/javase/7/docs/api/javax/net/ssl/SSLContext.html#init%28javax.net.ssl.KeyManager[],%20javax.net.ssl.TrustManager[],%20java.security.SecureRandom%29\">\n+ * SSLContext.html#init\n+ * </a>\n+ * <p>\n+ * TODO Specify which Oracle JSSE versions the above has been verified.\n+ * </p>\n+ * @since 4.4\n+ */\n+public class SSLContextBuilder {\n+\n+ static final String TLS = \"TLS\";\n+\n+ private String protocol;\n+ private final Set<KeyManager> keyManagers = new LinkedHashSet<>();\n+ private String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm();\n+ private String keyStoreType = KeyStore.getDefaultType();\n+ private final Set<TrustManager> trustManagers = new LinkedHashSet<>();\n+ private String trustManagerFactoryAlgorithm = TrustManagerFactory.getDefaultAlgorithm();\n+ private SecureRandom secureRandom;\n+ private Provider provider;\n+\n+ public static SSLContextBuilder create() {\n+ return new SSLContextBuilder();\n+ }\n+\n+ /**\n+ * Sets the SSLContext protocol algorithm name.\n+ *\n+ * @param protocol\n+ * the SSLContext protocol algorithm name of the requested protocol. See\n+ * the SSLContext section in the <a href=\n+ * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#SSLContext\">Java\n+ * Cryptography Architecture Standard Algorithm Name\n+ * Documentation</a> for more information.\n+ * @return this builder\n+ * @see <a href=\n+ * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#SSLContext\">Java\n+ * Cryptography Architecture Standard Algorithm Name Documentation</a>\n+ * @since 4.4.7\n+ */\n+ public SSLContextBuilder setProtocol(final String protocol) {\n+ this.protocol = protocol;\n+ return this;\n+ }\n+\n+ public SSLContextBuilder setSecureRandom(final SecureRandom secureRandom) {\n+ this.secureRandom = secureRandom;\n+ return this;\n+ }\n+\n+ public SSLContextBuilder setProvider(final Provider provider) {\n+ this.provider = provider;\n+ return this;\n+ }\n+\n+ public SSLContextBuilder setProvider(final String name) {\n+ this.provider = Security.getProvider(name);\n+ return this;\n+ }\n+\n+ /**\n+ * Sets the key store type.\n+ *\n+ * @param keyStoreType\n+ * the SSLkey store type. See\n+ * the KeyStore section in the <a href=\n+ * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#KeyStore\">Java\n+ * Cryptography Architecture Standard Algorithm Name\n+ * Documentation</a> for more information.\n+ * @return this builder\n+ * @see <a href=\n+ * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#KeyStore\">Java\n+ * Cryptography Architecture Standard Algorithm Name Documentation</a>\n+ * @since 4.4.7\n+ */\n+ public SSLContextBuilder setKeyStoreType(final String keyStoreType) {\n+ this.keyStoreType = keyStoreType;\n+ return this;\n+ }\n+\n+ /**\n+ * Sets the key manager factory algorithm name.\n+ *\n+ * @param keyManagerFactoryAlgorithm\n+ * the key manager factory algorithm name of the requested protocol. See\n+ * the KeyManagerFactory section in the <a href=\n+ * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#KeyManagerFactory\">Java\n+ * Cryptography Architecture Standard Algorithm Name\n+ * Documentation</a> for more information.\n+ * @return this builder\n+ * @see <a href=\n+ * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#KeyManagerFactory\">Java\n+ * Cryptography Architecture Standard Algorithm Name Documentation</a>\n+ * @since 4.4.7\n+ */\n+ public SSLContextBuilder setKeyManagerFactoryAlgorithm(final String keyManagerFactoryAlgorithm) {\n+ this.keyManagerFactoryAlgorithm = keyManagerFactoryAlgorithm;\n+ return this;\n+ }\n+\n+ /**\n+ * Sets the trust manager factory algorithm name.\n+ *\n+ * @param trustManagerFactoryAlgorithm\n+ * the trust manager algorithm name of the requested protocol. See\n+ * the TrustManagerFactory section in the <a href=\n+ * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#TrustManagerFactory\">Java\n+ * Cryptography Architecture Standard Algorithm Name\n+ * Documentation</a> for more information.\n+ * @return this builder\n+ * @see <a href=\n+ * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#TrustManagerFactory\">Java\n+ * Cryptography Architecture Standard Algorithm Name Documentation</a>\n+ * @since 4.4.7\n+ */\n+ public SSLContextBuilder setTrustManagerFactoryAlgorithm(final String trustManagerFactoryAlgorithm) {\n+ this.trustManagerFactoryAlgorithm = trustManagerFactoryAlgorithm;\n+ return this;\n+ }\n+\n+ public SSLContextBuilder loadTrustMaterial(\n+ final KeyStore truststore,\n+ final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {\n+ final TrustManagerFactory tmfactory = TrustManagerFactory\n+ .getInstance(trustManagerFactoryAlgorithm == null ? TrustManagerFactory.getDefaultAlgorithm()\n+ : trustManagerFactoryAlgorithm);\n+ tmfactory.init(truststore);\n+ final TrustManager[] tms = tmfactory.getTrustManagers();\n+ if (tms != null) {\n+ if (trustStrategy != null) {\n+ for (int i = 0; i < tms.length; i++) {\n+ final TrustManager tm = tms[i];\n+ if (tm instanceof X509TrustManager) {\n+ tms[i] = new TrustManagerDelegate((X509TrustManager) tm, trustStrategy);\n+ }\n+ }\n+ }\n+ addAll(this.trustManagers, tms);\n+ }\n+ return this;\n+ }\n+\n+ public SSLContextBuilder loadTrustMaterial(\n+ final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {\n+ return loadTrustMaterial(null, trustStrategy);\n+ }\n+\n+ public SSLContextBuilder loadTrustMaterial(\n+ final File file,\n+ final char[] storePassword,\n+ final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {\n+ Args.notNull(file, \"Truststore file\");\n+ final KeyStore trustStore = KeyStore.getInstance(keyStoreType);\n+ try (FileInputStream inStream = new FileInputStream(file)) {\n+ trustStore.load(inStream, storePassword);\n+ }\n+ return loadTrustMaterial(trustStore, trustStrategy);\n+ }\n+\n+ public SSLContextBuilder loadTrustMaterial(\n+ final File file,\n+ final char[] storePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {\n+ return loadTrustMaterial(file, storePassword, null);\n+ }\n+\n+ public SSLContextBuilder loadTrustMaterial(\n+ final File file) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {\n+ return loadTrustMaterial(file, null);\n+ }\n+\n+ public SSLContextBuilder loadTrustMaterial(\n+ final URL url,\n+ final char[] storePassword,\n+ final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {\n+ Args.notNull(url, \"Truststore URL\");\n+ final KeyStore trustStore = KeyStore.getInstance(keyStoreType);\n+ try (InputStream inStream = url.openStream()) {\n+ trustStore.load(inStream, storePassword);\n+ }\n+ return loadTrustMaterial(trustStore, trustStrategy);\n+ }\n+\n+ public SSLContextBuilder loadTrustMaterial(\n+ final URL url,\n+ final char[] storePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {\n+ return loadTrustMaterial(url, storePassword, null);\n+ }\n+\n+ public SSLContextBuilder loadKeyMaterial(\n+ final KeyStore keystore,\n+ final char[] keyPassword,\n+ final PrivateKeyStrategy aliasStrategy)\n+ throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {\n+ final KeyManagerFactory kmfactory = KeyManagerFactory\n+ .getInstance(keyManagerFactoryAlgorithm == null ? KeyManagerFactory.getDefaultAlgorithm()\n+ : keyManagerFactoryAlgorithm);\n+ kmfactory.init(keystore, keyPassword);\n+ final KeyManager[] kms = kmfactory.getKeyManagers();\n+ if (kms != null) {\n+ if (aliasStrategy != null) {\n+ for (int i = 0; i < kms.length; i++) {\n+ final KeyManager km = kms[i];\n+ if (km instanceof X509ExtendedKeyManager) {\n+ kms[i] = new KeyManagerDelegate((X509ExtendedKeyManager) km, aliasStrategy);\n+ }\n+ }\n+ }\n+ addAll(keyManagers, kms);\n+ }\n+ return this;\n+ }\n+\n+ public SSLContextBuilder loadKeyMaterial(\n+ final KeyStore keystore,\n+ final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {\n+ return loadKeyMaterial(keystore, keyPassword, null);\n+ }\n+\n+ public SSLContextBuilder loadKeyMaterial(\n+ final File file,\n+ final char[] storePassword,\n+ final char[] keyPassword,\n+ final PrivateKeyStrategy aliasStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {\n+ Args.notNull(file, \"Keystore file\");\n+ final KeyStore identityStore = KeyStore.getInstance(keyStoreType);\n+ try (FileInputStream inStream = new FileInputStream(file)) {\n+ identityStore.load(inStream, storePassword);\n+ }\n+ return loadKeyMaterial(identityStore, keyPassword, aliasStrategy);\n+ }\n+\n+ public SSLContextBuilder loadKeyMaterial(\n+ final File file,\n+ final char[] storePassword,\n+ final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {\n+ return loadKeyMaterial(file, storePassword, keyPassword, null);\n+ }\n+\n+ public SSLContextBuilder loadKeyMaterial(\n+ final URL url,\n+ final char[] storePassword,\n+ final char[] keyPassword,\n+ final PrivateKeyStrategy aliasStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {\n+ Args.notNull(url, \"Keystore URL\");\n+ final KeyStore identityStore = KeyStore.getInstance(keyStoreType);\n+ try (InputStream inStream = url.openStream()) {\n+ identityStore.load(inStream, storePassword);\n+ }\n+ return loadKeyMaterial(identityStore, keyPassword, aliasStrategy);\n+ }\n+\n+ public SSLContextBuilder loadKeyMaterial(\n+ final URL url,\n+ final char[] storePassword,\n+ final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {\n+ return loadKeyMaterial(url, storePassword, keyPassword, null);\n+ }\n+\n+ protected void initSSLContext(\n+ final SSLContext sslContext,\n+ final Collection<KeyManager> keyManagers,\n+ final Collection<TrustManager> trustManagers,\n+ final SecureRandom secureRandom) throws KeyManagementException {\n+ sslContext.init(\n+ !keyManagers.isEmpty() ? keyManagers.toArray(new KeyManager[0]) : null,\n+ !trustManagers.isEmpty() ? trustManagers.toArray(new TrustManager[0]) : null,\n+ secureRandom);\n+ }\n+\n+ public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException {\n+ final SSLContext sslContext;\n+ final String protocolStr = this.protocol != null ? this.protocol : TLS;\n+ if (this.provider != null) {\n+ sslContext = SSLContext.getInstance(protocolStr, this.provider);\n+ } else {\n+ sslContext = SSLContext.getInstance(protocolStr);\n+ }\n+ initSSLContext(sslContext, keyManagers, trustManagers, secureRandom);\n+ return sslContext;\n+ }\n+\n+ static class TrustManagerDelegate implements X509TrustManager {\n+\n+ private final X509TrustManager trustManager;\n+ private final TrustStrategy trustStrategy;\n+\n+ TrustManagerDelegate(final X509TrustManager trustManager, final TrustStrategy trustStrategy) {\n+ super();\n+ this.trustManager = trustManager;\n+ this.trustStrategy = trustStrategy;\n+ }\n+\n+ @Override\n+ public void checkClientTrusted(\n+ final X509Certificate[] chain, final String authType) throws CertificateException {\n+ this.trustManager.checkClientTrusted(chain, authType);\n+ }\n+\n+ @Override\n+ public void checkServerTrusted(\n+ final X509Certificate[] chain, final String authType) throws CertificateException {\n+ if (!this.trustStrategy.isTrusted(chain, authType)) {\n+ this.trustManager.checkServerTrusted(chain, authType);\n+ }\n+ }\n+\n+ @Override\n+ public X509Certificate[] getAcceptedIssuers() {\n+ return this.trustManager.getAcceptedIssuers();\n+ }\n+\n+ }\n+\n+ static class KeyManagerDelegate extends X509ExtendedKeyManager {\n+\n+ private final X509ExtendedKeyManager keyManager;\n+ private final PrivateKeyStrategy aliasStrategy;\n+\n+ KeyManagerDelegate(final X509ExtendedKeyManager keyManager, final PrivateKeyStrategy aliasStrategy) {\n+ super();\n+ this.keyManager = keyManager;\n+ this.aliasStrategy = aliasStrategy;\n+ }\n+\n+ @Override\n+ public String[] getClientAliases(\n+ final String keyType, final Principal[] issuers) {\n+ return this.keyManager.getClientAliases(keyType, issuers);\n+ }\n+\n+ public Map<String, PrivateKeyDetails> getClientAliasMap(\n+ final String[] keyTypes, final Principal[] issuers) {\n+ final Map<String, PrivateKeyDetails> validAliases = new HashMap<>();\n+ for (final String keyType: keyTypes) {\n+ final String[] aliases = this.keyManager.getClientAliases(keyType, issuers);\n+ if (aliases != null) {\n+ for (final String alias: aliases) {\n+ validAliases.put(alias,\n+ new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias)));\n+ }\n+ }\n+ }\n+ return validAliases;\n+ }\n+\n+ public Map<String, PrivateKeyDetails> getServerAliasMap(\n+ final String keyType, final Principal[] issuers) {\n+ final Map<String, PrivateKeyDetails> validAliases = new HashMap<>();\n+ final String[] aliases = this.keyManager.getServerAliases(keyType, issuers);\n+ if (aliases != null) {\n+ for (final String alias: aliases) {\n+ validAliases.put(alias,\n+ new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias)));\n+ }\n+ }\n+ return validAliases;\n+ }\n+\n+ @Override\n+ public String chooseClientAlias(\n+ final String[] keyTypes, final Principal[] issuers, final Socket socket) {\n+ final Map<String, PrivateKeyDetails> validAliases = getClientAliasMap(keyTypes, issuers);\n+ return this.aliasStrategy.chooseAlias(validAliases, socket);\n+ }\n+\n+ @Override\n+ public String[] getServerAliases(\n+ final String keyType, final Principal[] issuers) {\n+ return this.keyManager.getServerAliases(keyType, issuers);\n+ }\n+\n+ @Override\n+ public String chooseServerAlias(\n+ final String keyType, final Principal[] issuers, final Socket socket) {\n+ final Map<String, PrivateKeyDetails> validAliases = getServerAliasMap(keyType, issuers);\n+ return this.aliasStrategy.chooseAlias(validAliases, socket);\n+ }\n+\n+ @Override\n+ public X509Certificate[] getCertificateChain(final String alias) {\n+ return this.keyManager.getCertificateChain(alias);\n+ }\n+\n+ @Override\n+ public PrivateKey getPrivateKey(final String alias) {\n+ return this.keyManager.getPrivateKey(alias);\n+ }\n+\n+ @Override\n+ public String chooseEngineClientAlias(\n+ final String[] keyTypes, final Principal[] issuers, final SSLEngine sslEngine) {\n+ final Map<String, PrivateKeyDetails> validAliases = getClientAliasMap(keyTypes, issuers);\n+ return this.aliasStrategy.chooseAlias(validAliases, null);\n+ }\n+\n+ @Override\n+ public String chooseEngineServerAlias(\n+ final String keyType, final Principal[] issuers, final SSLEngine sslEngine) {\n+ final Map<String, PrivateKeyDetails> validAliases = getServerAliasMap(keyType, issuers);\n+ return this.aliasStrategy.chooseAlias(validAliases, null);\n+ }\n+\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"[provider=\" + provider + \", protocol=\" + protocol + \", keyStoreType=\" + keyStoreType\n+ + \", keyManagerFactoryAlgorithm=\" + keyManagerFactoryAlgorithm + \", keyManagers=\" + keyManagers\n+ + \", trustManagerFactoryAlgorithm=\" + trustManagerFactoryAlgorithm + \", trustManagers=\" + trustManagers\n+ + \", secureRandom=\" + secureRandom + \"]\";\n+ }\n+\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Use a fork of the Apache SSLContextBuilder
We need to make changes to the way the SSL context is built. |
686,936 | 01.06.2020 17:39:43 | -3,600 | 10395e81d13e2ada40a0e714761ef4998c4ccb1a | Increased error margin in response dribble test to reduce flakeyness | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java",
"diff": "@@ -40,6 +40,7 @@ public class ResponseDribbleAcceptanceTest {\nprivate static final int DOUBLE_THE_SOCKET_TIMEOUT = SOCKET_TIMEOUT_MILLISECONDS * 2;\nprivate static final byte[] BODY_BYTES = \"the long sentence being sent\".getBytes();\n+ public static final double ERROR_MARGIN = 200.0;\n@Rule\npublic WireMockRule wireMockRule = new WireMockRule(DYNAMIC_PORT, DYNAMIC_PORT);\n@@ -69,7 +70,7 @@ public class ResponseDribbleAcceptanceTest {\nassertThat(response.getStatusLine().getStatusCode(), is(200));\nassertThat(responseBody, is(BODY_BYTES));\nassertThat(duration, greaterThanOrEqualTo(SOCKET_TIMEOUT_MILLISECONDS));\n- assertThat((double) duration, closeTo(DOUBLE_THE_SOCKET_TIMEOUT, 100.0));\n+ assertThat((double) duration, closeTo(DOUBLE_THE_SOCKET_TIMEOUT, ERROR_MARGIN));\n}\n@Test\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Increased error margin in response dribble test to reduce flakeyness |
686,936 | 01.06.2020 17:40:28 | -3,600 | 7ba99b0f69e3c85b08ef2ed1be00576b60408f1f | Made URL match type explicit in diff reports if not path+query equality | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java",
"diff": "@@ -21,6 +21,9 @@ import com.github.tomakehurst.wiremock.common.xml.Xml;\nimport com.github.tomakehurst.wiremock.http.*;\nimport com.github.tomakehurst.wiremock.matching.*;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\n+import com.google.common.base.Joiner;\n+import com.google.common.base.Predicates;\n+import com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport java.net.URI;\n@@ -31,6 +34,7 @@ import java.util.Map;\nimport static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;\nimport static com.github.tomakehurst.wiremock.verification.diff.SpacerLine.SPACER;\nimport static com.google.common.base.MoreObjects.firstNonNull;\n+import static java.util.Arrays.asList;\npublic class Diff {\n@@ -66,9 +70,10 @@ public class Diff {\nbuilder.add(methodSection);\nUrlPattern urlPattern = firstNonNull(requestPattern.getUrlMatcher(), anyUrl());\n+ String printedUrlPattern = generatePrintedUrlPattern(urlPattern);\nDiffLine<String> urlSection = new DiffLine<>(\"URL\", urlPattern,\nrequest.getUrl(),\n- urlPattern.getExpected());\n+ printedUrlPattern);\nbuilder.add(urlSection);\nbuilder.add(SPACER);\n@@ -209,6 +214,17 @@ public class Diff {\n}\n}\n+ private String generatePrintedUrlPattern(UrlPattern urlPattern) {\n+ String matchPart = (urlPattern instanceof UrlPathPattern ? \"path\" : \"\") +\n+ (urlPattern.isRegex() ? \" regex\" : \"\");\n+\n+ matchPart = matchPart.trim();\n+\n+ return matchPart.isEmpty() ?\n+ urlPattern.getExpected() :\n+ \"[\" + matchPart + \"] \" + urlPattern.getExpected();\n+ }\n+\nprivate String generateOperatorString(ContentPattern<?> pattern, String defaultValue) {\nreturn isAnEqualToPattern(pattern) ? defaultValue : \" [\" + pattern.getName() + \"] \";\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java",
"diff": "@@ -86,7 +86,7 @@ public class DiffTest {\nassertThat(diff.toString(), is(\njunitStyleDiffMessage(\n\"ANY\\n\" +\n- \"/expected/.*\\n\",\n+ \"[path regex] /expected/.*\\n\",\n\"ANY\\n\" +\n\"/actual\\n\")\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/resources/not-found-diff-sample_no-path.txt",
"new_path": "src/test/resources/not-found-diff-sample_no-path.txt",
"diff": "-----------------------------------------------------------------------------------------------------------------------\n|\nGET | GET\n-/?q=correct | /q=wrong <<<<< URL does not match. When using a regex, \"?\" should be \"\\\\?\"\n+[regex] /?q=correct | /q=wrong <<<<< URL does not match. When using a regex, \"?\" should be \"\\\\?\"\n|\n|\n-----------------------------------------------------------------------------------------------------------------------\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/resources/not-found-diff-sample_query.txt",
"new_path": "src/test/resources/not-found-diff-sample_query.txt",
"diff": "Query params diff |\n|\nGET | GET\n-/thing | /thing?one=2&two=wrong%20things&three=abcde\n+[path] /thing | /thing?one=2&two=wrong%20things&three=abcde\n|\nQuery: one = 1 | one: 2 <<<<< Query does not match\nQuery: two [contains] two things | two: wrong things <<<<< Query does not match\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/resources/not-found-diff-sample_url-pattern.txt",
"new_path": "src/test/resources/not-found-diff-sample_url-pattern.txt",
"diff": "-----------------------------------------------------------------------------------------------------------------------\n|\nGET | GET\n-thing?query=value | /thing <<<<< URL does not match. When using a regex, \"?\" should be \"\\\\?\". URLs must start with a /\n+[regex] thing?query=value | /thing <<<<< URL does not match. When using a regex, \"?\" should be \"\\\\?\". URLs must start with a /\n|\n|\n-----------------------------------------------------------------------------------------------------------------------\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Made URL match type explicit in diff reports if not path+query equality |
686,981 | 01.06.2020 13:46:56 | -3,600 | f0af7942595b9dc08f7e52cab718060e0fe0069f | For testing, trust a public certificate added to the client key store
This fixes some of the tests. Breaks the new `realCertificateIsAccepted` test.
This is because calling `loadTrustMaterial` with a key store doesn't add its
certificates to the default trusted certificates, but instead replaces them
with the given key store. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"diff": "@@ -23,6 +23,7 @@ import org.apache.http.auth.UsernamePasswordCredentials;\nimport org.apache.http.client.config.RequestConfig;\nimport org.apache.http.client.methods.*;\nimport org.apache.http.config.SocketConfig;\n+import org.apache.http.conn.ssl.DefaultHostnameVerifier;\nimport org.apache.http.conn.ssl.NoopHostnameVerifier;\nimport org.apache.http.conn.ssl.TrustSelfSignedStrategy;\nimport org.apache.http.conn.ssl.TrustStrategy;\n@@ -31,10 +32,16 @@ import org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.ProxyAuthenticationStrategy;\n+import javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.SSLContext;\n+import javax.net.ssl.SSLSession;\nimport java.security.KeyStore;\n+import java.security.KeyStoreException;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.UnrecoverableEntryException;\nimport java.security.cert.X509Certificate;\nimport java.util.Collections;\n+import java.util.Enumeration;\nimport java.util.List;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n@@ -66,8 +73,10 @@ public class HttpClientFactory {\n.setMaxConnTotal(maxConnections)\n.setDefaultRequestConfig(RequestConfig.custom().setStaleConnectionCheckEnabled(true).build())\n.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeoutMilliseconds).build())\n- .useSystemProperties()\n- .setSSLHostnameVerifier(new NoopHostnameVerifier());\n+ .useSystemProperties();\n+\n+ HostnameVerifier hostnameVerifier = buildHostnameVerifier(trustSelfSignedCertificates, trustedHosts);\n+ builder.setSSLHostnameVerifier(hostnameVerifier);\nif (proxySettings != NO_PROXY) {\nHttpHost proxyHost = new HttpHost(proxySettings.host(), proxySettings.port());\n@@ -91,6 +100,14 @@ public class HttpClientFactory {\nreturn builder.build();\n}\n+ private static HostnameVerifier buildHostnameVerifier(boolean trustSelfSignedCertificates, List<String> trustedHosts) {\n+ if (trustSelfSignedCertificates) {\n+ return new NoopHostnameVerifier();\n+ } else {\n+ return new ExtraHostsHostnameVerifier(trustedHosts);\n+ }\n+ }\n+\npublic static CloseableHttpClient createClient(\nint maxConnections,\nint timeoutMilliseconds,\n@@ -107,6 +124,8 @@ public class HttpClientFactory {\n.setProtocol(\"TLS\");\nif (trustSelfSignedCertificates) {\nsslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());\n+ } else if (containsCertificate(trustStore)) {\n+ sslContextBuilder.loadTrustMaterial(trustStore, null);\n}\nreturn sslContextBuilder\n.build();\n@@ -115,6 +134,21 @@ public class HttpClientFactory {\n}\n}\n+ private static boolean containsCertificate(KeyStore trustStore) throws KeyStoreException {\n+ Enumeration<String> aliases = trustStore.aliases();\n+ while (aliases.hasMoreElements()) {\n+ String alias = aliases.nextElement();\n+ try {\n+ if (trustStore.getEntry(alias, null) instanceof KeyStore.TrustedCertificateEntry) {\n+ return true;\n+ }\n+ } catch (NoSuchAlgorithmException | UnrecoverableEntryException e) {\n+ // ignore\n+ }\n+ }\n+ return false;\n+ }\n+\nprivate static SSLContext buildAllowAnythingSSLContext() {\ntry {\nreturn SSLContextBuilder.create().loadTrustMaterial(null, new TrustStrategy() {\n@@ -166,4 +200,23 @@ public class HttpClientFactory {\nelse\nreturn new GenericHttpUriRequest(method.toString(), url);\n}\n+\n+ private static class ExtraHostsHostnameVerifier implements HostnameVerifier {\n+\n+ private final List<String> trustedHosts;\n+ private final DefaultHostnameVerifier defaultHostnameVerifier = new DefaultHostnameVerifier();\n+\n+ public ExtraHostsHostnameVerifier(List<String> trustedHosts) {\n+ this.trustedHosts = trustedHosts;\n+ }\n+\n+ @Override\n+ public boolean verify(String hostname, SSLSession session) {\n+ if (trustedHosts.contains(hostname)) {\n+ return true;\n+ } else {\n+ return defaultHostnameVerifier.verify(hostname, session);\n+ }\n+ }\n+ }\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryCertificateAcceptsRealValidCertificatesTest.java",
"diff": "+package com.github.tomakehurst.wiremock.http;\n+\n+import org.apache.http.HttpResponse;\n+import org.apache.http.client.methods.HttpGet;\n+import org.junit.Test;\n+\n+import java.util.Collections;\n+\n+import static com.github.tomakehurst.wiremock.common.HttpClientUtils.getEntityAsStringAndCloseStream;\n+\n+public class HttpClientFactoryCertificateAcceptsRealValidCertificatesTest extends HttpClientFactoryCertificateVerificationTest {\n+\n+ public HttpClientFactoryCertificateAcceptsRealValidCertificatesTest() {\n+ super(Collections.<String>emptyList(), \"localhost\", true);\n+ }\n+\n+ @Test\n+ public void realCertificateIsAccepted() throws Exception {\n+\n+ HttpResponse response = client.execute(new HttpGet(\"https://www.example.com/\"));\n+\n+ getEntityAsStringAndCloseStream(response);\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryCertificateVerificationTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryCertificateVerificationTest.java",
"diff": "@@ -6,9 +6,12 @@ import com.github.tomakehurst.wiremock.crypto.CertificateSpecification;\nimport com.github.tomakehurst.wiremock.crypto.InMemoryKeyStore;\nimport com.github.tomakehurst.wiremock.crypto.Secret;\nimport com.github.tomakehurst.wiremock.crypto.X509CertificateSpecification;\n+import org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\n+import org.apache.http.client.methods.HttpGet;\nimport org.junit.After;\nimport org.junit.Before;\n+import org.junit.Test;\nimport java.io.File;\nimport java.security.KeyPair;\n@@ -18,6 +21,7 @@ import java.security.cert.Certificate;\nimport java.util.Date;\nimport java.util.List;\n+import static com.github.tomakehurst.wiremock.common.HttpClientUtils.getEntityAsStringAndCloseStream;\nimport static com.github.tomakehurst.wiremock.common.ProxySettings.NO_PROXY;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\nimport static com.github.tomakehurst.wiremock.crypto.InMemoryKeyStore.KeyStoreType.JKS;\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | For testing, trust a public certificate added to the client key store
This fixes some of the tests. Breaks the new `realCertificateIsAccepted` test.
This is because calling `loadTrustMaterial` with a key store doesn't add its
certificates to the default trusted certificates, but instead replaces them
with the given key store. |
686,981 | 01.06.2020 16:10:05 | -3,600 | aa3dee9e49f889c3af78a08ab95695fef924a541 | Move SSL classes into their own package | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.http;\nimport com.github.tomakehurst.wiremock.common.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\n+import com.github.tomakehurst.wiremock.http.ssl.SSLContextBuilder;\nimport org.apache.http.HttpHost;\nimport org.apache.http.auth.AuthScope;\nimport org.apache.http.auth.UsernamePasswordCredentials;\n"
},
{
"change_type": "RENAME",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/SSLContextBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java",
"diff": "*\n*/\n-package com.github.tomakehurst.wiremock.http;\n+package com.github.tomakehurst.wiremock.http.ssl;\nimport org.apache.http.ssl.PrivateKeyDetails;\nimport org.apache.http.ssl.PrivateKeyStrategy;\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Move SSL classes into their own package |
686,981 | 01.06.2020 16:36:45 | -3,600 | aada711a86bbc29ce132b8faef4692c42196acb1 | Allow trusting additional certificates
Previously a client had to choose between the default trusted certificates
and those in a custom trust store. This commit allows trusting the certificates
in a custom trust store in addition to those in the default trusted certificates. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ArrayFunctions.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import static java.util.Arrays.copyOf;\n+\n+public final class ArrayFunctions {\n+\n+ public static <T> T[] concat(T[] first, T[] second) {\n+ if (first.length + second.length == 0) {\n+ return first;\n+ }\n+ T[] both = copyOf(first, first.length + second.length);\n+ System.arraycopy(second, 0, both, first.length, second.length);\n+ return both;\n+ }\n+\n+ private ArrayFunctions() {\n+ throw new UnsupportedOperationException(\"not instantiable\");\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ListFunctions.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import java.util.ArrayList;\n+import java.util.List;\n+\n+public final class ListFunctions {\n+\n+ public static <A, B extends A> Pair<List<A>, List<B>> splitByType(A[] items, Class<B> subType) {\n+ List<A> as = new ArrayList<>();\n+ List<B> bs = new ArrayList<>();\n+ for (A a : items) {\n+ if (subType.isAssignableFrom(a.getClass())) {\n+ bs.add((B) a);\n+ } else {\n+ as.add(a);\n+ }\n+ }\n+ return new Pair<>(as, bs);\n+ }\n+\n+ private ListFunctions() {\n+ throw new UnsupportedOperationException(\"Not instantiable\");\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Pair.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import java.util.Objects;\n+\n+import static java.util.Objects.requireNonNull;\n+\n+public final class Pair<A, B> {\n+\n+ public final A a;\n+ public final B b;\n+\n+ public Pair(A a, B b) {\n+ this.a = requireNonNull(a);\n+ this.b = requireNonNull(b);\n+ }\n+\n+ public static <A, B> Pair<A, B> pair(A a, B b) {\n+ return new Pair<>(a, b);\n+ }\n+\n+ @Override\n+ public boolean equals(Object o) {\n+ if (this == o) return true;\n+ if (!(o instanceof Pair)) return false;\n+ Pair<?, ?> pair = (Pair<?, ?>) o;\n+ return a.equals(pair.a) && b.equals(pair.b);\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return Objects.hash(a, b);\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return a + \"=\" + b;\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/CompositeTrustManager.java",
"diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import javax.net.ssl.X509TrustManager;\n+import java.security.cert.CertificateException;\n+import java.security.cert.X509Certificate;\n+import java.util.ArrayList;\n+import java.util.Iterator;\n+import java.util.List;\n+\n+import static java.util.Arrays.asList;\n+import static java.util.Arrays.copyOf;\n+\n+/**\n+ * Implementation of {@link X509TrustManager} that delegates to multiple nested\n+ * X509TrustManagers.\n+ * <p>\n+ * {@link javax.net.ssl.SSLContext#init(javax.net.ssl.KeyManager[], javax.net.ssl.TrustManager[], java.security.SecureRandom)}\n+ * accepts an array of {@link javax.net.ssl.TrustManager} instances, but\n+ * {@link sun.security.ssl.SSLContextImpl#chooseTrustManager(javax.net.ssl.TrustManager[])}\n+ * chooses the first instance of X509TrustManager in the array. So in order to\n+ * provide a composite trust manager that will trust based on the decision of\n+ * more than one X509TrustManager we need to create a new implementation that\n+ * delegates its decision to one or more real X509TrustManager instances.\n+ * <p>\n+ * The contract of this class is that a check will pass if it passes against any\n+ * of its trust managers. If it passes against none of them, the\n+ * {@link CertificateException} thrown by the last of them is propagated.\n+ */\n+class CompositeTrustManager implements X509TrustManager {\n+\n+ private final List<X509TrustManager> trustManagers;\n+ private final X509Certificate[] acceptedIssuers;\n+\n+ CompositeTrustManager(List<X509TrustManager> trustManagers) {\n+ if (trustManagers.isEmpty()) {\n+ throw new IllegalArgumentException(\"A trust manager must be provided\");\n+ }\n+ this.trustManagers = trustManagers;\n+ acceptedIssuers = loadAcceptedIssuers(trustManagers);\n+ }\n+\n+ private X509Certificate[] loadAcceptedIssuers(List<X509TrustManager> trustManagers) {\n+ List<X509Certificate> result = new ArrayList<>();\n+ for (X509TrustManager trustManager : trustManagers) {\n+ result.addAll(asList(trustManager.getAcceptedIssuers()));\n+ }\n+ return result.toArray(new X509Certificate[0]);\n+ }\n+\n+ @Override\n+ public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {\n+ checkAllTrustManagers(new CertificateChecker() {\n+ @Override\n+ public void check(X509TrustManager tm) throws CertificateException {\n+ tm.checkClientTrusted(chain, authType);\n+ }\n+ });\n+ }\n+\n+ @Override\n+ public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {\n+ checkAllTrustManagers(new CertificateChecker() {\n+ @Override\n+ public void check(X509TrustManager tm) throws CertificateException {\n+ tm.checkServerTrusted(chain, authType);\n+ }\n+ });\n+ }\n+\n+ @Override\n+ public X509Certificate[] getAcceptedIssuers() {\n+ return copyOf(acceptedIssuers, acceptedIssuers.length);\n+ }\n+\n+ private void checkAllTrustManagers(CertificateChecker certificateChecker) throws CertificateException {\n+ for (Iterator<X509TrustManager> iterator = trustManagers.iterator(); iterator.hasNext(); ) {\n+ X509TrustManager tm = iterator.next();\n+ try {\n+ certificateChecker.check(tm);\n+ break;\n+ } catch (CertificateException e) {\n+ if (!iterator.hasNext()) {\n+ throw e;\n+ }\n+ }\n+ }\n+ }\n+\n+ private interface CertificateChecker {\n+ void check(X509TrustManager tm) throws CertificateException;\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java",
"diff": "package com.github.tomakehurst.wiremock.http.ssl;\n+import com.github.tomakehurst.wiremock.common.ListFunctions;\n+import com.github.tomakehurst.wiremock.common.Pair;\nimport org.apache.http.ssl.PrivateKeyDetails;\nimport org.apache.http.ssl.PrivateKeyStrategy;\nimport org.apache.http.ssl.TrustStrategy;\n@@ -61,9 +63,12 @@ import java.security.cert.X509Certificate;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.LinkedHashSet;\n+import java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n+import static com.github.tomakehurst.wiremock.common.ArrayFunctions.concat;\n+import static com.github.tomakehurst.wiremock.common.ListFunctions.splitByType;\nimport static java.util.Collections.addAll;\n/**\n@@ -194,24 +199,49 @@ public class SSLContextBuilder {\npublic SSLContextBuilder loadTrustMaterial(\nfinal KeyStore truststore,\n- final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {\n- final TrustManagerFactory tmfactory = TrustManagerFactory\n- .getInstance(trustManagerFactoryAlgorithm == null ? TrustManagerFactory.getDefaultAlgorithm()\n- : trustManagerFactoryAlgorithm);\n+ final TrustStrategy trustStrategy\n+ ) throws NoSuchAlgorithmException, KeyStoreException {\n+\n+ String algorithm = trustManagerFactoryAlgorithm == null ? TrustManagerFactory.getDefaultAlgorithm() : trustManagerFactoryAlgorithm;\n+ TrustManager[] tms = loadTrustManagers(truststore, algorithm);\n+ TrustManager[] allTms = truststore == null ? tms : concat(tms, loadDefaultTrustManagers());\n+ TrustManager[] tmsWithStrategy = trustStrategy == null ? allTms : addStrategy(allTms, trustStrategy);\n+\n+ Pair<List<TrustManager>, List<X509TrustManager>> split = splitByType(tmsWithStrategy, X509TrustManager.class);\n+ List<TrustManager> otherTms = split.a;\n+ List<X509TrustManager> x509Tms = split.b;\n+ if (!x509Tms.isEmpty()) {\n+ this.trustManagers.add(new CompositeTrustManager(x509Tms));\n+ }\n+ this.trustManagers.addAll(otherTms);\n+ return this;\n+ }\n+\n+ private TrustManager[] loadTrustManagers(KeyStore truststore, String algorithm) throws NoSuchAlgorithmException, KeyStoreException {\n+ final TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(algorithm);\ntmfactory.init(truststore);\n- final TrustManager[] tms = tmfactory.getTrustManagers();\n- if (tms != null) {\n- if (trustStrategy != null) {\n- for (int i = 0; i < tms.length; i++) {\n- final TrustManager tm = tms[i];\n- if (tm instanceof X509TrustManager) {\n- tms[i] = new TrustManagerDelegate((X509TrustManager) tm, trustStrategy);\n+ TrustManager[] tms = tmfactory.getTrustManagers();\n+ return tms == null ? new TrustManager[0] : tms;\n}\n+\n+ private TrustManager[] loadDefaultTrustManagers() throws KeyStoreException, NoSuchAlgorithmException {\n+ return loadTrustManagers(null, TrustManagerFactory.getDefaultAlgorithm());\n}\n+\n+ private TrustManager[] addStrategy(TrustManager[] allTms, TrustStrategy trustStrategy) {\n+ TrustManager[] withStrategy = new TrustManager[allTms.length];\n+ for (int i = 0; i < allTms.length; i++) {\n+ withStrategy[i] = addStrategy(allTms[i], trustStrategy);\n}\n- addAll(this.trustManagers, tms);\n+ return withStrategy;\n+ }\n+\n+ private TrustManager addStrategy(TrustManager tm, TrustStrategy trustStrategy) {\n+ if (tm instanceof X509TrustManager) {\n+ return new TrustManagerDelegate((X509TrustManager) tm, trustStrategy);\n+ } else {\n+ return tm;\n}\n- return this;\n}\npublic SSLContextBuilder loadTrustMaterial(\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/common/ArrayFunctionsTest.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import org.junit.Test;\n+\n+import static com.github.tomakehurst.wiremock.common.ArrayFunctions.concat;\n+import static org.junit.Assert.*;\n+\n+public class ArrayFunctionsTest {\n+\n+ private final Integer[] empty = new Integer[0];\n+\n+ @Test\n+ public void concatEmptyAndEmpty() {\n+ assertArrayEquals(empty, concat(empty, empty));\n+ }\n+\n+ @Test\n+ public void concatNonEmptyAndEmpty() {\n+ Integer[] first = {1, 2};\n+\n+ Integer[] result = concat(first, empty);\n+ assertArrayEquals(new Integer[] { 1, 2 }, result);\n+\n+ first[0] = 10;\n+ assertArrayEquals(new Integer[] { 1, 2 }, result);\n+ }\n+\n+ @Test\n+ public void concatEmptyAndNonEmpty() {\n+ Integer[] second = {1, 2};\n+\n+ Integer[] result = concat(empty, second);\n+ assertArrayEquals(new Integer[] { 1, 2 }, result);\n+\n+ second[0] = 10;\n+ assertArrayEquals(new Integer[] { 1, 2 }, result);\n+ }\n+\n+ @Test\n+ public void concatNonEmptyAndNonEmpty() {\n+ Integer[] first = {1, 2};\n+ Integer[] second = {3, 4};\n+\n+ Integer[] result = concat(first, second);\n+ assertArrayEquals(new Integer[] { 1, 2, 3, 4 }, result);\n+\n+ first[0] = 10;\n+ second[0] = 30;\n+ assertArrayEquals(new Integer[] { 1, 2, 3, 4 }, result);\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/common/ListFunctionsTest.java",
"diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+import org.junit.Test;\n+\n+import java.util.Collections;\n+\n+import static com.github.tomakehurst.wiremock.common.ListFunctions.splitByType;\n+import static com.github.tomakehurst.wiremock.common.Pair.pair;\n+import static java.util.Arrays.asList;\n+import static java.util.Collections.singletonList;\n+import static org.junit.Assert.*;\n+\n+public class ListFunctionsTest {\n+\n+ @Test\n+ public void emptyArrayReturnsTwoEmptyLists() {\n+ Number[] input = new Number[0];\n+\n+ assertEquals(\n+ pair(Collections.<Number>emptyList(), Collections.<Integer>emptyList()),\n+ splitByType(input, Integer.class)\n+ );\n+ }\n+\n+ @Test\n+ public void singletonArrayNonMatchingReturnsSingletonAndEmptyList() {\n+ Number[] input = new Number[] { 1L };\n+\n+ assertEquals(\n+ pair(singletonList(1L), Collections.<Integer>emptyList()),\n+ splitByType(input, Integer.class)\n+ );\n+ }\n+\n+ @Test\n+ public void singletonArrayMatchingReturnsEmptyAndSingletonList() {\n+ Number[] input = new Number[] { 1 };\n+\n+ assertEquals(\n+ pair(Collections.<Number>emptyList(), singletonList(1)),\n+ splitByType(input, Integer.class)\n+ );\n+ }\n+\n+ @Test\n+ public void splitsTheArrayAsExpected() {\n+ Number[] input = new Number[] { 1, 1L, 2, 2L, 3, 3L };\n+\n+ assertEquals(\n+ pair(asList(1L, 2L, 3L), asList(1, 2, 3)),\n+ splitByType(input, Integer.class)\n+ );\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ssl/CompositeTrustManagerTest.java",
"diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import org.jmock.Expectations;\n+import org.jmock.Mockery;\n+import org.junit.After;\n+import org.junit.Test;\n+import org.junit.function.ThrowingRunnable;\n+\n+import javax.net.ssl.X509TrustManager;\n+import java.math.BigInteger;\n+import java.security.InvalidKeyException;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.NoSuchProviderException;\n+import java.security.Principal;\n+import java.security.PublicKey;\n+import java.security.SignatureException;\n+import java.security.cert.CertificateEncodingException;\n+import java.security.cert.CertificateException;\n+import java.security.cert.CertificateExpiredException;\n+import java.security.cert.CertificateNotYetValidException;\n+import java.security.cert.X509Certificate;\n+import java.util.Date;\n+import java.util.Set;\n+\n+import static java.util.Arrays.asList;\n+import static java.util.Collections.singletonList;\n+import static org.junit.Assert.*;\n+\n+public class CompositeTrustManagerTest {\n+\n+ private final Mockery context = new Mockery();\n+ {\n+ context.setDefaultResultForType(X509Certificate[].class, new X509Certificate[0]);\n+ }\n+ private final X509TrustManager trustManager1 = mockX509TrustManager(\"trustManager1\");\n+ private final X509TrustManager trustManager2 = mockX509TrustManager(\"trustManager2\");\n+ private final X509Certificate[] chain = new X509Certificate[0];\n+ private final String authType = \"AN_AUTH_TYPE\";\n+\n+ @Test\n+ public void checkServerTrustedPassesForSingleTrustManager() throws CertificateException {\n+\n+ context.checking(new Expectations() {{\n+ allowing(trustManager1).checkServerTrusted(chain, authType);\n+ }});\n+\n+ CompositeTrustManager compositeTrustManager = new CompositeTrustManager(singletonList(\n+ trustManager1\n+ ));\n+\n+ compositeTrustManager.checkServerTrusted(chain, authType);\n+ }\n+\n+ @Test\n+ public void checkServerTrustedFailsForSingleTrustManager() throws CertificateException {\n+\n+ final CertificateException invalidCertForTrustManager1 = new CertificateException(\"Invalid cert for trustManager1\");\n+\n+ context.checking(new Expectations() {{\n+ allowing(trustManager1).checkServerTrusted(chain, authType);\n+ will(throwException(invalidCertForTrustManager1));\n+ }});\n+\n+ final CompositeTrustManager compositeTrustManager = new CompositeTrustManager(singletonList(\n+ trustManager1\n+ ));\n+\n+ CertificateException thrown = assertThrows(CertificateException.class, new ThrowingRunnable() {\n+ @Override\n+ public void run() throws Throwable {\n+ compositeTrustManager.checkServerTrusted(chain, authType);\n+ }\n+ });\n+ assertEquals(invalidCertForTrustManager1, thrown);\n+ }\n+\n+ @Test\n+ public void checkServerTrustedIfBothWouldPass() throws CertificateException {\n+\n+ context.checking(new Expectations() {{\n+ allowing(trustManager1).checkServerTrusted(chain, authType);\n+ allowing(trustManager2).checkServerTrusted(chain, authType);\n+ }});\n+\n+ CompositeTrustManager compositeTrustManager = new CompositeTrustManager(asList(\n+ trustManager1,\n+ trustManager2\n+ ));\n+\n+ compositeTrustManager.checkServerTrusted(chain, authType);\n+ }\n+\n+ @Test\n+ public void checkServerTrustedIfFirstWouldPass() throws CertificateException {\n+\n+ context.checking(new Expectations() {{\n+ allowing(trustManager1).checkServerTrusted(chain, authType);\n+\n+ allowing(trustManager2).checkServerTrusted(chain, authType);\n+ will(throwException(new CertificateException(\"Invalid cert for trustManager2\")));\n+ }});\n+\n+ CompositeTrustManager compositeTrustManager = new CompositeTrustManager(asList(\n+ trustManager1,\n+ trustManager2\n+ ));\n+\n+ compositeTrustManager.checkServerTrusted(chain, authType);\n+ }\n+\n+ @Test\n+ public void checkServerTrustedIfSecondWouldPass() throws CertificateException {\n+\n+ context.checking(new Expectations() {{\n+ allowing(trustManager1).checkServerTrusted(chain, authType);\n+ will(throwException(new CertificateException(\"Invalid cert for trustManager1\")));\n+\n+ allowing(trustManager2).checkServerTrusted(chain, authType);\n+ }});\n+\n+ CompositeTrustManager compositeTrustManager = new CompositeTrustManager(asList(\n+ trustManager1,\n+ trustManager2\n+ ));\n+\n+ compositeTrustManager.checkServerTrusted(chain, authType);\n+ }\n+\n+ @Test\n+ public void checkServerNotTrustedIfNeitherPass() throws CertificateException {\n+\n+ final CertificateException invalidCertForTrustManager2 = new CertificateException(\"Invalid cert for trustManager2\");\n+\n+ context.checking(new Expectations() {{\n+ allowing(trustManager1).checkServerTrusted(chain, authType);\n+ will(throwException(new CertificateException(\"Invalid cert for trustManager1\")));\n+\n+ allowing(trustManager2).checkServerTrusted(chain, authType);\n+ will(throwException(invalidCertForTrustManager2));\n+ }});\n+\n+ final CompositeTrustManager compositeTrustManager = new CompositeTrustManager(\n+ asList(trustManager1, trustManager2)\n+ );\n+\n+ CertificateException thrown = assertThrows(CertificateException.class, new ThrowingRunnable() {\n+ @Override\n+ public void run() throws Throwable {\n+ compositeTrustManager.checkServerTrusted(chain, authType);\n+ }\n+ });\n+\n+ assertEquals(invalidCertForTrustManager2, thrown);\n+ }\n+\n+ @Test\n+ public void returnAllAcceptedIssuers() {\n+\n+ final X509Certificate cert1 = new FakeX509Certificate(\"cert1\");\n+ final X509Certificate cert2 = new FakeX509Certificate(\"cert2\");\n+ final X509Certificate cert3 = new FakeX509Certificate(\"cert3\");\n+ final X509Certificate cert4 = new FakeX509Certificate(\"cert4\");\n+\n+ final X509TrustManager trustManager1 = context.mock(X509TrustManager.class, \"newTrustManager1\");\n+ final X509TrustManager trustManager2 = context.mock(X509TrustManager.class, \"newTrustManager2\");\n+\n+ context.checking(new Expectations() {{\n+ allowing(trustManager1).getAcceptedIssuers();\n+ will(returnValue(new X509Certificate[] { cert1, cert2 }));\n+\n+ allowing(trustManager2).getAcceptedIssuers();\n+ will(returnValue(new X509Certificate[] { cert3, cert4 }));\n+ }});\n+\n+ final CompositeTrustManager compositeTrustManager = new CompositeTrustManager(\n+ asList(trustManager1, trustManager2)\n+ );\n+\n+ X509Certificate[] acceptedIssuers = compositeTrustManager.getAcceptedIssuers();\n+\n+ assertArrayEquals(new X509Certificate[] { cert1, cert2, cert3, cert4 }, acceptedIssuers);\n+\n+ acceptedIssuers[2] = new FakeX509Certificate(\"cert5\");\n+\n+ assertArrayEquals(new X509Certificate[] { cert1, cert2, cert3, cert4 }, compositeTrustManager.getAcceptedIssuers());\n+ }\n+\n+ @After\n+ public void checkMockeryContextSatisfied() {\n+ context.assertIsSatisfied();\n+ }\n+\n+ private X509TrustManager mockX509TrustManager(String name) {\n+ final X509TrustManager trustManager = context.mock(X509TrustManager.class, name);\n+ context.checking(new Expectations() {{\n+ allowing(trustManager).getAcceptedIssuers();\n+ }});\n+ return trustManager;\n+ }\n+\n+ private static class FakeX509Certificate extends X509Certificate {\n+\n+ private final String name;\n+\n+ public FakeX509Certificate(String name) {\n+ this.name = name;\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"X509Certificate{\" + name + \"}\";\n+ }\n+\n+ @Override\n+ public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public int getVersion() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public BigInteger getSerialNumber() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public Principal getIssuerDN() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public Principal getSubjectDN() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public Date getNotBefore() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public Date getNotAfter() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public byte[] getTBSCertificate() throws CertificateEncodingException {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public byte[] getSignature() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public String getSigAlgName() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public String getSigAlgOID() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public byte[] getSigAlgParams() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public boolean[] getIssuerUniqueID() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public boolean[] getSubjectUniqueID() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public boolean[] getKeyUsage() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public int getBasicConstraints() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public byte[] getEncoded() throws CertificateEncodingException {\n+ return name.getBytes();\n+ }\n+\n+ @Override\n+ public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public PublicKey getPublicKey() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public boolean hasUnsupportedCriticalExtension() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public Set<String> getCriticalExtensionOIDs() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public Set<String> getNonCriticalExtensionOIDs() {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+\n+ @Override\n+ public byte[] getExtensionValue(String oid) {\n+ throw new UnsupportedOperationException(\"Not implemented\");\n+ }\n+ }\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Allow trusting additional certificates
Previously a client had to choose between the default trusted certificates
and those in a custom trust store. This commit allows trusting the certificates
in a custom trust store in addition to those in the default trusted certificates. |
686,985 | 02.06.2020 16:30:38 | -7,200 | 33717fb74f36c081b76a5f70024d7f3767921bef | In scenarios where one wants to use a subclass of ResponseDefinition, they should be able to override the copy method. The reason for that is that the static copyOf is already used in Wiremock codebase. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ResponseDefinition.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ResponseDefinition.java",
"diff": "@@ -203,21 +203,25 @@ public class ResponseDefinition {\n}\npublic static ResponseDefinition copyOf(ResponseDefinition original) {\n+ return original.copy();\n+ }\n+\n+ public ResponseDefinition copy() {\nResponseDefinition newResponseDef = new ResponseDefinition(\n- original.status,\n- original.statusMessage,\n- original.body,\n- original.bodyFileName,\n- original.headers,\n- original.additionalProxyRequestHeaders,\n- original.fixedDelayMilliseconds,\n- original.delayDistribution,\n- original.chunkedDribbleDelay,\n- original.proxyBaseUrl,\n- original.fault,\n- original.transformers,\n- original.transformerParameters,\n- original.wasConfigured\n+ this.status,\n+ this.statusMessage,\n+ this.body,\n+ this.bodyFileName,\n+ this.headers,\n+ this.additionalProxyRequestHeaders,\n+ this.fixedDelayMilliseconds,\n+ this.delayDistribution,\n+ this.chunkedDribbleDelay,\n+ this.proxyBaseUrl,\n+ this.fault,\n+ this.transformers,\n+ this.transformerParameters,\n+ this.wasConfigured\n);\nreturn newResponseDef;\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | In scenarios where one wants to use a subclass of ResponseDefinition, they should be able to override the copy method. The reason for that is that the static copyOf is already used in Wiremock codebase. (#1324)
Co-authored-by: Wojtek <wojtek@trafficparrot.com> |
686,981 | 02.06.2020 15:39:19 | -3,600 | df6d7a4dae045c7637cc7f3a8ab02ada79ad8f7f | Simplify loading of trust material
`loadTrustMaterial` was always called with one of the two values being null,
so separate it into two methods. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"diff": "@@ -124,9 +124,9 @@ public class HttpClientFactory {\n.loadKeyMaterial(trustStore, trustStoreSettings.password().toCharArray())\n.setProtocol(\"TLS\");\nif (trustSelfSignedCertificates) {\n- sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());\n+ sslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy());\n} else if (containsCertificate(trustStore)) {\n- sslContextBuilder.loadTrustMaterial(trustStore, null);\n+ sslContextBuilder.loadTrustMaterial(trustStore);\n}\nreturn sslContextBuilder\n.build();\n@@ -152,7 +152,7 @@ public class HttpClientFactory {\nprivate static SSLContext buildAllowAnythingSSLContext() {\ntry {\n- return SSLContextBuilder.create().loadTrustMaterial(null, new TrustStrategy() {\n+ return SSLContextBuilder.create().loadTrustMaterial(new TrustStrategy() {\n@Override\npublic boolean isTrusted(X509Certificate[] chain, String authType) {\nreturn true;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java",
"diff": "@@ -198,16 +198,14 @@ public class SSLContextBuilder {\n}\npublic SSLContextBuilder loadTrustMaterial(\n- final KeyStore truststore,\n- final TrustStrategy trustStrategy\n+ final KeyStore truststore\n) throws NoSuchAlgorithmException, KeyStoreException {\nString algorithm = trustManagerFactoryAlgorithm == null ? TrustManagerFactory.getDefaultAlgorithm() : trustManagerFactoryAlgorithm;\nTrustManager[] tms = loadTrustManagers(truststore, algorithm);\n- TrustManager[] allTms = truststore == null ? tms : concat(tms, loadDefaultTrustManagers());\n- TrustManager[] tmsWithStrategy = trustStrategy == null ? allTms : addStrategy(allTms, trustStrategy);\n+ TrustManager[] allTms = concat(tms, loadDefaultTrustManagers());\n- Pair<List<TrustManager>, List<X509TrustManager>> split = splitByType(tmsWithStrategy, X509TrustManager.class);\n+ Pair<List<TrustManager>, List<X509TrustManager>> split = splitByType(allTms, X509TrustManager.class);\nList<TrustManager> otherTms = split.a;\nList<X509TrustManager> x509Tms = split.b;\nif (!x509Tms.isEmpty()) {\n@@ -217,6 +215,17 @@ public class SSLContextBuilder {\nreturn this;\n}\n+ public SSLContextBuilder loadTrustMaterial(\n+ final TrustStrategy trustStrategy\n+ ) throws NoSuchAlgorithmException, KeyStoreException {\n+\n+ TrustManager[] tms = loadTrustManagers(null, TrustManagerFactory.getDefaultAlgorithm());\n+ TrustManager[] tmsWithStrategy = addStrategy(tms, trustStrategy);\n+\n+ addAll(this.trustManagers, tmsWithStrategy);\n+ return this;\n+ }\n+\nprivate TrustManager[] loadTrustManagers(KeyStore truststore, String algorithm) throws NoSuchAlgorithmException, KeyStoreException {\nfinal TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(algorithm);\ntmfactory.init(truststore);\n@@ -244,52 +253,6 @@ public class SSLContextBuilder {\n}\n}\n- public SSLContextBuilder loadTrustMaterial(\n- final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {\n- return loadTrustMaterial(null, trustStrategy);\n- }\n-\n- public SSLContextBuilder loadTrustMaterial(\n- final File file,\n- final char[] storePassword,\n- final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {\n- Args.notNull(file, \"Truststore file\");\n- final KeyStore trustStore = KeyStore.getInstance(keyStoreType);\n- try (FileInputStream inStream = new FileInputStream(file)) {\n- trustStore.load(inStream, storePassword);\n- }\n- return loadTrustMaterial(trustStore, trustStrategy);\n- }\n-\n- public SSLContextBuilder loadTrustMaterial(\n- final File file,\n- final char[] storePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {\n- return loadTrustMaterial(file, storePassword, null);\n- }\n-\n- public SSLContextBuilder loadTrustMaterial(\n- final File file) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {\n- return loadTrustMaterial(file, null);\n- }\n-\n- public SSLContextBuilder loadTrustMaterial(\n- final URL url,\n- final char[] storePassword,\n- final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {\n- Args.notNull(url, \"Truststore URL\");\n- final KeyStore trustStore = KeyStore.getInstance(keyStoreType);\n- try (InputStream inStream = url.openStream()) {\n- trustStore.load(inStream, storePassword);\n- }\n- return loadTrustMaterial(trustStore, trustStrategy);\n- }\n-\n- public SSLContextBuilder loadTrustMaterial(\n- final URL url,\n- final char[] storePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {\n- return loadTrustMaterial(url, storePassword, null);\n- }\n-\npublic SSLContextBuilder loadKeyMaterial(\nfinal KeyStore keystore,\nfinal char[] keyPassword,\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Simplify loading of trust material
`loadTrustMaterial` was always called with one of the two values being null,
so separate it into two methods. |
686,981 | 02.06.2020 16:01:51 | -3,600 | 4c3fb3fa8e71d165595839b889eb894864cf0151 | Extract a `buildSslContext` method | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"diff": "@@ -32,6 +32,7 @@ import org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.ProxyAuthenticationStrategy;\n+import org.apache.http.ssl.SSLContexts;\nimport javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.SSLContext;\n@@ -92,13 +93,23 @@ public class HttpClientFactory {\n}\n}\n+ final SSLContext sslContext = buildSslContext(trustStoreSettings, trustSelfSignedCertificates);\n+ builder.setSSLContext(sslContext);\n+\n+ return builder.build();\n+ }\n+\n+ private static SSLContext buildSslContext(\n+ KeyStoreSettings trustStoreSettings,\n+ boolean trustSelfSignedCertificates\n+ ) {\nif (trustStoreSettings != NO_STORE) {\n- builder.setSSLContext(buildSSLContextWithTrustStore(trustStoreSettings, trustSelfSignedCertificates));\n+ return buildSSLContextWithTrustStore(trustStoreSettings, trustSelfSignedCertificates);\n} else if (trustSelfSignedCertificates) {\n- builder.setSSLContext(buildAllowAnythingSSLContext());\n+ return buildAllowAnythingSSLContext();\n+ } else {\n+ return SSLContexts.createSystemDefault();\n}\n-\n- return builder.build();\n}\nprivate static HostnameVerifier buildHostnameVerifier(boolean trustSelfSignedCertificates, List<String> trustedHosts) {\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Extract a `buildSslContext` method |
686,981 | 03.06.2020 09:57:48 | -3,600 | 1efd22467ce5023a47495a3b9f031843d01effd9 | Make CompositeTrustManager extend X509ExtendedTrustManager
Will allow deciding how to verify on the basis of requested host.
Involves switching to Mockito as JMock doesn't like mocking classes. | [
{
"change_type": "MODIFY",
"old_path": "build.gradle",
"new_path": "build.gradle",
"diff": "@@ -113,6 +113,7 @@ allprojects {\nexclude group: \"org.hamcrest\", module: \"hamcrest-core\"\nexclude group: \"org.hamcrest\", module: \"hamcrest-library\"\n}\n+ testCompile 'org.mockito:mockito-core:3.3.3'\ntestCompile \"org.skyscreamer:jsonassert:1.2.3\"\ntestCompile 'com.toomuchcoding.jsonassert:jsonassert:0.4.12'\ntestCompile 'org.awaitility:awaitility:2.0.0'\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/CompositeTrustManager.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/CompositeTrustManager.java",
"diff": "package com.github.tomakehurst.wiremock.http.ssl;\n+import javax.net.ssl.SSLEngine;\n+import javax.net.ssl.X509ExtendedTrustManager;\nimport javax.net.ssl.X509TrustManager;\n+import java.net.Socket;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.util.ArrayList;\n@@ -11,8 +14,8 @@ import static java.util.Arrays.asList;\nimport static java.util.Arrays.copyOf;\n/**\n- * Implementation of {@link X509TrustManager} that delegates to multiple nested\n- * X509TrustManagers.\n+ * Implementation of {@link X509ExtendedTrustManager} that delegates to multiple\n+ * nested X509ExtendedTrustManagers.\n* <p>\n* {@link javax.net.ssl.SSLContext#init(javax.net.ssl.KeyManager[], javax.net.ssl.TrustManager[], java.security.SecureRandom)}\n* accepts an array of {@link javax.net.ssl.TrustManager} instances, but\n@@ -26,20 +29,20 @@ import static java.util.Arrays.copyOf;\n* of its trust managers. If it passes against none of them, the\n* {@link CertificateException} thrown by the last of them is propagated.\n*/\n-class CompositeTrustManager implements X509TrustManager {\n+class CompositeTrustManager extends X509ExtendedTrustManager {\n- private final List<X509TrustManager> trustManagers;\n+ private final List<X509ExtendedTrustManager> trustManagers;\nprivate final X509Certificate[] acceptedIssuers;\n- CompositeTrustManager(List<X509TrustManager> trustManagers) {\n+ CompositeTrustManager(List<X509ExtendedTrustManager> trustManagers) {\nif (trustManagers.isEmpty()) {\nthrow new IllegalArgumentException(\"A trust manager must be provided\");\n}\n- this.trustManagers = trustManagers;\n- acceptedIssuers = loadAcceptedIssuers(trustManagers);\n+ this.trustManagers = new ArrayList<>(trustManagers);\n+ this.acceptedIssuers = loadAcceptedIssuers(this.trustManagers);\n}\n- private X509Certificate[] loadAcceptedIssuers(List<X509TrustManager> trustManagers) {\n+ private X509Certificate[] loadAcceptedIssuers(List<X509ExtendedTrustManager> trustManagers) {\nList<X509Certificate> result = new ArrayList<>();\nfor (X509TrustManager trustManager : trustManagers) {\nresult.addAll(asList(trustManager.getAcceptedIssuers()));\n@@ -51,7 +54,7 @@ class CompositeTrustManager implements X509TrustManager {\npublic void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {\ncheckAllTrustManagers(new CertificateChecker() {\n@Override\n- public void check(X509TrustManager tm) throws CertificateException {\n+ public void check(X509ExtendedTrustManager tm) throws CertificateException {\ntm.checkClientTrusted(chain, authType);\n}\n});\n@@ -61,20 +64,60 @@ class CompositeTrustManager implements X509TrustManager {\npublic void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {\ncheckAllTrustManagers(new CertificateChecker() {\n@Override\n- public void check(X509TrustManager tm) throws CertificateException {\n+ public void check(X509ExtendedTrustManager tm) throws CertificateException {\ntm.checkServerTrusted(chain, authType);\n}\n});\n}\n+ @Override\n+ public void checkClientTrusted(final X509Certificate[] chain, final String authType, final Socket socket) throws CertificateException {\n+ checkAllTrustManagers(new CertificateChecker() {\n+ @Override\n+ public void check(X509ExtendedTrustManager tm) throws CertificateException {\n+ tm.checkClientTrusted(chain, authType, socket);\n+ }\n+ });\n+ }\n+\n+ @Override\n+ public void checkServerTrusted(final X509Certificate[] chain, final String authType, final Socket socket) throws CertificateException {\n+ checkAllTrustManagers(new CertificateChecker() {\n+ @Override\n+ public void check(X509ExtendedTrustManager tm) throws CertificateException {\n+ tm.checkServerTrusted(chain, authType, socket);\n+ }\n+ });\n+ }\n+\n+ @Override\n+ public void checkClientTrusted(final X509Certificate[] chain, final String authType, final SSLEngine engine) throws CertificateException {\n+ checkAllTrustManagers(new CertificateChecker() {\n+ @Override\n+ public void check(X509ExtendedTrustManager tm) throws CertificateException {\n+ tm.checkClientTrusted(chain, authType, engine);\n+ }\n+ });\n+ }\n+\n+ @Override\n+ public void checkServerTrusted(final X509Certificate[] chain, final String authType, final SSLEngine engine) throws CertificateException {\n+ checkAllTrustManagers(new CertificateChecker() {\n+ @Override\n+ public void check(X509ExtendedTrustManager tm) throws CertificateException {\n+ tm.checkServerTrusted(chain, authType, engine);\n+ }\n+ });\n+ }\n+\n@Override\npublic X509Certificate[] getAcceptedIssuers() {\nreturn copyOf(acceptedIssuers, acceptedIssuers.length);\n}\nprivate void checkAllTrustManagers(CertificateChecker certificateChecker) throws CertificateException {\n- for (Iterator<X509TrustManager> iterator = trustManagers.iterator(); iterator.hasNext(); ) {\n- X509TrustManager tm = iterator.next();\n+ for (Iterator<X509ExtendedTrustManager> iterator = trustManagers.iterator(); iterator.hasNext(); ) {\n+ X509ExtendedTrustManager tm = iterator.next();\ntry {\ncertificateChecker.check(tm);\nbreak;\n@@ -87,6 +130,6 @@ class CompositeTrustManager implements X509TrustManager {\n}\nprivate interface CertificateChecker {\n- void check(X509TrustManager tm) throws CertificateException;\n+ void check(X509ExtendedTrustManager tm) throws CertificateException;\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java",
"diff": "package com.github.tomakehurst.wiremock.http.ssl;\n-import com.github.tomakehurst.wiremock.common.ListFunctions;\nimport com.github.tomakehurst.wiremock.common.Pair;\nimport org.apache.http.ssl.PrivateKeyDetails;\nimport org.apache.http.ssl.PrivateKeyStrategy;\n@@ -41,6 +40,7 @@ import javax.net.ssl.SSLEngine;\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.TrustManagerFactory;\nimport javax.net.ssl.X509ExtendedKeyManager;\n+import javax.net.ssl.X509ExtendedTrustManager;\nimport javax.net.ssl.X509TrustManager;\nimport java.io.File;\nimport java.io.FileInputStream;\n@@ -205,9 +205,9 @@ public class SSLContextBuilder {\nTrustManager[] tms = loadTrustManagers(truststore, algorithm);\nTrustManager[] allTms = concat(tms, loadDefaultTrustManagers());\n- Pair<List<TrustManager>, List<X509TrustManager>> split = splitByType(allTms, X509TrustManager.class);\n+ Pair<List<TrustManager>, List<X509ExtendedTrustManager>> split = splitByType(allTms, X509ExtendedTrustManager.class);\nList<TrustManager> otherTms = split.a;\n- List<X509TrustManager> x509Tms = split.b;\n+ List<X509ExtendedTrustManager> x509Tms = split.b;\nif (!x509Tms.isEmpty()) {\nthis.trustManagers.add(new CompositeTrustManager(x509Tms));\n}\n@@ -352,7 +352,6 @@ public class SSLContextBuilder {\nprivate final TrustStrategy trustStrategy;\nTrustManagerDelegate(final X509TrustManager trustManager, final TrustStrategy trustStrategy) {\n- super();\nthis.trustManager = trustManager;\nthis.trustStrategy = trustStrategy;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryCertificateAcceptsRealValidCertificatesTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryCertificateAcceptsRealValidCertificatesTest.java",
"diff": "@@ -3,10 +3,13 @@ package com.github.tomakehurst.wiremock.http;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.junit.Test;\n+import org.junit.function.ThrowingRunnable;\n+import javax.net.ssl.SSLException;\nimport java.util.Collections;\nimport static com.github.tomakehurst.wiremock.common.HttpClientUtils.getEntityAsStringAndCloseStream;\n+import static org.junit.Assert.assertThrows;\npublic class HttpClientFactoryCertificateAcceptsRealValidCertificatesTest extends HttpClientFactoryCertificateVerificationTest {\n@@ -21,4 +24,15 @@ public class HttpClientFactoryCertificateAcceptsRealValidCertificatesTest extend\ngetEntityAsStringAndCloseStream(response);\n}\n+\n+ @Test\n+ public void invalidRealCertificateIsRejected() {\n+\n+ assertThrows(SSLException.class, new ThrowingRunnable() {\n+ @Override\n+ public void run() throws Exception {\n+ client.execute(new HttpGet(\"https://wiremock.org/\"));\n+ }\n+ });\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/com/github/tomakehurst/wiremock/http/ssl/CompositeTrustManagerTest.java",
"new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ssl/CompositeTrustManagerTest.java",
"diff": "package com.github.tomakehurst.wiremock.http.ssl;\n-import org.jmock.Expectations;\n-import org.jmock.Mockery;\n-import org.junit.After;\nimport org.junit.Test;\nimport org.junit.function.ThrowingRunnable;\n-import javax.net.ssl.X509TrustManager;\n+import javax.net.ssl.X509ExtendedTrustManager;\nimport java.math.BigInteger;\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\n@@ -25,25 +22,21 @@ import java.util.Set;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\nimport static org.junit.Assert.*;\n+import static org.mockito.BDDMockito.given;\n+import static org.mockito.BDDMockito.willThrow;\n+import static org.mockito.Mockito.mock;\n+import static org.mockito.Mockito.when;\npublic class CompositeTrustManagerTest {\n- private final Mockery context = new Mockery();\n- {\n- context.setDefaultResultForType(X509Certificate[].class, new X509Certificate[0]);\n- }\n- private final X509TrustManager trustManager1 = mockX509TrustManager(\"trustManager1\");\n- private final X509TrustManager trustManager2 = mockX509TrustManager(\"trustManager2\");\n+ private final X509ExtendedTrustManager trustManager1 = mockX509ExtendedTrustManager();\n+ private final X509ExtendedTrustManager trustManager2 = mockX509ExtendedTrustManager();\nprivate final X509Certificate[] chain = new X509Certificate[0];\nprivate final String authType = \"AN_AUTH_TYPE\";\n@Test\npublic void checkServerTrustedPassesForSingleTrustManager() throws CertificateException {\n- context.checking(new Expectations() {{\n- allowing(trustManager1).checkServerTrusted(chain, authType);\n- }});\n-\nCompositeTrustManager compositeTrustManager = new CompositeTrustManager(singletonList(\ntrustManager1\n));\n@@ -56,10 +49,8 @@ public class CompositeTrustManagerTest {\nfinal CertificateException invalidCertForTrustManager1 = new CertificateException(\"Invalid cert for trustManager1\");\n- context.checking(new Expectations() {{\n- allowing(trustManager1).checkServerTrusted(chain, authType);\n- will(throwException(invalidCertForTrustManager1));\n- }});\n+ willThrow(invalidCertForTrustManager1)\n+ .given(trustManager1).checkServerTrusted(chain, authType);\nfinal CompositeTrustManager compositeTrustManager = new CompositeTrustManager(singletonList(\ntrustManager1\n@@ -77,11 +68,6 @@ public class CompositeTrustManagerTest {\n@Test\npublic void checkServerTrustedIfBothWouldPass() throws CertificateException {\n- context.checking(new Expectations() {{\n- allowing(trustManager1).checkServerTrusted(chain, authType);\n- allowing(trustManager2).checkServerTrusted(chain, authType);\n- }});\n-\nCompositeTrustManager compositeTrustManager = new CompositeTrustManager(asList(\ntrustManager1,\ntrustManager2\n@@ -93,12 +79,8 @@ public class CompositeTrustManagerTest {\n@Test\npublic void checkServerTrustedIfFirstWouldPass() throws CertificateException {\n- context.checking(new Expectations() {{\n- allowing(trustManager1).checkServerTrusted(chain, authType);\n-\n- allowing(trustManager2).checkServerTrusted(chain, authType);\n- will(throwException(new CertificateException(\"Invalid cert for trustManager2\")));\n- }});\n+ willThrow(new CertificateException(\"Invalid cert for trustManager2\"))\n+ .given(trustManager2).checkServerTrusted(chain, authType);\nCompositeTrustManager compositeTrustManager = new CompositeTrustManager(asList(\ntrustManager1,\n@@ -111,12 +93,8 @@ public class CompositeTrustManagerTest {\n@Test\npublic void checkServerTrustedIfSecondWouldPass() throws CertificateException {\n- context.checking(new Expectations() {{\n- allowing(trustManager1).checkServerTrusted(chain, authType);\n- will(throwException(new CertificateException(\"Invalid cert for trustManager1\")));\n-\n- allowing(trustManager2).checkServerTrusted(chain, authType);\n- }});\n+ willThrow(new CertificateException(\"Invalid cert for trustManager1\"))\n+ .given(trustManager1).checkServerTrusted(chain, authType);\nCompositeTrustManager compositeTrustManager = new CompositeTrustManager(asList(\ntrustManager1,\n@@ -131,17 +109,15 @@ public class CompositeTrustManagerTest {\nfinal CertificateException invalidCertForTrustManager2 = new CertificateException(\"Invalid cert for trustManager2\");\n- context.checking(new Expectations() {{\n- allowing(trustManager1).checkServerTrusted(chain, authType);\n- will(throwException(new CertificateException(\"Invalid cert for trustManager1\")));\n-\n- allowing(trustManager2).checkServerTrusted(chain, authType);\n- will(throwException(invalidCertForTrustManager2));\n- }});\n+ willThrow(new CertificateException(\"Invalid cert for trustManager1\"))\n+ .given(trustManager1).checkServerTrusted(chain, authType);\n+ willThrow(invalidCertForTrustManager2)\n+ .given(trustManager2).checkServerTrusted(chain, authType);\n- final CompositeTrustManager compositeTrustManager = new CompositeTrustManager(\n- asList(trustManager1, trustManager2)\n- );\n+ final CompositeTrustManager compositeTrustManager = new CompositeTrustManager(asList(\n+ trustManager1,\n+ trustManager2\n+ ));\nCertificateException thrown = assertThrows(CertificateException.class, new ThrowingRunnable() {\n@Override\n@@ -161,20 +137,13 @@ public class CompositeTrustManagerTest {\nfinal X509Certificate cert3 = new FakeX509Certificate(\"cert3\");\nfinal X509Certificate cert4 = new FakeX509Certificate(\"cert4\");\n- final X509TrustManager trustManager1 = context.mock(X509TrustManager.class, \"newTrustManager1\");\n- final X509TrustManager trustManager2 = context.mock(X509TrustManager.class, \"newTrustManager2\");\n-\n- context.checking(new Expectations() {{\n- allowing(trustManager1).getAcceptedIssuers();\n- will(returnValue(new X509Certificate[] { cert1, cert2 }));\n+ given(trustManager1.getAcceptedIssuers()).willReturn(new X509Certificate[] { cert1, cert2 });\n+ given(trustManager2.getAcceptedIssuers()).willReturn(new X509Certificate[] { cert3, cert4 });\n- allowing(trustManager2).getAcceptedIssuers();\n- will(returnValue(new X509Certificate[] { cert3, cert4 }));\n- }});\n-\n- final CompositeTrustManager compositeTrustManager = new CompositeTrustManager(\n- asList(trustManager1, trustManager2)\n- );\n+ final CompositeTrustManager compositeTrustManager = new CompositeTrustManager(asList(\n+ trustManager1,\n+ trustManager2\n+ ));\nX509Certificate[] acceptedIssuers = compositeTrustManager.getAcceptedIssuers();\n@@ -185,16 +154,9 @@ public class CompositeTrustManagerTest {\nassertArrayEquals(new X509Certificate[] { cert1, cert2, cert3, cert4 }, compositeTrustManager.getAcceptedIssuers());\n}\n- @After\n- public void checkMockeryContextSatisfied() {\n- context.assertIsSatisfied();\n- }\n-\n- private X509TrustManager mockX509TrustManager(String name) {\n- final X509TrustManager trustManager = context.mock(X509TrustManager.class, name);\n- context.checking(new Expectations() {{\n- allowing(trustManager).getAcceptedIssuers();\n- }});\n+ private X509ExtendedTrustManager mockX509ExtendedTrustManager() {\n+ final X509ExtendedTrustManager trustManager = mock(X509ExtendedTrustManager.class);\n+ when(trustManager.getAcceptedIssuers()).thenReturn(new X509Certificate[0]);\nreturn trustManager;\n}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Make CompositeTrustManager extend X509ExtendedTrustManager
Will allow deciding how to verify on the basis of requested host.
Involves switching to Mockito as JMock doesn't like mocking classes. |
686,981 | 03.06.2020 10:40:34 | -3,600 | 8dd8c702bde0b5ff2351771589d82d7190328aa4 | Make TrustManagerDelegate extend X509ExtendedTrustManager
Will allow deciding how to verify on the basis of requested host. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java",
"diff": "@@ -18,6 +18,8 @@ package com.github.tomakehurst.wiremock.http;\nimport com.github.tomakehurst.wiremock.common.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\nimport com.github.tomakehurst.wiremock.http.ssl.SSLContextBuilder;\n+import com.github.tomakehurst.wiremock.http.ssl.TrustEverythingStrategy;\n+import com.github.tomakehurst.wiremock.http.ssl.TrustSelfSignedStrategy;\nimport org.apache.http.HttpHost;\nimport org.apache.http.auth.AuthScope;\nimport org.apache.http.auth.UsernamePasswordCredentials;\n@@ -26,8 +28,6 @@ import org.apache.http.client.methods.*;\nimport org.apache.http.config.SocketConfig;\nimport org.apache.http.conn.ssl.DefaultHostnameVerifier;\nimport org.apache.http.conn.ssl.NoopHostnameVerifier;\n-import org.apache.http.conn.ssl.TrustSelfSignedStrategy;\n-import org.apache.http.conn.ssl.TrustStrategy;\nimport org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\n@@ -41,7 +41,6 @@ import java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.UnrecoverableEntryException;\n-import java.security.cert.X509Certificate;\nimport java.util.Collections;\nimport java.util.Enumeration;\nimport java.util.List;\n@@ -163,12 +162,7 @@ public class HttpClientFactory {\nprivate static SSLContext buildAllowAnythingSSLContext() {\ntry {\n- return SSLContextBuilder.create().loadTrustMaterial(new TrustStrategy() {\n- @Override\n- public boolean isTrusted(X509Certificate[] chain, String authType) {\n- return true;\n- }\n- }).build();\n+ return SSLContextBuilder.create().loadTrustMaterial(new TrustEverythingStrategy()).build();\n} catch (Exception e) {\nreturn throwUnchecked(e, SSLContext.class);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java",
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java",
"diff": "@@ -30,7 +30,6 @@ package com.github.tomakehurst.wiremock.http.ssl;\nimport com.github.tomakehurst.wiremock.common.Pair;\nimport org.apache.http.ssl.PrivateKeyDetails;\nimport org.apache.http.ssl.PrivateKeyStrategy;\n-import org.apache.http.ssl.TrustStrategy;\nimport org.apache.http.util.Args;\nimport javax.net.ssl.KeyManager;\n@@ -41,7 +40,6 @@ import javax.net.ssl.TrustManager;\nimport javax.net.ssl.TrustManagerFactory;\nimport javax.net.ssl.X509ExtendedKeyManager;\nimport javax.net.ssl.X509ExtendedTrustManager;\n-import javax.net.ssl.X509TrustManager;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n@@ -246,8 +244,8 @@ public class SSLContextBuilder {\n}\nprivate TrustManager addStrategy(TrustManager tm, TrustStrategy trustStrategy) {\n- if (tm instanceof X509TrustManager) {\n- return new TrustManagerDelegate((X509TrustManager) tm, trustStrategy);\n+ if (tm instanceof X509ExtendedTrustManager) {\n+ return new TrustManagerDelegate((X509ExtendedTrustManager) tm, trustStrategy);\n} else {\nreturn tm;\n}\n@@ -346,12 +344,12 @@ public class SSLContextBuilder {\nreturn sslContext;\n}\n- static class TrustManagerDelegate implements X509TrustManager {\n+ static class TrustManagerDelegate extends X509ExtendedTrustManager {\n- private final X509TrustManager trustManager;\n+ private final X509ExtendedTrustManager trustManager;\nprivate final TrustStrategy trustStrategy;\n- TrustManagerDelegate(final X509TrustManager trustManager, final TrustStrategy trustStrategy) {\n+ TrustManagerDelegate(final X509ExtendedTrustManager trustManager, final TrustStrategy trustStrategy) {\nthis.trustManager = trustManager;\nthis.trustStrategy = trustStrategy;\n}\n@@ -375,6 +373,29 @@ public class SSLContextBuilder {\nreturn this.trustManager.getAcceptedIssuers();\n}\n+ @Override\n+ public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {\n+ trustManager.checkClientTrusted(chain, authType, socket);\n+ }\n+\n+ @Override\n+ public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {\n+ if (!this.trustStrategy.isTrusted(chain, authType, socket)) {\n+ trustManager.checkServerTrusted(chain, authType, socket);\n+ }\n+ }\n+\n+ @Override\n+ public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {\n+ trustManager.checkClientTrusted(chain, authType, engine);\n+ }\n+\n+ @Override\n+ public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {\n+ if (!this.trustStrategy.isTrusted(chain, authType, engine)) {\n+ trustManager.checkServerTrusted(chain, authType, engine);\n+ }\n+ }\n}\nstatic class KeyManagerDelegate extends X509ExtendedKeyManager {\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/TrustEverythingStrategy.java",
"diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import javax.net.ssl.SSLEngine;\n+import java.net.Socket;\n+import java.security.cert.X509Certificate;\n+\n+public class TrustEverythingStrategy implements TrustStrategy {\n+ @Override\n+ public boolean isTrusted(X509Certificate[] chain, String authType) {\n+ return true;\n+ }\n+\n+ @Override\n+ public boolean isTrusted(X509Certificate[] chain, String authType, Socket socket) {\n+ return true;\n+ }\n+\n+ @Override\n+ public boolean isTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {\n+ return true;\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/TrustSelfSignedStrategy.java",
"diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import javax.net.ssl.SSLEngine;\n+import java.net.Socket;\n+import java.security.cert.X509Certificate;\n+\n+public class TrustSelfSignedStrategy implements TrustStrategy {\n+ @Override\n+ public boolean isTrusted(X509Certificate[] chain, String authType) {\n+ return chain.length == 1;\n+ }\n+\n+ @Override\n+ public boolean isTrusted(X509Certificate[] chain, String authType, Socket socket) {\n+ return chain.length == 1;\n+ }\n+\n+ @Override\n+ public boolean isTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {\n+ return chain.length == 1;\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/TrustStrategy.java",
"diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import javax.net.ssl.SSLEngine;\n+import java.net.Socket;\n+import java.security.cert.X509Certificate;\n+\n+public interface TrustStrategy {\n+\n+ boolean isTrusted(X509Certificate[] chain, String authType);\n+\n+ boolean isTrusted(X509Certificate[] chain, String authType, Socket socket);\n+\n+ boolean isTrusted(X509Certificate[] chain, String authType, SSLEngine engine);\n+}\n"
}
]
| Java | Apache License 2.0 | tomakehurst/wiremock | Make TrustManagerDelegate extend X509ExtendedTrustManager
Will allow deciding how to verify on the basis of requested host. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.