com.github.tomakehurst.wiremock.http.Request Java Examples
The following examples show how to use
com.github.tomakehurst.wiremock.http.Request.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WireMockBase.java From blueocean-plugin with MIT License | 6 votes |
@Override public Response transform(Request request, Response response, FileSource files, Parameters parameters) { // if gzipped, ungzip they body and discard the Content-Encoding header if (response.getHeaders().getHeader("Content-Encoding").containsValue("gzip")) { Iterable<HttpHeader> headers = Iterables.filter( response.getHeaders().all(), (HttpHeader header) -> header != null && !header.keyEquals("Content-Encoding") && !header.containsValue("gzip") ); return Response.Builder.like(response) .but() .body(Gzip.unGzip(response.getBody())) .headers(new HttpHeaders(headers)) .build(); } return response; }
Example #2
Source File: RedirectTest.java From gradle-download-task with Apache License 2.0 | 6 votes |
@Override public Response transform(Request request, Response response, FileSource files, Parameters parameters) { if (redirects == null) { redirects = parameters.getInt("redirects"); } String nl; if (redirects > 1) { redirects--; nl = "/" + REDIRECT + "?r=" + redirects; } else { nl = "/" + TEST_FILE_NAME; } return Response.Builder.like(response) .but().headers(response.getHeaders() .plus(new HttpHeader("Location", nl))) .build(); }
Example #3
Source File: BoxDeveloperEditionAPIConnectionTest.java From box-java-sdk with Apache License 2.0 | 6 votes |
private void mockListener() { this.wireMockRule.addMockServiceRequestListener(new RequestListener() { @Override public void requestReceived(Request request, Response response) { try { JwtClaims claims = BoxDeveloperEditionAPIConnectionTest.this .getClaimsFromRequest(request); if (BoxDeveloperEditionAPIConnectionTest.this.jtiClaim == null) { BoxDeveloperEditionAPIConnectionTest.this.jtiClaim = claims.getJwtId(); } } catch (Exception ex) { Assert.fail("Could not save JTI claim from request"); } } }); }
Example #4
Source File: BoxDeveloperEditionAPIConnectionTest.java From box-java-sdk with Apache License 2.0 | 6 votes |
private JwtClaims getClaimsFromRequest(Request request) throws Exception { // Get the JWT out of the request body String body = request.getBodyAsString(); String[] tokens = body.split("&"); String jwt = null; for (String s : tokens) { String[] parts = s.split("="); if (parts[0] != null && parts[0].equals("assertion") && parts[1] != null) { jwt = parts[1]; } } if (jwt == null) { throw new Exception("No jwt assertion found in request body"); } // Parse out the JWT to verify the claims JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setSkipSignatureVerification() .setSkipAllValidators() .build(); return jwtConsumer.processToClaims(jwt); }
Example #5
Source File: AbstractGitHubWireMockTest.java From github-branch-source-plugin with MIT License | 6 votes |
@Override public Response transform(Request request, Response response, FileSource files, Parameters parameters) { if ("application/json" .equals(response.getHeaders().getContentTypeHeader().mimeTypePart())) { return Response.Builder.like(response) .but() .body(response.getBodyAsString() .replace("https://api.github.com/", "http://localhost:" + githubApi.port() + "/") .replace("https://raw.githubusercontent.com/", "http://localhost:" + githubRaw.port() + "/") ) .build(); } return response; }
Example #6
Source File: FailingWebhookTest.java From wiremock-webhooks-extension with Apache License 2.0 | 6 votes |
@Before public void init() { targetServer.addMockServiceRequestListener(new RequestListener() { @Override public void requestReceived(Request request, Response response) { if (request.getUrl().startsWith("/callback")) { latch.countDown(); } } }); reset(); notifier.reset(); targetServer.stubFor(any(anyUrl()) .willReturn(aResponse().withStatus(200))); latch = new CountDownLatch(1); client = new WireMockTestClient(rule.port()); WireMock.configureFor(targetServer.port()); }
Example #7
Source File: WebhooksAcceptanceTest.java From wiremock-webhooks-extension with Apache License 2.0 | 6 votes |
@Before public void init() { targetServer.addMockServiceRequestListener(new RequestListener() { @Override public void requestReceived(Request request, Response response) { if (request.getUrl().startsWith("/callback")) { latch.countDown(); } } }); reset(); notifier.reset(); targetServer.stubFor(any(anyUrl()) .willReturn(aResponse().withStatus(200))); latch = new CountDownLatch(1); client = new WireMockTestClient(rule.port()); WireMock.configureFor(targetServer.port()); System.out.println("Target server port: " + targetServer.port()); System.out.println("Under test server port: " + rule.port()); }
Example #8
Source File: IntegrationTest.java From prebid-server-java with Apache License 2.0 | 6 votes |
@Override public com.github.tomakehurst.wiremock.http.Response transform( Request request, com.github.tomakehurst.wiremock.http.Response response, FileSource files, Parameters parameters) { final String newResponse; try { newResponse = cacheResponseFromRequestJson(request.getBodyAsString(), parameters.getString("matcherName")); } catch (IOException e) { return com.github.tomakehurst.wiremock.http.Response.response() .body(e.getMessage()) .status(500) .build(); } return com.github.tomakehurst.wiremock.http.Response.response().body(newResponse).status(200).build(); }
Example #9
Source File: SchemaRegistryMock.java From schema-registry-transfer-smt with Apache License 2.0 | 5 votes |
@Override public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition, final FileSource files, final Parameters parameters) { String versionStr = Iterables.get(this.urlSplitter.split(request.getUrl()), 3); SchemaMetadata metadata; if (versionStr.equals("latest")) { metadata = SchemaRegistryMock.this.getSubjectVersion(getSubject(request), versionStr); } else { int version = Integer.parseInt(versionStr); metadata = SchemaRegistryMock.this.getSubjectVersion(getSubject(request), version); } return ResponseDefinitionBuilder.jsonResponse(metadata); }
Example #10
Source File: SchemaRegistryMock.java From fluent-kafka-streams-tests with MIT License | 5 votes |
@Override public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition, final FileSource files, final Parameters parameters) { final String subject = Iterables.get(this.urlSplitter.split(request.getUrl()), 1); try { final int id = SchemaRegistryMock.this.register(subject, new Schema.Parser() .parse(RegisterSchemaRequest.fromJson(request.getBodyAsString()).getSchema())); final RegisterSchemaResponse registerSchemaResponse = new RegisterSchemaResponse(); registerSchemaResponse.setId(id); return ResponseDefinitionBuilder.jsonResponse(registerSchemaResponse); } catch (final IOException e) { throw new IllegalArgumentException("Cannot parse schema registration request", e); } }
Example #11
Source File: SchemaRegistryMock.java From fluent-kafka-streams-tests with MIT License | 5 votes |
@Override public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition, final FileSource files, final Parameters parameters) { final List<Integer> versions = SchemaRegistryMock.this.listVersions(this.getSubject(request)); log.debug("Got versions {}", versions); return ResponseDefinitionBuilder.jsonResponse(versions); }
Example #12
Source File: SchemaRegistryMock.java From fluent-kafka-streams-tests with MIT License | 5 votes |
@Override public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition, final FileSource files, final Parameters parameters) { final String versionStr = Iterables.get(this.urlSplitter.split(request.getUrl()), 3); final SchemaMetadata metadata; if (versionStr.equals("latest")) { metadata = SchemaRegistryMock.this.getSubjectVersion(this.getSubject(request), versionStr); } else { final int version = Integer.parseInt(versionStr); metadata = SchemaRegistryMock.this.getSubjectVersion(this.getSubject(request), version); } return ResponseDefinitionBuilder.jsonResponse(metadata); }
Example #13
Source File: WireMockVerifyHelper.java From spring-cloud-contract with Apache License 2.0 | 5 votes |
public void configure(T result) { Map<String, Object> configuration = getConfiguration(result); byte[] requestBodyContent = getRequestBodyContent(result); if (requestBodyContent != null) { String actual = new String(requestBodyContent, Charset.forName("UTF-8")); for (JsonPath jsonPath : this.jsonPaths.values()) { new JsonPathValue(jsonPath, actual).assertHasValue(Object.class, "an object"); } } configuration.put("contract.jsonPaths", this.jsonPaths.keySet()); if (this.contentType != null) { configuration.put("contract.contentType", this.contentType); MediaType resultType = getContentType(result); assertThat(resultType).isNotNull().as("no content type"); assertThat(this.contentType.includes(resultType)).isTrue() .as("content type did not match"); } if (this.builder != null) { this.builder.willReturn(getResponseDefinition(result)); StubMapping stubMapping = this.builder.build(); Request request = getWireMockRequest(result); MatchResult match = stubMapping.getRequest().match(request); assertThat(match.isExactMatch()).as("wiremock did not match request") .isTrue(); configuration.put("contract.stubMapping", stubMapping); } }
Example #14
Source File: WireMockBase.java From blueocean-plugin with MIT License | 5 votes |
@Override public Response transform(Request request, Response response, FileSource files, Parameters parameters) { if ("application/json" .equals(response.getHeaders().getContentTypeHeader().mimeTypePart())) { return Response.Builder.like(response) .but() .body(response.getBodyAsString().replace(sourceUrl, getServerUrl(rule))) .build(); } return response; }
Example #15
Source File: GithubMockBase.java From blueocean-plugin with MIT License | 5 votes |
@Override public Response transform(Request request, Response response, FileSource files, Parameters parameters) { if ("application/json" .equals(response.getHeaders().getContentTypeHeader().mimeTypePart())) { return Response.Builder.like(response) .but() .body(response.getBodyAsString() .replace("https://api.github.com/", "http://localhost:" + githubApi.port() + "/") ) .build(); } return response; }
Example #16
Source File: MockOriginServer.java From styx with Apache License 2.0 | 5 votes |
private static HttpHandler newHandler(RequestHandler wireMockHandler) { return (httpRequest, ctx) -> httpRequest.aggregate(MAX_CONTENT_LENGTH) .map(fullRequest -> { LOGGER.info("Received: {}\n{}", new Object[]{fullRequest.url(), fullRequest.body()}); return fullRequest; }) .flatMap(fullRequest -> { Request wmRequest = new WiremockStyxRequestAdapter(fullRequest); com.github.tomakehurst.wiremock.http.Response wmResponse = wireMockHandler.handle(wmRequest); return Eventual.of(toStyxResponse(wmResponse).stream()); }); }
Example #17
Source File: SchemaRegistryMock.java From schema-registry-transfer-smt with Apache License 2.0 | 5 votes |
@Override public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition, final FileSource files, final Parameters parameters) { try { final int id = SchemaRegistryMock.this.register(getSubject(request), new Schema.Parser() .parse(RegisterSchemaRequest.fromJson(request.getBodyAsString()).getSchema())); final RegisterSchemaResponse registerSchemaResponse = new RegisterSchemaResponse(); registerSchemaResponse.setId(id); return ResponseDefinitionBuilder.jsonResponse(registerSchemaResponse); } catch (final IOException e) { throw new IllegalArgumentException("Cannot parse schema registration request", e); } }
Example #18
Source File: SchemaRegistryMock.java From schema-registry-transfer-smt with Apache License 2.0 | 5 votes |
@Override public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition, final FileSource files, final Parameters parameters) { final List<Integer> versions = SchemaRegistryMock.this.listVersions(getSubject(request)); log.debug("Got versions {}", versions); return ResponseDefinitionBuilder.jsonResponse(versions); }
Example #19
Source File: SchemaRegistryMock.java From schema-registry-transfer-smt with Apache License 2.0 | 5 votes |
@Override protected String getSubject(Request request) { List<String> parts = StreamSupport.stream(this.urlSplitter.split(request.getUrl()).spliterator(), false) .collect(Collectors.toList()); // return null when this is just /config return parts.size() < 2 ? null : parts.get(1); }
Example #20
Source File: AbstractInstancesProxyControllerIntegrationTest.java From Moss with Apache License 2.0 | 5 votes |
@Override public Response transform(Request request, Response response, FileSource files, Parameters parameters) { return Response.Builder.like(response) .headers(HttpHeaders.copyOf(response.getHeaders()) .plus(new HttpHeader("Connection", "Close"))) .build(); }
Example #21
Source File: MockOriginServer.java From styx with Apache License 2.0 | 5 votes |
private static HttpHandler newHandler(String originId, RequestHandler wireMockHandler) { return (httpRequest, ctx) -> httpRequest.aggregate(MAX_CONTENT_LENGTH) .map(fullRequest -> { LOGGER.info("{} received: {}\n{}", new Object[]{originId, fullRequest.url(), fullRequest.body()}); return fullRequest; }) .flatMap(fullRequest -> { Request wmRequest = new WiremockStyxRequestAdapter(fullRequest); com.github.tomakehurst.wiremock.http.Response wmResponse = wireMockHandler.handle(wmRequest); return Eventual.of(toStyxResponse(wmResponse).stream()); }); }
Example #22
Source File: CustomVelocityResponseTransformer.java From AuTe-Framework with Apache License 2.0 | 5 votes |
private URL getRequestUrl(Request request) { try { return new URL(request.getAbsoluteUrl()); } catch (MalformedURLException e) { log.error("Invalid url", e); throw new RuntimeException(e); } }
Example #23
Source File: SchemaRegistryMock.java From fluent-kafka-streams-tests with MIT License | 4 votes |
@Override public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition, final FileSource files, final Parameters parameters) { final List<Integer> ids = SchemaRegistryMock.this.delete(this.getSubject(request)); return ResponseDefinitionBuilder.jsonResponse(ids); }
Example #24
Source File: ConnectionCloseExtension.java From spring-boot-admin with Apache License 2.0 | 4 votes |
@Override public Response transform(Request request, Response response, FileSource files, Parameters parameters) { return Response.Builder.like(response) .headers(HttpHeaders.copyOf(response.getHeaders()).plus(new HttpHeader("Connection", "Close"))).build(); }
Example #25
Source File: RequestVerifierFilter.java From spring-cloud-netflix with Apache License 2.0 | 4 votes |
@Override public Optional<Request> getOriginalRequest() { return Optional.of(this); }
Example #26
Source File: EventStreamTest.java From box-java-sdk with Apache License 2.0 | 4 votes |
@Test @Category(UnitTest.class) public void delayBetweenCalls() throws InterruptedException { final String realtimeServerURL = "/realtimeServer?channel=0"; final int delay = 2000; final long[] times = new long[2]; stubFor(options(urlEqualTo("/events")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"entries\": [ { \"url\": \"http://localhost:53620" + realtimeServerURL + "\", " + "\"max_retries\": \"3\", \"retry_timeout\": 60000 } ] }"))); stubFor(get(urlMatching("/events\\?.*stream_position=now.*")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"next_stream_position\": 123 }"))); stubFor(get(urlMatching("/realtimeServer.*")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"message\": \"new_change\" }"))); stubFor(get(urlMatching("/events\\?.*stream_position=123")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"next_stream_position\": 456, \"entries\": [ { \"type\": \"event\", " + "\"event_id\": \"1\" } ] }"))); stubFor(get(urlMatching("/events\\?.*stream_position=456")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"next_stream_position\": 789, \"entries\": [ { \"type\": \"event\", " + "\"event_id\": \"1\" } ] }"))); BoxAPIConnection api = new BoxAPIConnection(""); api.setBaseURL("http://localhost:53620/"); final EventStream stream = new EventStream(api, -1, delay); final EventListener eventListener = mock(EventListener.class); stream.addListener(eventListener); final Object requestLock = new Object(); this.wireMockRule.addMockServiceRequestListener(new RequestListener() { @Override public void requestReceived(Request request, Response response) { boolean firstCall = request.getUrl().contains("stream_position=123"); boolean secondCall = request.getUrl().contains("stream_position=456"); boolean lastCall = request.getUrl().contains("stream_position=789"); if (firstCall) { times[0] = System.currentTimeMillis(); } if (secondCall) { times[1] = System.currentTimeMillis(); } if (lastCall) { synchronized (requestLock) { requestLock.notify(); } } } }); stream.start(); synchronized (requestLock) { requestLock.wait(); } Assert.assertTrue("Calls should be be 2s apart", times[1] - times[0] >= delay); }
Example #27
Source File: EventStreamTest.java From box-java-sdk with Apache License 2.0 | 4 votes |
@Test @Category(UnitTest.class) public void duplicateEventsAreNotReported() throws InterruptedException { final String realtimeServerURL = "/realtimeServer?channel=0"; stubFor(options(urlEqualTo("/events")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"entries\": [ { \"url\": \"http://localhost:53620" + realtimeServerURL + "\", " + "\"max_retries\": \"3\", \"retry_timeout\": 60000 } ] }"))); stubFor(get(urlMatching("/events\\?.*stream_position=now.*")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"next_stream_position\": 0 }"))); stubFor(get(urlMatching("/realtimeServer.*")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"message\": \"new_change\" }"))); stubFor(get(urlMatching("/events\\?.*stream_position=0")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"next_stream_position\": 1, \"entries\": [ { \"type\": \"event\", " + "\"event_id\": \"1\" } ] }"))); stubFor(get(urlMatching("/events\\?.*stream_position=1")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"next_stream_position\": -1, \"entries\": [ { \"type\": \"event\", " + "\"event_id\": \"1\" } ] }"))); BoxAPIConnection api = new BoxAPIConnection(""); api.setBaseURL("http://localhost:53620/"); final EventStream stream = new EventStream(api); final EventListener eventListener = mock(EventListener.class); stream.addListener(eventListener); final Object requestLock = new Object(); this.wireMockRule.addMockServiceRequestListener(new RequestListener() { @Override public void requestReceived(Request request, Response response) { boolean requestUrlMatch = request.getUrl().contains("-1"); if (requestUrlMatch) { synchronized (requestLock) { requestLock.notify(); } } } }); stream.start(); synchronized (requestLock) { requestLock.wait(); } verify(eventListener).onEvent(any(BoxEvent.class)); }
Example #28
Source File: EventStreamTest.java From box-java-sdk with Apache License 2.0 | 4 votes |
@Test @Category(UnitTest.class) public void canStopStreamWhileWaitingForAPIResponse() throws InterruptedException { final long streamPosition = 123456; final String realtimeServerURL = "/realtimeServer?channel=0"; stubFor(options(urlEqualTo("/events")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"entries\": [ { \"url\": \"http://localhost:53620" + realtimeServerURL + "\", " + "\"max_retries\": \"3\", \"retry_timeout\": 60000 } ] }"))); stubFor(get(urlPathMatching("/events")) .withQueryParam("stream_position", WireMock.equalTo("now")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"next_stream_position\": " + streamPosition + ",\"entries\":[] }"))); stubFor(get(urlMatching("/realtimeServer.*")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{ \"message\": \"new_change\" }"))); BoxAPIConnection api = new BoxAPIConnection(""); api.setBaseURL("http://localhost:53620/"); final EventStream stream = new EventStream(api); final Object requestLock = new Object(); this.wireMockRule.addMockServiceRequestListener(new RequestListener() { @Override public void requestReceived(Request request, Response response) { String streamPositionURL = realtimeServerURL + "&stream_position=" + streamPosition; boolean requestUrlMatch = request.getUrl().contains(streamPositionURL); if (requestUrlMatch) { stream.stop(); synchronized (requestLock) { requestLock.notify(); } } } }); stream.start(); synchronized (requestLock) { requestLock.wait(); } assertThat(stream.isStarted(), is(false)); }
Example #29
Source File: SchemaRegistryMock.java From schema-registry-transfer-smt with Apache License 2.0 | 4 votes |
@Override public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition, final FileSource files, final Parameters parameters) { Config config = new Config(SchemaRegistryMock.this.getCompatibility(getSubject(request))); return ResponseDefinitionBuilder.jsonResponse(config); }
Example #30
Source File: CustomVelocityResponseTransformer.java From AuTe-Framework with Apache License 2.0 | 4 votes |
@Override public ResponseDefinition transform( final Request request, final ResponseDefinition responseDefinition, final FileSource files, final Parameters parameters ) throws RuntimeException { final VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.init(); final ToolManager toolManager = new ToolManager(); toolManager.setVelocityEngine(velocityEngine); context = toolManager.createContext(); URL url = getRequestUrl(request); addBodyToContext(request.getBodyAsString()); addHeadersToContext(request.getHeaders()); context.put("requestAbsoluteUrl", request.getAbsoluteUrl()); context.put("requestUrl", request.getUrl()); context.put("requestMethod", request.getMethod()); context.put("queryParams", urlExtractor.extractQueryParameters(url)); context.put("pathSegments", urlExtractor.extractPathSegments(url)); context.put("staticContext", staticContexts.computeIfAbsent(url.getPath(), k -> new HashMap<>())); context.put(ExtendedScript.MQ_PROPERTIES, properties); String body; if (responseDefinition.specifiesBodyFile() && templateDeclared(responseDefinition)) { body = getRenderedBody(responseDefinition); } else if (responseDefinition.specifiesBodyContent()) { try { body = getRenderedBodyFromFile(responseDefinition); } catch (ParseException e) { body = e.getMessage(); e.printStackTrace(); } } else { return responseDefinition; } if (isPresentConvertCommand(responseDefinition.getHeaders().getHeader(MultipartConstant.CONVERT_BASE64_IN_MULTIPART.getValue()))) { log.info(" >>> "); log.info(body); return buildResponse(parseConvertBody(body), body, responseDefinition, true); } return buildResponse(null, body, responseDefinition, false); }