Tag Archives: java

Apache Camel OpenAPI Contract-First Example in SpringBoot

Contract-First means what the name implies that we write the contract between client and server first and implement the code for it after. This is a good way to break up the task of creating an API in smaller parts which can be handled over multiple professions. For example, the OpenAPI specification can be created by an IT-architect and the implementation can be done by a programmer, and lastly the API documentation can be carried out by an communications expert.

In this article I’m going to build a simple OpenAPI implementation in Apache Camel and it’s rest-openapi component in a SpringBoot application.

1. We start with the API Specification:

openapi: 3.0.3
info:
  title: Basic API
  version: "1.0"
paths:
  /test:
    get:
      operationId: test
      responses:
        200:
          description: Default response
  /user/{userId}:
    get:
      operationId: getUser
      parameters:
        - name: userId
          in: path
          required: true
          schema:
            type: string
      responses:
        200:
          description: Default response

A few things to note here:
/test – this is the url that the client will use
operationId for the test endpoint – is the route that will receive the call from url above
/user/{userId} – url with parameter that the client will use
operationId – here the operationId does not match the url, which is fine. The call will go to the route direct:getUser with the userId in a header on the message seen below

2. Implementation of the Camel solution

package com.example.contract_first_example;


import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;


/**
 * A Camel Java DSL Router for Contract First Example
 */
@Component
public class MyApp extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        rest().openApi().specification("hello-rest-service.yaml");

        from("direct://hello")
            .setBody().constant("Hello from Camel!");

        from("direct://getUser")
            .process(exchange -> {
                exchange.getMessage().setBody("Hello from user: " 
                             + exchange.getMessage().getHeader("userId"));
            });
    }
}

3. Now the implementation is done and we move on to testing:

PS C:\Users\niklas> curl -XGET localhost:8080/hello
Hello from Camel!
PS C:\Users\niklas> curl -XGET localhost:8080/user/11
Hello from user: 11

And that is all there is – pretty simple, like most things in the Camel world 😉

Tested on Java 17, OpenAPI 3.0, Apache Camel 4.9.0 and SpringBoot 3.3.4 in a Windows 10 environment

Example of the Builder Pattern in Java

A small example of the Builder Pattern in Java. We are going to build cars with different colors, brands and models 🙂

Car.java

public class Car {
    private String brand;
    private String color;
    private String model;

    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String getModel() {
        return model;
    }
    public void setModel(String model) {
        this.model = model;
    }
}

CarBuilder.java

public class CarBuilder {
    private Car car;
    
    private CarBuilder() {
        car = new Car();
    }
    public static CarBuilder aCar() {
        return new CarBuilder();
    }
    public CarBuilder withBrand(String brand) {
        car.setBrand(brand);
        return this;
    }
    public CarBuilder withColor(String color) {
        car.setColor(color);
        return this;
    }
    public CarBuilder withModel(String model) {
        car.setModel(model);
        return this;
    }
    public Car build() {
        return car;
    }
}

With these two classes above we can now build some cars:
Main.java

public class Main {
    public static void main(String[] args) {
        Car myFirstCar = CarBuilder.aCar().withBrand("Volvo")
                                          .withColor("Blue")
                                          .withModel("XC90")
                                          .build();

        Car mySecondCar = CarBuilder.aCar().withBrand("Skoda")
                                           .withColor("Grey")
                                           .withModel("130L")
                                           .build();
        System.out.println("My first car was a " + myFristCar.getBrand());
        System.out.println("My second car was a " + mySecondCar.getBrand());
    }
}

Should print:

My first car was a Volvo
My Second car was a Skoda

Tested on Ubuntu 20.04.4 LTS and Java 21

WireMock: Verify payload sent to a mocked service in JUnit 5

This was not totally logical to me so I’ll write the solution down here for myself and anyone else that might have the same problem as me 🙂

The solution is to use the WireMock.verify function to setup a payload assertion.

Example (pseudo code):

import com.github.tomakehurst.wiremock.client.WireMock;
import com.niklasottosson.myApplication;
import org.junit.jupiter.api.Test;

import static com.github.tomakehurst.wiremock.client.WireMock.equalToXml;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;


public class MyApplicationIntegrationTest {

  @Test
  public void happyCaseTest() {

    String expected = "Hello Test";
    String myPath = "/mymockservice"

    // 1. Setup WireMock
    WireMock.stubFor(post(urlEqualTo(myPath))
       .willReturn(
             aResponse()
                   .withStatus(200)
                   .withHeader("Content-Type", "text/xml")
                   .withBody("Hello from mock service")));        

   // 2. Run system under test
   myApplication.start();        

   // 3. Verify payload sent to mock service
   WireMock.verify(
       postRequestedFor(urlEqualTo(myPath))
            .withRequestBody(equalToXml(expected))
    );
  }
}

1. Setup a WireMock stub for receiving calls from myApplication on a specific path
2. Start system under test, myApplication in this case
3. Verify that a call has been made to the path AND with a request payload matching our “expected” result. If this validates the payload is as “expected” 🙂

So in conclusion, WireMock is doing the assertion here, not our testing framework

Tested with WireMock v.3.1.0