Unit & Integration Testing REST Services

Generate REST Service

Use the Netbeans New, RESTful Web Services from Entity Classes, to create the required REST service code.
This has a small impact on the AnEntity class, adding the JAXB @XmlRootElement annotation. The key class created here though is AnEntityFacadeREST.java. I made two tweaks to the generated code at this point.

1. Replace the magic string constants values by the MediaType.APPLICATION_XML and MediaType.APPLICATION_JSON constants; just for personal preference.
2. Amend the @POST (create) service to return the URL of the created resource.

In the generated class file AbstractFacade.java, the create method was changed to:

public T createEntity(T entity) {
  EntityManager entityManager = getEntityManager();
  return entity;

Notice that this performs an entityManager.flush() in order to generate the entity’s id.
Just for consistency, the edit and remove method names were changed to editEntity and removeEntity.

Then the REST service class file (AnEntityFacadeREST.java) the create method was changed to:

public Response create(AnEntity entity) {
  AnEntity newEntity = super.createEntity(entity);
  URI newEntityUri = uriInfo.getRequestUriBuilder().path(newEntity.getId().toString()).build();
  return Response.created(newEntityUri).entity(newEntity).contentLocation(newEntityUri).build();

together with adding the class variable:

UriInfo uriInfo;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.