jamy Van den Borre
03/01/2024, 8:56 AMMuhammad Maaz Khalid
03/01/2024, 4:01 PM{
"request": {
"method": "POST",
"urlPathPattern": "/orders",
"headers": {
"Content-Type": {
"equalTo": "application/xml"
},
"Host": {
"contains": "wiremock"
}
}
},
"response": {
"status": 201,
"body": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<OrderResponse>\n<Order>\n<id>{{parameters.orderId}}</id>\n<Quantity>{{parameters.quantity}}</Quantity>\n</Order>\n<OrderStatus>RECEIVED</OrderStatus>\n</OrderResponse>",
"headers": {
"Content-Type": "application/xml"
},
"transformers": [
"response-template"
],
"transformerParameters": {
"orderId": "{{randomValue type='UUID'}}",
"quantity": "${jsonPath request.body '$.Order.Quantity'}"
}
},
"serveEventListeners": [
{
"name": "webhook",
"parameters": {
"method": "POST",
"url": "<https://anywebhook.com/update>",
"body": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<OrderResponse>\n<Order>\n<id>{{parameters.orderId}}</id>\n<Quantity>{{parameters.quantity}}</Quantity>\n</Order>\n<OrderStatus>COMPLETE</OrderStatus>\n</OrderResponse>"
}
}
]
}
Hi All
Can you please guide what am I doing WRONG in transformerParameters to generate unique orderid using uuid. Also I want to use same order id in both response and web-hook call.
Also the quantity that I received from request I want to place it in both response body and web hook bodyOrçun BALCILAR
03/04/2024, 8:22 AMZAKARIA BOURHIL
03/04/2024, 4:12 PMpackage net.javaguides.springboot.integration;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import net.javaguides.springboot.model.Intern;
import net.javaguides.springboot.repository.InternRepository;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("wiremock")
public class InternControllerITwiremock {
private static WireMockServer wireMockServer;
@Autowired
private MockMvc mockMvc;
private static String urlToStub;
private static long internId;
@BeforeAll
static void init() {
wireMockServer = new WireMockServer(
new WireMockConfiguration()
.port(7070)
);
wireMockServer.start();
WireMock.configureFor("localhost", 7070);
internId = 1L;
urlToStub = String.format("/api/interns/%d", internId);
}
@Test
void shouldCallGetAllInterns() throws Exception {
Intern resource = getExpectedInternResponse();
stubFor(WireMock.get(urlMatching(urlToStub))
.willReturn(aResponse()
.withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.withBody("{ \"id\": 1, \"firstName\": \"salma\", \"lastName\": \"mhalou\" , \"email\": \"<mailto:salma@gmail.com|salma@gmail.com>\" }")
.withStatus(OK.value())));
mockMvc.perform(get("/api/interns/{id}", internId))
.andDo(print()).andExpect(status().isOk())
.andExpect(content().json(parseToJson(resource)));
verify(getRequestedFor(urlPathEqualTo(urlToStub)));
}
private static String parseToJson(Intern intern) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(intern);
}
private Intern getExpectedInternResponse(){
return Intern.builder()
.firstName("salma")
.lastName("mhalou")
.email("<mailto:salma@gmail.com|salma@gmail.com>")
.build();
}
}
this is my controller :
package net.javaguides.springboot.contoller;
import lombok.AllArgsConstructor;
import net.javaguides.springboot.model.Intern;
import net.javaguides.springboot.service.InternService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController // make this class as Spring MVC Controller
@RequestMapping("/api/interns")// provide a base URL for all the REST APIs defined in this controller
@AllArgsConstructor
public class InternController {
private InternService internService;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Intern createIntern(@RequestBody Intern intern){
return internService.saveIntern(intern);
}
@GetMapping
@ResponseStatus(HttpStatus.OK)
public List<Intern> getAllInterns(){
return internService.getAllInterns();
}
@GetMapping("{id}")
public ResponseEntity<Intern> getInternById(@PathVariable("id") long internId){
return internService.getInternById(internId)
.map(ResponseEntity::ok)
.orElseGet(()-> ResponseEntity.notFound().build());
}
@PutMapping("{id}")
public ResponseEntity<Intern> updateIntern(@PathVariable("id") long internId ,@RequestBody Intern intern){
return internService.getInternById(internId)
.map(
savedIntern ->{
savedIntern.setFirstName(intern.getFirstName());
savedIntern.setLastName(intern.getLastName());
savedIntern.setEmail(intern.getEmail());
Intern updatedIntern = internService.updateIntern(savedIntern);
return new ResponseEntity<>(updatedIntern , HttpStatus.OK);
})
.orElseGet(()-> ResponseEntity.notFound().build());
}
@DeleteMapping("{id}")
public ResponseEntity<String> deleteIntern(@PathVariable("id") long internId){
internService.deleteIntern(internId);
return new ResponseEntity<>("intern deleted successfully !!!",HttpStatus.OK);
}
}
and my service :
package net.javaguides.springboot.service.impl;
import lombok.AllArgsConstructor;
import net.javaguides.springboot.exception.InternNotFoundException;
import net.javaguides.springboot.model.Intern;
import net.javaguides.springboot.repository.InternRepository;
import net.javaguides.springboot.service.InternService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
@AllArgsConstructor
public class InternServiceImpl implements InternService {
private InternRepository internRepository;
@Override
public Intern saveIntern(Intern intern) {
// boolean exist = internRepository.checkInternEmailExists(intern.getEmail());
// if (exist){
// throw new ResourceNotFoundException("intern email already exist with this email : "+intern.getEmail());
// }
Optional<Intern> internSaved = internRepository.findByEmail(intern.getEmail());
if (internSaved.isPresent()){
throw new InternNotFoundException("intern email already exist with this email : "+intern.getEmail());
}
return internRepository.save(intern);
}
@Override
public List<Intern> getAllInterns() {
return internRepository.findAll();
}
@Override
public Optional<Intern> getInternById(long id) {
Optional<Intern> optionalIntern = internRepository.findById(id);
if (optionalIntern.isPresent()) {
return optionalIntern;
} else {
throw new InternNotFoundException("Intern not found with id : " + id);
}
}
@Override
public Intern updateIntern(Intern updatedIntern) {
Optional<Intern> internSaved = internRepository.findById(updatedIntern.getId());
if (internSaved.isEmpty()){
throw new InternNotFoundException("Intern not found with id : "+updatedIntern.getId());
}
return internRepository.save(updatedIntern);
}
@Override
public void deleteIntern(long id) {
Optional<Intern> optionalIntern = internRepository.findById(id);
if (optionalIntern.isPresent()) {
internRepository.deleteById(id);
} else {
throw new InternNotFoundException("Intern not found with id : " + id);
}
}
}
Žiga sternad
03/04/2024, 6:39 PMstandalone version 3.4.1
I have set up my Mac machine network to use HTTP and HTTPS to my local address with specified ports:
• port = 9999
• https-port = 2424
IP:
• Tried both 127.0.0.1 and actual local IP address.
I have also set up my own certificate using OpenSSL and keytool and I’m adding these when starting the server:
• --https-keystore cert/keystore.jks
• --keystore-password xxx
• --key-manager-password xxx
• --keystore-type JKS
Additional flags I set for running a server:
• --proxy-all “https://censored.net”
• --https-port 2424
• --verbose
• --bind-address 0.0.0.0
• --preserve-host-header
• --enable-browser-proxying
• --trust-all-proxy-targets
I have installed the server.cert
that was generated via. OpenSSL to the Simulator device and gave permissions/enabled it.
When I start the Application on my device, I’m just not getting any response. There is no traffic visible in the terminal.
Opening localhost:9999/__admin/
in Safari of the device works fine and I can see traffic printer to terminal.
I would really appreciate anyones help 🙏 I’ve spend the whole day trying to figure this out 😐Federico Silveri
03/05/2024, 12:11 PMJava
that stopped working after upgrading the version from 3.0.4
to 3.4.2
issue:
My test is failing because I have a timeout set to 3" and my API are not receiving any response from WireMock within that timeframe.
This is how I configured the WireMockServer instance:
final WireMockConfiguration options = new WireMockConfiguration().dynamicPort();
this.wireMockServer = new WireMockServer(options);
this.wireMockServer.start();
And here is my stub:
this.wireMockServer.stubFor(get(new UrlPathPattern(containing(**URL**), true))
.inScenario("test scenario")
.whenScenarioStateIs(STARTED)
.willSetStateTo("test scenario 1")
.withHeader(AUTHORIZATION, equalTo("Bearer " + token))
.willReturn(aResponse()
.withBody(mapper.serialize(response).orElseThrow())
.withHeader(CONTENT_TYPE, APPLICATION_JSON)));
I tried to progressively upgrade the version from 3.0.4
and I'm starting to see the issue from 3.3.1
(same issue with 3.3.0
but I'm not using it since it's been marked as discarded). I tried to look at the release note but I couldn't find anything to the issue I'm having.
I would really appreciate anyones help 🙏 🙂Jackie chen
03/05/2024, 9:51 PMCaused by: java.io.EOFException: Unexpected end of ZLIB input stream
at java.base/java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:245)
at java.base/java.util.zip.InflaterInputStream.read(InflaterInputStream.java:159)
at java.base/java.util.zip.GZIPInputStream.read(GZIPInputStream.java:118)
at org.apache.http.client.entity.LazyDecompressingInputStream.read(LazyDecompressingInputStream.java:70)
at java.base/java.io.FilterInputStream.read(FilterInputStream.java:133)
at java.base/java.io.PushbackInputStream.read(PushbackInputStream.java:183)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._loadMore(UTF8StreamJsonParser.java:220)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.parseEscapedName(UTF8StreamJsonParser.java:1985)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.slowParseName(UTF8StreamJsonParser.java:1891)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._parseName(UTF8StreamJsonParser.java:1675)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:757)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:401)
Jackie chen
03/06/2024, 3:44 AMŽiga sternad
03/06/2024, 1:58 PMapache-httpClient/5.3.1 (Java/17.0.9)
instead of the custom header that was set by the client (in my case an Android device)?
I would like to know how I can avoid this scenario, because if I’m not forwarding the right user-agent, my client gets blocked by the server and returns code 403.Vivek T
03/07/2024, 12:30 AMRaghunath
03/07/2024, 5:57 AMJackie chen
03/07/2024, 1:24 PM.gzipDisabled( true )//
Chris Connor
03/07/2024, 5:01 PM<h1>Bad Message 400</h1><pre>reason: Bad HostPort</pre>
With no record of the request in the normal wiremock logs so it’s not even reaching wiremock.
We’re mocking an SDK request so just wondering if theres headers or something that’s causing Jetty to blow up 🤷Bas Dijkstra
03/08/2024, 9:30 AMquantity
from the request body in a response.
Using "quantity": "{{jsonPath request.body '$.quantity'}}"
it works, but that converts the element in the response to a string, not an integer. If I remove the double quotes, WireMock tells me my JSON is invalid.
How can I easily return request body integer values as an integer in the response?Benoit LEFEVRE -CAMPUS-
03/08/2024, 1:59 PMŽiga sternad
03/11/2024, 10:09 AMuser-agent
header as it is sent from the client, proxied via. Wiremock, to the server. In my case, we need to forward the exact value as it was sent by the client.
I have tried to create an extension to remove and re-add the header, with the code below:
public class UrlAndHeadersModifyingFilter implements StubRequestFilterV2 {
@Override
public RequestFilterAction filter(Request request, ServeEvent serveEvent) {
String originalUserAgent = "example-user-agent";
Request wrappedRequest = RequestWrapper.create()
.removeHeader("User-Agent")
.addHeader("User-Agent", originalUserAgent)
.wrap(request);
return RequestFilterAction.continueWith(wrappedRequest);
}
@Override
public String getName() {
return "url-and-header-modifier";
}
}
I can see the value being updated in the http://localhost:9999/__admin/requests logs, but the server receives the updated version of the header: apache-httpClient/5.3.1 (Java/17.0.9)
I also tried to enable .notifier(new ConsoleNotifier(true))
and I see all requests/responses in the terminal. All the request logs contain the original User-agent that is coming from the client.
Am I missing something? 😐
I would like to know if this is even solvable with the Wiremock, or is it a bug or something that is not supported?
Really appreciate some thoughts / feedback on this 🙏 🙇
cc: @Tomjerrymon albert
03/12/2024, 5:23 PMRohan Kudale
03/18/2024, 2:09 PMUtku K
03/20/2024, 11:09 AMfun stubXXX(statusCode: Int, accountId: Int, responseSample: Sample): StubMapping {
return stubFor(
get(urlEqualTo("/accounts/$accountId/eligibility"))
.willReturn(
aResponse()
.withStatus(statusCode)
.withHeader(CONTENT_TYPE, APPLICATION_JSON)
.withBody(getReadSampleText(responseSample))
)
)
}
Language: kotlinMatt DC
03/22/2024, 3:36 PMIvan
03/22/2024, 5:37 PMio.grpc.StatusRuntimeException: UNKNOWN: HTTP status code 200
invalid content-type: null
headers: Metadata(:status=200,grpc-status-name=OK,matched-stub-id=00e9561b-a02a-4553-bf36-6be6d397766e)
DATA-----------------------------
{
}
DATA-----------------------------
at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:268)
at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:249)
at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:167)
My stub is the following one:
private final WireMockGrpcService wireMockGrpcService =
new WireMockGrpcService(
new WireMock(getPort()),
UnaryEnvelopeRelayServiceGrpc.SERVICE_NAME
);
private ManagedChannel channel;
@BeforeEach
void init() {
channel = ManagedChannelBuilder.forAddress("localhost", getPort()).usePlaintext().build();
enricherClient = new EnricherClient(UnaryEnvelopeRelayServiceGrpc.newBlockingStub(channel));
}
@AfterEach
void tearDown() {
channel.shutdown();
}
@Test
void should_return_failure_when_initiation_fails() {
wireMockGrpcService.stubFor(
method("relay")
.willReturn(message(Envelope.newBuilder().build())));
Any idea what could be causing this issue?Troy Snowden
03/25/2024, 10:30 AMJackie chen
03/26/2024, 6:43 AM2024-03-26 15:09:15.995 Unable to generate a certificate authority
com.github.tomakehurst.wiremock.http.ssl.CertificateGenerationUnsupportedException: Your runtime does not support generating certificates at runtime
at com.github.tomakehurst.wiremock.http.ssl.CertificateAuthority.generateCertificateAuthority(CertificateAuthority.java:72)
at com.github.tomakehurst.wiremock.jetty94.SslContexts.buildKeyStore(SslContexts.java:124)
at com.github.tomakehurst.wiremock.jetty94.SslContexts.buildSslContextFactory(SslContexts.java:76)
at com.github.tomakehurst.wiremock.jetty94.SslContexts.buildManInTheMiddleSslContextFactory(SslContexts.java:52)
at com.github.tomakehurst.wiremock.jetty94.Jetty94HttpServer.applyAdditionalServerConfiguration(Jetty94HttpServer.java:128)
at com.github.tomakehurst.wiremock.jetty9.JettyHttpServer.<init>(JettyHttpServer.java:109)
at com.github.tomakehurst.wiremock.jetty94.Jetty94HttpServer.<init>(Jetty94HttpServer.java:45)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at com.github.tomakehurst.wiremock.jetty9.JettyHttpServerFactory.buildHttpServer(JettyHttpServerFactory.java:73)
at com.github.tomakehurst.wiremock.WireMockServer.<init>(WireMockServer.java:75)Prebeesh S
03/26/2024, 7:31 AMDescription:
An attempt was made to call a method that does not exist. The attempt was made from the following location:
org.wiremock.webhooks.Webhooks.<init>(Webhooks.java:46)
The following method did not exist:
'org.apache.http.impl.client.CloseableHttpClient com.github.tomakehurst.wiremock.http.HttpClientFactory.createClient()'
The calling method's class, org.wiremock.webhooks.Webhooks, was loaded from the following location:
jar:file:/C:/Users/e5665964/.m2/repository/org/wiremock/wiremock-webhooks-extension/1.0.0/wiremock-webhooks-extension-1.0.0.jar!/org/wiremock/webhooks/Webhooks.class
The called method's class, com.github.tomakehurst.wiremock.http.HttpClientFactory, is available from the following locations:
jar:file:/C:/Users/e5665964/.m2/repository/com/github/tomakehurst/wiremock-standalone/2.27.2/wiremock-standalone-2.27.2.jar!/com/github/tomakehurst/wiremock/http/HttpClientFactory.class
jar:file:/C:/Users/e5665964/.m2/repository/com/github/tomakehurst/wiremock/2.21.0/wiremock-2.21.0.jar!/com/github/tomakehurst/wiremock/http/HttpClientFactory.class
The called method's class hierarchy was loaded from the following locations:
com.github.tomakehurst.wiremock.http.HttpClientFactory: file:/C:/Users/e5665964/.m2/repository/com/github/tomakehurst/wiremock-standalone/2.27.2/wiremock-standalone-2.27.2.jar
Action:
Correct the classpath of your application so that it contains compatible versions of the classes org.wiremock.webhooks.Webhooks and com.github.tomakehurst.wiremock.http.HttpClientFactory
Jackie chen
03/26/2024, 10:27 AM{
"id": "f3ce7712-0c1c-478b-b92e-de7394c9998c",
"request": {
"urlPattern": "/extends.*",
"method": "ANY"
},
"response": {
"status": 200,
"proxyBaseUrl": "<https://abc.com>"
},
"uuid": "f3ce7712-0c1c-478b-b92e-de7394c9998c",
"priority": 1
}
when i send https://abc.com/extends using Wiremock as a browser proxy, the ResponseTransformer response.isFromProxy() is false? why is it false even if it matches the proxy request matching? This happens on Java 17 only.Utku K
03/26/2024, 2:39 PMpatch(urlEqualTo("/endpoint"))
.withHeader(EXECUTOR_USER, equalTo("123")) // it should be 123
.willReturn(
aResponse()
.withStatus(statusCode)
.withBody(mockResponse)
)
)
Slackbot
03/27/2024, 3:21 PMRain Oksvort
03/27/2024, 4:52 PM<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-standalone</artifactId>
<version>2.27.2</version>
<scope>test</scope>
</dependency>
I want to create a mock server and test if expected header was actually posted. To do this I have invented the following code:
@Test
void testHeaders() throws InterruptedException {
String expectedBody = "Expected body";
String expectedPath = "/expectedPath";
String expectedHeaderName = "X-Custom-Header";
String expectedHeaderValue = "Custom Value";
wireMockServer = new WireMockServer(WireMockConfiguration.options().port(8080));
httpClient = HttpClients.createDefault();
wireMockServer.start();
StubMapping stubMapping = wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo(expectedPath))
.withHeader(expectedHeaderName, WireMock.equalTo(expectedHeaderValue))
.willReturn(WireMock.aResponse()));
int i = 10_000;
//Sleep in loop to get some time to make request from curl
while (i > 0){Thread.sleep(10);i -=100;}
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo(expectedPath)).withHeader(expectedHeaderName, WireMock.equalTo(expectedHeaderValue)));
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
wireMockServer.stop();
}
What's the good way to run it in background? For example if I just put breakpoint directly WireMock.verify without having while (i > 0){Thread.sleep(10);i -=100;} in my code then I cannot make requests to server from curl despite the fact that. wireMockServer.stop() has not yet been called. Is there any option to start it in new thread or are developers supposed to manually deal with creating threads?Mayank Arora
03/27/2024, 11:05 PMRain Oksvort
03/28/2024, 2:45 PMwireMockServer = new WireMockServer(WireMockConfiguration.options().port(8080));
httpClient = HttpClients.createDefault();
wireMockServer.start();
Is there a way to do it Spring way and use annotations instead? For example here https://wiremock.org/docs/solutions/spring-boot/ it talks about @EnableWireMock
annotation. But when I try to add it to my code then with my dependency Intellij can't find where to import EnableWireMock.
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-standalone</artifactId>
<version>2.27.2</version>
<scope>test</scope>
</dependency>
I also tried this dependency:
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>3.0.1</version>
<type>pom</type>
<scope>test</scope>
</dependency>
But still no way to import @EnableWireMock annotation.
Is there any way in java 8 not to initialize it in Java but rather use annotations like example on your home page?