In this chapter we are going to create service layer which exposes backend functionality via REST services with JSON transport.
First we create the REST API as interface in api/src/main/java/org/example/app/ordermanagement/service/api/rest/OrdermanagementRestService
@Path("/ordermanagement/v1")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public interface OrdermanagementRestService {
@GET
@Path("/order/{id}/")
OrderEto findOrder(@PathParam("id") long id);
// ...
}
Now we create a REST implementation class in core/src/main/java/org/example/app/ordermanagement/service/impl/rest/OrdermanagementRestServiceImpl
.
Simply implement your REST interface as Java class and annotate it with @Named
:
@Named
public class OrdermanagementRestServiceImpl implements OrdermanagementRestService {
@Inject
private Ordermanagement ordermanagement;
public OrderEto findOrder(long id) {
// TODO
}
// ...
}
The URL of the service should be like this (what will retrive order with ID 1
as JSON):
http://localhost:8081/services/rest/ordermanagement/v1/order/1
Simple GET
requests can be easily tested via URL in your browser.
For testing other methods such as POST
or DELETE
see rest testing.
If you have time left, create an automated integration test.
Therefore, we define a subsystem tests in
core/src/test/java/org/example/app/ordermanagement/service/impl/rest/OrdermanagementRestServiceTest
public class OrdermanagementRestServiceTest extends RestServiceTest {
@Test
public void testFindOrder() {
String login = "admin";
String password = "admin";
OrdermanagementRestService service = getServiceClientFactory().create(OrdermanagementRestService.class,
new ServiceClientConfigBuilder().host("localhost").authBasic().userLogin(login).userPassword(password)
.buildMap());
OrderEto order = service.findOrder(1L);
assertThat(order.getPrice()).isEqualTo(new BigDecimal("25.50"));
}
}
At the first look this appears to be the same as our test of the use-case or repository.
However, technically here a full server with HTTP stack is started within JUnit.
The JUnit test itself invokes the server via HTTP GET request and de-serializes the JSON from the server response back to OrderEto
. Besides authentication and all such aspects are also tested.
To make this work you need to ensure you have a proper service client implementation available. Therefore add the following dependency to core/pom.xml
:
<dependency>
<groupId>com.devonfw.java.starters</groupId>
<artifactId>devon4j-starter-cxf-client-rest</artifactId>
</dependency>
The same infrastructure with ServiceClientFactory
can also be used for microservices.