Spring Boot - Microservice- JaxRS Jersey - HATEOAS - JerseyTest - Integration
In this article, we discuss how to write a Spring Boot microservice based on Spring Jax-Rs Jersey, HATEOAS API, and JerseyTest framework integration.
Join the DZone community and get the full member experience.
Join For FreeIn this article, we discuss how to write a Spring Boot microservice based on Spring Jax-Rs Jersey, HATEOAS API, and JerseyTest framework integration. We are going to take the material of our previous article Spring Boot - Microservice - Spring Data REST and HATEOAS Integration and rewrite it for new Spring Jax-Rs Jersey usage.
You may also like: REST API — What Is HATEOAS?
Both articles are based on the sample project written by Greg Turnquist one of the authors of the Spring HATEOAS - Reference Documentation. If you are already familiar with this project and its problem domain feel free to skip its description. Otherwise, we do encourage you to keep reading.
Maven Project Dependencies
The project has the following Maven dependencies.
The following is the relevant snippet from the project pom file.
xxxxxxxxxx
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework</groupId>
<artifactId>jersey-test-framework-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Project Code Structure
This project has the following structure.
KievSpringJaxrsJerseyAndHateoasApplication.java — Spring Boot Application class generated by the Spring Boot. You have seen similar codes many times by now. The addition of the highlighted static property mapperString is necessary for the integration with the JerseyTest framework and would be discussed in detail later.
JerseyConfig.java — Plain vanilla Jersey 2.x configuration file. There is nothing special about it. As we can see, here the single endpoint is registered.
CustomOrderHateoasController.java, OrdersModel.java, and HalConfig.java – Custom controller, aka registered endpoint, and its support and configuration classes accordingly. It is here where the integration between Spring Jax-Rs Jersey and HATEOAS API happens.
KievSpringJaxrsJerseyAndHateoasApplcationTests.java, MockMvc.java, and MockMvcConfig.java – Classes responsible for integration JerseyTest framework with Spring Boot application.And that what makes them rather interesting.
We are ready to start to dissect the project. But before we do that, let's refresh our memory what are the goals for the project. The following are relevant excerpts taken from the README.adoc document.
Defining the Problem
PROBLEM: You wish to implement the concept of orders. These orders have certain status codes that dictate what transitions the system can take, e.g. an order can’t be fulfilled until it’s paid for, and a fulfilled order can’t be canceled.
SOLUTION: You must encode a set of OrderStatus
codes, and enforce them using a custom Spring Web MVC controller. This controller should have routes that appear alongside the ones provided by Spring Data REST.
Let's describe the basics of an ordering system.
That starts with a domain object:
xxxxxxxxxx
name = "ORDERS") // (1) (
class Order {
private Long id; // (2)
private OrderStatus orderStatus; // (3)
private String description; // (4)
private Order() {
this.id = null;
this.orderStatus = OrderStatus.BEING_CREATED;
this.description = "";
}
public Order(String description) {
this();
this.description = description;
}
...
}
The next step in defining your domain is to define OrderStatus
. Assuming we want a general flow of Create an order
⇒ Pay for an order
⇒ Fulfill an order
, with the option to cancel only if you have not yet paid for it, this will do nicely:
xxxxxxxxxx
public enum OrderStatus {
BEING_CREATED, PAID_FOR, FULFILLED, CANCELLED;
/**
* Verify the transition between {@link OrderStatus} is valid.
*
* NOTE: This is where any/all rules for state transitions should be kept and enforced.
*/
static boolean valid(OrderStatus currentStatus, OrderStatus newStatus) {
if (currentStatus == BEING_CREATED) {
return newStatus == PAID_FOR || newStatus == CANCELLED;
} else if (currentStatus == PAID_FOR) {
return newStatus == FULFILLED;
} else if (currentStatus == FULFILLED) {
return false;
} else if (currentStatus == CANCELLED) {
return false;
} else {
throw new RuntimeException("Unrecognized situation.");
}
}
}
At the top are the actual states. At the bottom is a static validation method. This is where the rules of state transitions are defined, and where the rest of the system should look to discern whether or not a transition is valid.
The last step to get off the ground is a Spring Data repository definition:
xxxxxxxxxx
public interface OrderRepository extends CrudRepository<Order, Long> {
}
This repository extends Spring Data Commons' CrudRepository, filling in the domain and key types (Order and Long).
The following class preloads some testing data. We do believe that @Configuration annotation should be used instead of the @Component, but we are trying to reuse the code of our foundation as much as possible and that is the reason why we have @Component annotation in place.
xxxxxxxxxx
public class DatabaseLoader {
CommandLineRunner init(OrderRepository repository) { // (1)
return args -> { // (2)
repository.save(new Order("grande mocha")); // (3)
repository.save(new Order("venti hazelnut machiatto"));
};
}
}
It should be stated that right here, you can launch your application. Spring Boot will launch the web container, preload the data, and then bring Spring Data REST online. Spring Data REST with all of its prebuilt, hypermedia-powered routes, will respond to calls to create, replace, update and delete Order
objects.
Spring Data REST will know nothing of valid and invalid state transitions. Its pre-built links will help you navigate from /api
to the aggregate root for all orders, to individual entries, and back. But there will no concept of paying for, fulfilling, or canceling orders. At least, not embedded in the hypermedia. The only hint end users may have are the payloads of the existing orders.
That’s not effective.
No, it’s better to create some extra operations and then serve up their links when appropriate.
That concludes the description of our preliminary steps. At this point, you should know the goals of the project. We do know what has to be done, so let's see how it can be done. Let's talk about Spring Jax-Rs Jersey and HATEOAS integration.
Spring Jax-Rs Jersey and HATEOAS Integration
In a moment we would talk about the endpoint CustomOrderHateoasController and its support and configuration files. First, let's make it crystal clear what this integration with HATEOAS is all about. So what is the deal?
As we know a core principle of HATEOAS is that resources should be discoverable through the publication of the links that point to available resources. For example, if we issue an HTTP GET to the root URL of our project we should see the following output.
The first link should direct us to the resource orders, while the latest link should direct us to the ALPS document. We do not have an ALPS document for this demo, so let's issue an HTTP GET to the first link, aka orders. We should see the following output, and now we can see that there are two orders and we can pay or cancel them accordingly.
Let's stop here for a second and contemplate what is the difference between the first root resource and the second orders resource. Well, one thing that comes to mind is the observation that the orders resource is dealing with the data from the repository while the root resource does not.
It means, that the second resource would use EntityModel from Spring Data JPA, and that is where we have to start doing some integration with HATEOAS API provided by Spring. Let's look at the relevant methods from CustomOrderHateoasController.java.
That is where support class OrderModel.java comes into the picture.
This static class is responsible for the root resource HAL description. Due to the fact that it does not use EntityModel, we can have the property named _links, and Jersey would generate JSON according to our expectations. After all, we are in control, we are masters of our domain! We would like to point out that this representation is written manually, but it should be acceptable.
After all, we are talking about microservices, and that implies that the root API that is not excessively large. Otherwise, it would not be a microservice but something else. Anyway, let's take a look at what is going on when we have to generate HAL representation for the resource orders.
Here we can see the property named _embedded so the Jersey would generate it accordingly. But then we can see that we are using instantiation of the EntityModel interface, and this instantiation is out of our reach. It does not have property _links, but links instead.
So what does it mean and why do we care? We care, because the Jersey would generate the next representation.
The highlighted boxes show where the problem is. Here we can clearly see that Jersey generated links and not the _links that we would like to have. It makes sense after all links are what we have in the EntityModel. It means we are ready to start integration with Spring HATEOAS that would lead us to the HAL format. Let's consider and welcome the HalConfig.java, the configuration class that makes the things done.
Now you can start the spring boot application and follow steps outlined in the README.adoc document.
xxxxxxxxxx
$ curl localhost:8080/api/orders/1 { "orderStatus" : "BEING_CREATED", "description" : "grande mocha", "_links" : {
"self" : {
"href" : "http://localhost:8080/api/orders/1"
},
"order" : {
"href" : "http://localhost:8080/api/orders/1"
},
"payment" : {
"href" : "http://localhost:8080/api/orders/1/pay"
},
"cancel" : {
"href" : "http://localhost:8080/api/orders/1/cancel"
}
}
====
Apply the payment link:
====
$ curl -X POST localhost:8080/api/orders/1/pay { "id" : 1, "orderStatus" : "PAID_FOR", "description" : "grande mocha" }
$ curl localhost:8080/api/orders/1 { "orderStatus" : "PAID_FOR", "description" : "grande mocha", "_links" : {
"self" : {
"href" : "http://localhost:8080/api/orders/1"
},
"order" : {
"href" : "http://localhost:8080/api/orders/1"
},
"fulfill" : {
"href" : "http://localhost:8080/api/orders/1/fulfill"
}
}
====
The `pay` and `cancel` links have disappeared, replaced with a `fulfill` link.
Fulfill the order and see the final state:
====
$ curl -X POST localhost:8080/api/orders/1/fulfill { "id" : 1, "orderStatus" : "FULFILLED", "description" : "grande mocha" }
$ curl localhost:8080/api/orders/1 { "orderStatus" : "FULFILLED", "description" : "grande mocha", "_links" : {
"self" : {
"href" : "http://localhost:8080/api/orders/1"
},
"order" : {
"href" : "http://localhost:8080/api/orders/1"
}
}
Everything works as expected. It means our integration Jax-Rs Jersey with the HATEOAS API was a sweet-sweet success. But wait! What is this highlighted line above all about? What is this mapperString? Yes, indeed! What is it?
Spring Boot Integration With JerseyTest Framework
We are using it for the integration of the Spring Boot application and the JerseyTest framework. After all, we are living in a material world, and they do demand unit tests over here for the loaf of bread. So we can't stop, we don't have any choice but to keep going instead. As you probably know, Jax-Rs Jersey is its own world, and in this world, they do like the JerseyTest framework.
We do have to accept it as a fact and live with it. They do also like the Grizzly test container, and it is ok with us too. So what do we have at the end? We do have the JerseyTest framework and Grizzly test container to use. Remember our pom file above, the last two dependencies? If the answer is No, then scroll the text back and take a look.
So now you know what we have to do. We have to run test cases written by Greg Turnquist OrderIntegrationTest.java. It should not be a big problem, right? Well, the answer is yes and no. The truth is we can't use it the way it is. The reason is quite simple. It was written by Spring folks for Spring crowd. In other words, it is based on the Spring MockMvc test framework. And our JerseyTest application is not MVC. Does it mean, that we should rewrite the test cases, reuse the logic but not the already written code?
We can do that. But what about if you have a ton of already written JUnit test cases for the Spring MVC, and now they are telling you that you are migrating to the Jersey world. Yeah, all the way! Are you going to do the rewrite? Take a breath and don't panic. At least, don't panic yet.
We are excited to let you know that you don't have to. While you can't reuse all the Spring MockMVC written code, you can reuse a chunk of it, and most importantly you would be able to execute all already written JUnit test cases without any modification but with a little bit of help, of course. Now (drum beats) Ladies and Gentlemen let us introduce you to the Spring Boot – JerseyTest integration!
Where do we start? We would start with the existing code. Let's see what we have.
The first things to notice are the _links, highlighted by a red box. Also there are such instance methods as perform(), andDo(), andExpect(). These methods are chained. In other words, their return value is the instance itself (this.mvc). We can also deduct that these instance methods arguments are static methods calls. Let's list some of them to make things clear: get(), post(), jsonPath(), and ext.
Let's start talking about these things one by one. Let's start talking about the _links. At this point of our discussion, we should be familiar with its origin. It is the HAL links representation. As our JerseyTest application is not integrated with HATEOAS yet, and we can assume that it would fail here. And it does. Consider the KievSpringJaxrsJerseyAndHateoasApplcationTests.java.
The JerseyTest application has its own application context. By default, it would try to use XML spring schema-based configuration. That would be our first failure. After all the spring boot application that we generated is based on the annotation-based configuration. So the first highlighted line is taking care of that.
We can see that we are trying to process our Spring Boot application, and our expectation is that everything would be loaded. It does, but it is not the same. One thing you would notice that the repository lost test loaded data. That is easy to fix, and we can reload the test data. Not big deal, we can say to ourselves. After all, we are running tests, and it makes sense to load some data for the tests. So we are good at that.
However, to our surprise, we would discover that the loaded HATEOAS integration, the object mapper, does not deliver. The mapper would be in the JerseyTest context, but the generated representation would be links, not the _links that the written test cases expect. It is obvious that some trickery has to be done in order to remedy the situation.
Remember, the mapperString the static property of the Spring Boot application class? You sure do. So what do we know? We know that the object mapper from the Spring Boot application context delivers. So we can try to grab this instance and push it to the JerseyTest context. That is what the property mapperSpring is for. And the approach works!
So what is this object MVC that we are getting from the JerseyTest application context (line 55)? One thing is for sure, it can't be original MockMvc from the Spring Boot testing framework. If you guessed as so, you were right! It is not! It is our adapter, that puts all pieces of the puzzle in place. Here is how it works. But before we go to its discussion, let's take a look at his configuration. So we do know how it gets into the JerseyTest application context.
So it is an instance of the MockMvc.java the adapter that we wrote to be able to reuse existing Junit test cases. With the help of the class, we are able to execute the test written for the Spring MockMvc test framework in the JerseyTest suite. It is simple, it is rather crude but it makes the job done! Feel free to explore it, of course. Before we complete the article and thank you for the reading, we would like to highlight some of its features like static and instance methods invocations. That we believe is informative.
Let's dissect the statement this.mvc.perform(get("/api"))
xxxxxxxxxx
public static Pair<String, String> get(String path) {
return Pair.of(HttpMethod.GET, path);
}
public static Pair<String, String> post(String path) {
return Pair.of(HttpMethod.POST, path);
}
...
public MockMvc perform(Pair<String, String> methodPath) {
String httpMethod = methodPath.getFirst();
String path = methodPath.getSecond();
if (HttpMethod.GET.equals(httpMethod)) {
Response response = client
.target(String.format("%s://%s%s", baseUri.getScheme(), baseUri.getAuthority(), path)).request()
.get();
setResponse(response);
} else if (HttpMethod.POST.equals(httpMethod)) {
Response response = client
.target(String.format("%s://%s%s", baseUri.getScheme(), baseUri.getAuthority(), path)).request()
.post(Entity.json(null));
setResponse(response);
}
return this;
}
As you can see, we are invoking our endpoint deployed to the Grizzly test container by means of the JerseyTest framework.
The other interesting statement to consider is .andExpect(jsonPath("$._embedded.orders[0].orderStatus", is("BEING_CREATED")))
xxxxxxxxxx
public static COMMAND jsonPath(String expression, String expected) {
COMMAND.JSON_PATH.setExpression(expression);
COMMAND.JSON_PATH.setExpected(expected);
return COMMAND.JSON_PATH;
}
public static String is(String expected) {
return expected;
}
...
public MockMvc andExpect(MockMvc.COMMAND command) throws Exception {
switch (command) {
case PRINT:
break;
case STATUS_OK: {
if (!Response.Status.OK.equals(Response.Status.fromStatusCode(response.getStatus())))
throw new Exception();
break;
}
case CONTENT_HAL_JSON: {
String contentType = response.getHeaderString("Content-Type");
if (!(MediaTypes.HAL_JSON).equals(MediaType.valueOf(contentType)))
throw new Exception();
break;
}
case JSON_PATH: {
String expression = COMMAND.JSON_PATH.getExpression();
String expected = COMMAND.JSON_PATH.expected;
String json = getJson();
Object[] args = {};
JsonPathExpectationsHelper helper = new JsonPathExpectationsHelper(expression, args);
Object rawActual = helper.evaluateJsonPath(json);
boolean isNumeric = expected.chars().allMatch(Character::isDigit);
if (isNumeric) {
Integer actualValue = (Integer) rawActual;
rawActual = String.format("%d", actualValue);
}
String actualUri = (String) rawActual;
String expectedUri = expected;
if (PORT_HANDLING.SET_EXPECTED_PORT_FROM_ACTUAL.equals(portHandling) && expectedUri.startsWith("http://")) {
// very naive approach, but it is good enough for demo
URL originalURL = new URL(expected);
// add port
URL portURL = new URL(originalURL.getProtocol(), originalURL.getHost(), baseUri.getPort(),
originalURL.getFile());
expectedUri = portURL.toString();
}
if (!expectedUri.equals(actualUri))
throw new Exception();
break;
}
case IS4XXCLIENTERROR: {
if (!Response.Status.Family.CLIENT_ERROR.equals(Response.Status.Family.familyOf(response.getStatus())))
throw new Exception();
break;
}
case CONTENT_APPLICATION_JSON: {
String contentType = response.getHeaderString("Content-Type");
if (!(MediaType.APPLICATION_JSON).equals(MediaType.valueOf(contentType)))
throw new Exception();
break;
}
case CONTENT_STRING: {
String expected = COMMAND.CONTENT_STRING.getExpected();
String json = getJson();
if (!json.equals(expected))
throw new Exception();
break;
}
default:
throw new Exception();
}
return this;
}
It is worth mentioning the class JsonPathExpectationsHelper.java (line 121). It is part of the Spring MockMvc testing framework, and it is the real core component that process expectations and actual expressions — things like "$._embedded.orders[0].orderStatus" and ext.
The last part to mention is the JerseyTest client that the MockMvc is using in order to invoke the endpoint deployed to the Grizzly container (perform()). The setup happens before every test. Consider the following.
By default, the JerseyTest resets the test container before every test. As a result, we have to reset the client in our MVC adapter.
Conclusions
That's it. Feel free to take the code from the GitHub and give it a spin. Feel free to expand it and use it, if it does make a sense. After all, they do say that it is better to see something once than to hear about it a thousand times. The saying is an Asian proverb. One of the authors is living and working there. So if you find yourself in Seoul, Republic of Korea, stop by and say Hi to Bogdan. As for myself, I am a bit tired. In fact, I am tired a lot lately. Time to sleep. Rest in peace Konstantin. :)
Further Reading
HATEOAS REST Services With Spring
RESTful Web Services With Spring Boot, Gradle, HATEOAS, and Swagger
Opinions expressed by DZone contributors are their own.
Comments